text:
Q: Application design, global image collection We have an application, n-tier like structured, but I wouldn't say it's n-tiered.
The top most Form /AKA MainForm/ connects to a DB and gets a list of available modules, according to which it starts loading different modules. Each module is a separate project having 1 top level class that derives from an abstract class, from which all modules derive.
So on and on, so far we have everything running just fine, passing around connections strings, dialogs between modules and the main app.
the next step is to implement a global icon library that each module is to use, the catch is that each module should be able to load its own images to it.
I'm thinking of a global static class that returns currently running instance of ImageList class. I don't know where to start with that, so could anyone please provide an example of global Class that could be used statically without the need of declaring or passing it around? is it possible at all?
EDIT:
rephrase attempt: ideally a global resource to which each separate module is able to insert resources, out of which each module is able to get images if they exist. I don't even know where to start or what to look for.
EDIT 2:
just checked:
   had 3 projects: 1 main, 1 child, 1 inbetween
main references inbetween
child references inbetween
1 main starts and calls static methods on "inbetween" loading some strings into it. Using Reflection "main" instance loads child.dll and instantiates the object using the reflection, then calls a method defined in an interface in "inbetween" on the child obj which in turn calls the static method on the "inbetween" after which "main" prints all the strings in the static "inbetween". And it works! I was like WTF? I guess Reflection combines the 2 "inbetweens"

A: public static class Foo
{
    public static int Bar()
    {
        return 1;
    }

    public static void AddImage(Image img, String key){...}
    public static Image GetImage(String key){...}
}

A: So, you mean u need a "module static" (behaves like thread static but aim at module) method?

A: One easy way would have a shared library that each module would have a reference to. So each module would know the existence of the class offered by the shared library. You could then have a class in that shared library to manage your images.
To make it more elegant, I would look into Dependency Injection framework like Unity. Have the shared library (infrastructure library) hold the definition of an Interface to manage images. Then have a module that implements that specific interface and then register that implementater in the unity container.  So each module would go through the unity container to RESOLVE the Interface.
this way each module are not tightly coupled to the module that implements the interface but only to the shared library which only contains the definition of the interface.


text:
Q: Multiplication in Laravel controller not displaying in view I am trying to multiply the total dollar amount of cart items by a sales tax amount and have that displayed in my view. It seems to be working, or at least I get no errors, but I get no tax displayed in my view.
In my payment controller I have this
public function showPayment() {
    $cart = Session::get('cart');
    $payment_info = Session::get('payment_info');

    if($payment_info['status'] == 'on_hold') {
        $sales_tax = $cart->totalPrice * .085;
        return view('cart.payments', ['payment_info' => $payment_info], ['cartItems' => $cart]);
        $sales_tax = $cartItems->totalPrice * .085;

    }else{
        return redirect()->route("home");
    }
}

And in my view I have this

Taxes: {{ $sales_tax }}

All my other data is working properly, just not the sales tax.

A: that's because you're returning the view before the multiplication  in the blade try this :

Taxes: {{ $cart_item->totalPrice * 0.85 }}

A: What @Bahaedin was implying is that you need to specifically define the sales tax variable if you want to use it as it is in the view. And, since it's bad practice to do logic/calculations in blade, here is one approach that would solve your issue.
 if($payment_info['status'] == 'on_hold') {
    $sales_tax = $cart->totalPrice * .085; //move this before the return statement && cart seems to be an object.
    return view('cart.payments', ['payment_info' => $payment_info, 'cartItems' => $cart, 'sales_tax' => $sales_tax]); //one array, include $sales_tax as a variable.

And in your blade

Taxes: {{ $sales_tax }}

Also, note that if you are sending $cartItem variable into the view, then you would need to reference it using $cartItem not $cart_item so $cart_item['data']['sales_tax'] would not have worked even if you had sent sales_tax in a $cartItem array. If the way you did the multiplication is any hint, I would say $cart is an object, not an array.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Matlab: find neighboring instances of NaN without loops Essentially, I have a matrix of data with many "holes" represented by NaN, and I want to retrieve the indices of all NaN's that are clustered fewer than 4 times in a single column.
e.g. with the matrix:
A =
    23    12    NaN   56    60    21    NaN
    60    56    94    22    45    NaN   NaN
    23    55    19    83    NaN   NaN   NaN
    NaN   NaN   NaN   NaN   NaN   NaN   NaN
    NaN   NaN   NaN   NaN   NaN   NaN   NaN
    NaN   NaN   NaN   NaN   NaN   NaN   NaN
    84    99    43    32    89    12    NaN
    76    92    73    47    22    12    10
    23    55    12    93    61    94    20
    NaN   NaN   NaN   NaN   NaN   NaN   NaN
    41    16    83    39    82    37    43
    14    78    92    40    81    29    60

it would return:
ans =
    [4; 5; 6; 10; 16; 17; 18; 22; 25; 28; 29; 30; 34; 40; 41; 42; 46; 58; 70; 82]

So far, I have a vector with the indices of all the NaN values from
nan_list=find(isnan(A(:)))

but I don't know how to extract sequential numbers from that vector without using loops, which would be too expensive. I also tried something similar to the answer posted by b3 here, by switching all NaN's to a value that doesn't appear in the matrix, but that code was not as transferable for other data sets.
Thanks for any suggestions!

A: Code
N = 4; %// Fewer than clusters of N or N+ NaNs are to be detecteed
nan_pos = isnan(A) %// Find NaN positions as a binary array
conv_res = conv2(double(nan_pos),[0 ones(1,N)]')==N %//' Perform convolution
start_ind = find(conv_res(N+1:end,:)) %// Find positions where clusters of N or N+ NaNs start
nan_pos(unique(bsxfun(@plus,start_ind,[0:N-1])))=0 %// Get positions of all those clustered N or N+ NaNs and set them in NaN position array as zeros
out = find(nan_pos) %// Finally the desired output

Example
As an example, let's try this code on a slightly different input that would hopefully test out various aspects of the problem -
A = [
    23    12    NaN   56    60    21    NaN
    60    56    94    22    45    NaN   NaN
    23    55    19    83    NaN   NaN   NaN
    NaN   NaN   NaN   NaN   NaN   NaN   NaN
    NaN   NaN   NaN   NaN   NaN   NaN   NaN
    NaN   NaN   NaN   NaN   NaN   NaN   NaN
    84    99    43    32    89    12    NaN
    76    92    73    47    22    12    10
    23    55    12    93    61    94    20
    NaN   NaN   NaN   NaN   NaN   NaN   NaN
    41    NaN   NaN    39    82    37   43
    14    78    NaN    40    81   NaN   60]

Now, let's assume that we are looking to find indices of cluster fewer than 3 NaNs. Thus editing N as 3 in the code, the output is -
out =
    10    22    23    25    46    58    70    72    82

This makes sense when we look into the input.

A: This should work:
[rows, ~] = size(A);
maxNansPerCol = 4;

% find which columns have few enough NaNs
Anans = isnan(A);
nansInCols = sum(Anans);
qualifyingCols = nansInCols <= maxNansPerCol;

% zero the other columns
mask = repmat(qualifyingCols,rows,1);
B = Anans .* mask;

% get the NaN locations
indices = find(B(:));

(Apologies if something is slightly off--I don't have MATLAB on this computer to test it)


text:
Q: align radio input-group-addon with a radio form-check in bootstrap 4 i use a bootstrap 4 form with the bootstrap grid.
the user should add a temperature if present, otherwise the user should select the "N.A." radio button.
how can i align the two different elements properly.
i created that example:
https://jsfiddle.net/p7ewb94m/5/

<form>

    Temperature

          <input type="radio" name="gridRadios">

        <input type="text" class="form-control">
        °C

           <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios1" value="option1" checked>
           N.A.

</form>

A: you need to align elements properly in row,Have a look at this might help you

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

     <form class="form-inline" role="form">

      Temperature
        &nbsp

              <input type="radio" name="gridRadios">

            <input type="text" class="form-control">
            °C

    &nbsp

          <input type="radio" id="amount_25" name="amount" value="25" checked="">
          N.A

    </form>

expand snippet(full page) to see on large display


text:
Q: How can i rotate the character head when moving the mouse cursor around? But the player should look around with the head i think in the world space. For example if i move the mouse cursor around and it's pointing on a mountain the player should look at the mountain. But the main goal is to rotate the head whe just moving the mouse around in the game window while the game is running.
Maybe i also don't need so many variables of rotating, speed, x,y ? Maybe i can use less variables for all of that. I want to keep the other parts in the script and to add the head part.
using UnityEngine;
using System.Collections;

[AddComponentMenu("Camera-Control/Mouse Orbit with zoom")]
public class MouseOrbitImproved : MonoBehaviour
{
    public Transform target;
    public float distance = 5.0f;
    public float xSpeed = 120.0f;
    public float ySpeed = 120.0f;

    public float yMinLimit = 3.0f;//-20f;
    public float yMaxLimit = 80f;

    public float distanceMin = .5f;
    public float distanceMax = 15f;

    public Transform boneToRotate;
    int speed;
    float friction;
    float lerpSpeed;
    private float xDeg;
    private float yDeg;
    private Quaternion fromRotation;
    private Quaternion toRotation;

    private Rigidbody rigidbody;

    float x = 0.0f;
    float y = 0.0f;

    public float rotationSpeed = 5f;

    // Use this for initialization
    void Start()
    {
        speed = 3;
        friction = 3f;
        lerpSpeed = 3f;

        Vector3 angles = transform.eulerAngles;
        x = angles.y;
        y = angles.x;

        rigidbody = GetComponent<Rigidbody>();

        // Make the rigid body not change rotation
        if (rigidbody != null)
        {
            rigidbody.freezeRotation = true;
        }
    }

    void LateUpdate()
    {
        if (Input.GetAxis("Mouse X") != 0 || Input.GetAxis("Mouse Y") != 0)
        {
            xDeg -= Input.GetAxis("Mouse X") * speed * friction;
            yDeg += Input.GetAxis("Mouse Y") * speed * friction;
            fromRotation = boneToRotate.rotation;
            toRotation = Quaternion.Euler(yDeg, xDeg, 0);
            boneToRotate.rotation = Quaternion.Lerp(fromRotation, toRotation, Time.deltaTime * lerpSpeed);

            Debug.Log("Mouse Freedom");
        }

        if (target && Input.GetMouseButton(1))
        {
            x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
            y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;

            y = ClampAngle(y, yMinLimit, yMaxLimit);

            Quaternion rotation = Quaternion.Euler(y, x, 0);

            distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel") * 5, distanceMin, distanceMax);

            RaycastHit hit;
            if (Physics.Linecast(target.position, transform.position, out hit))
            {
                distance -= hit.distance;
            }
            Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
            Vector3 position = rotation * negDistance + target.position;

            transform.rotation = rotation;
            transform.position = position;

            transform.rotation = Quaternion.RotateTowards(transform.rotation, rotation, rotationSpeed);

            if (target != null)
            {
                target.rotation = Quaternion.RotateTowards(transform.rotation, rotation, rotationSpeed);
            }
        }
    }

    public static float ClampAngle(float angle, float min, float max)
    {
        if (angle < -360F)
            angle += 360F;
        if (angle > 360F)
            angle -= 360F;
        return Mathf.Clamp(angle, min, max);
    }
}

The script is attached to the Main Camera.
In the boneToRotate variable i dragged the EthanHead from the ThirdPersonController.
The part i just added now for rotating the head is:
In the top:
public Transform boneToRotate;
int speed;
float friction;
float lerpSpeed;
private float xDeg;
private float yDeg;
private Quaternion fromRotation;
private Quaternion toRotation;

In Start:
speed = 3;
friction = 3f;
lerpSpeed = 3f;

In Update:
if (Input.GetAxis("Mouse X") != 0 || Input.GetAxis("Mouse Y") != 0)
            {
                xDeg -= Input.GetAxis("Mouse X") * speed * friction;
                yDeg += Input.GetAxis("Mouse Y") * speed * friction;
                fromRotation = boneToRotate.rotation;
                toRotation = Quaternion.Euler(yDeg, xDeg, 0);
                boneToRotate.rotation = Quaternion.Lerp(fromRotation, toRotation, Time.deltaTime * lerpSpeed);

                Debug.Log("Mouse Freedom");
            }

But it's not working at all. The head is not rotating at all with the mouse cursor.

A: First initialize your variables with proper values -
void Start()
{
    speed = 3;
    friction = 3f;
    lerpSpeed = 3f;
    xDeg = 0f;
    yDeg = 0f;
    fromRotation = boneToRotate.rotation;
    toRotation = boneToRotate.rotation;
    ...
    ...
}

Then move lerp function out of the if condition -
if (Input.GetAxis("Mouse X") != 0 || Input.GetAxis("Mouse Y") != 0)
{
    xDeg -= Input.GetAxis("Mouse X") * speed * friction;
    yDeg += Input.GetAxis("Mouse Y") * speed * friction;
    fromRotation = boneToRotate.rotation;
    toRotation = Quaternion.Euler(yDeg, xDeg, 0);

    Debug.Log("Mouse Freedom");
}
boneToRotate.rotation = Quaternion.Lerp(fromRotation, toRotation, Time.deltaTime * lerpSpeed);


text:
Q: Angularjs passing values I have input element like this
 <input type="text" name="a_id" ng-model="cont.a_id"  ui-event="{blur: 'blurCallback(a_id)'}"/>

in my controller I have
$scope.blurCallback = function (a_id) {
        $scope.aId = a_id;
        alert($scope.aId);
    }

When I run this alert gives me "undefined"
Please let me know what I am doing wrong that it wont pass the value when entered

A: 'a_id' is undefined. you should pass 'cont.a_id'  as the argument to the function. check this plunk http://plnkr.co/edit/E6AJ4NFDJT3CtJXAzom1?p=preview


text:
Q: tinymce formating not working on live Using tinymce for content, it works fine on local server but break formatting on remote server.
saving content:
mysql_real_escape_string( htmlentities($slide_name,ENT_QUOTES,'UTF-8'))

when retrieve:
html_entity_decode($slide_name, ENT_QUOTES,'UTF-8')

on local server it display content correctly:

Contact: 0000-245

on remote (after 1st update):

Contact: 0000-245

use utf8_general_ci collation for both databases (remote/local)

A: After lot of searching and Toby Allen hint I found a solution.
Here was a problem:
magic_quotes_gpc were ON on remote server and magic_quotes_gpc were OFF on Local server.
As we can't control remote server up to php configuration level so we need to OFF magic_quotes_gpc run time.
Found a code snip from php.net
<?php
if (get_magic_quotes_gpc()) {
    $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
    while (list($key, $val) = each($process)) {
        foreach ($val as $k => $v) {
            unset($process[$key][$k]);
            if (is_array($v)) {
                $process[$key][stripslashes($k)] = $v;
                $process[] = &$process[$key][stripslashes($k)];
            } else {
                $process[$key][stripslashes($k)] = stripslashes($v);
            }
        }
    }
    unset($process);
}
?>

if possible OFF magic_quotes_gpc using php.ini otherwise we can use function like above to switch OFF magic_quotes_gpc runtime.
I am posting this answer for future searchers.


text:
Q: How is summation related with integration? How can the following be represented as an integral?
$$\sum_{x=0}^nxP^x$$
I tried:

*

*$\displaystyle\sum_{x=1}^5x=15$

*$\displaystyle\int_1^5x\;dx=12$
Isn't the logic behind both the same? Shouldn't they both give the same result?
I have seen the following thread but I don't seem to understand what is explained. If possible explain in layman's terms:

*

*relation between integral and summation


text:
Q: PHP Cant search for specific words in an array created from file I have been trying to extract specific words from an array which was created from a text file using file() function in php.
The text file sample.txt is like this:
A registration has been received.

Name: test
Lastname: test2
Email: test@test.com
Company/School: Test2
Company2: test3
Address1: test4
Address2: test5
City: test6
State: test7
Country: test8
Zipcode: test9

Now I have used file() function to put this text file into an array.
$file_name='sample.txt';
$file_array=file($file_name);

Then I traversed through loop to extract each value and search for word say 'Name' from this array.
    $data1='Name';

    foreach($file_array as $value){
    if(stripos($value,$data1)===FALSE)
        echo "Not Found";
     else
       echo "Found";
    }

But it always prints 'Not Found'. I have tried using strpos,strstr, preg_match but to no avail. Also if I use a normal array of words instead of creating from file, it works properly.
Thanks in Advance.
Update: My objective in this problem is to first detect what field it is ex. 'Name' and then its value ex. 'test'

A: It certainly could be a line ending problem or an issue with your file encoding, I'm not sure exactly how file() handles whitespace either.
As a suggestion on how to improve the code, if you create yourself a keyed array from the data then you can use the more reliable array_key_exists() function to search for your fields.
$file_name = 'sample.txt';
$file_data = file($file_name);

// loop through each line
foreach ($file_data as $line) {

// from each line, create a two item array
$line_items = explode(":", $line);

// build an associative (keyed) array
// stripping whitespace and using lowercase for keys
$file_array[trim(strtolower($line_items[0]))] = trim($line_items[1]);
}

Now you can use array_key_exists as follows:
if (array_key_exists("name", $file_array) === false) {
  print "Not found.";
} else {
  print "Found.";
  // and now it's simple to get that value
  print "<br />Value of name:  " . $file_array['name'];
}

A: most likely you still have newline characters at the end of each "line" in your array. Try loading it like this:
$file_array=file($file_name, FILE_IGNORE_NEW_LINES);


text:
Q: Data sharing using App Groups works on simulator but not on device I developed a single page app and a keyboard extension, and I want to send data from my keyboard extensions to my app. I have created an App Group and added it to both targets; the entitlement files are located under each target folder.
In the simulator, it works fine; but when I run it on my device, I cannot access data saved by the extension. Interestingly, I can access data on the extension, saved by the app.
When running my app and extension on the simulator, I get no warnings/errors, but when running on the device I get the following warning when writing data to the shared container:
2020-11-05 12:19:14.542150-0600 TestKeyboard[2887:46080] [User Defaults] Couldn't write values for keys (
    "test_key2"
) in CFPrefsPlistSource<0x282052000> (Domain: DOMAIN_NAME, User: kCFPreferencesCurrentUser, ByHost: No, Container: (null), Contents Need Refresh: No): setting preferences outside an application's container requires user-preference-write or file-write-data sandbox access

In other forums, I saw that sometimes these messages appear but the values are still stored in the shared container, but that's not my case.
Not sure if this information helps, but I do not have an apple developer paid subscription.
I am running this code on an iPhone 8 Plus, iOS 13.6. XCode version 12.1.
Thank you.

A: As pointed out by @EmilioPelaez, the keyboard extension needs full access so that App Groups can work. It worked in the simulator, because keyboard extensions in the simulators are always granted full access.
To grant full access to a keyboard extension, set RequestsFullAccess to True, in the NSExtension -> NSExtensionAttributes extension's plist.


text:
Q: Xcode debugging C++ view global variables No trouble viewing self/local variables, but can't view global variables in the debugging window while running C++ programs.
For example:
int global = 0;
void func(int arg1, int arg2) {
    page_table_base_register = nullptr; // defined globally elsewhere
    int local = arg1;
}

xcode example:

I'd like to see the status of page_table_base_register, which is defined globally elsewhere, as well as the status of global even though it is not used in the func. I can only inspect the arguments of the function and local variable in the Xcode debugging stack window. The Linked picture shows the Xcode debugging stack window that I'm referring to.
Is there any way to do this?

A: Xcode doesn't have a dedicated UI for global variables.  But you can get a live display of the results of any expression in the Xcode Locals view by bringing up the context menu in the Locals area and choosing "Add expression".  For the expression, use the name of the global variable you want to see.


text:
Q: knockout - Using containerless control flow syntax on select option I want to show/hide an option element inside a select element.
I tried using the containerless control flow syntax:
<select>
    <!-- ko if: 'a'=='b'-->
        <option>option1</option>
    <!-- /ko -->
</select>

The option element still renders on the DOM with an empty value (Causing the combo box to have blank line).
I've also tried using the regular "if" binding :
<select>
        <option data-bind:"if('a'=='b')">option1</option>
</select>

But it dose not have any effect.
Can I use containerless control flow syntax or "if" binding ?
Is there another way to achieve that ?


text:
Q: Runtime reconfigurable FPGA clock routing I have a design with multiple inputs and outputs that should have different bit rates, configurable at runtime. Since there are more I/Os than PLLs, I need to share some PLLs, e.g.:

*

*port 1: 1 Mbps

*port 2: 1 Mbps

*port 3: 15 Mbps

Ideally, I'd like to route an 1 MHz clock to the output stage of ports 1 and 2, and a 15 MHz clock to the output stage of port 3. If port 2 gets reconfigured to use 15 MHz as well, the clock routing should be changed so port 2 switches to the other clock network. If instead port 3 is reconfigured to 20 MHz, the PLL driving that clock network should be reconfigured at runtime.
Is that possible with normal FPGA architectures to make clock routing elements visible to VHDL, or should I just go with generating a clock that has a high chance of being a multiple of any baud rates I want to support, and dividing it locally on each port with enables?

A: Dividing clocks locally is probably going to be the most straightfoward solution.  A major advantage is that the whole design will sit in one clock domain, so you don't have to worry about clock domain crossing.
Another option to consider for generating clock enables: instead of using a simple frequency divider, use a DDS-style accumulator.  This provides much finer frequency resolution, at the expense of a clock cycle of jitter.  But the jitter should not be a major issue if the system clock frequency is high enough.  This provides much finer control vs. a simple divider at lower division factors.  IMHO, this is probably the most straightforward and most flexible solution.
However, there are some other options to consider if you really want to use separate clocks.  At least on Xilinx devices, you have BUFGMUX primitives that can be used to select between two input clocks.  So what you could do is have, say, one "standard" clock that is provided to all channels, and one or more reconfigurable clocks that can be provided to small groups of channels.  Most likely you would want to use a separate PLL to generate these other clocks so you can also change the VCO frequency if needed.  In this way, you will have some additional flexibility, although unfortunately not complete flexibility as you only have 2 clock routing options for each channel.  There are also a limited number of BUFGMUX sites available.


text:
Q: C - How to assign a value inside my macro? I am trying to assign a value inside my x-macro, but I don't really understand why it is not working:
#include <stdio.h>

typedef struct
{
    int a;
    int b;
} struct_t;

#define MY_LIST \
    MY_ELEMENT(a) \
    MY_ELEMENT(b)

#define MY_ELEMENT(x) struct_t x; \
x.a=33;
MY_LIST
#undef MY_ELEMENT

int main(void)
{
    fprintf(stdout, "a: %d\n", a.a);
    return 0;
}

When compiling this I get the following error:
test.c:14:2: error: expected '=', ',', ';', 'asm' or   '__attribute__' before '.' token
 x.a=33;

Could somebody explain why I am getting this error and how to solve this?

A: You need to look into the preprocessed form of your code in your source file slethoprod.c. With GCC, you can get it with gcc -C -E slethoprod.c > slethoprod.i then inspect (with an editor or a pager) that slethoprod.i file.
It contains stuff like:
struct_t a; a.a = 33; struct_t b; b.a = 33;

which is obviously not valid C code (since it has some assignment outside of any function, at file scope; remember that an initialization in a declaration is not an assignment).
You might want to have some definition (with initialization) such as
struct_t a = {33};

or even (for readability purposes) a struct initialization like
struct_t b = {.a=33};

and you could play fancy preprocessor tricks to get that.
Look into some C reference site and/or study the C11 standard n1570 to learn more about C. Read also the documentation of your compiler (e.g. GCC) and of your preprocessor (e.g. cpp).
BTW, I personally feel that naming a global with the same name a as some field in it is poor taste (even if it is legal, since field names and global variables have different namespaces). For readability purposes, I recommend avoiding that.

A: Assigning values to structure fields outside of function scope isn't appropriate, so your original code doesn't work
#define MY_ELEMENT(x) struct_t x; \
x.a=33;
MY_LIST //<-- Inaproppriate
#undef MY_ELEMENT

If you want to use current macro, you should write like this:
#include <stdio.h>

typedef struct
{
    int a;
    int b;
} struct_t;

#define MY_LIST \
    MY_ELEMENT(a) \
    MY_ELEMENT(b)

#define MY_ELEMENT(x) struct_t x; \
x.a=33;

int main(void)
{
  MY_LIST;
  fprintf(stdout, "a: %d\n", a.a);
  return 0;
}

Or you can change your macro this way: #define MY_ELEMENT(x) struct_t x = {33, 0};
or even better this: #define MY_ELEMENT(x) struct_t x = {.a = 33};
and leave the rest of your code as is.
So that way you will initialize your variable right in macro.

A: The error you are referring mainly happens when there is a ; missing somewhere in code.
In this case if you add \ after x.a=33; and then call MY_LIST it goes away.
But then you should call MY_LIST in function for a to be defined in main
here is a working version of your code
#include <stdio.h>

typedef struct
{
    int a;
    int b;
} struct_t;

#define MY_LIST \
    MY_ELEMENT(a) \
    MY_ELEMENT(b)

#define MY_ELEMENT(x) struct_t x; \
x.a=33;

int main(void)
{
    MY_LIST;
    fprintf(stdout, "a: %d\n", a.a);
    return 0;
}


text:
Q: Swift 3: How can I shorten an optional check coupled with a condition check of that optional? Consider this example. The else if condition checks on the string object looks big and chunky.
class A { var bObject =  B() }

class B { var cObject = C() }

class C {
    var flag = FALSE
    var stringObj: String? = "Hello"
}

var aObject = A()

if aObject.bObject.cObject.flag == TRUE {

    //do something
    }
else if aObject.bObject.cObject.stringObject != nil && aObject.bObject.cObject.stringObj!.characters.count > 0 && aObject.bObject.cObject.stringObj! == "Hello" {

    //do something
}
else {

}

I'd like to use something like the one below, where the optionally bound variable is used in the same conditional check. But the code wouldn't compile for obvious reasons
else if let unwrappedOptional = aObject.bObject.cObject.stringObj && unwrappedOptional.characters.count > 0 && unwrappedOptional == "Hello" {

    //do something
}

Is there a more elegant way to handle this?

A: You can use condition with if let this way.
else if let unwrappedOptional = aObject.bObject.cObject.stringObj, unwrappedOptional == "Hello" {

    //do something
}

Note: No need to compare characters.count to 0 because "do something" will only execute if unwrappedOptional is equal to Hello.

A: You can make your code like this:
class A { var bObject =  B() }
class B { var cObject = C() }
class C {
    var flag = true
    var stringObj: String? = "Hello"
}

var aObject = A()

if aObject.bObject.cObject.flag == true {

} else if let unwrappedObj = aObject.bObject.cObject.stringObj, !unwrappedObj.isEmpty, unwrappedObj == "Hello" {
    //do something
} else {

}

As @NiravD said, there is no need for the !unwrappedObj.isEmpty but i'm just putting it here because your .count > 0 line is also sorta ugly.


text:
Q: What is the best way to represent scoring variables? The data I got is like this:
Number  Age  Headache painful fatigue
1       43       5       2       3
1       45       3       3       3
1       46       6       5       2
2       66       1       0       3
2       67       1       4       5
2       68       4       6       6
2       69       5       7       8

The same number refers to the same person. Scores in headache, painful and fatigue are from 0 to 10. Whtat's the best way to visualise/present the variation of the scores in each symptoms for all the patients in general? (better with the age parameter) Hope to generate the conclusion something like from the average age x to x_1, the scores of painful are increasing.

A: I wouldn't try to combine different Y scales (It makes the graph confusing.), so I would put the different response variables in their own plots.
Grouping observations that belong to the same person makes sense.
You could do something along these lines:
library(tidyverse)
library(cowplot)

df = data.frame(
  cbind(Number = c(1,1,1,2,2,2,2),
    Age = c(43,45,46,66,67,68,69),
    Headache = c(5,3,6,1,1,4,5),
    painful = c(2,3,5,0,4,6,7),
    fatigue = c(3,3,2,3,5,6,8))
  ) %>%
  mutate(Number = factor(Number))

p1 <- df %>%
  ggplot(aes(x = Age, y = Headache)) +
  geom_line() +
  geom_point() +
  facet_grid(cols = vars(Number), scales = "free_x") +
  theme_bw()

p2 <- df %>%
  ggplot(aes(x = Age, y = painful)) +
  geom_line() +
  geom_point() +
  facet_grid(cols = vars(Number), scales = "free_x") +
  theme_bw()

p3 <- df %>%
  ggplot(aes(x = Age, y = fatigue)) +
  geom_line() +
  geom_point() +
  facet_grid(cols = vars(Number), scales = "free_x") +
  theme_bw()

plot_grid(p1, p2, p3, ncol = 1)

Alternatively, if there are more Number cases, you could do this:
p1 <- df %>%
  ggplot(aes(x = Age, y = Headache, group = Number, color = Number)) +
  geom_line() +
  geom_point() +
  scale_x_continuous(breaks = seq(40, 70, by = 5)) +
  theme_bw()

p2 <- df %>%
  ggplot(aes(x = Age, y = painful, group = Number, color = Number)) +
  geom_line() +
  geom_point() +
  scale_x_continuous(breaks = seq(40, 70, by = 5)) +
  theme_bw()

p3 <- df %>%
  ggplot(aes(x = Age, y = fatigue, group = Number, color = Number)) +
  geom_line() +
  geom_point() +
  scale_x_continuous(breaks = seq(40, 70, by = 5)) +
  theme_bw()

plot_grid(p1, p2, p3, ncol = 1)

When you have a lot more patients, you could use box plots or density curves.


text:
Q: Java substring check I have a String2.  I want to check whether String2 exists in String1.  String1's length can be less or greater or equal than String2.  Also String2 can be null or empty sometimes.  How can I check this in my Java code?

A: You should try using String#contains.

A: For older versions, you could use indexOf. If string2 is not in string1, indexOf will give you -1. You need to ensure beforehand that both Strings are not null though to avoid a NullPointerException.

A: The obvious answer is String1.contains(String2);
It will throw a NullPointerException if String1 is null. I would check that String1 is not null before trying the comparison; the other situations should handle as you would expect.

A: Here is a simple test class:
public class Test002 {

    public static void main(String[] args) {

        String string1 = "Java is Great!";
        String string2 = "eat";

        if (string1 != null && string2 != null & string2.length() <= string1.length() & string1.contains(string2)) {
            System.out.println("string1 contains string2");
        }

    }
}


text:
Q: How to reset Principal attributeMap in Apereo CAS 6.1.x? I am a beginner of CAS. I want to reset Principal attributeMap after loging successfully, and no solution in similar questions. Can anyone help me? Thanks for your advice!
CAS Version:6.1.6

A:
I want to reset Principal attributeMap after logging successfully, and no solution in similar questions.

The reason you can't "find solution in similar questions" is because,

*

*It cannot be done without a great deal of coding.

*It's a bad idea. You cannot change the verified subject identify after it has been verified. Once the credentials are verified and the attributes are collected, that collection is final.

Rather than asking what is possible, it would be best if you described why you want to do this, and then folks can help you with alternatives once your use case and objectives are clearer.


text:
Q: Display two large buttons stretched over the entire screen I'd like to display just two buttons in my application which should get streched over the entire screen. It should not matter if I use an iphone or ipad. Beside that, the app gets only presented in landscape mode.
I am using the newest version of xcode and storyboards. I found some settings which did sound promising and searched on the internet, but it had no effect on the buttons.

A: In storyboard, go to the view controller you'd like to add the buttons to.  Search for uibuttons in the objects on the bottom right and drag and drop them on the view.
Now you need to add the constraints.  Say you want the buttons side by side and spanning across the screen with equal widths.  Hold control down, click the left uibutton, and drag left to the view. Click horizon spacing to left margin.  A blue line will appear. If you click it and view the inspector, you can make sure the horizontal spacing is 0. Do the same for the right uibutton but with the right margin. Next, control drag from the left button to the right button and select equal widths.  And lastly you can control drag to from the left button to itself and select height to fix the height.do the same for the right button.  You will need to also provide a y position for the buttons by control dragging up to view and select vertical spacing from the top margin.
Now whatever size screen, you'll have two buttons, side by side, equal widths, spanning the whole screen width. You can modify the constraints as you need.
Note that if you click the buttons and go to the inspector on the right, you can customize the buttons.
EDIT
To make the buttons one above the other, I would place both buttons on the screen, but I would start with the constraints of the top button.  When you make the constraints, always keep in mind that the frame (x and y position, and width and height) need to be completely determined by the constraints.  So start with the position.  Control drag from the button up to the main view.  You can select center vertically or vertical spacing from top margin for example to set he y position. Control drag from the button left tot the view and create a constraint to set the x position, like leading space (fixes to horizontal distance between the left margin and the button)
Now the size... For the width you can do a few things. You can control drag from the button to itself and select width. This will fix the width to always be whatever it is in storyboard.  A better way is to control drag right to the main view and select trailing space (fixes the spacing from the button to the right margin). Since you have fixed the x position by fixing the leading space and now fixed the trailing space, there is only one possibility for the width to meet both constraints. Thus it's not necessary to create another constraint for the width.  You can fix the height though.
For the second button, to set the y position, you can control drag from the button to the button above and select vertical spacing to fix the distance between the buttons.  For the x position you can control drag again from the button to the button above and align the left edges of the button.  And for the size, you can control drag again from the button to the button above and make them equal heights and widths. So the second buttons frame is completely determined by the one above.
You can also set the frame of the second button based on the main view similar to the first button, so it really depends on your style.  There are multiple ways of setting the constraints so it really depends on your  preference.


text:
Q: How to use a UICollectionViewController's custom initializer with UICollectionViewCompositionalLayout? Let's say you wanted to use a custom initializer to instantiate UICollectionViewController.
With UICollectionViewFlowLayout, it's straightforward:
init() {
    let layout = UICollectionViewFlowLayout()
    super.init(collectionViewLayout: layout)
}

But, UICollectionViewCompositionalLayout's designated initializers require a few parameters, most importantly the section parameter:
UICollectionViewCompositionalLayout(section:, configuration:)
// or
UICollectionViewCompositionalLayout(sectionProvider:, configuration:)

This means I have to create the entire layout within the custom initializer of UICollectionViewController. If the layout incorporates things like enum as a section identifier, that has to be in the initializer as well.  If you have to include NSCollectionLayoutEnvironment in your layout, it also becomes problematic.
init() {
    let item = /..
    let group = /..
    let section = /..
    let layout = UICollectionViewCompositionalLayout(section: section)
    super.init(collectionViewLayout: layout)
}

I'm looking at the Apple's examples and all of them use UIViewController instead of UICollectionViewController by default. Even though the examples don't use any custom initializers, this method does get around the aforementioned problem by allowing us to create the layout afterwards:
var collectionView: UICollectionView! = nil
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: createLayout())

You can now simply use the UIViewController's custom initializer.
What is the best way to use UICollectionViewCompositionalLayout with a custom initializer?

A: You may be over-thinking this. There is absolutely no law preventing you from changing the layout assigned to a collection view; its collectionViewLayout property is assignable at any time.
So just assign a "dummy" layout to the collection view controller in the initializer, and then do the real creation and assignment of the layout in viewDidLoad just as you normally would.
Just to give a common use case: how would you create a collection view controller in the storyboard if you wanted to use a compositional layout? What I do is give the collection view in the storyboard a flow layout. Then in viewDidLoad I create the real layout (the compositional layout) in code and assign it to self.collectionView.collectionViewLayout, and no harm done.


text:
Q: Hugepage/Superpage support for ARMv5 I was looking through some recent additions to the linux kernel which added code to support 1MB Pages for ARMv6 and ARMv7, Freebsd also has support built-in since 2013 but it is also limited to ARMv6 and ARMv7. Linux also supports the usage of huge-pages to map kernel-memory on ARMv5, but not for userspace.
As I'm thinking about adding support for userspace Hugepages on ARMv5 I would like to know if there are any architectural hurdles which make it impossible to implement.
Is there a reason hugepages are not supported for userspace applications on ARMv5? Or is it just a matter of "Somebody has to implement that"? On Linux i could see that they use the former access-permission/domain bits to save some extra information, AFAICT that would not be possible on ARMv5. But is that the only reason or is there something else I might have missed?


text:
Q: Suggestion for a data structure for ranking users based on scores I'm looking to use create and maintain the ranks in memory.
Scores associated with user ids and ranks are computed based on the scores.  The following functionality should be supported.

*

*Sort ranks based on scores ascending or descending. Insertion or deletion in O (log n) time.

*Given a user id, lookup user's rank/score along with n preceding and succeeding ranks in O(log n) time. E.g. get ranks of user 8347 with 5 preceding and succeeding ranks.

*Retrieve n number of ranks from any offset x. E.g. get 100 ranks starting from 800

Given these requirements, are there any suggestions on which data structure suits these requirements the best?

A: I think you can do this very efficiently using a combination of an order statistic tree and a hash table.
An order statistic tree is an augmented binary search tree that in addition to storing elements in sorted order, allows for lookup of elements by their index in the tree.  That is, the structure supports O(lg n) insertion, deletion, and lookup of values by their key, as well as O(lg n) lookup of an element given its index.  If you store the scores in this structure, you can easily insert or update new scores, as well as keeping track of the rank of each element in the tree.
In order to associate users with their scores, you could combine this structute with an auxiliary hash table mapping from user IDs to the nodes in the order statistic tree holding the score for that user.  This would give you O(1) access to a player's score in addition to the O(lg n) lookup of a score's rank.
Hope this helps!

A: Use an in-memory SQLite database.

A: How about a priority-queue?
Each person will have a score, toss it into the priority-queue, and it'll do the work of sorting in ascending/descending priority/value/rank/etc.

A: binary search tree, one implementation - http://en.wikipedia.org/wiki/AA_tree
Space   O(n)            O(n)
Search  O(log n)    O(log n)
Insert  O(log n)    O(log n)
Delete  O(log n)    O(log n)


text:
Q: How to ensure nvidia_current module loads during boot I am running Ubuntu 12.10 on an Asus G75V laptop with nvidia gforce GTX 660M. I first run 12.04 on this machine and was able to install nvidia_current drivers from swat ppa:
sudo apt-add-repository ppa:ubuntu-x-swat/x-updates
sudo apt-get update
sudo apt-get install nvidia-current

This worked in 12.04 and after rebooting the machine my graphics where working properly. After upgrade to 12.10 however, the machine boots into a low resolution desktop which I can not really interact with. I suspect this is due to the driver not being loaded properly. To fix this, I have to switch to ctrl+alt+F1 session and manually load the nvidia_current module and restart the desktop manager:
sudo modprobe nvidia_current
sudo service lightdm restart

Now everything works fine again. However, I would like not to have to do this every time I reboot the machine. I also dont want to hack an script to do this on load. Basically, if things are setup currectly, the nvidia_current driver which is installed should load. How can I make sure nvidia_current driver module loads properly when system starts?
Edit: I tried removing the ppa and installing nvidia-current-update as was suggested in the comments. However, I still face the same problem. The only difference is that now when I restart I come back to desktop with this distorted image:

It appears that nvidia module is not being loaded properly when system boots, even though working drivers are installed.
Again, to work around this issue I can switch to ctrl+alt+F1 session and login. Then I can run this code to get the driver loaded and the desktop back:
sudo modprobe nvidia_current_updates
sudo service lightdm restart

I thought it may be that nvidia_current_updates is somehow being blacklisted somewhere or that nouveau driver is not being blacklisted. So I went into /etc/modprobe.d directory and take a look around. I could not find any evidence of that. Here is the content of nvidia-graphic-drivers.conf which seems relevant:
:/etc/modprobe.d$ cat nvidia-graphics-drivers.conf
# This file was installed by nvidia-current-updates
# Do not edit this file manually

blacklist nouveau
blacklist lbm-nouveau
blacklist nvidia-173
blacklist nvidia-96
blacklist nvidia-current
blacklist nvidia-173-updates
blacklist nvidia-96-updates
alias nvidia nvidia_current_updates
alias nouveau off
alias lbm-nouveau off

A: Since the ppa:ubuntu-x-swat/x-updates PPA currently doesn't have any packages for Quantal, I'd suggest removing it.
sudo apt-get install ppa-purge

sudo ppa-purge ppa:ubuntu-x-swat/x-updates

Then install the recommended or experimental Nvidia driver. You can make sure the module loads by adding it to /etc/modules.


text:
Q: actualizar datos chartjs tengo un problema al querer actualizar un grafico de chartjs mediante un select que contiene los meses, al seleccionar otro mes para que actualice el gráfico me lo duplica y en vez de tener una barra me parecen dos y si hago otra selección me aparecen tres barras, lo que yo necesito es que al cambiar el select me actualice los datos del grafico en la barra que ya esta creada, dejo mi codigo a continuación ojalá me puedan ayudar.
Con este codigo traigo los datos y los dejo en un array.
getMaquinarias(){
            let me=this;

            var url=this.ruta + '/dashboardmaquianria2?idmes=' + me.idmes;

            axios.get(url).then(function (response) {
                var respuesta= response.data;
                me.arrayMotoniveladoras = respuesta.motoniveladoras;
                //cargamos los datos del chart
                 me.loadMaquinarias();

            })
            .catch(function (error) {
                console.log(error);
            });
        },

Y con el siguiente código genero el gráfico y quiero actualizarlo.
loadMaquinarias(){
             let me=this;

             me.arrayMotoniveladoras.map(function(x){
                me.varMesMaquinaria.push(x.nombre_centro);
                me.varTotalMaquinaria.push(x.total);
            });
            me.varMaquinaria=document.getElementById('motoniveladoras').getContext('2d');
            me.charMaquinaria = new Chart(me.varMaquinaria, {
                type: 'bar',
                data: {
                    labels: me.varMesMaquinaria,
                    datasets: [{
                        label: 'COSTO',
                        data: me.varTotalMaquinaria,
                        backgroundColor: 'rgba(75, 192, 42, 0.5)',
                        borderColor: 'rgba(75, 192, 42, 0.5)',
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero:true
                            }
                        }]
                    }
                }
            });

        },

A: Debes destruir la grafica para que la vuelva a crear y no se sobreponga
if (window.myPie) {
   window.myPie.clear();
   window.myPie.destroy();
}
window.myPie = new Chart(ctx, config);


text:
Q: What is the use of ad events? I have developed an application and I am looking forward to launching it. I have placed one banner ad from Admob in my layout. I have tested it using a test ad . It is working fine. But, I would like to know how the banner ad will respond to events(like click) once I upload my app using real ads. I have not implemented any Ad Event methods; Do I have to? If yes, then could you please tell me how. On the other hand; should I override methods like onPause(),onResume() etc.. for the AdView? Many thanks in advance.

A: In Ad-Mob doc you will find out that Callbacks are optional if you want to work with ad then you can use them other wise its ok and yeah you have to maintain Activity lifecycle with ad. Hope this will helps you  ! Cheers !


text:
Q: TypeError/Undefined when adding conditional formatting to my bar chart I'm trying to add conditional formatting to my simple bar chart. It's partially working, until I attempt to hover one of the bars, then I get the following error:
TypeError: c[(this.position + "Field")] is undefined
Contents of data.csv:
date,est_sleep,bool_field
2017-11-01,7.5,0
2017-10-31,8,0
2017-10-30,7,1

HTML Code:

Current results:

A: This error appears because of this string:
...
svg.selectAll('rect')
  .data(data) // <== !!!
...

It looks like you rewrite data binding that this library sets under the hood. I did not work with dimple.js, maybe exist the more elegant solution, but I can suggest you this solution:
svg.selectAll('rect')
  .style("fill", function(d,i){
    if(data[i].bool_field == 1) // <== get data item by index
      return "#f00";
    else
      return "#99C1DC";
  })
  .style("stroke", function(d,i){
    if(data[i].bool_field == 1) // <== get data item by index
      return "#931D1D";
    else
      return "#98B5C9";
  });

You can get appropriate data item by index, without .data() method. Look at the hidden code snippet below, it works:

data = d3.csvParse(`date,est_sleep,bool_field
2017-11-01,7.5,0
2017-10-31,8,0
2017-10-30,7,1`);

var svg = window.dimple.newSvg("#chartContainer", 500, 600);

        var myChart = new dimple.chart(svg, data);
        myChart.setBounds(60, 30, 400, 300)
        myChart.addCategoryAxis("x", "date");
        var y = myChart.addMeasureAxis("y", "est_sleep");
        var x = myChart.addSeries(null, dimple.plot.bar);
        x.addOrderRule("date", true);

        myChart.draw();

        svg.selectAll('rect')
        .style("fill", function(d,i){
            if(data[i].bool_field == 1)
                return "#f00";
            else
                return "#99C1DC";
        })
        .style("stroke", function(d,i){
            if(data[i].bool_field == 1)
                return "#931D1D";
            else
                return "#98B5C9";
        });


text:
Q: sinon spy doesn't register call in a generator loop? I want to check that a piece of code is being called, so I'm using a sinon spy to assert this.  However, the spy seems to be failing, despite console.logs showing that the code has been called correctly.
I'm wondering if my function being a generator is causing my spy to misreport what it's doing.
my code (i've taken out some chunks for brevity):
  isBlacklisted(release, jobUUID) {

    names.forEach((name) => {
      this._spawnPythonProcessGenerator(
        this.IS_BLACKLISTED_SCRIPT,
        name
      ).next().value
        .then((data) => {
          console.log(data);
        })
        .catch((err) => {
          this._errorEvent(release, name, err, jobUUID);
        });
    }, this);
  }

  _errorEvent(release, name, err, jobUUID) {
    console.log('got here');
  }

  *_spawnPythonProcessGenerator(scriptSrc, name) {
    const pythonProcess = this._childProcess.spawn(
      'python3',
      [...arguments]
    );
    yield new Promise((resolve, reject) => {
      pythonProcess.stderr.on('data', (err) => {
        reject(err.toString());
      });

      pythonProcess.stdout.on('data', (data) => {
        resolve(data.toString());
      });
    });
  }

and my tests:
const Blacklist = require('../../src/Blacklist2');
const childProcess = require('child_process');
const uuid = require('uuid/v4');

describe('Blacklist', () => {
  let blacklist;
  beforeEach(() => {
    blacklist = new Blacklist(childProcess);
    blacklist.IS_BLACKLISTED_SCRIPT = './test/helpers/good.py';
  });
  describe('isBlacklisted', () => {
    it('should call the _errorEvent for every name in a release when the blacklist application is not available', async () => {
      let release = {
        id: 1001,
        asset_controller: {
          id: 54321,
        },
        display_name: 'Blah',
        names: [
          {
            id: 2001,
            name: 'Blah',
          },
        ],
      };

      blacklist.IS_BLACKLISTED_SCRIPT = './test/helpers/'+ uuid() +'.py';

      const spy = sinon.spy(blacklist, '_errorEvent');
      blacklist.isBlacklisted(release, uuid());

      console.log(spy);
      sinon.assert.calledTwice(spy);
      spy.restore();
    });
  });
});

my spy reports:

notCalled: true

A: I'll expand my comment into an actual answer, hopefully that helps.
Your problem lies with asynchrony, not with the generator. You need isBlacklisted to return a promise you can wait on. Otherwise your assertion happens before the spy is called.
Something like this:
isBlacklisted(release, jobUUID) {
    let promises = names.map((name) => {
      return this._spawnPythonProcessGenerator(
        this.IS_BLACKLISTED_SCRIPT,
        name
      ).next().value
        .then((data) => {
          console.log(data);
        })
        .catch((err) => {
          this._errorEvent(release, name, err, jobUUID);
        });
    }, this);

    return Promise.all(promises);
}

Then, in your test:
return blacklist.isBlacklisted(release, uuid())
    .then(() => {
        sinon.assert.calledTwice(spy);
    });

Also... This isn't related to your problem, but your _spawnPythonProcessGenerator method doesn't need to be a generator. You're only using the first value of it by calling next like that and calling the whole thing over again for each array item.
It will work the same if you take out the *, change yield to return, and  skip the .next().value when you call it. You also probably want to rename it because it's not a generator.
_spawnPythonProcess(scriptSrc, name) {
    const pythonProcess = this._childProcess.spawn(
      'python3',
      [...arguments]
    );
    return new Promise((resolve, reject) => {
      pythonProcess.stderr.on('data', (err) => {
        reject(err.toString());
      });

      pythonProcess.stdout.on('data', (data) => {
        resolve(data.toString());
      });
    });
}

When you call it:
let promises = names.map((name) => {
  return this._spawnPythonProcess(
    this.IS_BLACKLISTED_SCRIPT,
    name
  )
    .then((data) => {
      console.log(data);
    })
    .catch((err) => {
      this._errorEvent(release, name, err, jobUUID);
    });
}, this);

return Promise.all(promises);


text:
Q: FMS server-side code not executing I'm trying to create a RTMP Streaming application but I can't seem to get the server-side code to run. I've checked the logs on RootInstaller/logs/test, but nothing inside it.  I am running everything locally also.
Here's what I have:
ActionScript3 file
public function btnConnectHandler(event:MouseEvent):void
{
nc = new NetConnection();
nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
    nc.connect("rtmp://localhost/test");
}

fms.ini:
TEST_DIR = C:\Program Files\Adobe\Flash Media Server 4.5\applications\test

Main.acs
// Called when a client connects
application.onConnect = function(client) {
    // accept the new client's connection
    application.acceptConnection(client);

    // send a message
    trace(client.id + " is connected");
}

Also inside my applications folder I have the following files:
allowedHTMLdomains.txt
Application.xml
main.acs

A: Add a simple trace function (like trace("onConnect is called")) at the first line of the onConnect method. Does it log?


text:
Q: JavaScript OO Design So I am creating a complex application with JavaScript. I am using an OO design so the majority of my code is in different files for maintainability. How can I import all of the files that I need to create my application?

A: I would recommend a module-loading framework.  RequireJS is a popular option for this, used by the Dojo Toolkit.  Using RequireJS, the AMD (Asynchronous Module Definition) loader will auto-load dependencies for you and you can also define your own modules.
If you're familiar with other programming languages, require is the counterpart to import or #include but in the web, this is asynchronous.  This makes management easier (dependencies are explicit rather than implicit) and you don't need to worry about the order of your javascript files.

A: I would have a look at browserify: http://browserify.org/

A: You can use some class loader framework like RequireJS and yepnope.js, but if you have many different files it can get slow. Importing files one by one is not a great idea because it will slow down your page dramatically due to too many server requests. If you have many files it's better to do some grouping and fetch groups of them together using one request. Although many people feel this is premature optimization it can help to pick a framework that allows you to do this grouping.


text:
Q: Automate Browser Searching I need to search a number of websites for different values. Can anyone think of a way to have chrome:

*

*Open a specific site

*Use the search function on that site to search for "X"

*Take a screenshot/output that result

*Move on to the next site and do the same steps.

*Once completed, start the process again for a new value "X+1"

Thanks!


text:
Q: How to get an empty Illuminate\Database\Eloquent\Relations\Relation element? normaly I will use return $this->belongsToMany(...) to get elements wich are connected to the actuel element in a table.
But at the beginning my students won't have created the second table so the command above will fail.
Do you have any idea how to retun an empty element of Illuminate\Database\Eloquent\Relations\Relation to prevent the view to break?
Thank you in advance!

A: You dont need an Illuminate\Database\Eloquent\Relations\Relation object but an Illuminate\Database\Eloquent\Collection.
You can instantiate it like this:
$empty_collection = new Illuminate\Database\Eloquent\Collection;


text:
Q: Django set_cookie working on localhost but not on ngrok? I am using Django to return a cookie in a response via set_cookie:
response.set_cookie(
  key = settings.SIMPLE_JWT['AUTH_COOKIE'],
  value = data["refresh"],
  expires = settings.SIMPLE_JWT['REFRESH_TOKEN_LIFETIME'],
  path = settings.SIMPLE_JWT['AUTH_COOKIE_PATH'],
  secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'],
  httponly = settings.SIMPLE_JWT['AUTH_COOKIE_HTTP_ONLY'],
  samesite = settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE'],
)

where the values are:
SIMPLE_JWT = {
  'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
  'REFRESH_TOKEN_LIFETIME': timedelta(days=1),

  ...

  'AUTH_COOKIE': 'refresh_token',
  'AUTH_COOKIE_SECURE': False,
  'AUTH_COOKIE_HTTP_ONLY' : True,
  'AUTH_COOKIE_PATH': '/',
  'AUTH_COOKIE_SAMESITE': 'Lax',
}

CORS is all set up correctly. I am also sending withCredentials: true, in my axios requests correctly.
My problem is that when I test in development (i.e. Frontend hosted at http://127.0.0.1:3000/ and Backend hosted on http://127.0.0.1:8000/) the system works (i.e. the cookie gets set). However, when I use ngrok to tunnel my backend to a secure url, nothing works. I still get the set-cookie headers in my response, so I am receiving the cookies - it's just not setting them. Also, I am on Safari (since I know Chrome has an issue with setting cookies due to requiring values for samesite and secure).
This is my response: here
Any help would be greatly appreciated. Thank you!


text:
Q: MySQL Server flashes on and off on mac. How to fix? I just downloaded the macOS 10.15 (x86, 64-bit), DMG Archive version of MySQL following https://youtu.be/TpOMn5_YIyw?t=305.
But the server just flashes green for a second and then back to red when I click start.
It will flash intermittently to green and then back to red. In the terminal, I will type
sudo /usr/local/mysql/support-files/mysql.server start

and it returns
Starting MySQL
. ERROR! The server quit without updating PID file (/usr/local/mysql/data/Eileens-MacBook-Air.local.pid).

The result is the same when I type
sudo /usr/local/mysql/support-files/mysql.server restart

or

sudo /usr/local/mysql/support-files/mysql.server stop

Not sure how to fix this. Not sure if this matters, but

*

*my mac also recently updated to the Catalina OS

*I installed mysql twice bc I'm a noob and thought the first time it didn't work because I thought you were supposed to find it in the launch page and not system preferences.

I have minimal coding background so this is all very new to me. Very much appreciate the help since google and youtube hasn't given much help.

A: I just had the same issue on my Mac running 10.13.6. I fixed it by clicking "Initialize database" in the MySQL pane from System Preferences.


text:
Q: Помогите разобраться, где ошибка Python import math
x=90
Pi=3.14
RAD=90
ta=math.tan(math.radians(X))
Formula=2*Pi*RAD*ta
print(Formula)

A: *

*Как уже другие сказали, у вас переменная x, а не X.

*Модуль math определяет число «пи» более точно, чем вы — используйте math.pi.

*То, чего вы хотите сделать, бессмысленно, так как значение тангенс 90o неопределенно — оно стремится к положительной бесконечности, значит, вы получите какое-то очень большое число, не имеющего никакого значения.

*Но и ваша Formula еще более бессмысленна, т.к вы в ней умножаете радианы на градусы, не говоря о том, что даже умножение градусов на градусы или радианов на радианы не имеет смысла.


text:
Q: Is there a way to generate a router module that will automatically be imported in app-module.ts in angular? I want to use the new router module for my angular 6 project, So I wondering if is there a way to generate angular 7's new router module that will automatically be imported in app-module.ts?

A: No.  In angular 4+ platforms 'ng new' supports adding routing interactively. Implementing Routing in ng7 is same as in ng6. You can manually add a module using ng g module <moduele-name>. Later, import RouterModule from @angular/router.
That being said, I don't see a reason why you want to use Routing from ng7 when your project is on ng6. Both support lazyloading for children. IMO, migrating the entire project to one version makes more sense.
https://www.techiediaries.com/angular-routing-lazy-loading-loadchildren/


text:
Q: Why do JavaScript Sets/Maps use `size` instead of `length`? While looking over new changes to JavaScript I noticed that Set and Map use .size instead of .length like arrays would.
This seems like a pointless diversion from what's normal with arrays - just one more thing to remember.
Was there a good design reason for this?

A: There's a lot of discussion in the esdiscuss thread "Set length property". This was a hotly debated issue, so it's not surprising that you do not necessarily agree with the resolution.
There is a tremendous amount of arguing about this in esdiscuss. Ultimately, the argument that prevailed (as evidenced by the fact that ES2015's Sets have size and not length) was summarized in a post by David Bruant:

...for me 'length' refers to a measurement with something like a ruler. You start at 0 and see up to where it goes. This is very accurate for an array which is an indexed set (starting at 0 and growing) and for arrays as considered in C (continuous sequence of bytes) which ECMAScript arrays seem inspired of. This is probably less relevant for unordered collections such as sets which I'd tend to consider as a messy bag.

And further discussed in a post by Dean Landolt:

Just wanted to jump in and say non-writable length is consistent with String behavior as well, but David makes a good point about length implying metric topology. David's suggestion of count is nice. ISTM what we're talking about is cardinality, but no need to get too silly w/ precision. Though size is just fine with me, and has plenty of prior art.

A: While apsillers' Jan 27, 2016 answer adds great links, a code example is missing. The size of a set is a read-only getter while that's not the case for arrays which allow modifying the length to truncate the array.

let arr = [1, 2, 3, 4]
arr.length = 2
console.log("modified length array", arr) // [1, 2]

let mySet = new Set([1, 2, 3, 4])
mySet.length = 2
mySet.size = 2
console.log("modified length set", [...mySet]) // [1, 2, 3, 4]

let str = "1234"
str.length = 2
console.log("modified length string", str) // "1234"


text:
Q: Is there a dependency or api that allows me to show specific places? I'm trying to create a button that says show nearby hospitals, and for the user to click on this button and see the specific hospitals near him.. how can i do that? Is there a dependency or api that allows me to show specific places?

A: I would recommend Google Places API - On click of your button you can pass location to the API to search for specific types of businesses, return a map, a list, etc.
Check out the docs: https://developers.google.com/maps/documentation/places/web-service/overview


text:
Q: WSO2 Identity Server: Error while loading Identity Provider I'm evaluating WSO2 Identity Server 5.0.0 SP1. I'm receiving an error when I click on the "Resident Identity Provider" link in the admin website. This error message is "Error while loading Identity Provider". I'll include the stack from the log file at the end of this post.
So far, all I have configured is a secondary user store which is connected to an Active Directory server. The users and groups are being displayed in the users/roles screens. I do get another error if I click on the User Profile link.
I have installed new SSL certificates for the Identity Server and updated the XML config files to use the hostname instead of localhost.
Does anyone have any suggestions what may be wrong? What I'm trying to do is test if I can login the the WSO2 dashboard with a user from the active directory - so far everything has failed.
Error from logs:
>     IdentityProviderMgtServiceIdentityApplicationManagementExceptionException
>     TID[-1234] [IS] [2015-03-06 14:06:39,690] ERROR {org.wso2.carbon.idp.mgt.ui.client.IdentityProviderMgtServiceClient} -
> IdentityProviderMgtServiceIdentityApplicationManagementExceptionException
> sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
> sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
> sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown
> Source) java.lang.reflect.Constructor.newInstance(Unknown Source)
> java.lang.Class.newInstance(Unknown Source)
> org.wso2.carbon.idp.mgt.stub.IdentityProviderMgtServiceStub.getResidentIdP(IdentityProviderMgtServiceStub.java:1307)
> org.wso2.carbon.idp.mgt.ui.client.IdentityProviderMgtServiceClient.getResidentIdP(IdentityProviderMgtServiceClient.java:86)
> org.apache.jsp.idpmgt.idp_002dmgt_002dedit_002dload_002dlocal_jsp._jspService(org.apache.jsp.idpmgt.idp_002dmgt_002dedit_002dload_002dlocal_jsp:91)
> org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
> javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
> org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:403)
> org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:492)
> org.apache.jasper.servlet.JspServlet.service(JspServlet.java:378)
> javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
> org.wso2.carbon.ui.JspServlet.service(JspServlet.java:155)
> org.wso2.carbon.ui.TilesJspServlet.service(TilesJspServlet.java:80)
> javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
> org.eclipse.equinox.http.helper.ContextPathServletAdaptor.service(ContextPathServletAdaptor.java:37)
> org.eclipse.equinox.http.servlet.internal.ServletRegistration.service(ServletRegistration.java:61)
> org.eclipse.equinox.http.servlet.internal.ProxyServlet.processAlias(ProxyServlet.java:128)
> org.eclipse.equinox.http.servlet.internal.ProxyServlet.service(ProxyServlet.java:68)
> javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
> org.wso2.carbon.tomcat.ext.servlet.DelegationServlet.service(DelegationServlet.java:68)
> org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
> org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
> org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
> org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:605)
> org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:544)
> org.eclipse.equinox.http.servlet.internal.RequestDispatcherAdaptor.include(RequestDispatcherAdaptor.java:37)
> org.eclipse.equinox.http.helper.ContextPathServletAdaptor$RequestDispatcherAdaptor.include(ContextPathServletAdaptor.java:369)
> org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:1015)
> org.apache.jasper.runtime.PageContextImpl.include(PageContextImpl.java:700)
> sun.reflect.GeneratedMethodAccessor50.invoke(Unknown Source)
> sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
> java.lang.reflect.Method.invoke(Unknown Source)
> org.apache.tiles.jsp.context.JspUtil.doInclude(JspUtil.java:87)
> org.apache.tiles.jsp.context.JspTilesRequestContext.include(JspTilesRequestContext.java:88)
> org.apache.tiles.jsp.context.JspTilesRequestContext.dispatch(JspTilesRequestContext.java:82)
> org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:465)
> org.apache.tiles.jsp.taglib.InsertAttributeTag.render(InsertAttributeTag.java:140)
> org.apache.tiles.jsp.taglib.InsertAttributeTag.render(InsertAttributeTag.java:117)
> org.apache.tiles.jsp.taglib.RenderTagSupport.execute(RenderTagSupport.java:171)
> org.apache.tiles.jsp.taglib.RoleSecurityTagSupport.doEndTag(RoleSecurityTagSupport.java:75)
> org.apache.tiles.jsp.taglib.ContainerTagSupport.doEndTag(ContainerTagSupport.java:80)
> org.apache.jsp.admin.layout.template_jsp._jspx_meth_tiles_insertAttribute_7(org.apache.jsp.admin.layout.template_jsp:603) org.apache.jsp.admin.layout.template_jsp._jspService(org.apache.jsp.admin.layout.template_jsp:335)
> org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
> javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
> org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:403)
> org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:492)
> org.apache.jasper.servlet.JspServlet.service(JspServlet.java:378)
> javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
> org.wso2.carbon.ui.JspServlet.service(JspServlet.java:155)
> org.wso2.carbon.ui.TilesJspServlet.service(TilesJspServlet.java:80)
> javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
> org.eclipse.equinox.http.helper.ContextPathServletAdaptor.service(ContextPathServletAdaptor.java:37)
> org.eclipse.equinox.http.servlet.internal.ServletRegistration.service(ServletRegistration.java:61)
> org.eclipse.equinox.http.servlet.internal.ProxyServlet.processAlias(ProxyServlet.java:128)
> org.eclipse.equinox.http.servlet.internal.ProxyServlet.service(ProxyServlet.java:68)
> javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
> org.wso2.carbon.tomcat.ext.servlet.DelegationServlet.service(DelegationServlet.java:68)
> org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
> org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
> org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
> org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
> org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412)
> org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
> org.eclipse.equinox.http.servlet.internal.RequestDispatcherAdaptor.forward(RequestDispatcherAdaptor.java:30)
> org.eclipse.equinox.http.helper.ContextPathServletAdaptor$RequestDispatcherAdaptor.forward(ContextPathServletAdaptor.java:362)
> org.apache.tiles.servlet.context.ServletTilesRequestContext.forward(ServletTilesRequestContext.java:198)
> org.apache.tiles.servlet.context.ServletTilesRequestContext.dispatch(ServletTilesRequestContext.java:185)
> org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:419)
> org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:370)
> org.wso2.carbon.ui.action.ActionHelper.render(ActionHelper.java:52)
> org.wso2.carbon.ui.TilesJspServlet.service(TilesJspServlet.java:101)
> javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
> org.eclipse.equinox.http.helper.ContextPathServletAdaptor.service(ContextPathServletAdaptor.java:37)
> org.eclipse.equinox.http.servlet.internal.ServletRegistration.service(ServletRegistration.java:61)
> org.eclipse.equinox.http.servlet.internal.ProxyServlet.processAlias(ProxyServlet.java:128)
> org.eclipse.equinox.http.servlet.internal.ProxyServlet.service(ProxyServlet.java:68)
> javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
> org.wso2.carbon.tomcat.ext.servlet.DelegationServlet.service(DelegationServlet.java:68)
> org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
> org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
> org.wso2.carbon.tomcat.ext.filter.CharacterSetFilter.doFilter(CharacterSetFilter.java:61)
> org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
> org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
> org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
> org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
> org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
> org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
> org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
> org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:178)
> org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
> org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:56)
> org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
> org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:141)
> org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:156)
> org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
> org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:52)
> org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
> org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
> org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
> org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
> org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653)
> java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
> java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
> java.lang.Thread.run(Unknown Source)

A: In case others hit this - it seems the problem is if you use a certificate alias other than 'wso2carbon' in the JKS keystore when you change the SSL certificate.


text:
Q: Jhipster React Form Grid Layout Issue I'm currently using the latest version of Jhipster 7.6.0 and Node 16.14.0. If we try to arrange form fields in column view in other words if we wrap ValidatedField to  and , the field values are not populated during Edit mode of the page and the same is true for insert mode. The attached link is showing a simple layout change on the existing user management page, and we are trying to see Last Name and First Name in one row, and we are unable to see the value or update the value if we realign these fields in multiple columns views.
Does anyone know a simple workaround we can use ValidatedForm and ValidatedField in Row, Col, and regular CRUD works like with other pages generated by the framework? Please let me know if more clarification or detail is needed on this case.
Layout and code Sample from User Management page


text:
Q: How to use Shap with a LSTM neural network? I am working with keras to generate LSTM neural net model. I want to find Shapley values for each of the model's features using the shap package. The problem, of course, is that the model's LSTM layer requires a three dimensional input (samples, time steps, features), but the shap package requires a two dimensional input. Is there anyway around this problem?
Below I've included some code that reproduces the issue.

import numpy as np
from random import uniform

N=100

#Initlaize input/output vectors
x1=[]
x2=[]
x3=[]
y1=[]
y2=[]

#Generate some data
for i in range(N):
    x1.append(i/100+uniform(-.1,.1))
    x2.append(i/100+uniform(-3,5)+2)
    x3.append(uniform(0,1)/np.sqrt(i+1))

    y1.append(2*x1[i]-.5*x2[i]+x3[i]+uniform(-1,1))
    y2.append(x1[i]+3*x3[i]+5+uniform(-1,3))

#Convert lists to numpy arrays
x1=np.array(x1).reshape(N,1)
x2=np.array(x2).reshape(N,1)
x3=np.array(x3).reshape(N,1)

y1=np.array(y1).reshape(N,1)

#Assemble into matrices
X = np.hstack((x1, x2, x3))
Y = y1

# reshape input to be [samples, time steps, features]
X = np.reshape(X, (X.shape[0], 1, X.shape[1]))

#Import keras functions
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import LSTM

#Lets build us a neural net!
model=Sequential()
model.add(LSTM(4, input_shape=(1,3)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam',run_eagerly=())
model.fit(X, Y, epochs=100, batch_size=10, verbose=2)

import shap
import tensorflow as tf
tf.compat.v1.disable_eager_execution()

DE=shap.KernelExplainer(model.predict,shap.sample(X,10))
shap_values = DE.shap_values(X) # X is 3d numpy.ndarray

I have tried reshaping X into a two dimensional array in the shap_values function, but that does not work. Similarly, trying to feed a two dimensional array into the LSTM layer causes an error as well.


text:
Q: Is there a command to copy an entire folder (along with contents) to another location in batch xcopy C:\Users\xp\AA C:\Users\xp\BB /s

This copies the content of the directory AA to directory BB but I want to copy the entire folder AA to be copied to BB.
Example: Source has a folder AA which contains files a.txt, b.txt.
The command above copies a.txt,b.txt to the BB folder but I want the folder AA to be copied into BB so that it becomes:
C:\Users\xp\BB\AA\a.txt

A: I tried a lot of suggestions using COPY, XCOPY, ROBOCOPY and what not but all failed to create the source folder.
Using a small batch file (with absolutely no error checking) does the job for me:
for %%D in (%1) do set d=%%~nD
md %2\%d%
copy %1\* %2\%d%

Calling this batch file like this mycpy.cmd C:\Temp\AA C:\Temp\BB copies the folder AA including it's content to C:\Temp\BB.
Or in one line:
for %%D in (%1) do md %2\%%~nD && copy %1\* %2\%%~nD

A: it's general usage is:
ROBOCOPY source destination [file [file]...] [options]
typical usage: robocopy source destination /E /Z
/E - will make proper dir tree (includes empty dirs)
/Z - restartable mode, specially useful if copy over network
ROBOCOPY C:\Users\xp\ C:\Users\xp\BB\ /E /Z [/XD dirs [dirs]... :: eXclude Directories matching given names/paths.]


text:
Q: How to disable animations with Protractor in an AngularJS app? As suggested on the Protractor page I tried adding the following in my config file:
onPrepare: function() {

    var disableNgAnimate = function() {
        angular.module('disableNgAnimate', []).run(['$animate', function($animate) {
            $animate.enabled(false);
        }]);
    };

    browser.addMockModule('disableNgAnimate', disableNgAnimate);

    browser.getCapabilities().then(function(caps) {
        browser.params.browser = caps.get('browserName');
    });
}

And it did not turn off the animations.
I am dealing with a website that is heavily animated and this screws my tests a lot..
P.S. I am using the TypeScript definition for Protractor, does this matter?

A: You disabled just ng-animations.
For me is much better to make animation duration 1ms instead of turning it off.
(becuse of some animation event handlers in code)
Try code below it will accelerate CSS animation, so it can solve your problem
onPrepare: function () {
    // disable animations when testing
    var disableAnimation = function () {
        angular.module('disableAnimation', []).run(function ($animate) {

            // disable css animations
            var style = document.createElement('style');
            style.type = 'text/css';
            style.innerHTML = '* {' +
                '-webkit-transition-duration: 1ms !important;' +
                '-moz-transition-duration: 1ms !important;' +
                '-o-transition-duration: 1ms !important;' +
                '-ms-transition-duration: 1ms !important;' +
                'transition-duration: 1ms !important;' +
                '-webkit-animation-duration: 1ms !important;' +
                '-moz-animation-duration: 1ms !important;' +
                '-o-animation-duration: 1ms !important;' +
                '-ms-animation-duration: 1ms !important;' +
                'animation-duration: 1ms !important;' +
                '}';
            document.getElementsByTagName('head')[0].appendChild(style);

            // disable angular ng animations
            $animate.enabled(false);
        });
    };

    browser.addMockModule('disableAnimation', disableAnimation);
}


text:
Q: Making orthogonal arrows in Forest This appears as a basic question but I guess its important for those beginning to learn forest using the working example in this question (which typically looks like the Figure 2 here). I would like the first arrows of the parent look as shown in Figure 1.  I have been trying this for a while and haven't figured it out. I also think it would also be beneficial to others if I ask here. I have used the code in the link provided as a benchmark.

Edit: I edited the first MWE and modified the one in the linked question for clarity. The problem is that following the style in Figure 2, when the children "Straighten the Arrows" in this diagram increases to say ten columns. The arrow from the parent begins to cross some of them.
\documentclass{article}
\usepackage{forest}
\usetikzlibrary{shadows,arrows.meta}

\tikzset{parent/.style={align=center,text width=2cm,fill=green!20,rounded corners=2pt},
child/.style={align=center,text width=2.8cm,fill=green!50,rounded corners=6pt},
grandchild/.style={fill=pink!50,text width=2.3cm}
}
\begin{document}
\begin{forest}
for tree={%
thick,
drop shadow,
l sep=0.6cm,
s sep=0.8cm,
node options={draw,font=\sffamily},
edge={semithick,-Latex},
where level=0{parent}{},
where level=1{
    minimum height=1cm,
    child,
    parent anchor=south west,
    tier=p,
    l sep=0.25cm,
    for descendants={%
        grandchild,
        minimum height=0.6cm,
        anchor=150,
        edge path={
            \noexpand\path[\forestoption{edge}]
            (!to tier=p.parent anchor) |-(.child anchor)\forestoption{edge label};
        },
    }
}{},
}
[Forest
[Straighten
    [
        [
            [ ]
        ]
    ]
]
[The
    [
        [
            [
                [ ]
            ]
        ]
    ]
]
[Arrows
    [
        [
            [
                [
                    []
                ]
            ]
        ]
    ]
]
]
\end{forest}
\end{document}

A: There are quite a lot of examples of this structure already. The following is adapted from https://tex.stackexchange.com/a/299500/, where explanatory notes can be found.

\documentclass[border=10pt]{standalone}
\usepackage[edges]{forest}
\usepackage[T1]{fontenc}
\tikzset{%
  parent/.style={align=center,text width=3cm,rounded corners=3pt},
  child/.style={align=center,text width=3cm,rounded corners=3pt}
}
\begin{document}
\begin{forest}
  for tree={
    % edge+={->},% uncomment for arrows
    draw,
    rounded corners,
    node options={align=center,},
    text width=2.7cm,
  },
  where level=0{%
    parent anchor=children,
  }{%
    folder,
    grow'=0,
    if level=1{% this changes the edges from level 0 to nodes at level 1
      before typesetting nodes={child anchor=north},
      edge path'={(!u.parent anchor) -- ++(0,-5pt) -| (.child anchor)},
    }{},
  }
  [LMS, fill=gray!25, parent
  [Funktionale \\Anforderungen, for tree={fill=brown!25, child}
  [Lerninhalte organisieren]
  [Lerninhalte erstellen]
  [Lerninhalte abfragen]
  [Kommunikation]
  [Benutzerkonten\-führung]
  [Steuerungs\-funktionen]
  ]
  [Nicht-Funktionale Anforderungen, for tree={fill=red!25,child}, calign with current edge
  [Zuverl{\"a}ssig\-keit]
  [Skalierbar\-keit und Effizienz]
  [Benutzer\-freundlich\-keit]
  [Portierbarkeit]
  [Datenschutz / Informationssicherheit]
  [Erweiterbar\-keit]
  [Anpassbarkeit]
  ]
  [Technische Rahmen\-bedinungen, for tree={fill=blue!25, child}
  [System\-architektur]
  [Software\-kriterien]
  [Schnittstellen]
  [Wartung und Support
  [Support\-leistungen]
  [Software-Pflege]
  ]
  ]
  ]
  ]
\end{forest}
\end{document}

EDIT
To address the edited question, one way to get the desired effect is to set parent anchor=center for the root node and make the parts of the edges which overwrite the node invisible. You could put them on a background layer using the background library. Or you could just use `blend mode=lighten. For example,
\documentclass[border=10pt]{standalone}
\usepackage[edges]{forest}
\usepackage[T1]{fontenc}
\tikzset{%
  parent/.style={align=center,text width=3cm,rounded corners=3pt},
  child/.style={align=center,text width=3cm,rounded corners=3pt}
}
\begin{document}
\begin{forest}
  for tree={
    % forked edges,
    draw,
    rounded corners,
    node options={align=center,},
    text width=2.7cm,
  },
  where level=0{%
    parent anchor=center,
  }{%
    folder,
    grow'=0,
    if level=1{%
      before typesetting nodes={child anchor=north},
      edge path'={(!u.parent anchor) -| (.child anchor)},
      edge+={blend mode=lighten},
    }{},
  }
  [LMS, fill=gray!25, parent
  [Funktionale \\Anforderungen, for tree={fill=brown!25, child}
  [Lerninhalte organisieren]
  [Lerninhalte erstellen]
  [Lerninhalte abfragen]
  [Kommunikation]
  [Benutzerkonten\-führung]
  [Steuerungs\-funktionen]
  ]
  [Nicht-Funktionale Anforderungen, for tree={fill=red!25,child}, calign with current edge
  [Zuverl{\"a}ssig\-keit]
  [Skalierbar\-keit und Effizienz]
  [Benutzer\-freundlich\-keit]
  [Portierbarkeit]
  [Datenschutz / Informationssicherheit]
  [Erweiterbar\-keit]
  [Anpassbarkeit]
  ]
  [Technische Rahmen\-bedinungen, for tree={fill=blue!25, child}
  [System\-architektur]
  [Software\-kriterien]
  [Schnittstellen]
  [Wartung und Support
  [Support\-leistungen]
  [Software-Pflege]
  ]
  ]
  ]
  ]
\end{forest}
\end{document}

If your edges are lighter than the node, rather than darker, use blend mode=darken instead.


text:
Q: using crypt in php password script allows for password with extra characters? ok, so I'm trying to create some password protected web pages using PHP 5.4 script and MySQL. Running a sample produced some unexpected results!
I created the password using:
$salt = "";
$salt.=substr("./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",mt_rand(0,63), 1);
$salt .= substr("./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", mt_rand(0, 63), 1);
$pw1 = crypt($pw,$salt);

and stored the $pw1 in MySQL database.
then in my authentication pages, I retrieved the db password and used user input from a form to validate the user, checking like this:
get $db_pw from database then...
if (crypt($user_password,$db_pw) == $db_pw) ... proceed

All worked fine, but if I enter a string longer than the password it still passed thru ok.  For example: if my password was "stack", if I entered "stackoverflow" it would pass ok.  If I entered "stac" it would stop as intended.
I've tried searching on this but could not find anything similar.
What am I doing wrong?

A: It looks like the crypt function has this little caveat:

The standard DES-based crypt() returns the salt as the first two characters of the output. It also only uses the first eight characters of str, so longer strings that start with the same eight characters will generate the same result (when the same salt is used).

So I presume that what happens does not happen on "stack" and "stackoverflow" but does with e.g. "stackove" and "stackoverflow".
Using crypt() is a really bad idea. Use PBKDF2 or bcrypt instead of crypt of the stone age.


text:
Q: What is By in Selenium driver.findElement(By.id(//[@id='kishr']));

What is By above?
Is this class ,reference or object ?

A: By is an abstract class
and
id is a static method, so is linkText, partialLinkText, name, tagName, xpath, className, cssSelector in By abstract class.
Since it's a class level methods, you don't really need an object to call these methods.
By.id or By.xpath etc. should suffice.
Official docs

A: By is an abstract class its provides a way to various search criteria's to locate the locator, it provides 8 method for 8 locator stategies,All 8 method are static so call them we have to use class name,


text:
Q: What does "TypeError: unhashable type: 'slice'" mean? And how can I fix it? accounts = {"key":"value","thy":"l23","user2":"psw2"}
a = input("Enter username: ")
b = input("Enter password: ")
if accounts[a:b] == True:
    print("Welcome")

TypeError: unhashable type: 'slice'

What does the error mean? How can I fix it?

A: If I understand what you're trying to do (validate a username and password), you need to go about it this way:
accounts = {"key":"value","thy":"l23","user2":"psw2"}
a = input("Enter username: ")
b = input("Enter password: ")
if accounts[a] and accounts[a] == b:
    print("Welcome")

This tests to see if a password exists for the entered user, then tests to see if the entered password matches the one stored in accounts.
The major problem with this method is that the entered password is printed out when you type it in. To get around this, use the getpass.getpass() function.

A: The
if accounts[a:b] == True:

should read
if accounts.get(a) == b:

The reason I used accounts.get(a) instead of accounts[a] is that the former would return None if a does not contain a valid username (the latter would raise an exception).


text:
Q: How to make R's gamm work faster?  Last night I started a complex calculation with gamm() and it took me...

     user        system       elapsed
    9259.76      326.05     9622.64 (s)

...meaning it took me 160 minutes or 2.67 hours for that calculation. The problem is that I have to do around 50 or even 100 more of these! So I was wondering if there is any way that could speed up these calculations. I compared the 32bit with the 64bit version (4gb) and R 2.12.2 to calculate a less complex gamm().

32bit solution
 User      System        elapsed
 41.87        0.01       42.01

64 bit solution
  User      System      elapsed
 40.06        2.82       43.05

but it took even longer using 64bit!
My question now:

Would it help to simply buy more ram, for example 8GB DDR3? or would that be a waste of money? Or would the compiler package in R 2.13.0 be able to handle that properly? I do not think that rcpp can handle gamm() functions, or am I wrong?

any comments welcome!
the gamm() model call for the 160min process was:
  g1 <- gamm(CountPP10M    ~ s(tempsurf,bs="cr")
                           + s(salsurf,bs="cr")
                           + s(speedsurf,bs="cr")
                           + s(Usurf,bs="cr")
                           + s(Vsurf,bs="cr")
                           + s(Wsurf,bs="cr")
                           + s(water_depth,bs="cr")
                           + s(distance.to.bridge,bs="cr")
                           + s(dist_land2,bs="cr")
                           + s(Dist_sventa,bs="cr"),
                           data=data,
                           random=list(ID_Station=~1),
                           family=poisson,
                           methods="REML",
                           control=lmc)
            )

A: You are not going to be able to achieve substantial speed-up here as most of the computation will be being done inside compiled C code.
If you are fitting correlation structures in gamm() then you can either simplify the correlation structure you want to fit (i.e. don't use corARMA(p=1, .....) when corAR1(....) would suffice. Or nest the correlations within years if you have many observations per year, rather than for the whole time interval.
If you aren't fitting correlation structures, gam() can fit simple random effects, and if you need more complex random effects, consider the gamm4 which is by the same author as mgcv but which uses the lme4 package (lmer()) instead of the slower/older nlme package (lme()).
You could try simpler bases for the smooth terms; bs = "cr" rather than the default thin-plate spline bases.
If all else fails, and you are just facing big-data issues, the best you can do is exploit multiple cores (manually split a job into ncores chunks and run them in BATCH mode over night, or by one of the parallel processing packages on R) and run models as the weekend. If you do this, make sure you wrap your gamm() calls in try() so that the whole job doesn't stop because you have a convergence problem part way through the run.

A: If gamm() is in R code rather than C it might be worth using the byte-code compiler that is new in R 2.13.  There is a new core package called compiler and you can compile a function using the cmpfun() function.
More details can be found here:
http://www.r-bloggers.com/the-new-r-compiler-package-in-r-2-13-0-some-first-experiments/


text:
Q: Nested keyof keyof T in Typescript I have an interface like this...
export interface IMyInterface {
  test1: {
    test1Sub: {
      test1SubSub: string
    }
  },
  test2: {
    test2Sub: {
      test2SubSub: string
    }
  }
}

I would like to be able to strongly type the names of the nested levels into a generic function to give TypeScript intellisense something like this which is in a generic class passing in Type T.
  getSetting = (level1: keyof T, level2: keyof keyof T) => {
    console.log(level1, level2)
  }

Is this possible?  How I have it at the moment it gives me this warning, it works fine for 'test1' but not 'test1Sub;
settings.getPageSettings('test1', 'test1Sub')

Argument of type '"test1Sub"' is not assignable to parameter of type '"toString" | "valueOf" | "toLocaleString"'

A: You don't want keyof keyof for the sub-level as this will the the keys of each type defined by keyof IMyInterface, instead you want keyof T[K]
Here's a quick playground.
export interface IMyInterface {
  test1: {
    test1Sub: {
      test1SubSub: string
    }
  },
  test2: {
    test2Sub: {
      test2SubSub: string
    }
  }
}

function getSetting<T extends IMyInterface, K extends keyof T>(level1: K, level2: keyof T[K]) {
    console.log(level1, level2)
  }

// usage
const myInterface:IMyInterface ={
  test1: {
    test1Sub: {
      test1SubSub: 'subsub1'
    }
  },
  test2: {
    test2Sub: {
      test2SubSub: 'subsub2'
    }
  }
}

getSetting('test1', 'test1Sub');

getSetting('test2', 'test1Sub');
//                   ^^^^^^^^
// Argument of type '"test1Sub"' is not assignable to parameter of type '"test2Sub"'