text:
Q: Get value from div with javascript: Always get undefined I had this problem when I get the value from a div:
function sync(){
    var n1 = document.getElementById('editor').value;
    alert(n1);
    var n2 = document.getElementById('news');
    n2.value = n1;
}

div with id editor looks like this:

When I put something in that div it will alert me undefined and that will also come in the textarea i paste it in too. So the problem is obviously by this:
var n1 = document.getElementById('editor').value;

What am I doing wrong?

A: I think it's important to note that even if
 was a HTMLInputElement you would still keep getting undefined because your div,

Has no value attribute, here is an example of a div with a value attribute:

However, as mentioned in other answers, even though you have entered a value it, .value will still return undefined because
 is a HTML element and not a HTMLInputElement.
If you really need to store some information in the value of the div you can always do something like this:

Right after the div loads, you force 'hello' as the value.
The only reason you'd do this is if you really want to store data within the div's value and can't store it within the innerHTML because the div is visible.
If you want to store the information within your div like this:

all the information i want to store

Then document.getElementById('editor').innerHTML;  is the correct solution, but remember that users will be able to see the information on the webpage.

A: Try this
var n1 = document.getElementById('editor').innerHTML; // or innerText, or textContent

A: HTML Elements and HTMLInputElements are different things.
The value attribute is present in HTMLInputElement in HTMLInputElement Reference
div elements are HTMLElement
If you change your div to input your Javascript will work fine.
The option is to use innerHTML as said in another answer but be aware that this could be HTML fragment at times if you don't control the HTML or over time forget the Javascript and can lead to defects as things.
FYI plain  elements attribute reference(there is no value)


text:
Q: Using pass on an usb I really like the way pass stores passwords but i want to know if i can use it to save from another location that isnt ~/.password-store (lets say a usb).

A: Set the environment variable PASSWORD_STORE_DIR to the location you want and just use pass normally.

A: You could always symlink it
ln /mnt/usb/file.pass ~/.password-store

redpajama_set_name: RedPajamaStackExchange


text:
Q: Which classes of matrices contain $A$ and which contain $B$?
14. In the list below, which classes of matrices contain $A$ and which contain $B$?
$$ A = \begin{bmatrix}
        0 & 1 & 0 & 0 \\
        0 & 0 & 1 & 0 \\
        0 & 0 & 0 & 1 \\
        1 & 0 & 0 & 0 \\
        \end{bmatrix} \ \ \ \textrm{and}\ \ \ B = \frac14\begin{bmatrix}
        1 & 1 & 1 & 1 \\
        1 & 1 & 1 & 1 \\
        1 & 1 & 1 & 1 \\
        1 & 1 & 1 & 1 \\
        \end{bmatrix}
$$
  Orthogonal, invertible, projection, permutation, Hermitian, rank-$1$, diagonalizable, Markov. Find the eigenvalues of $A$ and $B$.

I am pretty confused about classes; I don't know what it means, so I can't really do part A and I need your help with it?
For part B, I got all eigenvalues are $1$ for matrix $A$, and $0$ for matrix $B$. Is this what you get?
Thanks.


text:
Q: Advanced slicing: Python lists vs Numpy arrays I want to swap rows in a two-dimensional array. Using advanced slicing is quite convenient for this purpose:
In [50]: l
Out[50]: [[0, 1], [2, 3], [4, 5], [6, 7]]

In [51]: l[::2], l[1::2] = l[1::2], l[::2]

In [52]: l
Out[52]: [[2, 3], [0, 1], [6, 7], [4, 5]]

However, this does not work if I convert the list into Numpy array:
In [60]: arr
Out[60]:
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7]])

In [61]: arr[::2], arr[1::2] = arr[1::2], arr[::2]

In [62]: arr
Out[62]:
array([[2, 3],
       [2, 3],
       [6, 7],
       [6, 7]])

Why does this method of swapping not work for Numpy arrays?

A:
Why does this method of swapping not work for numpy arrays?

In short: Numpy arrays are true multidimensional objects and provide views on data. Python list objects are not.
You are only ever indexing one list with l[...], and never the contents of the nested and independent row list objects. Slicing also produces new list objects with references to the nested lists copied to the slice result.
Numpy slicing on the other hand addresses individual cells and series of cells in the whole matrix, and you are given views on the data; you can mutate the result of a numpy array slice and see the changes reflected in the original array.
The latter is what is going wrong for you here; as you assign the second row to the cells of the first row, the reference to the first row cells change with the assignment because they are not a copy but a view, and you end up copying the second row cells back to the second row via the first row.
So if you want to swap rows in a numpy array, you'll have to create a copy first:
source = arr.copy()
arr[::2], arr[1::2] = source[1::2], source[::2]


text:
Q: Handling environment variables in flask with docker deployment I'm setting up flask with docker. I've two ways to set environment variables, one in flask .cfg files and another in docker .env files.
I'm wondering which one is the better practice. Evaluating the pros and cons, if I move my environment variables to docker .env files, I would have to do os.environ.get at all the places in my application code, including handling of defaults which brings extra dependency inside application from os environment variables. On the other hand, adding environment variables like DB password, secret keys, etc inside flask config might not be a right idea, although all my environment variables and defaults would be at one single place.

A: You don't have to settle for one or the other.
Is not an unusual practice to use environment variables for configuring every aspect of your application, including DB passwords. This is staring to be an often practice in container environments such as Kubernetes or using docker secrets as they give the ability of keeping critical information encrypted and mount it as an environment variable to your container.
You could directly check in your application for the values of the environment variables or another option is to have an entrypoint in docker that checks for those values and ends up creating a configuration file that you use in your application.
 This last option allows you to use environment variables to configure your application or if you don't want to you could directly mount a configuration file to your container skipping the envs completely.
This is used for example on the logstash docker image.

A: Just to add to the great answer by Esteban Garcia, another good way is to use both. Have a configuration file, class-based configs are great here because you can take advantage of config inheritance, and have all non-sensitive options in there. For the sensitive stuff like secrets, database passwords, etc - define them right in the config with os.environ.get to extract these values from the environment. So it ends up looking like this:
class DefaultConfig(Config):
    TESTING = False
    DEBUG = False
    SECRET_KEY = os.getenv('APP_SECRET_KEY')
    SQLALCHEMY_DATABASE_URI = os.getenv('APP_DATABASE_URI')

This way you can keep using app.config and not have to do os.environ.get all over your app.

A: This is my 2 cents to the subject.
The problem
I was working on porting a flask app to docker and wanted to move my settings.py config vars to env vars so they will be picked up by the container's env. This way, it's easier to deploy it on an external service like ECS just by setting env vars and the app will still the same.
Because I had a lot of config vars on settings.py and didn't want to set each of them by hand on the flask app creation, I came up with the following solution.
Also, I will be using docker-compose to execute all the containers.
Migrate from .py to .env
First thing is to move from python code to a syntax that is compatible with docker-compose. So, if you have this in settings.py:
# *****************************
# Environment specific settings
# *****************************

# DO NOT use "DEBUG = True" in production environments
DEBUG = True

# DO NOT use Unsecure Secrets in production environments
SECRET_KEY = 'This is an UNSECURE Secret. CHANGE THIS for production environments.'

# SQLAlchemy settings
SQLALCHEMY_DATABASE_URI = 'postgresql:///../app.postgresql'

Rename that file to settings.env and change the content to:
# *****************************
# Environment specific settings
# *****************************

# DO NOT use "DEBUG=True" in production environments
DEBUG=True

# DO NOT use Unsecure Secrets in production environments
SECRET_KEY=This is an UNSECURE Secret. CHANGE THIS for production environments.

# SQLAlchemy settings
SQLALCHEMY_DATABASE_URI=postgresql:///../app.postgresql

Note that you have to remove all white spaces and quotes (doubles and singles)
After that, you need to load that file on the docker-compose.yaml file:
version: '3.1'
services:
    web:
        image: web-server
        env_file: path_to/settings.env

Then, when you create Flask app, do the following:
# Instantiate Flask
app = Flask(__name__)

for variable, value in os.environ.items():
    app.config[env_name] = value

If you don't want to load all available env vars on flask
You can add a prefix to the vars on settings.env like this:
YOURAPP_DEBUG=True

And then on the app creation:
# Instantiate Flask
app = Flask(__name__)

for variable, value in os.environ.items():
    if variable.startswith("YOURAPP_"):
        env_name = variable.split("YOURAPP_")[1]
        app.config[env_name] = value


text:
Q: Python decorator that dynamically sets cache based on function parameter I am currently using pyfscache to create a cache in a custom directory and limit the length of storage. Here is my current code:
Import pyfscache
Import pandas as pd

def cache_one_day(func):
    years = 0
    days = 1
    cache = pyfscache.FSCache(CACHE_DIRECTORY, years=years, days=1)
    return cache(func)

@cache_one_day
def get_data(year):
    columns = [str(year), str(year + 1), str(year + 2)]
    data = [1, 2, 3]
    df = pd.DataFrame(data, columns=columns)
    return df

I would additionally like to change the cache time limit based on the year parameter for get_data. So for example, if the year is 2017 I want to refresh the data often and set the days = 1 (as shown). But if the year is 2015, I already know the data will not change and I'd prefer to create an archive where the years = 99.
I know I can write an if statement in the get_data function but this isn't the only function I want to use this logic on. Therefore, I'd rather use something else. I already looked into class decorators and tiered decorators and tried to write each, but I get errors. For example, this code:
class my_decorator(object):

    def __init__(self, view_func):
        self._years = 0
        self._seconds = 0
        self.view_func = view_func
        wraps(view_func)(self)

    def __call__(self, request, *args, **kwargs):
        if request == 2017:
            self._seconds = 1
        else:
            self._years = 1
        cache = pyfscache.FSCache(CACHE_DIRECTORY, years=self._years,
                                  seconds=self._seconds)
        return cache(self.view_func(request, *args, **kwargs))

returns 'DataFrame' object has no attribute 'name'
Any guidance?

A: You could use a wrapper function in your decorator function to split function and arguments:
def cache_one_day(fn):
    def wrapper(*args, **kw):
        # args[0] --> years (2017)
        # cache =  ...
        return fn(*args,**kw)
    return wrapper

@cache_one_day
def get_data(year):
    columns = [str(year), str(year + 1), str(year + 2)]
    data = [1, 2, 3]
    df = pd.DataFrame(data, columns=columns)
    return df

get_data(2017)


text:
Q: .NET MVC Core view not binding results to controller I have been unable to get the posted form values from the view to bind to the controller as it seems to return null in the ViewModel despite the contents of the post request being sent through. I have included the contents of the View and Controller as I'm assuming I must be missing something simple as I'm fairly new to .NET MVC.
View
  @model IEnumerable<MyPortal.ViewModels.SubscriptionsViewModel>

    @{
    ViewBag.Title = "Subscriptions";
    }

Subscriptions

            <form>

                    <input type="text" value="" class="form-control" placeholder="Search by [Name or [ID]" />

                        <button class="btn btn-default" type="button">Search</button>

            </form>

                    MemberID
                    SubscriptionRef
                    SubType
                    StartDate
                    EndDate
                    PrimaryPays
                    Save

                @foreach (var item in Model)
                {

                    @*
                    <input type="hidden" name="SubscriptionRef" value="@item.SubscriptionRef" />*@
                    @*
                    @item.MemberID

                    @item.SubscriptionRef
                    @item.SubType
                    @item.StartDate
                    @item.EndDate
                    @Html.CheckBox("PrimaryPaysInd", "PrimaryPaysIndBool") @item.PrimaryPaysInd @item.PrimaryPaysIndBool	*@
                    @using (Html.BeginForm("save", "secure", FormMethod.Post, new { redeemTransaction = Model }))
                    {
                    @Html.HiddenFor(modelItem => item.SubscriptionRef)
                    @Html.DisplayFor(modelItem => item.MemberID)
                    @Html.DisplayFor(modelItem => item.SubscriptionRef)
                    @Html.DisplayFor(modelItem => item.SubType)
                    @Html.DisplayFor(modelItem => item.StartDate)
                    @Html.DisplayFor(modelItem => item.EndDate)
                    @Html.CheckBoxFor(modelItem => item.PrimaryPaysIndBool)
                    @item.PrimaryPaysInd

                    <button class="btn btn-primary" id="btnSave" name="save" value="Save"> Save</button>
                    }

                }

Controller
        using Microsoft.AspNetCore.Mvc;
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Threading.Tasks;
        using MyPortal.ViewModels;
        using Microsoft.AspNetCore.Authorization;
        using MyPortal.Models;
        using System.Diagnostics;
        using Microsoft.Extensions.Logging;
        using Microsoft.EntityFrameworkCore;
        using AutoMapper;
        namespace MyPortal.Controllers
        {
        public class SecureController : Controller
        {
            private ILogger _logger;
            private PortalContext _context;

            public SecureController(ILogger<SecureController> logger, PortalContext context)
            {
                _context = context;
                _logger = logger;
            }

            public ActionResult Search([FromForm]SubscriptionsViewModel subscriptions)
            {
                var searchParam = subscriptions.searchParam;
                return RedirectToAction("index");
            }

            public IEnumerable<SubscriptionsViewModel> GetAllSubscriptionsById()
            {
                return (from s in _context.Subscriptions
                        where s.MemberID == 123
                        select new SubscriptionsViewModel
                        {
                            MemberID = s.MemberID,
                            SubTypeID = s.SubTypeID,
                            SubscriptionRef = s.SubscriptionRef,
                            StartDate = s.StartDate,
                            EndDate = s.EndDate,
                            PrimaryPaysInd = s.PrimaryPaysInd
                        }).Take(15).ToList();
            }

            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult save([FromForm]SubscriptionsViewModel reedemTransaction)
            {
                _logger.LogInformation("******************");
                _logger.LogInformation("EXECUTING POST");
                _logger.LogInformation("******************");
                if (ModelState.IsValid)
                {
                    var newSubscription = Mapper.Map<Subscription>(reedemTransaction);
                    _logger.LogInformation("***********************");
                    _logger.LogInformation("SubscriptionRef: " + reedemTransaction.SubscriptionRef);
                    _logger.LogInformation("PrimaryPaysInd: " + reedemTransaction.PrimaryPaysInd);
                    _logger.LogInformation("************************");
                    return RedirectToAction("subscription", "secure");
                }
                return RedirectToAction("index", "secure");
            }
        }
    }


text:
Q: Java SAX Parsing There's an XML stream which I need to parse. Since I only need to do it once and build my java objects, SAX looks like the natural choice. I'm extending DefaultHandler and implementing the startElement, endElement and characters methods, having members in my class where I save the current read value (taken in the characters method).
I have no problem doing what I need, but my code got quite complex and I'm sure there's no reason for that and that I can do things differently.
The structure of my XML is something like this:
<players>
  <player>
    <id></id>
    <name></name>
    <teams total="2">
      <team>
        <id></id>
        <name></name>
        <start-date>
          <year>2009</year>
          <month>9</month>
        </start-date>
        <is-current>true</is-current>
      </team>
      <team>
        <id></id>
        <name></name>
        <start-date>
          <year>2007</year>
          <month>11</month>
        </start-date>
        <end-date>
          <year>2009</year>
          <month>7</month>
        </end-date>
      </team>
    </teams>
  </player>
</players>

My problem started when I realized that the same tag names are used in several areas of the file. For example, id and name exist for both a player and a team. I want to create instances of my java classes Player and Team. While parsing, I kept boolean flags telling me whether I'm in the teams section so that in the endElement I will know that the name is a team's name, not a player's name and so on.
Here's how my code looks like:
public class MyParser extends DefaultHandler {

    private String currentValue;
    private boolean inTeamsSection = false;
    private Player player;
    private Team team;
    private List<Team> teams;

    public void characters(char[] ch, int start, int length) throws SAXException {
        currentValue = new String(ch, start, length);
    }

    public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
        if(name.equals("player")){
            player = new Player();
        }
        if (name.equals("teams")) {
            inTeamsSection = true;
            teams = new ArrayList<Team>();
        }
        if (name.equals("team")){
            team = new Team();
        }
    }

    public void endElement(String uri, String localName, String name) throws SAXException {
        if (name.equals("id")) {
            if(inTeamsSection){
                team.setId(currentValue);
            }
            else{
                player.setId(currentValue);
            }
        }
        if (name.equals("name")){
            if(inTeamsSection){
                team.setName(currentValue);
            }
            else{
                player.setName(currentValue);
            }
        }
        if (name.equals("team")){
            teams.add(team);
        }
        if (name.equals("teams")){
            player.setTeams(teams);
            inTeamsSection = false;
        }
    }
}

Since in my real scenario I have more nodes to a player in addition to the teams and those nodes also have tags like name and id, I found myself messed up with several booleans similar to the inTeamsSection and my endElement method becomes long and complex with many conditions.
What should I do differently? How can I know what a name tag, for instance, belongs to?
Thanks!

A: It's difficult to advise without knowing more about your requirements, but the fact that you are surprised that "my code got quite complex" suggests that you were not well informed when you chose SAX. SAX is a low-level programming interface capable of very high performance, but that's because the parser is doing far less work for you, and you therefore need to do a lot more work yourself.

A: There is one neat trick when writing a SAX parser: It is allowed to change the
ContentHandler of a XMLReader while parsing. This allows to separate the
parsing logic for different elements into multiple classes, which makes the
parsing more modular and reusable. When one handler sees its end element it
switches back to its parent. How many handlers you implement would be left to
you. The code would look like this:
public class RootHandler extends DefaultHandler {
    private XMLReader reader;
    private List<Team> teams;

    public RootHandler(XMLReader reader) {
        this.reader = reader;
        this.teams = new LinkedList<Team>();
    }

    public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
        if (name.equals("team")) {
            // Switch handler to parse the team element
            reader.setContentHandler(new TeamHandler(reader, this));
        }
    }
}

public class TeamHandler extends DefaultHandler {
    private XMLReader reader;
    private RootHandler parent;
    private Team team;
    private StringBuilder content;

    public TeamHandler(XMLReader reader, RootHandler parent) {
        this.reader = reader;
        this.parent = parent;
        this.content = new StringBuilder();
        this.team = new Team();
    }

    // characters can be called multiple times per element so aggregate the content in a StringBuilder
    public void characters(char[] ch, int start, int length) throws SAXException {
        content.append(ch, start, length);
    }

    public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
        content.setLength(0);
    }

    public void endElement(String uri, String localName, String name) throws SAXException {
        if (name.equals("name")) {
            team.setName(content.toString());
        } else if (name.equals("team")) {
            parent.addTeam(team);
            // Switch handler back to our parent
            reader.setContentHandler(parent);
        }
    }
}

A: I strongly recommend to stop parsing yourself, and grab good XML data-binding library. XStream (http://x-stream.github.io/) is may personal favorite, but there many different libraries. It may be even able to parse your POJOs on the spot, without any configuration required (if you use property names and pluralisation to match the XML structure).

A: I do something very similar, but instead of having boolean flags to tell me what state I'm in, I test for player or team being non-null. Makes things a bit neater. This requires you to set them to null when you detect the end of each element, after you've added it to the relevant list.

A: If you need prettier code please use StAX, this comparison of all XML parsing APIs suggests that StAX is a much better option.
StAX performance in most tests is better than that of any other API implementation too.
So I personally don't see any reason to go on with SAX unless you're doing some legacy related programming.


text:
Q: Not able to assume role via lambda function - Python Hi I am having this bizarre problem since yesterday. I have a python module web_token.py when I try to run it manually on pycharm and print request_url it works completely fine and outputs the requested_url. But when I zip my web_token.py and fetch_accounts.py together and upload it to lambda function it gives me following error -

An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:sts::5398XXXXXXX:assumed-role/sandbox-amp_sandbox-dev/sandbox-dev-amp_sandbox is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::4540XXXXXXXX:role/AMPSandbox

I even tried giving it FullAdministrativeAccess but still it dosent seem to work. Although I am able to generate requested_url when running the web_token.py in stanalone mode in pycharm. Can someone please provide some guidance will really appreciate it.
Code snippet from

retrieve_accounts.py

import boto3

import web_token

def get_account(event, context):
    client = boto3.client('dynamodb')
    NameID = "test@orgz.com"
    ManagerEmail = "test1@orgaz.com"
    response = client.scan(
        TableName='Sandbox-Users',
        ScanFilter={
            'NameID': {
                'AttributeValueList': [
                    {
                        'S': NameID,
                    },
                ],
                'ComparisonOperator': 'EQ'
            }
        }
    )
    return web_token.request_url

web_token.py

import httplib
import urllib, json
import boto3

client = boto3.client('sts')
assumed_role_object = client.assume_role(
    RoleArn="arn:aws:iam::4540XXXXXXXX:role/AMPSandboxRole",
    RoleSessionName="AssumeRoleSession"
)

# Step 3: Format resulting temporary credentials into JSON
json_string_with_temp_credentials = '{'
json_string_with_temp_credentials += '"sessionId":"' + assumed_role_object.get("Credentials").get("AccessKeyId") + '",'
json_string_with_temp_credentials += '"sessionKey":"' + assumed_role_object.get("Credentials").get("SecretAccessKey") + '",'
json_string_with_temp_credentials += '"sessionToken":"' + assumed_role_object.get("Credentials").get("SessionToken") + '"'
json_string_with_temp_credentials += '}'

# Step 4. Make request to AWS federation endpoint to get sign-in token. Construct the parameter string with
# the sign-in action request, a 12-hour session duration, and the JSON document with temporary credentials
# as parameters.
request_parameters = "?Action=getSigninToken"
request_parameters += "&SessionDuration=43200"
request_parameters += "&Session=" + urllib.quote_plus(json_string_with_temp_credentials)
request_url = "/federation" + request_parameters

conn = httplib.HTTPSConnection("signin.aws.amazon.com")
conn.request("GET", request_url)
r = conn.getresponse()
# Returns a JSON document with a single element named SigninToken.
signin_token = json.loads(r.read())

request_parameters = "?Action=login"
request_parameters += "&Issuer=sandbox.com"
request_parameters += "&Destination=" + urllib.quote_plus("https://console.aws.amazon.com/")
request_parameters += "&SigninToken=" + signin_token["SigninToken"]
request_url = "https://signin.aws.amazon.com/federation" + request_parameters

UPDATE :
I have two policies attached to sandbox-amp_sandbox-dev role-
InfraLoggingPolicy[in 5398XXXXXXX]
    {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "sqs:SendMessage",
                "sqs:SendMessageBatch"
            ],
            "Resource": "arn:aws:sqs:*:131703196249:org-logging-prod",
            "Effect": "Allow"
        },
        {
            "Action": [
                "ec2:DescribeInstances",
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "*",
            "Effect": "Allow"
        },
        {
            "Effect": "Allow",
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::em-log-intake-us-east-1-prod/*",
                "arn:aws:s3:::em-log-intake-us-west-2-prod/*"
            ]
        }
    ]
}

sandbox-amp_sandbox-policy-dev[in 5398XXXXXXX]
    {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Action": "dynamodb:*",
            "Resource": "arn:aws:dynamodb:*:*:*"
        }
    ]
}

UPDATE 2.0
These above policies are from my account number 5398XXXXXXX. I have following role in 4540XXXXXXXX account AMPSandboxRole under which I have following policies
AssumeRole[in 4540XXXXXXXX]
    {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Resource": "arn:aws:iam::*:role/AMPSandboxRole",
            "Action": "sts:AssumeRole"
        }
    ]
}

organizationaccess in [4540XXXXXXXX]
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "organizations:Describe*",
                "organizations:List*",
                "organizations:CreateAccount",
                "organizations:MoveAccount"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "organizations:MoveAccount"
            ],
            "Resource": "arn:aws:organizations::454084028794:root/o-eyec2h6qr0/r-ekzh"
        },
        {
            "Effect": "Allow",
            "Action": [
                "organizations:*"
            ],
            "Resource": "arn:aws:organizations::45xxxxxxxxxx:ou/o-eyec2h6qr0/ou-ekzh-x2xcsupl"
        }
    ]
}

UPDATE 3.0
Trust relationship in 45xxxxxxxxxx
 {
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::53xxxxxxxxxx:root"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

A: The error says:

User: arn:aws:sts::5398XXXXXXX:assumed-role/sandbox-amp_sandbox-dev/sandbox-dev-amp_sandbox is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::4540XXXXXXXX:role/AMPSandbox

The AWS Lambda function is being executed under the role that you have listed above. It only has permission to call dynamodb:*. It also requires permission to call AssumeRole.
Your policy should be updated to:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "PermitDynamoDB",
      "Action": "dynamodb:*",
      "Effect": "Allow",
      "Resource": "*"
    },
    {
      "Sid": "PermitAssumeRole",
      "Action": [
        "sts:AssumeRole"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:iam::4540XXXXXXXX:role/AMPSandboxRole"
    }
  ]
}

A: You will need to Edit Trust Relationship and add the Role name which can be trusted.
Here is an example -
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::<<Account-ID>>:role/<Role_Name_to_be_trusted>",
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

Here is one useful link -
https://github.com/serverless/serverless/issues/3040

A: I think you forgot the Principal entry in your trust rlationship policy document:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "PermitAssumeRole",
      "Action": [
        "sts:AssumeRole"
      ],
       "Principal": {
        "Service": [
          "dynamodb.amazonaws.com",
          "lambda.amazonaws.com"
        ]
      },
      "Effect": "Allow",
      "Resource": "arn:aws:iam::4540XXXXXXXX:role/AMPSandboxRole"
    }
  ]
}

Trust policy is a document in JSON format in which you define who is allowed to assume the role. This trusted entity is included in the policy as the principal element in the document.

So your Trust Relationship policy document should include in the Principal element the AWS resource you are expecting to assume the role

A: I was finally able to figure this account with some from AWS team. So whenever assuming role from one account to another we need to explicitly provide access key and secret key of the account to which we are assuming role to. So it should look something like this -
sts_connection = boto3.client('sts',
                                  aws_access_key_id="",
                                  aws_secret_access_key="")

On providing these details I was finally able to assume role in a different account. Thanks everyone for your guidance and help.


text:
Q: delete item from main list if its empty in C# Entity In this code I check if Unit stock is empty for the same product Id which I selected, then I can delete product, but if so, I also want to delete Product Group for all products that have the same group Id after ensuring they all are empty. What should I do?
here are my model classes
public int Get(int? id)
{
    JalkahoitolaEntities entities = new JalkahoitolaEntities();
    List<int?> items = (from o in entities.Recieved_ammounts
                        where o.ProductId == id
                        select o.UnitStock).ToList();

    if (items.Sum() == 0 || items.Sum() == null)
    {
        Product ProductToBeRemoved = (from o in entities.Products
                                        where o.ProductId == id
                                        select o).First();
        entities.Products.Remove(ProductToBeRemoved);
        entities.SaveChanges();
    }

    entities.Dispose();
    return 1;
}

A: If I understood your question correctly, you want to delete ProductGroup then you are missing with deletion of ProductGroup .Update your code to add Deletion logic for ProductGroup as well.
Retrieve Prodcut to be removed
   Product ProductToBeRemoved = (from o in entities.Products
                                    where o.ProductId == id
                                    select o).First();
    entities.Products.Remove(ProductToBeRemoved);

Delete ProductGroup based on ProductToBeRemoved GroupId
    ProductGroup ProductGroupToBeRemoved = (from o in entities.ProductGroup
                                    where o.GroupId== ProductToBeRemoved .GroupId
                                    select o).First();
    entities.ProductGroup.Remove(ProductGroupToBeRemoved);

Then call the SaveChanges()
UPDATE : After reading OP's comment.
You don't need to write multiple queries for this. Try using some thing like
var prodGroupsToRemove = (from ra in entities.Recieved_ammounts
          join prod  in entities.Products on ra.ProductId  equals prod.ProductId
          join prodGrp in entities.ProductGroup on prod.GroupId equals prodGrp.GroupID
          where (ra.UnitStock > 0)
          select new { GroupId = prodGrp.GroupId , ProductId = prod.ProductId}).ToList();

Above query will return a list of GroupsID,ProductId you want to delete.
Note You need to filter out Products/Group based on result to delete.This might not work simple copy/paste, You may need to update it a bit.


text:
Q: How to evaluate coroutine in pycharms interactive debugger When interrupting execution of python async code with PyCharm's interactive debugger (breakpoints) we can inspect the environment with PyCharm's debugging tools like "evaluate expression" or "Execute Line in Python Console".
How can we evaluate coroutines within these debugging tools?

A: You can try to use PyCharm Evaluate async code plugin, link to  plugin https://plugins.jetbrains.com/plugin/14476-evaluate-async-code

A: No way at the moment, please vote for https://youtrack.jetbrains.com/issue/PY-22961

A: Update from October 2022
Make sure you have the latest version of PyCharm, because they said they added this


text:
Q: jQuery & HTML: Script works from console yet does not run from file or  I have a script for my site where the format and styling changes if the page is viewed from a mobile device. On 2/3 pages on the site the script works great, just as I want. However on the last one, the script for changing the format and styling runs but not completely. I have tried running the code from a script tag at the end and at the beginning of my .html document but nothing changes. the code is:
<script>
    if( jQuery.browser.mobile == true ) {
        alert(true);

        $("#siteHeader").css({
            "position": "absolute",
            "width": $(window).innerWidth + 10 + "px",
        });

        $("#mainContent").css({
            "top": "898px",
        });

        $("#queensTitle").css({
            "display": "none",
        });

        $("#pageTitle").css({
            "text-align": "left",
            "width": "100%",
        });

        $("#pageTitleText").css({
            "width": "93%",
            "margin-left": "20px",
        });

        $("#siteMenu").css({
            "padding-left": "0px",
            "padding-top": "7px",
            "height": "initial",
            "margin-top": "initial",
            "text-align": "center",
            "border-bottom": "28px solid #063e53",
        });

        $(".menuItems").css({
            "width": "100%",
            "height": "initial",
            "float": "initial",
            "margin": "auto",
            "font-size": "5em",
            "font-weight": "700",
            "padding": "0px",
        });

        $("body").width($("#siteMenu").width() - 15).css({
        });

        if ($(location).attr("pathname") == "/drama/about-us-template.html") {
            $("#aboutUsDesc").css({
                "font-size": "1.7em",
            });

            $("#backgroundImageAU").height(247 + $("#aboutUsTitleContainer").height() + $("#aboutUsDescContainer").height() + 21);
        };
    };
</script>

The #siteHeader format is changed and the #mainContent is changed but nothing else changes. However if I run the above code through the console or press CTRL-F5 when running the page it all works as I want it. What could possible be the problem here?
(PS. I have searched stackoverflow and found questions with similar titles but completely different scenarios, i tried their solutions anyways but to no avail)
Here is the link to my site. I am using the Google Chrome Developer Tools Device Emulation and my own phone to test mobile views.

A: If at any point the various bits of jQuery does not find an element in the DOM then it will throw an exception and the script will no longer execute.
$("#queensTitle")  => undefined

then calling
$("#queensTitle").css({ ... });

will cause the script to stop executing and nothing else after this point will get executed.
You should really could try checking for an element before trying to set the CSS
var elem = $("#queensTitle");
if ( elem ) {
   elem.css({ "display": "none" })
}

note that you don't need the extra ',' at between the end of the statement and the closing '}' as some browsers will thrown and exception as the parser is expecting additional statements.
Are there any actually any errors or exceptions reported in the browser console when you run the script?


text:
Q: Linq .SingleOrDefault - how to setup a default for a custom class? i went over some questions and searched google a bit,
but i couldnt find an answer ( That satisfies me ).
Basicly, i understand the SingleOrDefault return null or 0 ( depends on the type ).
but how can i make it return something else ?
return myChannels.All.Where(_Channel => _Channel.Guid == this.ParentChannelGuid).SingleOrDefault(_SPECIFICCHANNEL);
so, i want _SPECIFICCHANNEL to be returned in case it is not single..
can that be done ?

A: This can be accomplished in a rather simple way. If you create your own extension method that is more specific than the generic SingleOrDefault, then the compiler will prefer the more type-specific version. Here's an example that shows how to do that with a simple Person class (you can copy-paste it into LINQPad to quickly see the result):
public class Person
{
    public string Name { get; set; }

    public override string ToString()
    {
        return Name ?? "";
    }
}

public static class PersonExtensionMethod
{
    public static Person SingleOrDefault(this IEnumerable<Person> source)
    {
        var person = Enumerable.SingleOrDefault(source);

        if (person == null)
            return new Person { Name = "Unnamed" };

        return person;
    }
}

public static void Main()
{
    var emptyCollection = new Person[0];
    var nonEmptyCollection = new Person[] { new Person { Name = "Jack" } };

    Debug.WriteLine("Empty collection: " + emptyCollection.SingleOrDefault());
    Debug.WriteLine("Non-empty collection: " + nonEmptyCollection.SingleOrDefault());
}

In the above example, SingleOrDefault(IEnumerable<Person>), takes precedence over SingleOrDefault<T>(IEnumerable<T>) which is less specific.

A: Could you use DefaultIfEmpty() (psedo code follows) -
return myChannels.All.Where(_Channel => _Channel.Guid == this.ParentChannelGuid).DefaultIfEmpty(_SPECIFICCHANNEL).SingleOrDefault();

A:
but how can i make it return something else ?

You cannot. You can make your own method — as shown by Oskar Kjellin — to return someting else, but SingleOrDefault will always behave as programmed, which means return the default value (null, 0) for an item.

A: Why not just use the "??" operator and say
return myChannels.SingleOrDefault(_Channel => _Channel.Guid == this.ParentChannelGuid) ??_SPECIFICCHANNEL;

A: You will have to make an extension method:
    public static T SingleOr<T>(this IEnumerable<T> list, T defaultValue) where T : class
    {
        return list.SingleOrDefault() ?? defaultValue;
    }

There is no other way. All classes default to null.

A: You cannot define the default value of a type. It is always defined as null for reference types. For structs, it is an instance of the struct where all member fields in turn are set to their default values. For enums, it is always 0 (which may or may not be a defined value of the enum type in question)

A: Expanding on Oskar's answer of an extension method you can make that more generic so that it covers value as well as reference types with something like the below:
    public static T SingleOrSpecifiedDefault<T>(this IEnumerable<T> enumerable, Expression<Func<T, bool>> singleOrDefault, T defaultValue) where T : IComparable
    {
        T singleValue = enumerable.SingleOrDefault(singleOrDefault.Compile());
        if (singleValue == null || singleValue.CompareTo(default(T)) == 0)
        {
            return defaultValue;
        }

        return singleValue;
    }

This allows you to specify the same LINQ expression that you'd use with SingleOrDefault as well as the defaultValue (which will be used if no match is found).


text:
Q: after start the angular project visual studio shows typescript errors in lib.dom.d.ts file i have angular project , the project run from VS 2017  .. but showing too much errors (tslint error) for typescript file located on C:\Program Files (x86)\Microsoft SDKs\TypeScript\3.2\lib.dom.d.ts
after run the project the visual studio show errors but the website works
how i can disable this errors ?

tsconfig.js file:
  "compileOnSave": false,
  "compilerOptions": {
    "importHelpers": true,
    "module": "esnext",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es2015",
    "skipLibCheck": true,
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ],
    "plugins": [
      { "name": "tslint-language-service" }
    ]
  }
}


text:
Q: How to calculate dimen for different values folder I have a dimen.xml defined in values folder
<dimen name="dimen_button_border_width">2dp</dimen>
<dimen name="version_txt_size">14sp</dimen>

How if I need to add dimen for different values folder like mdpi,hdpi,xxhdpi . What happens to the value of 2dp& 14sp in corresponding folders. Is there any mathematical formula ?

A: check out what these units are in here
in short: 1dp (density pixel) means 1*density_factor in px, no matter of folder
so 1dp on mdpi device  is 1px, on xxhdpi device  is 3*1px and so on
you don't need to put same integer in different qualifying folders, it will be calculated same way. but you may when you want e.g. bigger space on low-res devices (different value)
for example - you have thick line separator, very thin, height is 0.5dp. on xxxhdpi device it will be 0.5 x 4 = 2px. but same value for mdpi device will be 0.5 x 1 = 0px (because of int rounding) and your thick separator is gone... in this case you may put in values-mdpi and values-hdpi (1.5 factor) folders  different, fixed value in px already instead of dp (in above example it should be 1px overriding 0.5dp -> 0px)

A:
How if I need to add dimen for different values folder like mdpi,hdpi,xxhdpi

You do not need to add dimension resources for different density-based resource sets.

What happens to the value of 2dp& 14sp in corresponding folders. Is there any mathematical formula ?

14sp is the same in all densities. 2dp is the same in all densities. So, the mathematical formula is equality.


text:
Q: Is there an equivalent concept in iOS development to an Android product flavor? We utilize product flavors in Android to keep the same code under source control, but conditionally target the endpoints to dev/qa/production servers based on the flavor selected. For reference:
http://tools.android.com/tech-docs/new-build-system/build-system-concepts
For example, when we want to test a new endpoint in the "dev" environment we can have a file in src/dev/res/values/endpoints.xml that has an entry that's the XML equivalent of urlbase = https://dev-endpoint.ourserver.com/v3/, and build using the "dev" product flavor to build an APK pointed to our dev environment.
Is there an equivalent concept for iOS development?

A: Yes.  If you select your project in the left bar, then select your Project under Project in the inner left bar, and select Info on the inner top bar, you will see a section labeled Configurations.  You can configurations here.
Then select your Target on the inner left bar and select Build Settings on the inner top bar.  Search for "preproc" in the search box.  Under the Apple LLVM - Preprocessing section, you can add custom Preprocessor Macros.  For your configurations, define something like "DEV=1", etc.
Now in your code you can say #if DEV, etc.
Many projects use AFNetworking to talk to their back end.  You can set the baseURL for your AFHTTPSessionManager subclass, or whatever, based on the defines.


text:
Q: How to query for nested document inside of nested document in mongodb? I'm trying to query a search parameter to match values of a nested document inside an already nested document.
I get my search parameter value from the request using this code :
It could have multiple values, so they're split separately into an array.
_params.rewardTypes = _params.rewardTypes ? _params.rewardTypes.split(",") : null

the rewardTypes is an array in my document, as it's got a key field that I'm trying to query for.

My current query for key field in _rewardTypes is
              _rewardDetails: {
                $elemMatch: {
                  _rewardTypes: {
                    $elemMatch: {
                      key: {
                        $in: _params.rewardTypes,
                      },
                    },
                  },
                },
              },

This works, and I do get rewardTypes with matching key names as in the parameter array, however I get other documents' rewardTypes that don't match the parameter that I searched for. Is my query correct or am I missing something ?


text:
Q: Sed sed: -e expression #1, unterminated `s' command I'm trying to run this sed command using Renovate, the tool doesn't really matter I think but I'm getting the following error
"find . -name release-notes.md -type f -exec sh -c 'sed -i '1s#^#some text#' \"$1\"' sh {} \\;",

"stderr":"/bin/sh: 1: Syntax error: Unterminated quoted string\n",

Note that it works fine without the space within the sed expression (some text), meaning that the following works fine
"find . -name release-notes.md -type f -exec sh -c 'sed -i '1s#^#sometext#' \"$1\"' sh {} \\;",

Thanks

A: In the expression sh -c 'sed -i '1s#^#some text#' \"$1\"', the second single quote (the one immediately before "1s") terminates the opening quote and the string 1s#^#some text# is unquoted.  It's very common to see the script argument to sed quoted with single quotes, but it's not at all necessary.  In your case, the 2 simplest solutions are:
sh -c 'sed -i 1s#^#some\ text# \"$1\"'

and
sh -c 'sed -i \"1s#^#some text#\" \"$1\"'

But you could simplify everything by avoiding the unnecessary layer of quoting and doing:
-exec sed -i -e '1s#^#some text#' {} \;

The -e isn't strictly necessary, but the non-standard -i wants a backup suffix in some versions, and I find it cleaner to explicitly use -e to avoid confusion.

A: find . -name release-notes.md -type f -exec sed -i '1s/\(some text\)/\"\1\"/' {} \;

Using a capture group is often easier then a look behind (or ahead).  The above code worked for me.  Unsure why you calls sh, -exec will use the default shell, and that should work?  unless you have an edge case?

A: Correct me if I am wrong, but I think this will work.
#!/bin/sh -x

find . -name release-notes.md > stack
while read line
do
echo "some text" > newfile
sed -n '2,$p' "${line}" >> newfile
mv -v newfile "${line}"
done < stack

I personally dislike using -exec with find.  I feel that find commands are frequently complex enough as it is, without trying to jam everything into a single line.  I frequently see problems with find exec lines which I am able to bypass with methods such as the above.


text:
Q: How to cut video files by frame Does anyone know of a software that could be installed/compiled for linux that is able to cut video by the frame? Thanks.

A: ffmpeg can do it. If the video codec is inter-coded and you want precise frame accuracy, you'll have to re-encode the video. If you need to not re-encode the video, then ffmpeg will cut from the nearest GOP boundary before the specified cut point.
Cut and stream-copy:
ffmpeg -i input -ss T -t D -c copy -fflags +genpts output

-ss T specifies the starting point expressed as timecode in the format of S+[.m...] e.g. 24 or 65.22 or [HH:]MM:SS[.m...] e.g. 02:34:11.644
-t D specifies the duration in the same format.
This won't be frame accurate if the start point isn't at a GOP boundary.
Cut and re-encode:
ffmpeg -i input -ss T -t D -fflags +genpts output

Same as above, but this will be frame-accurate.
If you need to specify in and out points by frame numbers:
ffmpeg -i input -vf trim=start_frame=n:end_frame=m -af atrim=start=s:end=t -fflags +genpts output

n and m are the frame numbers of the video in and out points. s and t are the timecodes for the corresponding audio.
The codecs chosen for the re-encoded videos will be according to whichever defaults ffmpeg has set for the output container e.g. H.264 and AAC for MP4.


text:
Q: Merging two tables with some business logic for overfill I have a bit of a challenge ahead of me with a report I need to write.
I have an ordered selected list of results, which has the following:
+---------+----------+----------+
| Header  | estimate | TargetId |
+---------+----------+----------+
| Task 1  |       80 |        1 |
| Task 2  |       30 |        1 |
| Task 3  |       40 |        2 |
| Task 4  |       10 |        2 |
+---------+----------+----------+

I'd like to join this onto another set of data containing the Target information:
+--------+----------+
| Target | Capacity |
+--------+----------+
|      1 |      100 |
|      2 |       50 |
|      3 |       50 |
+--------+----------+

However I'd like to do some sort of pivot / cross join to fill each target to capacity and report this in a way to show a forecast of when each of the tasks for the target will be met.
+---------+----------+----------+----------+----------+---+---+
| Header  | Overfill | Target 1 | Target 2 | Target 3 | … | … |
+---------+----------+----------+----------+----------+---+---+
| Task 1  | No       |       80 |        0 |        0 | 0 | 0 |
| Task 2  | Yes      |       20 |       10 |        0 | 0 | 0 |
| Task 3  | No       |        0 |       40 |        0 | 0 | 0 |
| Task 4  | Yes      |        0 |        0 |       10 | 0 | 0 |
+---------+----------+----------+----------+----------+---+---+

Alternatively displayed:
+---------+--------+-----------+
| Header  | Target | Overfill% |
+---------+--------+-----------+
| Task 1  | 1      | 0         |
| Task 2  | 1,2    | 33.33     |
| Task 3  | 2      | 0         |
| Task 4  | 3      | 100%      |
+---------+--------+-----------+

The actual set of data will involve a few hundred tasks across 20 – 30 targets, unfortunately I don't have any code to show as a demonstration, short of the few simple selects, as I'm not sure how to approach the overfill.
I believe this could be achieved through C# easier however I was hoping this could be completed as a pure SP operation so I can return the data as I wish to display it.
Any help or a nudge in the right direction to take would be greatly appreciated,
Chris

A: Doing this in SQL is a bad idea, but it is possible with a recursive CTE.  The solution below uses a recursive CTE with a result set that maintains the state of the solution as it goes.  It queries one record for each source for each recursive iteration and updates the state with the results of certain calculations.  Depending on the state in the result it will either advance the sequence, the target, or both.
This solution assumes the targets and headers are sequentially ordered.  If the targets aren't sequentially ordered, you can use a CTE to add ROW_NUMBER() to targets.  Also if you have more than 32767 steps in the solution it will fail as that is the max recursion that sql server supports.  Steps should be at most tasks + targets.
One nice thing is that it will handle overflow across multiple targets.  For example, if a task has an estimate it that will fill up multiple targets, then the next task will start at the next available bucket, not the assigned one.  Go ahead and put some crazy numbers in there.
Finally, I didn't know how you were deriving overflow percentage, I don't know how you got the last row's result from your sample data.  I doubt whatever the answer should be would be difficult to derive once the criteria is known.
/** Setup Test Data **/
DECLARE @Tasks TABLE ( Header VARCHAR(20), Estimate INT, TargetId INT );
DECLARE @Targets TABLE ( TargetId INT, Capacity INT );

INSERT INTO @Tasks VALUES
( 'Task 1', 80, 1 ), ( 'Task 2', 30, 1 ), ( 'Task 3', 40, 2 ), ( 'Task 4', 10, 2 );

INSERT INTO @Targets VALUES ( 1, 100 ), ( 2, 50 ), ( 3, 50 );

/** Solution **/

WITH Sequenced AS (
    -- Added SequenceId for tasks as it feels janky to order by headers.
    SELECT CAST(ROW_NUMBER() OVER (ORDER BY Header) AS INT) [SequenceId], tsk.*
    FROM @Tasks tsk
)
, TargetsWithOverflow AS (
    SELECT *
    FROM @Targets
    UNION
    SELECT MAX(TargetId) + 1, 99999999 -- overflow target to store excess not handled by targets
    FROM @Targets
)
, src AS (
    -- intialize state
    SELECT 0 [SequenceId], CAST('' AS varchar(20)) [Header], 0 [Estimate], 0 [CurrentTargetId]
        , 0 [CurrentTargetFillLevel], 0 [SequenceRemainingEstimate], 0 [OverfillAmt]

    UNION ALL

    SELECT seq.SequenceId, seq.header, seq.Estimate, tgt.TargetId
        , CASE WHEN [Excess] <= 0 THEN TrueFillLevel + TrueEstimate -- capacity meets estimate
            ELSE tgt.Capacity -- there is excess estimate
        END
        , CASE WHEN [Excess] <= 0 THEN 0 -- task complete
            ELSE [Excess] -- task is not complete still some of estimate is left
        END
        , CASE WHEN tgt.TargetId != seq.TargetId THEN
            CASE WHEN [Excess] > 0 THEN [TrueEstimate] - [Excess] ELSE [TrueEstimate] END
            ELSE 0
        END
    FROM src
    INNER JOIN Sequenced seq ON
        (src.SequenceRemainingEstimate = 0 AND seq.SequenceId = src.SequenceId + 1)
        OR (src.SequenceRemainingEstimate > 0 AND seq.SequenceId = src.SequenceId)
    INNER JOIN TargetsWithOverflow tgt ON
        -- Part of target selection is based on if the sequence advanced.
        -- If the sequence has advanced then get the target assigned to the sequence
        -- Or use the current one if it is GTE to the assigned target.
        -- Otherwise get the target after current target.
        (tgt.TargetId = seq.TargetId AND tgt.TargetId > src.CurrentTargetId AND seq.SequenceId != src.SequenceId)
        OR (tgt.TargetId = src.CurrentTargetId AND tgt.Capacity >= src.CurrentTargetFillLevel AND seq.SequenceId != src.SequenceId)
        OR (tgt.TargetId = src.CurrentTargetId + 1 AND seq.SequenceId = src.SequenceId)
    CROSS APPLY (
        SELECT CASE WHEN tgt.TargetId != src.CurrentTargetId THEN 0 ELSE src.CurrentTargetFillLevel END [TrueFillLevel]
    ) forFillLevel
    CROSS APPLY (
        SELECT tgt.Capacity - [TrueFillLevel] [TrueCapacity]
    ) forCapacity
    CROSS APPLY (
        SELECT CASE WHEN src.SequenceRemainingEstimate > 0 THEN src.SequenceRemainingEstimate ELSE seq.Estimate END [TrueEstimate]
    ) forEstimate
    CROSS APPLY (
        SELECT TrueEstimate - TrueCapacity [Excess]
    ) forExcess
)
SELECT src.Header
    , LEFT(STUFF((SELECT ',' + RTRIM(srcIn.CurrentTargetId)
            FROM src srcIn
            WHERE srcIn.Header = src.Header
            ORDER BY srcIn.CurrentTargetId
            FOR XML PATH(''), TYPE).value('.', 'varchar(max)'), 1, 1, ''), 500)
    [Target]
    , CASE WHEN SUM(OverfillAmt) > 0 THEN 'Yes' ELSE 'No' END [Overfill]
    , SUM (OverfillAmt) / (1.0 * AVG(seq.Estimate)) [OverfillPct]
FROM src
INNER JOIN Sequenced seq ON seq.SequenceId = src.SequenceId
WHERE src.SequenceId != 0
GROUP BY src.Header
OPTION (MAXRECURSION 32767)

Output
Header               Target     Overfill OverfillPct
-------------------- ---------- -------- ----------------
Task 1               1          No       0.00000000000000
Task 2               1,2        Yes      0.33333333333333
Task 3               2          No       0.00000000000000
Task 4               2,3        Yes      1.00000000000000

I just re-read your question and realized that you intend to run this query within a Stored Procedure.  If that's the case, you could use techniques from this method and adapt them in a solution that uses a cursor.  I hate them, but I doubt it would work any worse than this solution, and wouldn't have the recursion limitation.  You'd just store the results into a temp table or table variable and then return the result of the stored procedure from that.


text:
Q: Как работать с кнопками? Мне нужно отображать в actionBar либо кнопку "reload" либо кнопку "home" в зависимости от текущей активити. Проиллюстрирую:

Как добавлять отдельно кнопку home - научился (использую actionBarSherlock)
Осталось разобраться с тем, как отображать/скрывать кнопку reload. Не получается сделать это в onCreateOptionsMenu просто достав нужную кнопку по id - вылетает ошибка.
У меня есть /menu/menu.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item
     android:id="@+id/reload_button"
     android:icon="@android:drawable/ic_menu_rotate">
</item>

И еще интересует вопрос как сделать так, чтобы текст был по середине actionBar.

A: 1) Отображать/скрывать кнопку reload:
MenuItem menuItem;

...

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    menuItem = menu.findItem(R.id.reload_button);
    return true;
}

И дальше использовать:
menuItem.setVisible(false);

2) Чтобы текст был посередине, нужно делать свой layout как кастомную вьюшку у actionBar
actionBar.setCustomView();


text:
Q: Mongoose populate with 2 Files and 2 Collections return empty array I have the problem that my populate query returns an empty array. I am aware of the countless posts, however none of them provided new insights for me.
My first Schema:
station.js
var stationSchema = new Schema({
    _id: Number,
    Tripcount: [{ type: Number, ref: 'Tripcount'}]
},
    {collection: 'stations'}
);
module.exports = mongoose.model('Station', stationSchema);

My second: trips.js
var tripSchema = new Schema({
    _id: Number,
    Tripcount: Number
},
    {collection: 'trips'}
);
module.exports = mongoose.model('Tripcount', tripSchema);

And my query looks like this, according to the majority of the answers this should do the job:
var Station = require('./station.js');
var query = Station.find()
        .populate({
            path: 'Tripcount',
            model : 'Tripcount'
        });
        query.exec(function(err, stations){
            if(err)
                res.send(err);
            res.json(stations);
        });

Using Postman to GET the stations, it shows Tripcount: []. Any ideas what I am doing wrong?

A: I thought I would add another answer based on previous comments. It seems that your data is not linking up. Mongoose populate will take the values in Station's Tripcount array and try and lookup the Tripcount object in the Tripcount collection using the _id field so lets say you have the following station
{
  _id: 1,
  Tripcount: [100, 101, 102]
}

In your Tripcount Collection you will need the following to match up with the Station Above
[
  {
    _id: 100,
    Tripcount: 2
  },
  {
    _id: 101,
    Tripcount: 4
  },
  {
    _id: 102,
    Tripcount: 6
  },
]

Then when you run your query you will get the following
{
  _id: 1,
  Tripcount: [
    {
      _id: 100,
      Tripcount: 2
    },
    {
      _id: 101,
      Tripcount: 4
    },
    {
      _id: 102,
      Tripcount: 6
    },
  ]
}

A: Can you try the following. Pass an empty object to your find method.
var Station = require('./station.js');
var query = Station.find({})
        .populate({
            path: 'Tripcount',
            model : 'Tripcount'
        });
        query.exec(function(err, stations){
            if(err)
                res.send(err);
            res.json(stations);
        });


text:
Q: Very slow SQL queries on varchar column I'll preface this question by stating that I am in no way a SQL expert.
However, I am trying to get a handle on what is happening with our database. We have been using a piece of code that would query a server database which has been working fine for years.
Recently though, we have been getting timeout errors. The database has grown over the years but it is still relatively small (the table in question has about 50 million records).
My suspicion is that the table has gotten too large for our non-professionally set up database to handle. So I tried to run a following simple query on the table SQL Management Studio:
SELECT *
FROM [dbo].[Table]
WHERE [Variable] = 'NNNNNNNN12'

The variable is set up as a varchar(50). This query took 30-60 seconds to complete. That seems like too much to me. We run a similar query on our software with the default timeout of 15 seconds.
Digging into a little bit, I realized that the table did not have a primary key designated. So I made the one but to my surprise it made it slower. The same query now takes about 5 seconds longer.
The next thing I tried was add an index for the varchar column but that again made it slower - adding another 10 seconds. Adding a full text index made it even worse with almost a minute response time.
The only thing I've managed to do was make it slower - so I need your help. Am I even on the right track here? Is 30 seconds reasonable for this type of query?  Any other ideas on what I can try?

A: It's good you solved the performance problem with index include. If you find the performance problems creeping back, you can try reorganising or rebuilding the indexes.
I had a table of about 10 million rows with clustered index and over time Sql Server 2005 (and 2008 after we upgraded) kept reverting back to using it, even when I created an index as above which included the main columns involved in the SELECT. Initially all was good, the execution plan was using the new index, but after a few weeks our queries would start timing out again and we'd find Sql Server was using clustered index scan again.
We never got to the bottom of why it happened but a reliable workaround was to rebuild the indexes and update the statistics.
ALTER INDEX ALL ON dbo.[Table] REBUILD
UPDATE STATISTICS dbo.[Table]

For us, this was quick - 5 to 10 minutes - but try it on a copy of your production database first to see how long it takes in your case.
Over time, indexes can become fragmented. They start out with the pages corresponding to consecutive keys being physically together and each page is filled up to the FILLFACTOR setting. With inserts or deletes, there may be page splits. Logically related pages are no longer physically together and instead of one page at 100% you have 2 pages at 50% usage. You're jumping around more on the disk to retrieve data and there are more half empty pages to load.
You can check fragmentation with
declare @db_id int = db_id('stackoverflow');
select db_name(database_id), object_name(object_id), *
from sys.dm_db_index_physical_stats ( @db_id, null, NULL, NULL, 'DETAILED' )

The column avg_fragmentation_in_percent should be as close to zero as possible for best performance. avg_page_space_used_in_percent is the average percentage of available data storage space used in all pages and should be high.

A: Take a look to the following scripts for some guidance..
USE YourDatabase
GO
SET STATISTICS IO, TIME ON;
GO
-- A table must have a primary key which implicity will create the clustered index
CREATE CLUSTERED INDEX CLIX_[Table]_YourPrimaryKey_Or_RowIdentifier ON [Table] (YourPrimaryKey_Or_RowIdentifier)
GO
-- A nonclustered index is needed if we are going to retrieve information using the Variable Column
CREATE NONCLUSTERED INDEX IX_Table_Variable ON [Table] (Variable)
GO
Select * FROM [dbo].[Table] where [Variable] = 'NN12345'
GO
--Check Results, copy the values from the messages tab to http://www.statisticsparser.com/
GO
Select [Variable] FROM [dbo].[Table] where [Variable] = 'NN12345'
GO
--Check Results, copy the values from the messages tab to http://www.statisticsparser.com/
--Compare the values for logical reads on the two executions
GO
--if you need more columns for the select statement, you can add them as included columns in this way:
GO
DROP INDEX IX_Table_Variable
GO
CREATE NONCLUSTERED INDEX IX_Table_Variable ON [Table] (Variable) INCLUDE (TheOthersColumns)
GO
--PLEASE make sure you are testing on the development environment prior to move to PROD.

Questions to be considered:

*

*Do I need all the columns during the output result?

*Any Varbinary or varchar(max) sql type during the execution? (slow performance if we have them included)

*Can you add more filters in order to involve more indexes during the execution plan?

A: For this query:
Select * FROM [dbo].[Table] where [Variable] = 'NN12345'

You need an index:
create index idx_table_variable on table(variable);

Then, there are a few cautions.  The variable and constant value need to be of the same type and collation.  So, if you have an index and the above query does not use the index, something else might be going on (such as collation incompatibilities between the table column and the default for the server or database).


text:
Q: Where is the compiled java code stored in an nsf / ntf? Where is the compiled java code stored in an nsf / ntf?   Or is it compiled from the java "files" at runtime?
I looked all through the java perspective but do not see anything that jumps out at me.

A: Under WebContent/WEB-INF/classes. You can find it with Navigator (Window -> Show Eclipse Views -> Navigator).


text:
Q: $.ajax anonymous function causing 500 error on Google App Engine Frustratingly the GoogleAppLauncher can't replicate this and the error only occurs on production. Essentially I have a form submitting json to mailchimp. It is erroring at the javascript and I can't work out why. You can see the 500 error if you try to submit the form - https://v-sons.appspot.com/our-underwear/#subscribe
On the server looks to be a Call to undefined function add_theme_support() however the console tells a different story (I don't understand whether the two relate / not).
In my console, the jQuery error references:
xhr.send( ( s.hasContent && s.data ) || null );

However digging deeper it looks to be a problem with the $.ajax anonymous function of this code block that's being submitted:
jQuery.ajax({
    url: action,
    type: 'POST',
    data: $stickyForm.serialize(),
    success: function(data)
    {
      window.location.hash = 'nearly';
      $('#modalOverlay').addClass('nearly').fadeIn();
      $('#stickyEmail').val("");
      $('#nickName').focus();
    }
});

I've tried to cover as much as I can with this, because to be honest I'm not sure where the problem really lies. It'd be really great to get an answer / some help though because I've been bashing keys for hours trying to work this out. The main problem is this isn't a problem on my local server, and I don't know from what end to attack the problem.
//
Update: It has just occurred to me that this error might have been created by issuing the other fix I used on this other related question I asked the community - 500 Error when Migrating Wordpress to Google Cloud

A: See AJAX Mailchimp signup form integration which suggests adding dataType: 'json' and setting contentType.


text:
Q: Why doesn't path.status report the network connection status correctly in my Swift app? I have some swift code which uses the Network framework to detect when network connectivity is available or not. If I have wifi turned on and I run my code my code reports that path.status is .satisfied and if I then turn off my wifi my code reports that path.status is .satisfied again. But then if I turn on my wifi again path.status is reported as .unsatisfied then a second later it reports it as .satisfied. What on earth is going on? I would expect path.status to change immediately when wifi is turned off and on and off etc.
Here is my NetworkServices class;
final class NetworkServices {

    static let sharedInstance = NetworkServices()

    private let queue = DispatchQueue.global(qos: .background)

    private let monitor: NWPathMonitor

    public private(set) var isConnected: Bool = false

    public private(set) var connectionType: ConnectionType = .unknown

    enum ConnectionType {
        case wifi
        case cellular
        case wiredEthernet
        case unknown
    }

    private init() {
        monitor = NWPathMonitor()
    }

    public func startMonitoring() {
        monitor.start(queue: queue)
        monitor.pathUpdateHandler = { [weak self] path in
            self?.isConnected = path.status == .satisfied
            print("DEBUG: path.status = \(path.status); isConnected = \(self!.isConnected)")
            self?.getConnectionType(path)
        }
    }

    public func stopMonitoring() {
        monitor.cancel()
    }

    private func getConnectionType(_ path: NWPath) {
        if path.usesInterfaceType(.wifi) {
            connectionType = .wifi
        } else if path.usesInterfaceType(.cellular) {
            connectionType = .cellular
        } else if path.usesInterfaceType(.wiredEthernet) {
            connectionType = .wiredEthernet
        } else {
            connectionType = .unknown
        }
    }
}

I call the startMonitoring method in my AppDelegate file's didFinishLaunchingWithOptions method

A: As you turn on wifi, It notify for NWPath update but until then connection has not been established, it takes some moment to connect.

A: The pathUpdateHandler does not work properly in an iOS simulator but works as expected on a real device.


text:
Q: Python Image Library(PIL) saving gif, TypeError: int() argument must be a string I am saving random images from a crawler but sometimes I am getting this error when I save the image,
PIL/GifImagePlugin.py, line 487, in _write_local_header
transparency = int(transparency)
TypeError: int() argument must be a string, a bytes-like object or a
number, not 'tuple'

If an extension is "gif" then I am saving the image
img.save(path, save_all=True)

I tried google but there were no solutions for this.
How can I solve this problem?

A: There seems to be an open Pillow issue for this bug https://github.com/python-pillow/Pillow/issues/2803


text:
Q: Finding Median for continuous distribution I have a homework problem asking  me to find the median of $Y$, where $Y=e^Z$ and $Z \sim N(0,1)$.
I found that the density of $Y=e^Z$ equals $f(Y)=\frac{1}{y \sqrt{2\pi}}e^{-\frac{(ln(y))^2}{2}}$; $y>0$.
To find the median, $f(m)=\int_{-\infty}^m f(y)dy = \int_0^m \frac{1}{y\sqrt{2\pi}}e^{-\frac{(ln(y))^2}{2}}= \frac{1}{2}$.
However I am having a hard time solving the integral. Before solving it myself I went to Wolfram Alpha and it said that there was an error. Is there an easier way to do this computation or did I do something wrong previously?
Any help is appreciated, thank you!

A: The median of $Y=e^Z$ is $1$.  Since $Z \sim N(0,1)$, half of $Z$ is less than or equal to $0$.  So half of $Y$ is less than or equal to $e^0=1$.

A: Monotonic-increasing transforms commute with calculation of quantiles. i.e. $\text{median}(e^Z)$ is $e^{\text{median}(Z)}$
Intuitively it's obvious -- if half the distribution is at or below it before you transform, half the distribution will remain at or below what you transform it to after you transform.
Proof is elementary and along the same lines. For your particular transform:
Let $Y=e^Z$
$F_Y(y) = P(Y\leq y) = P(e^Z\leq y) = P(Z\leq \log(y)) = F_Z(\log(y))$.
Let the median of $Z$ be $m$. Then setting $m=\log(y)$ we have $F_Z(\log(y))=\frac12$ but we see by the above set of equalities that this $\frac12$ is also the value of $F_Y(y) = F_Y(e^m)$.
So if you can find the median of the Gaussian, just transform it and you're done.


text:
Q: Html 5 FileReader always is error I am trying to read a image file, but it never succeeds.  The onerror method is always called.  Here is my code.
   dropZone.addEventListener('drop', function(e)
   {
    var f = e.dataTransfer.files[0];
    if(!f.type.match('image.*'))
    {
        return;
    }

    var reader = new FileReader();

    // Closure to capture the file information.
    reader.onload = handleReaderLoad;
    reader.onerror = function(e)
    {
        alert("it failed")
    }
    // Read in the image file as a data URL.
    reader.readAsDataURL(f);

}, false);
function handleReaderLoad(evt)
{
    alert("it worked")
}

This always fails.  Any help would be welcome. Thanks!

A: I think you'll probably be seeing this issue.
As a general rule you should look more closely at your errors rather than alert('failed') because the error code will give you a better idea of the issue, eg: alert(e.toString()) or alert(e.name + ": " + e.message)


text:
Q: Script in apptainer work for one user but stuck for other users in computing clusters We tried to pull a docker from docker hub and use the apptainer to shell into it and run the script inside the shell.
However, only one user can run the script correctly but others will get stuck after setting the LD variables.
I've added the -X flags and see the script stuck at execution of the executable binary file. We've tried to set the ~/.bashrc and ~/.bash_profile for user who can run the script to the default setting, the apptainer can still work. Is there any other possible troubleshooting direction we can go?
Minimal reproducible example/ Procedure:

*

*apptainer pull --name quantisnp_docker docker://samesense/quantisnp-matlab:byHand

*apptainer shell -H <Directory that contain quantisnp_docker> quantisnp_docker

*sh /usr/local/bin/quantisnp/quantisnp/linux64/run_quantisnp2.sh /usr/local/bin/quantisnp/MATLAB/MATLAB_Compiler_Runtime/v79 --chr 1:23 --outdir <outdir>
The script will stuck here.


text:
Q: How to iterate over points in VTK while finding the Nearest Neighbors of each point? I am using VTK for a project an just can not seem to figure out a section of it. I am trying to iterate through several thousand points and find the 5 closest points every point. Seems like a simple for loop operation but my problem is that for some reason, I am being told that the same 5 points are the closest point for every point in my data...which I know is not true. I will attach the bit of code I am describing Below:
  //test
  vtkSmartPointer<vtkPointSource> pointSource =
    vtkSmartPointer<vtkPointSource>::New();
   pointSource->SetNumberOfPoints( Output->GetNumberOfPoints() );
   pointSource->Update();

   vtkSmartPointer<vtkKdTreePointLocator> Tree =
     vtkSmartPointer<vtkKdTreePointLocator>::New();
   Tree->SetDataSet( pointSource->GetOutput() );
   Tree->BuildLocator();

   unsigned int k = 5;
   double testpoint[3];

   vtkSmartPointer<vtkIdList> result =
     vtkSmartPointer<vtkIdList>::New();

   for(vtkIdType n = 0; n < Output->GetNumberOfPoints(); n++)
     {

     result->Reset();
     Output->GetPoint( n,testpoint );
     Tree->Update();
     std::cout << "Point: " << testpoint[0] << ", " << testpoint[1] << ", " << testpoint[2] << ": " << endl;

     Tree->FindClosestNPoints(k, testpoint, result);

     for(vtkIdType i = 0; i < k; i++)
       {
       vtkIdType point_ind = result->GetId(i);
       double p[3];
       pointSource->GetOutput()->GetPoint(point_ind, p);
       std::cout << "Closest point " << i+1 << ": Point "
       << point_ind << ": (" << p[0] << ", " << p[1] << ", " << p[2] << ")" << std::endl;
       }

     }
     //end test

This is doing what I am trying to do...It is printing out the 5 closest points to the a point of interested, but despite the point of interest changing, the 5 closest points are remaining the same. I am assuming I am just passing over a small detail in my code but I could be wrong. If you need anymore information to help, just ask away.
Thank you for your time and help,
Luke H

A: I found the problem...I was using /vtkPointSource which generates random points and I was feeding in my points into that function. I am not sure why, but that made getting results out very difficult but once I passed in the correct information and placed a Reset() on the point Id array and the result Id array, it works like a champ. Hopefully this will same others some trouble because I spent some hrs working on this.
Luke H
 vtkSmartPointer<vtkKdTreePointLocator> Tree =
 vtkSmartPointer<vtkKdTreePointLocator>::New();
 Tree->SetDataSet( Output );
 Tree->BuildLocator();

 vtkSmartPointer<vtkIdList> result =
   vtkSmartPointer<vtkIdList>::New();

 vtkSmartPointer<vtkIdList> point_ind =
   vtkSmartPointer<vtkIdList>::New();

 unsigned int k = 5;

 double testpoint[3];

 for( vtkIdType n = 0; n < Output->GetNumberOfPoints(); n++ )
   {

   Output->GetPoint( n,testpoint );
   std::cout << "Point: " << testpoint[0] << ", " << testpoint[1]
     << ", " << testpoint[2] << ": " << endl;

   Tree->FindClosestNPoints( k, testpoint, result );

   for(vtkIdType i = 0; i < k; i++)
     {

 vtkIdType point_ind = result->GetId( i );

     double p[3];

     Output->GetPoint( point_ind, p );
 std::cout << "Closest point " << i+1 << ": Point "
   << point_ind << ": (" << p[0] << ", " << p[1] << ", "
       << p[2] << ")" << std::endl;

    }

    result->Reset();
point_ind->Reset();

  }


text:
Q: -webkit- doesn't work correctly on text-decoration I have transition that fade in/out my underlined text-decoration. It works perfectly on every browsers, except on Safari that doesn't make the fade in/out transition.
I have added -webkit-, as indicated on the MDN to make it work on Safari, but it doesn't seem to solve the problem (and I can't use border-bottom).
Here is my CSS:

.posts a:link {
  text-decoration: underline solid transparent;
  transition: text-decoration 0.3s ease;
  -webkit-transition: text-decoration 0.3s ease;
}

.posts a:hover {
  text-decoration-color: black;
}


text:
Q: How can I use settings from another form in project to populate file directory to list exe files Apologies in advance this is my first project.
I am creating a VB project and have created a settings(FormSettings.vb) page where the user browses to their steam library and that inputs into a text box(Textbox1.Text) and got it to save etc. On myy main form of the project I have a drop down box that I want to populate all the exe files which works ok when i specify the directory in the code but what I want it to do it pull the directory path from the users setting
Working
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim directory = "D:\Steam Library"
    Dim files() As System.IO.FileInfo
    Dim dirinfo As New System.IO.DirectoryInfo(directory)
    files = dirinfo.GetFiles("*.exe", IO.SearchOption.AllDirectories)
    For Each file In files
        cmbSelectGame.Items.Add(file)
    Next

End Sub'''

I have also tried
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim directory = FormSettings.Textbox1.Text
    Dim files() As System.IO.FileInfo
    Dim dirinfo As New System.IO.DirectoryInfo(directory)
    files = dirinfo.GetFiles("*.exe", IO.SearchOption.AllDirectories)
    For Each file In files
        cmbSelectGame.Items.Add(file)
    Next

End Sub

Any guidance is appreciated and thank you in advance


text:
Q: Windows 2016 -- Online Responder "Bad Signing Certificate" I'm configuring a CRL online responder, but running into a problem.   The configuration is a simple as could be I would think -- a fresh Server 2016 install, Enterprise root CA.  I go through the revocation config creation wizard as described in an MCSA guide book, signing the config with the CA certificate. There are no other certs to use, and this one is valid.
But when complete the status is "Bad signing certificate on array controller".  I have googled this and the fix seems to be to click "Assign Signing Certificate" and select the cert again there, but for me this is greyed out.
Any ideas?

A: Turns out there was another step required in configuring certificate services which is easy to miss (for a Windows novice anyway).  If you install the feature with cli -- "Add-WindowsFeature ADCS-Online-Cert" -- you will miss a post-install config step which won't present itself until you next open Server Manager.  When you do, click on the notification flag then 'next' through the dialog boxes.  Without this step you can still configure the online responder but it will be invalid.


text:
Q: Nesting react components dynamically , adding custom JSX on the fly inside the component?

   <Card>

          <Logo />

          <Timer />

   </Card>

I want to achieve something like this . I have created a component Card , Now I want that this component should contain any random JSX as well as other components .
I have got the way of nesting React Children using React.Children method , But I am not able to find , how to handle the additional JSX inside the component .

A: Do something like this,
var ParentComponent = React.createClass({
    render : function(){
        var el = (<component_you_want_to_nest />);
        return(
            <ComponentCardComponent nestComp={el} />
        )
    }
});

var ComponentCardComponent = React.createClass({
render : function(){

        {this.props.nestComp}

}

});

A: You can simply use this.props.children.
To handle this specific data-structure, you can use the React.Children utilities.
For example, if in your case you just want to add a wrapping div for every child component in Card, you can write:
const Card = React.createClass({
    render: function() {
        const wrappedChildren = React.Children.map(
            this.props.children,
            function(oneChild) {
                return (

                        {oneChild}

                );
            },
        );
        return (

                {wrappedChildren}

        );
    },
});

// then:
<Card>
   <Logo />
   <Timer />
</Card>


text:
Q: Update/Refresh Rate for monitoring iBeacons I've been playing around with Estimote Beacons for the last few days. I'm starting to doubt the effectiveness for iBeacons becouse of the high latency they have when it comes to determine a Beacons position.
When you move 2-3 meters it takes a few seconds until it gets the position right.
A usecase-scenario like, capturing a person walking by a beacon can be quite hard to determine.
Is it possible to manipulate the Update/Refresh Rate of a CLLocationManager or a CLBeaconRegion? e.g. every 0.1 Seconds

A: The reason that you are seeing it take so long for the iOS distance measurement (what they call "accuracy" in the CLBeacon object) to stabilize is because it is based on a running average of the RSSI -- the received signal strength.  This signal strength measurement is inherently noisy and it bounces all around.  That is why collecting multiple samples is necessary to smooth it out.
But because of this averaging, there is a lag.  The most recent estimate is based on measurements from several seconds ago.
You cannot change the refresh rate of the CLLocationManager or the CLBeaconRegion, but you may be able to get an iBeacon that transmits more often than the 1s baseline.  More transmissions gives you more RSSI measurements to work with, and it may help smooth out the noise.  Because I am not sure of the internal implementation of CoreLocation, I am not positive whether a higher iBeacon transmission rate would reduce the noise on the distance measurement.
You can always calculate your own distance measurement, too, based on RSSI and the Power calibration value sent out by an iBeacon.  If you use a single RSSI sample, then there will be no lag from averaging with earlier measurements, but you will have a high degree of variability.  You basically have to accept a tradeoff between filtering out noise and filtering out old measurements based on different positions.
If you want to try your own calculation, you can use something like below (See my answer to this question for details).
distanceInMeters =  0.89976 * (rssi/txPower)**7.7095 + 0.111

You have to set realistic expectations on how accurate this estimate is going to be.  Apple generally recommends that you don't use their "accuracy" measurement inside CLBeacon, unless it is in combination of other rougher measurements like "proximity" that bucketize the distance measurement into "immediate", "near" and "far" groupings.