text:
Q: How do you configure Mathematica 9 to automatically evaluate all notebooks? I have a Mathematica 6 course that I am using in Mathematica 9; there is no updated version. Every time I open a notebook I have to go to the Evaluation menu and click on "Evaluate Notebook". Is there a way for me to set it so that it automatically evaluates a notebook upon my opening it?

A: You can setup the initialization cells. Check this and this. Afterwards, you can just open a notebook and just evaluate any cell (e.g. 2+2 -> Shift+Enter) and accept to run all initialization cells.
One thing that helped me was checking NotebookEvaluate in the docs - this way I can evaluate all cells in another notebook without even having to open it.
You may find further information about options for cells in here.


text:
Q: Creating text file from two differerent folders in python I am trying to write a list with two different file folders (to a text file) in python; however, when I run my program only my second file path appends to the list and appears in my text file. How can I append my list so that the files in both folders display? I think my code is emptying the list after the first step. I want to keep the two folders separate and don't want to combine them just for the sake of the list.
import os
from os import listdir
from os.path import isfile, join

root = r'C:\GEO\Images\data\data_2008\ims_data_2008'
mylist = [ ]
for path, subdirs, files in os.walk(root):
     for name in files:
          mylist.append(os.path.join(path, name))

roottwo = r'C:\GEO\Images\data\data_2009\ims_data_2009'
mylist = [ ]
for path, subdirs, files in os.walk(roottwo):
     for name in files:
          mylist.append(os.path.join(path, name))

txt = open(r'C:\GEO6973\FinalExam\YoungResults\ims_data_list.txt', 'w')
txt.write('dir' + ',' + 'file' + '\n')
for item in mylist:
     list = mylist.pop(0)
     dir, filename = os.path.basename(os.path.dirname(list)), os.path.basename(list)
     txt.write(dir + ',' + filename + '\n')

with open(r'C:\GEO6973\FinalExam\YoungResults\ims_data_list.txt', 'r') as f:
     read_data = f.read()

A: As you say, your code is emptying the list after the first folder. You'll have to remove the second mylist = [ ] after roottwo, otherwise you will lose all data appended to the list thus far.
In the final loop, if you are trying to iterate over the paths appended to mylist don't use pop to access its contents. Instead:
for item in mylist:
    dir, filename = os.path.basename(os.path.dirname(item)), os.path.basename(item)
    txt.write(dir + ',' + filename + '\n')

Finally, try to avoid using list as a variable name since it is a reserved keyword in python.

A: After rootwo is set you are then calling mylist = [ ].  This creates a new list, effectively erasing all data that you previously appended to the list.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to check if app is running from xcode I'm using a test library to see me crash report, and I need to know if the app is running from Xcode, I know that exist the DEGUB parameter, but it does not work because if install app from xcode and open it, DEGUB parameter will be in YES.
Thanks.

A: Not exactly what you want, but you can check if the cable is plugged in, so if it's just for testing the solution should be enough.
[[UIDevice currentDevice] batteryLevel]

or
[[UIDevice currentDevice] UIDeviceBatteryState]


text:
Q: batch script copying file from only the last line of given text file I am trying to copy different file in given folder from a text file (line by line) and by using some specific keywords in lines but it is copying file from the last line. I am new in batch scripting so I don't know too much about syntax of batch script my code is
@echo off
setlocal disableDelayedExpansion
mkdir events_sorted
for /f "tokens=3-7" %%a in (input.txt) do set id=%%a-%%b-%%c-%%d%%e

for /r /d %%i in (.) do (
    cd %%i
    copy "%id%-00S.*" "%CD%/events_sorted/"
 )

pause

Thanx

A: You need to nest the for /R loop into your for /F loop by placing ( after do and putting ) at the end before pause. In addition, do not store the line string in variable id, simply use the line string directly within the copy command line. Furthermore, do not use cd %%i, but use %%i immediately rather than %CD%. Here is the fixed code:
@echo off
setlocal EnableExtensions DisableDelayedExpansion

mkdir "events_sorted"
for /F "usebackq tokens=3-7" %%a in ("input.txt") do (
    for /R /D %%i in (.) do (
        copy "%%a-%%b-%%c-%%d%%e-00S.*" "%%~i/events_sorted/"
    )
)
pause

endlocal
exit /B


text:
Q: Use Django's Generic Date Views There's a 404 error views.py
from django.urls import path, re_path
from blog import views

app_name = 'blog'
urlpatterns = [

    path('archive/<int:year>/<str:month>/<int:day>/',
         views.PostDAV.as_view(), name='post_day_archive'),
    path('archive/today/', views.PostTAV.as_view(), name='post_today_archive'),
]

urls.py
from django.views.generic.dates import DayArchiveView, TodayArchiveView

from blog.models import Post

class PostDAV(DayArchiveView):
    model = Post
    date_field = 'modify_dt'

class PostTAV(TodayArchiveView):
    model = Post
    date_field = 'modify_dt'

error code
Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/blog/archive/today/
Raised by:  blog.views.PostTAV
No posts available

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

When using DayArchiveView, template is opened, but 404 error occurs when using TodayArchiveView.On the official website of the library (https://docs.djangoproject.com/en/3.0/ref/class-based-views/generic-date-based/), I'm sure TodayArchiveView and DayArchiveView have the same template name, but why does 404 error occur only when I use TodayArchiveView? Why does the TodayArchiveView alone have 404 errors when both use the same template? Just in case, I named the template for TodayArchiveView as something else and tried using another template, but there is still a 404 error. Is there anything I missed? I'm sorry for my poor English.
stack trace
System check identified no issues (0 silenced).
May 20, 2020 - 12:05:42
Django version 3.0.6, using settings 'myblog.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Not Found: /
[20/May/2020 12:05:45] "GET / HTTP/1.1" 404 2135
[20/May/2020 12:05:51] "GET /blog/archive/ HTTP/1.1" 200 771
Not Found: /blog/archive/today/
[20/May/2020 12:05:57] "GET /blog/archive/today/ HTTP/1.1" 404 1731

The first 404 error occurred because I haven't set up the homepage yet. Please ignore it.


text:
Q: Getting range between two wildcards T-sql query syntax I have a decimal column that i need to to run a wildcard  query on in a case statement but the wildcards will need a between clause that is between one wildcard to another e.g
case when pct between '999.0%' and '700.0%' then 'Top percentile'
how do I write this please

A: Since pct is decimal then you cannot and you don't need to use the wildcard with it. Just remove the wild cards and the commas ' ':
SELECT ITEM
  , CASE WHEN pct > = 1000 THEN '1000% '
         WHEN pct BETWEEN 800 and 999 then '800 - 999% ' END
FROM table

Also 800 should come first instead of 999 in between.
You need also ELSE for other values less than 800.


text:
Q: Is it possible for a function to be smooth everywhere, analytic nowhere, yet Taylor series at any point converges in a nonzero radius? It is well-known that the function
$$f(x) = \begin{cases} e^{-1/x^2}, \mbox{if } x \ne 0 \\ 0, \mbox{if } x = 0\end{cases}$$
is smooth everywhere, yet not analytic at $x = 0$. In particular, its Taylor series exists there, but it equals $0 + 0x + 0x^2 + 0x^3 + ... = 0$, so while it has radius of convergence $\infty$, it is not equal to $f$ even in a tiny neighborhood of $0$.
There is also a function
$$f(x) = \sum_{n=0}^{\infty} e^{-\sqrt{2^n}} \cos(2^n x)$$
which is smooth everywhere (that is, $C^{\infty}$) yet analytic nowhere. In particular, the Taylor series at every point has radius of convergence $0$. In fact, "most" smooth functions are not analytic.
But this gets me wondering. Could there exist some function which is smooth everywhere, analytic nowhere, yet its Taylor series at any point has nonzero radius of convergence, and so converges to something, but that something is not the function, not even in a tiny neighborhood about the point of expansion? If yes, what is an example of such a function? If no, what is the proof that such a thing is impossible? And also, if no, what sort of restrictions exist on the convergence of the T.s.? At how many/what distribution of points can it converge to something which is not the function? I note that if we multiply together the two functions just given above, we have another smooth-everywhere, analytic-nowhere function, but this time at $0$ we have a convergent Taylor series (the same zero series as before -- just use the generalized Leibniz rule) which doesn't converge to the function in even a tiny neighborhood of $0$.
EDIT (Dec 31, 2013): With some Googling I came across a post to mathoverflow:
https://mathoverflow.net/a/81465

The Taylor series of the Fabius function at any dyadic rational actually has infinite radius of convergence (only finitely many terms are nonzero) but does not represent the function on any interval.

So it seems it is possible to have a function whose Taylor series converges to "the wrong thing" at a dense set of expansion points. But it still doesn't answer the question of whether that is possible for all expansion points on the entire real line.

A: No, this is not possible. Dave L. Renfro wrote an excellent historical Essay on nowhere analytic $C^\infty$ functions in two parts (with numerous references). See here: 1 (dated May 9, 2002 6:18 PM), and 2 (dated May 19, 2002 8:29 PM).
As indicated in part 1, in

Zygmunt Zahorski. Sur l'ensemble des points singuliers d'une fonction d'une variable réelle admettant les dérivées de tous les ordres, Fund. Math., 34, (1947), 183–245. MR0025545 (10,23c); and Supplément au mémoire "Sur l'ensemble des points singuliers d'une fonction d'une variable réelle admettant les dérivées de tous les orders", Fund. Math., 36, (1949), 319–320. MR0035329 (11,718a),

Zahorski suggested in 1947 the following classification of points where a function $f$ is $C^\infty$ but not analytic:

*

*A point $a$ is a C-point (for Cauchy) iff the formal Taylor series about $a$ associated to $f$ converges in a neighborhood of $a$, but the resulting analytic function does not coincide with $f$ in any neighborhood of $a$.

*The point $a$ is a P-point (for Pringsheim) iff the formal Taylor series of $f$ about $a$ has radius of convergence $0$.

Theorem (Zahorski). Let $C,P$ be sets of real numbers. The following are equivalent:

*

*$C$ and $P$ are the sets of C-points and P-points, respectively, of some $C^\infty$
function $f:\mathbb R\to\mathbb R$.

*The following 4 conditions hold:

*

*$C$ is a first category $F_\sigma$ set.

*$P$ is a $G_\delta$ set.

*$C\cap P=\emptyset$.

*$C\cup P$ is closed in $\mathbb R$.

As a corollary, note that if $f:\mathbb R\to\mathbb R$ is smooth, and its set of P-points is empty then, since no interval is first category (by the Baire category theorem), in every interval there must be points where $f$ is analytic.
Two other key references you may want to consult (also mentioned in Renfro's essay) are

Gerald Gustave Bilodeau. The origin and early development of nonanalytic infinitely differentiable functions, Arch. Hist. Exact Sci., 27 (2), (1982), 115–135. MR0677684 (84g:26017),

and

Helmut R. Salzmann, and Karl Longin Zeller. Singularitäten unendlich oft differenzierbarer Funktionen, Math. Z., 62 (1), (1955), 354–367. MR0071479 (17,134b).

(The latter contains a simplified proof of Zahorski's result.)
(Coincidentally, last term I had the opportunity to cover some of the results in this area in my analysis class. See also MathOverflow, for a version of this question, and the related question of whether the set of P-points can be $\mathbb R$.)


text:
Q: Head won't rotate with body I have made a script where I change the player direction base on the x-position on the x axis. But i want to do something so that the character can look up and down based on the y-position on the mouse. I tried to implement it, but it doesn't seem to work and I have no idea why.
Here is my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CharacterMovement : MonoBehaviour
{
    CharacterController characterController;

    private float xaxis = 0.0f;
    private float yaxis = 0.0f;
    public float horizontalMovementSpeed = 2f;
    public float verticalMovementSpeed = 2f;

    public float xSensitivity = 2f;
    public float ySensitivity = 2f;

    public Transform neck;

    void Start()
    {
        characterController = GetComponent<CharacterController>();
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update ()
    {
        if(!characterController.isGrounded)
        {
            transform.Translate(Input.GetAxis("Horizontal") * horizontalMovementSpeed * Time.deltaTime, 0f, Input.GetAxis("Vertical") * verticalMovementSpeed * Time.deltaTime);
            xaxis += Input.GetAxis("Mouse X") * xSensitivity;
            yaxis += Input.GetAxis("Mouse Y") * ySensitivity;
            transform.eulerAngles = new Vector2(0, xaxis);

            yaxis = Mathf.Clamp(yaxis, -40, 85);
            neck.eulerAngles = new Vector2(yaxis, 0);
        }
    }
}

A: I am assuming you are making a 2D game, as your code uses Vector2s.
You can change your implementation to use the transform.LookAt method, and pass through the mouse position.
https://docs.unity3d.com/ScriptReference/Transform.LookAt.html


text:
Q: Radio Button overlapping the Coressponding text
The radio buttons are overlapping the text value of them. Also it isnt taking the entire screen , i tried controlgroup asd well . What is the issue in this?
I am using jquery-1.10.min.js and jquery-mobile-1.4.0.min.js and following is the code snippet

    <form>

                    <input type="radio" name="income" value="Monthly">Monthly</input>

                    <input type="radio" name="income" value="Annually">Annually</input>

    </form>

A: I replaced yor code with the below code and its working fine.And the main reason for your misalignment is because of the jquery mobile inline style.In jqm, add an input with a type="radio" attribute and a corresponding label and  set the for attribute of the label to match the id of the input so they are semantically associated.

              <input type="radio" name="income" value="Monthly" id="radio-choice-2"/>
              Monthly

Demo :http://plnkr.co/edit/beYWdwSmtzYCaRS4ibYK?p=preview
I hope you find it useful


text:
Q: CEF3 browser displaying pages incorrectly I've been working to display a Chromium Embedded Framework browser window in my borderless win32 window. So far the window is created and the browser loads in, but two issues have presented.

*

*Messages don't seem to be getting sent to my window callback (which of course causes window dragging to not function).

*The browser is distorting the pages (almost like only some css is being loaded)

I'm presuming this is due to some glaring mistake I've made in implementing CEF3. What I have is cobbled together from the two example projects that come with a nightly build of CEF3. So the question is, does anyone see any clear mistakes I've made in implementing the browser?
Here's my Main.cpp
#include <Windows.h>

#include "include/cef_base.h"
#include "include/cef_app.h"
#include "ClientApp.h"
#include "ClientHandler.h"

#pragma comment(lib, "lib/libcef.lib")
#pragma comment(lib, "lib/libcef_dll_wrapper.lib")

// Fix Conflicting Macros
#define GET_X_LPARAM(lp)    ((int)(short)LOWORD(lp))
#define GET_Y_LPARAM(lp)    ((int)(short)HIWORD(lp))

// Window Variables
HINSTANCE g_instance;
HWND g_hwnd;
LPCWSTR g_window_class = L"MyUI";
INT g_window_width = 670;
INT g_window_height = 540;
BOOL g_drag_window = false;
SHORT g_mouse_x, g_mouse_y, g_mouse_x_prev, g_mouse_y_prev;

// CEF Variables
CefRefPtr<ClientApp> g_app;
CefRefPtr<ClientHandler> g_client_handler;

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
        case WM_DESTROY:
        {
            CefQuitMessageLoop();
            PostQuitMessage(0);
            break;
        }

        case WM_CREATE:
        {
            // Set window attributes
            RECT rect;
            GetClientRect(hWnd, &rect);
            CefWindowInfo info;
            info.SetAsChild(hWnd, rect);

            // Set browser settings
            CefBrowserSettings settings;

            //Create handler
            ::g_client_handler = new ClientHandler();

            // Create browser
            CefBrowserHost::CreateBrowserSync(info, ::g_client_handler.get(),
                "http://wikipedia.com", settings, NULL);

            break;
        }

        case WM_LBUTTONDOWN:
        {
            g_mouse_x = GET_X_LPARAM(lParam);
            g_mouse_y = GET_Y_LPARAM(lParam);
            if (g_mouse_y < 41)
            {
                g_mouse_x_prev = g_mouse_x;
                g_mouse_y_prev = g_mouse_y;
                SetCapture(hWnd);
                g_drag_window = true;
            }
            MessageBox(NULL, L"FLDKSJA", L"", MB_OK);
            break;
        }

        case WM_LBUTTONUP:
        {
            if (g_drag_window)
            {
                g_drag_window = false;
                ReleaseCapture();
            }
            break;
        }

        case WM_MOUSEMOVE:
        {
            if (g_drag_window && (wParam & MK_LBUTTON))
            {
                // code executed when the dialog window is moved around on the screen
                RECT win_rect;
                GetWindowRect(hWnd, &win_rect);
                int x_coord = GET_X_LPARAM(lParam);
                int y_coord = GET_Y_LPARAM(lParam);
                MoveWindow(hWnd,
                    win_rect.left + x_coord - g_mouse_x_prev,
                    win_rect.top + y_coord - g_mouse_y_prev,
                    win_rect.right - win_rect.left,
                    win_rect.bottom - win_rect.top,
                    false
                    );
                return 0;
            }
            break;
        }

        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
    }
}

BOOL InitWindow()
{
    WNDCLASSEX wc;

    // Register window class
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_DROPSHADOW;
    wc.lpfnWndProc = WndProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = ::g_instance;
    wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = ::g_window_class;
    wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

    if (!RegisterClassEx(&wc))
    {
        wchar_t msg[100];
        wsprintf(msg, L"Unable to register class!\nError: %i", GetLastError());
        MessageBox(NULL, msg, L"Error!",
            MB_ICONEXCLAMATION | MB_OK);
        return FALSE;
    }

    // Create window
    ::g_hwnd = CreateWindowEx(
        0,                        // Optional window styles.
        ::g_window_class,         // Window class
        L"",                      // Window text
        WS_POPUP,     // Window style

        // Position and size
        CW_USEDEFAULT, CW_USEDEFAULT, ::g_window_width, ::g_window_height,

        NULL,       // Parent window
        NULL,       // Menu
        ::g_instance,  // Instance handle
        NULL        // Additional application data
        );

    if (!::g_hwnd)
    {
        wchar_t msg[100];
        wsprintf(msg, L"Unable to create window!\nError: %i", GetLastError());
        MessageBox(NULL, msg, L"Error!",
            MB_ICONEXCLAMATION | MB_OK);
        return FALSE;
    }

    //Display window
    ShowWindow(::g_hwnd, SW_SHOWNORMAL);
    UpdateWindow(::g_hwnd);

    return TRUE;
}

INT APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, INT nCmdShow)
{
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);

    ::g_instance = hInstance;

    // Provide CEF with command-line arguments.
    CefMainArgs main_args(hInstance);

    // CEF applications have multiple sub-processes (render, plugin, GPU, etc)
    // that share the same executable. This function checks the command-line and,
    // if this is a sub-process, executes the appropriate logic.
    int exit_code = CefExecuteProcess(main_args, NULL, NULL);
    if (exit_code >= 0) {
        // The sub-process has completed so return here.
        return exit_code;
    }

    // Specify CEF global settings here.
    CefSettings settings;
    settings.no_sandbox = true;
    settings.multi_threaded_message_loop = false;
    settings.pack_loading_disabled = true;

    // ClientApp implements application-level callbacks for the browser process.
    ::g_app = new ClientApp();

    // Initialize CEF.
    CefInitialize(main_args, settings, ::g_app.get(), NULL);

    // Create main window.
    if (!InitWindow())
    {
        CefShutdown();
        return 1;
    }

    // Process messages.
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);

        CefDoMessageLoopWork();
    }

    // Shut down CEF.
    CefShutdown();

    return 0;
}

ClientApp.h
#pragma once
#include "include/cef_app.h"

class ClientApp : public CefApp,
                  public CefBrowserProcessHandler,
                  public CefRenderProcessHandler
{
public:
    ClientApp();
    ~ClientApp();

    // CefBase
    IMPLEMENT_REFCOUNTING(ClientApp);

    // CefApp
    virtual CefRefPtr<CefBrowserProcessHandler> GetBrowserProcessHandler()
    {
        return this;
    }

    virtual CefRefPtr<CefRenderProcessHandler> GetRenderProcessHandler()
    {
        return this;
    }

    //Context
    virtual void OnContextCreated(CefRefPtr<CefBrowser> browser,
        CefRefPtr<CefFrame> frame,
        CefRefPtr<CefV8Context> context);
};

ClientHandler.h
#pragma once
#include "include\cef_client.h"

class ClientHandler : public CefClient,
                      public CefLifeSpanHandler,
                      public CefLoadHandler
{
public:
    ClientHandler();
    ~ClientHandler();

    // CefClient
    virtual CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler()
    {
        return this;
    }
    virtual CefRefPtr<CefLoadHandler> GetLoadHandler()
    {
        return this;
    }

    // CefBase
    IMPLEMENT_REFCOUNTING(ClientHandler);
};

And this is how the browser is displaying Wikipedia.com:

A: Here is the generic code for both single threaded and multi threaded.
if (!settings.multi_threaded_message_loop) {
  // Run the CEF message loop. Blocks until recieves a WM_QUIT message.
  CefRunMessageLoop();
} else {
  MSG msg;
  // Run the application message loop.
  while (GetMessage(&msg, NULL, 0, 0)) {
  if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
  }
}

In other words try CefRunMessageLoop() alone.


text:
Q: Using hops and join against datasets, how to get the highest value of a certain property. DTL I'm running hops against a dataset in sesam and my output is as the example below, my problem is that need a join where i only end up with the property with the highest priority.
[{
    "id": "AAA",
    "priority": 10
  }, {
    "id": "AAB",
    "priority": 7
  }]

A: You can also solve this with the "max" function:
{
  "_id": "sort-by-prop",
  "type": "pipe",
  "source": {
    "type": "embedded",
    "entities": [{
      "_id": "foo",
      "bar": [{
        "id": "AAA",
        "priority": 10
      }, {
        "id": "AAB",
        "priority": 5
      }]
    }]
  },
  "transform": {
    "type": "dtl",
    "rules": {
      "default": [
        ["copy", "_id"],
        ["add", "foo",
          ["path", "id",
            ["max", "_.priority", "_S.bar"]
          ]
        ]
      ]
    }
  }
}

The result will be:
[
  {
    "_id": "foo",
    "foo": "AAA"
  }
]

A: You can solve this using "sorted", "reverse", "first" and "path":
{
  "_id": "sort-by-prop",
  "type": "pipe",
  "source": {
    "type": "embedded",
    "entities": [{
      "_id": "foo",
      "bar": [{
        "id": "AAA",
        "priority": 10
      }, {
        "id": "AAB",
        "priority": 5
      }]
    }]
  },
  "transform": {
    "type": "dtl",
    "rules": {
      "default": [
        ["copy", "_id"],
        ["add", "foo",
          ["path", "id",
            ["first",
              ["reversed",
                ["sorted", "_.priority", "_S.bar"]
              ]
            ]
          ]
        ]
      ]
    }
  }
}

The result will be:
[
  {
    "_id": "foo",
    "foo": "AAA"
  }
]


text:
Q: react native one variable update is other variable value I want to store one state variable value temporarily and change in only temporarily variable.
in my code original variable is var1 and temp variable is var2.

After update var2 value var1 value is automatically update.

Before update var2 value:-

After update var2 value:-

My Code:-
class DemoScreen extends Component {
    constructor(props) {
        super(props);
        this.state = {
            var1: {
                data:'variable 1 Data'
            },
            var2: {
                data:'variable 2 Data'
            }
        }
    }

    componentDidMount() {
        alert("var1 : " + this.state.var1.data + "\nvar2 : " + this.state.var2.data);
        this.setState({var2:this.state.var1});
    }

    render() {
        return(
            <View style={styles.container}>
                <TouchableOpacity
                    onPress={()=>{
                        var var2 = this.state.var2;
                        var2.data = "value changed";
                        this.setState({var2:var2});
                    }}>
                    <Text>Change Value for var2</Text>
                </TouchableOpacity>
                <TouchableOpacity
                    onPress={()=>{
                        alert("var1 : " + this.state.var1.data + "\nvar2 : " + this.state.var2.data);
                    }}>
                    <Text>Display Values</Text>
                </TouchableOpacity>
            </View>
        )
    }
}

why it is happening?
how to solve it?

A: I think what happens here is that you're setting var2 to the reference of var1 not its value, that's why that happens, what you need to do is to replace that line
this.setState({var2:this.state.var1});

With this line:
this.setState({var2: Object.assign({}, this.state.var1)});

Using Object.assign will clone the value of your object without returning its reference. Always remember Obj1 = Obj2 means that Obj1 equals the reference of Obj2 which means that the both of them considered the same object


text:
Q: How to do Code Coverage for Fluent NHibernate Mapping files I want to do code coverage for Fluent Nhibernate mappingfiles.Please tell me how to proceed if possible with sample code. I was able to unit test the mapping file using persistence configuration but unable to get code coverage for it.
Thanks in advance.

A: If you just want to get code coverage on the ClassMap mapping classes then simply creating an instance of each class will give you that. I'd question the usefulness of doing that since all it gains you is: "yup, I can create an instance of that class so class constructors in .NET  really work." I'd consider verifying the correctness of the mapping class more important than just exercising its constructor. This blog post has some good ideas on verifying mapping classes.


text:
Q: Debugging Event code If I wish to debug some code for a UI event, e.g.
public boolean onTouchEvent(MotionEvent me)
{
    // code to be debugged
}

... and I hold onto this thread (UI):
After 5 seconds I will get this warning: Key dispatching timed out sending to com.hos/com.hos.MyActivity ... null to Window ...
After 20 seconds I will get: Key dispatching timed out sending to com.hos/com.hos.MyActivity ... null to Window ... Continuing to wait for key to be dispatched
After 35 seconds I will get: Key dispatching timed out sending to com.hos/com.hos.MyActivity ... null to Window ... timed out expired process next Key & find new target
At this point, not only is my application frozen but so is the phone. Quite often I need to wait for the ANR and sometimes hard restart the phone.
Is there a way to debug this code for more than 35 seconds without freezing the app / phone?

A: If your processing may take more than milliseconds to process you may want to consider launching the processing in another thread which has access to a handler in the main thread.
Once you are done processing, you can then pass a message over to your handler which will then execute on the UI thread.  This will help prevent those errors from coming up as well as make debugging your code easier.
If you are looking for an automated UI testing framework, perhaps you could look into integrating Robotium into your project.


text:
Q: Estimating the expectation of a derivative Assume $Y$ is a continuously differential function of $X$. Given i.i.d. data $(x_i,y_i)_{i=1}^n$, I would like to estimate $E\left[\left.\frac{\partial Y}{\partial X}\right|_{X=X_0}\right]$.
What got me thinking about this problem was estimation of the coefficients in a linear regression using $E\left[\frac{\partial Y}{\partial X}\right]$ (I know it is not the best way to estimate the coefficients, and may even be a bad way to do so).
From this question Derivative of a random variable w.r.t. a deterministic variable, I know that $\frac{\partial Y}{\partial X}$ makes sense but I'm trying to understand how to estimate $\frac{\partial Y}{\partial X}$ when there is randomness (without randomness estimation can be done by finite differences, for example).
I don't have any good ideas how to estimate $E\left[\left.\frac{\partial Y}{\partial X}\right|_{X=X_0}\right]$ but if I was forced to give a way, I would give weights to points around $X_0$ based on how close they are to $X_0$ and then sample two points at a time based on the weights and first difference the two points and do this many times and take the sample average.
References / summary of techniques / specifics are greatly appreciated.

A: This looks like a good opportunity to apply Kernel Regression (part of the vast field of Nonparametric Regression).
You actually described the basic idea in your last full paragraph. You will be approximating $Y=f(x)$ using kernel-weighted sum of points about $x$, based on their distance from the point.
There are a number of possible kernels, but since you want $Y$ to be smooth, we should choose a kernel that uses all data points in it calculation (so there are no discontinuities). A familiar kernel is the Gaussian Kernel $K_{\sigma}$ with "bandwidth" $\sigma$:
$$K_g(x;\sigma):=\frac{1}{\sqrt{2\pi}\sigma}e^{\frac{x^2}{\sigma^2}}$$
If we use the Nadaraya-Watson Kernel, we can see that our function will have the following form for a set of sample pairs $(y_i,x_i) \in S$:
$$E[Y|X=x_0]\approx f(x_0;S,\sigma)=\frac{\sum\limits_{(x_i,y_i)\in S} K_{\sigma}(x_i-x_0)y_i}{\sum\limits_{(x_i,y_i)\in S} K_{\sigma}(x_i-x_0)}$$
We can approximate $E\left[\left.\frac{\partial Y}{\partial X}\right|_{X=X_0}\right]$ by taking the derivative of $f(x_0;S,\sigma)$ wrt. $x_0$:
$$E\left[\left.\frac{\partial Y}{\partial X}\right|_{X=X_0}\right] \approx \frac{\partial}{\partial x_0}\frac{\sum\limits_{(x_i,y_i)\in S} K_{\sigma}(x_i-x_0)y_i}{\sum\limits_{(x_i,y_i)\in S} K_{\sigma}(x_i-x_0)}$$
Not necessarily a pretty formula, but it will be (a) differentiable and (b) take into account all your data, not just data near your point of interest.
I don't have time right now to work out the whole derivative, but you can apply the quotient rule yourself to see what it will look like.

Response to OP Comment
The OP has stated that they want a "model free" estimate of the derivative at a given point. Unfortunately, the existence of the derivative presumes some model. The nonparametric approach above makes very weak assumptions about the nature of this function, based essentially on just the observed data and some basic smoothing transformations (to ensure that the derivative makes sense).
Also, to clarify: the link to the post about the derivative of a random variable wrt a deterministic variable assumes that the underlying point in the sample space is held fixed and that there is no interaction term between the deterministic and random parts of $Y$: (i.e., we are thinking of $Y$ as a linear function of  $(\omega,x)$, so $\frac{\partial Y}{\partial x}$ ends up being an ordinary function. If this is not the case, then you've entered the realm of stochastic differential equations, and its not simple at all. Now, if you have a bunch of data, you cannot assume that $\omega$ is the same for each point, so we need to develop methods to handle this. My approach above is model-free in this regard, but I'll expand on this below.
For notational simplicity, let's define the conditional random variable $Y_z:=(Y|X=z)$. Then we can model the derivative as follows:
$$\frac{d}{dz}Y_z = \lim_{z'\to z^+} \frac{Y_{z'}-Y_{z}}{z'-z} := Y'_z$$
Lets define the "secant" random variable as:
$$\delta Y_{z,z'} := \frac{Y_{z'}-Y_{z}}{z'-z}$$
The expected value of $\delta Y_{z,z'}$ follows from linearity of expectation:
$$E[\delta Y_{z,z'}] = \frac{E[Y|X=z'] - E[Y|X=z]}{z'-z} $$
Since you are assuming that $Y$ is continuously differentiable function of $X$, we know that $E[Y_z]$ is a smooth, univariate function of $z$, to which we can apply simple Calculus I concepts:
$$ \lim_{z'\to z^+} E[\delta Y_{z,z'}] = E\left[\lim_{z'\to z^+} \delta Y_{z,z'}\right] = E[Y'_z]$$
But, we also have:
$$ \lim_{z'\to z^+} E[\delta Y_{z,z'}] = \lim_{z'\to z^+} \frac{E[Y|X=z'] - E[Y|X=z]}{z'-z}= \frac{d}{dz}E[Y_z]$$
Therefore, $E[Y'_z]=\frac{d}{dz}E[Y_z]$. The latter we were able to get nonparametrically using kernel estimators.

Response No. 2 - Discussion of convergence
I'll start by stepping through the first convergence result:
$$ \lim_{z'\to z^+} E[\delta Y_{z,z'}] = E\left[\lim_{z'\to z^+} \delta Y_{z,z'}\right] = E[Y'_z]$$
Given all the subscripts involved, it may help to recast this using a notation that clarifies the variables:
$E[Y|X=z]\equiv E[Y_z]$ is a function of $z$ only, so lets call it $g(z)$. Then, we can see that:
$$\lim_{z'\to z^+} E[\delta Y_{z,z'}] = \lim_{z'\to z^+} \frac{g(z')-g(z)}{z'-z} \equiv \frac{dg}{dz}:=g'(z)\equiv \frac{d}{dz}E[Y_z](z)$$
So, this step is just the basic application of calculus (assuming the derivative even exists, which your question presumes).
Since you care about a particular $z=x_0$, the limit will just be a number, say, $c=g'(x_0)$.
Next, we have the issue of exchanging the limit and the integral. Let $f_{Y|X=z}(y):=h_z(y)$ be the density of $Y|X=z$. We need to show:
$$\lim_{z' \to z^+} \int \frac{y[h_{z'}(y)-h_{z}(y)]}{z'-z}dy= \int \lim_{z' \to z^+} \frac{y[h_{z'}(y)-h_{z}(y)]}{z'-z}dy$$
Indeed, this is where things are more technically complicated. In general, you can't interchange limit and integration. But, we can if we satisfy the Dominated Convergence Theorem:
Lets define a sequence $z_n:z_n\geq z, \lim_{n\to \infty} z_n = z$, and let:
$$f_n(y):=\frac{y[h_{z_n}(y)-h_{z}(y)]}{z_n-z}$$
Then we need to show:
$$\exists g(y): |f_n(y)|\leq g(y)\;\forall n,y\; \textrm{and}\; \int |g|dy <\infty$$
If we assume that $\delta Y_{z,z'} \xrightarrow{d} Y'_z$ and both posses smooth probability distributions (no discontinuities), then $h_{z_n} \to h_z$ pointwise. Now, we need to construct a bounding function $g$.
At this point we need additional assumptions on the distribution of $Y|X$. For example, if $Y$ is bounded then issues of integrability go away.For unbounded $Y$, we need some information on how $h_{z'}$ converges to $h_z$. Is it just pointwise or uniform too? (the latter is needed to allow exchange of the limit and integral).
So, I guess there was a bit more than simple calc I here...and the result may not be satisfactory from a theoretical sense.
Heres a practical suggestion:
Construct a series of relationships $Y(X)$ that cover the range of relationship types you expect (e.g., exponential, linear, log, sinusoidal, sigmoid). Program a script to generate random samples from $(Y,X)$ (with some distribution or lattice on X), and have it estimate expected value of the derivative using the kernel method and compare it to the theoretical expected derivative (you will need to decide on a distribution for your stochastic/random part in $Y(X)$.)
You will be able to do this comparison across an entire range of $X$ and many repetitions. This will give you the a reliable way to see if the method works for the kinds of problems you expect. Unfortunately, there are very few methods that work optimally in all cases, but the kernel method should get you close for reasonably behaved functions.


text:
Q: Global scope within document ready function
Possible Duplicate:
How do I create a globally accessible variable?

How to make variables and functions within:
$(function() {  })

global scope?

A: You have these choices.

*

*You can predeclare the variables before the function scope.

*You can use the window prefix to make them in the global scope.

Option #1:
var myGlobal;
$(function() {
    myGlobal = 4;
});

Option #2:
$(function() {
    window.myGlobal = 4;
});

A: If you want the code inside the closure be available globally, then I would recommend using JS namespaces. For example:
var myNameSpace = myNameSpace || {} //create a namespace

Using namespacing ensures you're not polluting the global namespace. Then inside your closure, you can extend the namespace with objects, functions, and variables:
$(function(){
  if(myNameSpace){
    myNameSpace.function1 = function(p1){ return $(p1).val() };
    myNameSpace.function2 = function(p2){ return $(p2).val() };
  }
})();

function1 and function2 should be available "globally" via myNameSpace.


text:
Q: finding $a,b,c,d$ of $\frac{x^2 +ax + b}{x^2 +cx +d}$ from its plot We Want to find $a,b,c,d$ of $\frac{x^2 +ax + b}{x^2 +cx +d}$ from its plot. If they can be found accurately, found the exact number. If they can be an interval, find that interval. (note that the extremum of plot is not at an accurately known point, we just know that its $x$ is between $(0,1)$ and $y$ is negative)
From the plot, I can find that the numerator must be $(x+1)(x-2) = x^2 - x -2$ so I get $a=-1 ,b=-2$. I can Also found that the denominator must not have real roots so $c^2 - 4d <0$ but I cannot find $c,d$ Note that it is known that $c , d$ has accurate values or intervals like $c=-4,d>10$ (just for example). So I don't want parametric answers like $-2\sqrt d < c < 2 \sqrt d$.

A: Disclaimer: This answer is subject to possible errors due to inaccurate readings of the graph.
The $y$-intercept of the graph seems to be at $y=-\frac23$, whence $\frac{b}{d}=-\frac23$ should be the case.  As $b=-2$, we conclude $d=3$.
The graph occurs to be symmetric about the line $x=\frac12$.  Therefore, the function is symmetric about the same axis.  Since the numerator $x^2+ax+b=x^2-x-2=\left(x-\frac12\right)^2-\frac{9}{4}$ is symmetric about this axis, the denominator must also be symmetric about $x=\frac12$ too.  That is, $x^2+cx+d=\left(x-\frac12\right)^2+k$ for some constant $k$.  Hence, $c=-1$.
The plot below shows the plot for $y=\frac{x^2-x-2}{x^2-x+3}$.  This looks almost identical to the OP's graph.


text:
Q: Get the top categories for each value in the column aside with one single query Say we have a table looking as follows:
country    product     order
France     cheese      1
UK         cheese      2
Germany    sausage     3
UK         beer        4
UK         beer        5
France     wine        6
France     pork        7
France     wine        8
Germany    pork        9
UK         butter      10
UK         cheese      11
Germany    pork        12
Germany    butter      13
UK         beer        14
France     cheese      15
UK         cheese      16
Germany    butter      17

My aim is to tweak this table so I could get the two more repeated products for each country. If possible, using one single query. The outcome should look like this:
country    product   count
France     cheese    2
France     wine      2
UK         beer      3
UK         cheese    3
Germany    pork      2
Germany    butter    2

A: WITH
cte1 AS (SELECT DISTINCT
                country,
                product,
                COUNT(*) OVER (PARTITION BY country, product) cnt
         FROM test),
cte2 AS (SELECT country,
                product,
                cnt,
                ROW_NUMBER() OVER (PARTITION BY country ORDER BY cnt DESC) rn
         FROM cte1)
SELECT country,
       product,
       cnt
FROM cte2
WHERE rn < 3;

fiddle
PS. If 2nd and 3rd (4th, 5th, ...) rows have the same amount of rows then indefinite (think as random) of them will be returned.

A: You can GROUP BY country, product to count the number of orders and then use RANK() window function to get the top 2 products for each country:
SELECT country, product, count
FROM (
  SELECT country, product, COUNT(*) count,
         RANK() OVER (PARTITION BY country ORDER BY COUNT(*) DESC) rnk
  FROM tablename
  GROUP BY country, product
) t
WHERE rnk <= 2

See the demo.
Results:
> country | product | count
> :------ | :------ | ----:
> France  | cheese  |     2
> France  | wine    |     2
> Germany | pork    |     2
> Germany | butter  |     2
> UK      | cheese  |     3
> UK      | beer    |     3


text:
Q: How to re-register a dynamically loaded angular templates' directive I have a directive which loads a template with a bunch on input fields. One of which is the jQuery/Bootstrap datepicker.
<my-directive-buttons></my-directive-buttons>

When a user selects/clicks on the datepicker field, the calendar is displayed. I have also attached an ng-click to the input field:

            <input type='text' class="form-control" ng-click="addCalendarFooter()"/>

On click, the calender is displayed and $scope.addCalendarFooter is called:
app.directive('myDrectiveButtons', function($compile) {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        scope: {

        },
        templateUrl: 'controls/input-fields.html',
        link: function(scope, elem, attrs) {

        },
        controller: function($scope) {

            $scope.addCalendarFooter = function() {
                $('#datepicker').append($('

').load('myDir/calendar/customFooter.html'));
            }

        }
    }
});

I am successful in appending the contents of customFooter.html to the calendar, however, within customFooter.html are further ng-clicks, which when pressed, are not being called. E.g
customFooter.html

    <button ng-click="controlClick()">Click Me</button>

Yet, if i move this button out of customFooter.html and in to input-field.html, to test the button logic is correct, the click is called.
I have tried $scope.$apply and $scope.digest after the .append, however i get a 'digest already in progress error'
UPDATE:
Based on comments, below, have tried to remove jQuery and use an 'angular way'
$scope.addCalendarFooter = function() {

    var html = "
<\div>";

    var myEl = angular.element(document.getElementsByClassName('datepicker');

    myEl.html(html);

     $compile(myEl)($scope)

}

The above inserts my .html template via the ng-include however is it replacing the contents of the datepicker rather than inserting at the bottom of it. Tried .append but that didn't worth either.

A: You're basically loading the footer manually and bypassing angular completely. Angular doesn't see that you're loading the html and so doesn't compile the html template and bind directives, including ng-click, at all.
You can use ng-include directive that loads the specified template, instead of making a custom one yourself. Or if your directive needs other functionality, just have the ng-include in the directive template itself.

A: What if you include your footer in your template initially but hide it with ng-if / ng-show. Then the function would only change a flag and show the previously hidden footer.

A: You said that your problem is the fact that after calling $scope.$apply or $scope.digest you get the $digest already in progress error.
A clever way to bypass this is using $evalAsync. One of  its biggest advantages is that it knows if it should perform an extra digest cycle of not.

A: If you're using ng-include don't forget the singlequotes at the begining and end of the path.
Angular doc about ng-include: https://docs.angularjs.org/api/ng/directive/ngInclude

make sure you wrap it in single quotes, e.g. src="'myPartialTemplate.html'"

it should be:
var html = "<ng-include src=\"'myDir/calendar/customFooter.html'\"><\ng-include>";
or:
var html = "
<\div>";
but not:
var html = "
<\div>";

A: Quoting from your UPDATE:

The above inserts my .html template via the ng-include however is it replacing the contents of the datepicker rather than inserting at the bottom of it. Tried .append but that didn't worth either.

The aforementioned issue is due to using .html() method which inserts HTML to a DOM node and overwrites any existing content of the selected node:
 var html = "
<\div>";
 var myEl = angular.element(document.getElementsByClassName('datepicker');
 myEl.html(html); // <== here
 $compile(myEl)($scope)

What you are doing with the above logic is that you first select the .datePicker element, then you replace its inner HTML with the .html() method.
As a workaround, you could have used .append() method instead.
NOTE: angular.element() is Angular's wrapper for an element just as in jQuery you had $(). Therefore, using document.getElementByClassName() method is redundant in your case.

Although the above workaround might solve your problem, but it is better to stick to a cleaner and concise approach which AngularJS may offer.
Angularesque Approach
You don't need to load a template partial by programmatically adding/appending the template in a controller function - at least in Angular's way. This way you might end up not binding the angular directive(s) within the dynamically added HTML correctly with a scope.
Instead, just include the partial within the original directive template (with ng-include) and use ngIf or ngShow to display it when the button is clicked.
Therefore, assuming that you've the footer template (customFooter.html) in the original directive template, you can achieve the expected result as in the following:
Directive Template

            <input type='text' class="form-control" ng-click="addCalendarFooter()"/>

Directive Controller
controller: function($scope) {
    $scope.addCalendarFooter = function() {
         $scope.isCalendarFooterAdded = true;
         // or use this if you want to toggle it
         // $scope.isCalendarFooterAdded = !$scope.isCalendarFooterAdded ? true: false;
    }
}

Plunkr mimicking a similar situation.


text:
Q: Verifying compatibility with legacy Intel processors I have an application that is intended to target a wide family of Intel processors, from archaic (Pentium, Pentium II) to modern (Haswell, Skylake). It features specific code paths tailored for the various extensions to the x86 instruction set (SSE, AVX, etc.). However, I only have access to computers dating back to Sandy Bridge and can not verify that the application will actually run on the oldest architectures supported. While it is true that CPUs that old are unlikely to be useful for any purpose, it would be good from a code quality point of view to know that a function named my_routine_sse2 does not accidentally use instructions from SSE3 or such.
What approaches do people usually take when facing this kind of problem? Are there automated tools that will scan functions and ensure illegal instructions are not present? Are there services (web or otherwise) that provide access to legacy computer architectures for testing and debugging?

A: Make unit tests that can run under bochs, to test all your my_routine_sse2 and so on functions.
You'll still need to test the whole app occasionally, to make sure you didn't screw up the CPU dispatcher, or include some non-baseline instructions outside of functions controlled by your dispatcher.
BTW, function pointers are very good for CPU dispatching.  At start-up, check CPUID and set some function pointers.  Later functions call through the function pointers to get whatever version of the function the dispatcher chose for this host.  Then you don't have a tree of conditional branches everywhere you want to use a function with optimized versions available.  x264 (the open source h.264 video encoder) uses this technique for its extensive collection of asm routines.

You're right that your sse2 functions shouldn't go beyond sse2, but if you set your baseline at SSE2, you can use it everywhere without checking.  Auto-vectorization can do nice things sometimes.  If you use floating point, you can get gcc to use a different ABI where float / double are passed/returned in SSE registers, instead of x87.  (Or maybe still passed on the stack, like other things in the outdated 32bit x86 ABI.)
All CPUs for the past ~10 years can run 64bit code, although some people have 32bit Windows on CPUs on newer CPUs.  Unfortunately it's still generally required to provide 32bit builds for people with legacy systems.
SSE2 might be a reasonable choice for a baseline, though.  The newest CPUs you'd exclude that way are AMD AthlonXP CPUs from just before the first AMD64 k8 cores.


text:
Q: Find index of a minimum property in a part of the collection I have a class Bar:
public class Bar
{
    public string Symbol { get; set; }
    public DateTime DateTime { get; set; }
    public double Open { get; set; }
    public double High { get; set; }
    public double Low { get; set; }
    public double Close { get; set; }
    public int Volume { get; set; }
}

and a collection
minDataCollection<Bar>

I am trying to find an index of a bar with lowest bar.Low within a "width" of bars starting n-bars back from the current bar.
The problem is if I create another collection of size "width" and find the minimum I will loose connection to indexes of main collection.

A: You can use LINQ's Select-with-an-index, then MinBy from MoreLINQ:
var index = collection.Select((value, index) => new { value, index })
                      .MinBy(pair => pair.value.Low).index;


text:
Q: Label in cyclic arrow diagram Consider the following code from TeXample.net:

How to refactor it for adding sloped labels on the outside of the arrows? Do you have a more elegant solution with TikZ?
% Overlapping arrows
% Author: Elena Botoeva
\documentclass{article}
\usepackage[margin=0.3cm, paperwidth=3.3cm, paperheight=3.3cm]{geometry}
\usepackage{tikz}
\usetikzlibrary{shadows}

\definecolor{darkblue}{rgb}{0.2,0.2,0.6}
\definecolor{darkred}{rgb}{0.6,0.1,0.1}
\definecolor{darkgreen}{rgb}{0.2,0.6,0.2}

\def\arrow{
  (10.75:1.1) -- (6.5:1) arc (6.25:120:1) [rounded corners=0.5] --
  (120:0.9) [rounded corners=1] -- (130:1.1) [rounded corners=0.5] --
  (120:1.3) [sharp corners] -- (120:1.2) arc (120:5.25:1.2)
  [rounded corners=1] -- (10.75:1.1) -- (6.5:1) -- cycle
}

\tikzset{
  ashadow/.style={opacity=.25, shadow xshift=0.07, shadow yshift=-0.07},
}

\def\arrows[#1]{
  \begin{scope}[scale=#1]
    \draw[color=darkred, %
    drop shadow={ashadow, color=red!60!black}] \arrow;

    \draw[color=darkgreen, bottom color=green!90!black, top color=green!60, %
    drop shadow={ashadow, color=green!60!black}] [rotate=120] \arrow;

    \draw[color=darkblue, right color=blue, left color=blue!60, %
    drop shadow={ashadow, color=blue!60!black}] [rotate=240] \arrow;

    % to hide the green shadow
    \draw[color=darkred, left color=red, right color=red!60] \arrow;
  \end{scope}
}

\begin{document}
\thispagestyle{empty}
\begin{center}
  \begin{tikzpicture}
    \arrows[1];
  \end{tikzpicture}
\end{center}
\end{document}


text:
Q: Sinon create stub instance - include protected properties My question is how does one include protected properties when creating a stub instance.
In my jest test I have:
const sandbox = createSandbox();
let manager: SinonStubbedInstance<EntityManager>;
let repo: Repo;

beforeEach(() => {
    manager = sandbox.createStubInstance(EntityManager);
    repo = new Repo(manager);
});

afterEach(() => sandbox.restore());

Which is attempting to make a stub of:
export declare class EntityManager {

/**
 * Connection used by this entity manager.
 */
readonly connection: Connection;

/**
 * Custom query runner to be used for operations in this entity manager.
 * Used only in non-global entity manager.
 */
readonly queryRunner?: QueryRunner;

/**
 * Once created and then reused by en repositories.
 */
protected repositories: Repository<any>[];

/**
 * Plain to object transformer used in create and merge operations.
 */
.......
}

So I don't seem to be able to have readonly properties and protected properties included in the stub.
At the "repo = new Repo(manager);" line.
The above code yields the following exception:
Argument of type 'SinonStubbedInstance<EntityManager>' is not assignable to parameter of type 'EntityManager'.
Property 'repositories' is missing in type 'SinonStubbedInstance<EntityManager>'.ts(2345)

Is there anyway to tell Sinon to include the properties?
Any help would be most appreciated.

A: I solved this problem with
repo = new Repo(manager as any);

A: I don't know what in your case the Repo does with the EntityManager, also it is not completely clear to me what you want to test here.. so based on this my answer is a bit generic, but maybe it points you in the right direction.
My idea: Maybe you should decouple them. I would approach it the following way:

*

*Create a getter in the EntityManager that gets all repos, name it for example getRepos()

*Create a mocked array that contains some Repos... const mockedRepos;

*Mock the getter of the EntityManager with your stub instance returning your mocked data:
manager.getRepos.returns(mockedRepos);
This way you don't need the protected repositories var in your test.


text:
Q: Code Splitting not working with CRA + React Route v4 + Code Splitting Code splitting not working when host app behind a webserver
My Setup:
I have an ejected CRA that is hosted using a Web Server under the path /management
Hence, If I go to myfacnywebsite.com/management I get my react app
Since I am hosting the app behind a WebServer I am setting "homepage": "/management" in package.json as per https://create-react-app.dev/docs/deployment#building-for-relative-paths
Also, since I am using react-router-v4 I am setting baseName to /management to make it work across refresh https://reacttraining.com/react-router/web/api/BrowserRouter/basename-string
Now, the problem is when I add code splitting at route level, everything works fine when I run app locally
However, when I app behind a webserver under path /management. The bundles requested are getting the URL of /management/management . I am confused what is going on
Code snippet from my index.ts file
ReactDOM.render(
  <Provider store={store}>
    <ApolloProvider client={cqrsClient}>
      <ErrorBoundary name="app" ErrorComponent={DefaultError}>
        <Router  basename="/management">
          <App />
        </Router>
      </ErrorBoundary>
    </ApolloProvider>
  </Provider>,
  document.getElementById("root")
);

Code snippet from my package.json for CRA
{
  "name": "FancyApp",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    ...
  },
  "scripts": {
    ...
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    ...
  },
  "babel": {
    ...
  },
  "homepage": "/management"
}

A: Here's a great video tutorial that goes over the right way of using React a Router and Suspense for code splitting and lazy loading: https://youtu.be/j8NJc60H294
You can use this code but I highly recommend the video above.
import React, { Suspense } from 'react';
import lazy from 'react-lazy-named';

const LoremIpsum = lazy(()=>import('react-lorem-ipsum'));

const BoringContent = () => (

Terms and Conditions

    <LoremIpsum avgWordsPerSentence={12} p={10} />
    <Suspense fallback={
Lorem ipsum
}>
      <LoremIpsum avgWordsPerSentence={12} p={10} />
    </Suspense>

);


text:
Q: Mysql effective indexes Currently I am creating indexes as I need them for a particular sql query.
But they are starting to overlap each other.
Is there any rule to define them effectively?
For example:

*

*If I have two indexes for column1 and column2, does the composite index by column1, column2 improve select by both columns?

*What is there any difference between an index by column1 and column2 over index by column2 and column1?

A: An index over two columns A and B is working as an index for column A also, but not as an index for column B.
I don't know if there is an simple rule for indexes, maybe just look for the columns involved in where clauses and order by statements in your queries and evaluate which to use.
Keep in mind that an index makes sense for a large number of rows where you search for a small subset. Indexes also slow down insertion and updates, so use them wisely. It is often enough to simply index all rows that are used to JOIN and add further ones if you run into performance issues.

A:
If I have two indexes for column1 and column2, does the composite index by column1, column2 improve select by both columns?

Yes, it does. Separate indexes have to get merged first or just one index is used.

What is there any difference between an index by column1 and column2 over index by column2 and column1?

In a compound index the order of the columns matters, yes. If your query has only column2 in the WHERE clause, a compound index over (column1, column2) will not be used.
If you have a compound index over (column1, column2) it can also be used if your query only has column1 in WHERE clause.
For additional information see other answers I gave to questions about indexing:
MYSQL Long super-keys
MySQL query optimization of LIKE term% ORDER BY int

A: Q: If I have two indexes for column1 and column2, does the composite index by column1, column2 improve select by both columns?
Yes then composite Index is better.
From Mysql
"mysql> SELECT * FROM tbl_name WHERE col1=val1 AND col2=val2;
If a multiple-column index exists on col1 and col2, the appropriate rows can be fetched directly. If separate single-column indexes exist on col1 and col2, the optimizer attempts to use the Index Merge optimization (see Section 8.3.1.4, "Index Merge Optimization"), or attempts to find the most restrictive index by deciding which index excludes more rows and using that index to fetch the rows."
Q:  What is there any difference between an index by column1 and column2 over index by column2 and column1?
Yes it will make difference. It depends on how you form your query.
From the Mysql docs:
Example If you have index like below on table :
INDEX name (last_name,first_name)
"The name index is an index over the last_name and first_name columns. The index can be used for lookups in queries that specify values in a known range for combinations of last_name and first_name values. It can also be used for queries that specify just a last_name value because that column is a leftmost prefix of the index."
You will get advantage of index for below query:
SELECT * FROM test WHERE last_name='Widenius';
But index is not used for lookups in the following queries:
SELECT * FROM test WHERE first_name='Michael';
Hope this will help !!

A: Q)If I have two indexes for column1 (A) and column2 (B), does the composite index by column1, column2 improve select by both columns?

*

*yes if you have a just two indices A and B, SELECT something from table where A = 1 and B =2 will be using just one of two indices, but if you have compound index A,B it will use it, which should be faster

Q) What is there any difference between an index by column1 and column2 over index by column2 and column1?

*

*sequence do matters in compound indices. Suppose you have the same query as above, and your table is 1 mln entries and only 50 of them match A=1 and 10000 match B=1, than compound index A,B will perform much better than B,A. So you need to choose first element of the index with the smallest cardinality.

This might be usefull
http://dev.mysql.com/doc/refman/5.0/en/multiple-column-indexes.html
http://stackoverflow.com/questions/1823685/when-should-i-use-a-composite-index


text:
Q: How to transform long to wide data in Stata? I have this data:
id  test    test_date   value
1   A   02/06/2014 12:26    11
1   B   02/06/2014 12:26    23
1   C   02/06/2014 13:17    43
1   D   02/06/2014 13:17    65
1   E   02/06/2014 13:17    34
1   F   02/06/2014 13:17    64
1   A   05/06/2014 15:14    234
1   B   05/06/2014 15:14    646
1   C   05/06/2014 16:50    44
1   E   05/06/2014 16:50    55
2   E   05/06/2014 16:50    443
2   F   05/06/2014 16:50    22
2   G   05/06/2014 16:59    445
2   B   05/06/2014 20:03    66
2   C   05/06/2014 20:03    77
2   D   05/06/2014 20:03    88
2   E   05/06/2014 20:03    44
2   F   05/06/2014 20:19    33
2   G   05/06/2014 20:19    22

I would like to transform this data into wide format like this:
id    date              A   B   C   D   E   F   G
1   02/06/2014 12:26    11  23  43  65  34  64  .
1   05/06/2014 15:14    234 646 44  .   55  .   .
2   05/06/2014 16:50    .   .   .   .   443 22  445
2   05/06/2014 20:03    .   66  77  88  44  33  22

I am using reshape command in Stata, but it is not producing required results:
reshape wide test_date value, i(id) j(test) string

Any idea how to do this?
UPDATE:
You're right that we need this missvar. I try to create this by programming, but failed. Let say with-in 2 hours of test date the batch will consider same. We have only 7 tests (A,B,C,D,E,F,G). First I try to find the time difference;
 bysort id: gen diff_bd = (test_date[_n] - test_date[_n-1])/(1000*60*60)

 bysort id: generate missvar = _n if diff_bd <= 2

A: The command is slightly misspecified. You want to reshape value. Look at the output you want and notice the observations are uniquely identified by id and test_date. Therefore, they should be in the i option.
reshape wide value, i(id test_date) j(test) string

This yields something close you what you want, you just need to rename a few variables to get exactly the output. Specifically:
rename test_date date
renpfix value

A: @jfeigenbaum has given part of the answer.
The problem I see is that you are missing a variable that identifies relevant sub-groups. These sub-groups seem to be bounded by test taking values A - G. But I may be wrong.
I've included this variable in the example data set, and named it missvar. I forced this variable into the data set believing it identifies groups that, although implicit in your original post, are important for your analysis.
clear
set more off

*----- example data -----

input ///
id  str1 test    str30 test_date   value missvar
1   A   "02/06/2014 12:26"    11 1
1   B   "02/06/2014 12:26"    23 1
1   C   "02/06/2014 13:17"    43 1
1   D   "02/06/2014 13:17"    65 1
1   E   "02/06/2014 13:17"    34 1
1   F   "02/06/2014 13:17"    64 1
1   A   "05/06/2014 15:14"    234 2
1   B   "05/06/2014 15:14"    646 2
1   C   "05/06/2014 16:50"    44 2
1   E   "05/06/2014 16:50"    55 2
2   E   "05/06/2014 16:50"    443 1
2   F   "05/06/2014 16:50"    22 1
2   G   "05/06/2014 16:59"    445 1
2   B   "05/06/2014 20:03"    66 2
2   C   "05/06/2014 20:03"    77 2
2   D   "05/06/2014 20:03"    88 2
2   E   "05/06/2014 20:03"    44 2
2   F   "05/06/2014 20:19"    33 2
2   G   "05/06/2014 20:19"    22 2
end

gen double tdate = clock( test_date, "DM20Yhm")
format %tc tdate

drop test_date
list, sepby(id)

*----- what you want ? -----

reshape wide value, i(id missvar tdate) j(test) string
collapse (min) tdate value?, by(id missvar)

rename value* *

list

There should be some way of identifying the groups programmatically. Relying on the original sort order of the data is one way, but it may not be the safest. It may be the only way, but only you know that.
Edit
Regarding your comment and the "missing" variable, one way to create it is:
// one hour is 3600000 milliseconds
bysort id (tdate): gen batch = sum(tdate - tdate[_n-1] > 7200000)

For your example data, this creates a batch variable identical to my missvar. You can also use time-series operators.
Let me emphasize the need for you to be carefull when presenting your example data. It must be representative of the real one or you might get code that doesn't suit it; that includes the possibility that you don't notice it because Stata gives no error.
For example, if you have the same test, applied to the same id within the two-hour limit, then you'll lose information with this code (in the collapse). (This is not a problem in your example data.)
Edit 2
In response to another question found in the comments:
Suppose a new observation for person 1, such that he receives a repeated test within the two-hour limit, but at a different time :
1   A   "02/06/2014 12:26"    11 1 // old observation
1   B   "02/06/2014 12:26"    23 1
1   A   "02/06/2014 12:35"    99 1 // new observation
1   C   "02/06/2014 13:17"    43 1
1   D   "02/06/2014 13:17"    65 1
1   E   "02/06/2014 13:17"    34 1
1   F   "02/06/2014 13:17"    64 1
1   A   "05/06/2014 15:14"    234 2
1   B   "05/06/2014 15:14"    646 2
1   C   "05/06/2014 16:50"    44 2
1   E   "05/06/2014 16:50"    55 2

Test A is applied at 12:26 and at 12:35. Reshape will have no problem with this, but the collapse will discard information because it is taking the minimum values amongst the id missvar groups; notice that for the variable valueA, new information (the 99) will be lost (so too happens with all other variables, but you are explicit about wanting to discard that). After the reshape but before the collapse you get:
. list, sepby(id)

     +--------------------------------------------------------------------------------------------------+
     | id   missvar                tdate   valueA   valueB   valueC   valueD   valueE   valueF   valueG |
     |--------------------------------------------------------------------------------------------------|
  1. |  1         1   02jun2014 12:26:00       11       23        .        .        .        .        . |
  2. |  1         1   02jun2014 12:35:00       99        .        .        .        .        .        . |
  3. |  1         1   02jun2014 13:17:00        .        .       43       65       34       64        . |
  4. |  1         2   05jun2014 15:14:00      234      646        .        .        .        .        . |
  5. |  1         2   05jun2014 16:50:00        .        .       44        .       55        .        . |
     |--------------------------------------------------------------------------------------------------|
  6. |  2         1   05jun2014 16:50:00        .        .        .        .      443       22        . |
  7. |  2         1   05jun2014 16:59:00        .        .        .        .        .        .      445 |
  8. |  2         2   05jun2014 20:03:00        .       66       77       88       44        .        . |
  9. |  2         2   05jun2014 20:19:00        .        .        .        .        .       33       22 |
     +--------------------------------------------------------------------------------------------------+

Running the complete code confirms what we just said:
. list, sepby(id)

     +--------------------------------------------------------------------------+
     | id   missvar                tdate     A     B    C    D     E    F     G |
     |--------------------------------------------------------------------------|
  1. |  1         1   02jun2014 12:26:00    11    23   43   65    34   64     . |
  2. |  1         2   05jun2014 15:14:00   234   646   44    .    55    .     . |
     |--------------------------------------------------------------------------|
  3. |  2         1   05jun2014 16:50:00     .     .    .    .   443   22   445 |
  4. |  2         2   05jun2014 20:03:00     .    66   77   88    44   33    22 |
     +--------------------------------------------------------------------------+

Suppose now a new observation for person 1, such that he receives a repeated test within the two-hour limit, but at the same time:
1   A   "02/06/2014 12:26"    11 1 // old observation
1   B   "02/06/2014 12:26"    23 1
1   A   "02/06/2014 12:26"    99 1 // new observation
1   C   "02/06/2014 13:17"    43 1
1   D   "02/06/2014 13:17"    65 1
1   E   "02/06/2014 13:17"    34 1
1   F   "02/06/2014 13:17"    64 1
1   A   "05/06/2014 15:14"    234 2
1   B   "05/06/2014 15:14"    646 2
1   C   "05/06/2014 16:50"    44 2
1   E   "05/06/2014 16:50"    55 2

Then the reshape won't work. Stata complains:

values of variable test not unique within id missvar tdate

and with reason. The error is clear in signalling the problem. (If not clear, go back to help reshape and work out some exercises.) The request makes no sense given the functioning of the command.
Finally, note it's relatively easy to check if something will work or not: just try it! All that was necessary in this case was to modify a bit the example data. Go back to help files and manuals, if necessary.


text:
Q: Input does not allow changing the value in the change I am trying to modify the input values in the change event and it does not allow me this is my code
<Input type="text" name="traMake" required value={truckEdit.tra.traMake} onChange={ingresarValoresMemoria} id="idMake" placeholder="Campo obligatorio" />

but when modifying the value by value = {truckEdit.tra.traMake} if it lets me modify it but my entity has this structure
const [truckEdit,setTruckEdit]= useState({
        truId           :'',
        driId           : '',
        TruExdate       : '',
        TruAddress      : '',
        tra             : ({
            traMake     : '',
            traOption   : '',
            traUnit     : '',
        }),
        TraUnit         : '',
        TraOption       : '',
        truDocurl       : ''
    });

is there any way to keep the structure and be able to avoid input blocking

A: The easiest way is to use Object Spread.
See the below code
  function handleTraMakeChange(newValue) {
    setTruckEdit({
      ...truckEdit,
      tra: {
        ...truckEdit.tra,
        ["traMake"]: newValue
      }
    });
  }

  return (
    <div className="App">
      <input
        type="text"
        name="traMake"
        required
        value={truckEdit.tra.traMake}
        onChange={(e) => handleTraMakeChange(e.target.value)}
        id="idMake"
        placeholder="Campo obligatorio"
      />
    </div>
  );

A: You need to update truckEdit.tra.traMake value onChange. You can do that by
<Input type="text" name="traMake" required value={truckEdit.tra.traMake} onChange={(e)=>{ingresarValoresMemoria(e, 'traMake')}} id="idMake" placeholder="Campo obligatorio" />

const ingresarValoresMemoria = (e, fieldName) => {
    setTruckEdit({
      ...truckEdit,
      tra: {
        ...truckEdit.tra,
        [fieldName]: e.target.value
      }
    });
  };

For other fields inside tra you'll need different inputs and you'll need to pass appropriate fieldName on their onChange functions.
Code Sand Box Link


text:
Q: Remove Duplicate words (only if followed) from char array I am a little bit stuck and cant find out what is wrong here.
I have an assignment to enter a sentence into char array and if there are duplicate and followed words(example : same same , diff diff.   but not : same word same.) they should be removed.
here is the function I wrote:
void Same(char arr[], char temp[]){
    int i = 0, j = 0, f = 0, *p, k = 0, counter = 0;
    for (i = 0; i < strlen(arr); i++){
        while (arr[i] != ' ' && i < strlen(arr)){
            temp[k] = arr[i];
            i++;
            k++;
            counter++;
        }
        temp[k] = '\0';
        k = 0;
        p = strstr((arr + i), (temp + j));
        if (p != NULL && (*p == arr[i])){
            for (f = 0; f < strlen(p); f++){
                *p = '*';
                p++;
            }
            f = 0;
        }
        j = counter;

    }
}

A: strtok is a handy function to grab the next word from a list (strsep is a better one, but is less likely to be available on your system).  Using strtok, an approach like the following might work, at least for simple examples...
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAXPHRASELEN 1000
#define MAXTOKLEN 100

int main(int argc, char ** argv)
{
    // Here is the sentence we are looking at
    char * tmp = "This is a test and and another test";
    // We will copy it to this variable
    char phrase[MAXPHRASELEN+1];
    strcpy(phrase, tmp);
    // And will put the altered text in this variable
    char new_phrase[MAXPHRASELEN+1];
    // This will be the last word we looked at
    char * lasttok = malloc(MAXTOKLEN+1);
    // This will be the current word
    char * tok = malloc(MAXTOKLEN+1);
    // Both words are initially empty
    new_phrase[0] = '\0';
    lasttok[0] = '\0';
    // Get the first word
    lasttok = strtok(phrase, " ");
    // If there is a word...
    if (lasttok != NULL) {
        // Put it in the altered text and add a space
        strcat(new_phrase, lasttok);
        strcat(new_phrase, " ");
        // As long as there is a next word
        while ( (tok = strtok(NULL, " ")) != NULL ) {
            // See if it is the same as the last word
            if (strcmp(tok,lasttok) != 0) {
                // If it isn't, copy it to the altered text
                strcat(new_phrase, tok);
                // and add a space
                strcat(new_phrase, " ");
                // The current word becomes the last word
                lasttok = tok;
            }
        }
    }
    // Print the lot
    printf("%s\n", new_phrase);
}

If you really must write your own routine for grabbing the individual words, you could do worse than emulate strtok.  It maintains a pointer to the beginning of current word in the string and puts a null character at the next separator (space character).  When called again, it just moves the pointer to the character past the null, and puts another null after the next separator.  Most string functions, when passed the pointer, will see the null as the end of the string and so just deal with the current word.
Minus comments, headers, and initialisation, it looks less threatening...
    lasttok = strtok(phrase, " ");
    if (lasttok != NULL) {
        strcat(new_phrase, lasttok);
        strcat(new_phrase, " ");
        while ( (tok = strtok(NULL, " ")) != NULL ) {
            if (strcmp(tok,lasttok) != 0) {
                strcat(new_phrase, tok);
                strcat(new_phrase, " ");
                lasttok = tok;
            }
        }
    }
    printf("%s\n", new_phrase);


text:
Q: making a browser-action mimic a server request I am not quite sure how to correctly phrase the title of this question but here goes… my app is all client-side, all the logic embedded in the web page, and nothing on the server except a simple web server. And I want to keep it that way.
Now, I have a few panels in my webpage that I are hidden by default.
┌─────────────────────────────────┐
│       https://server/home       │
└─────────────────────────────────┘
┌─────────────────────────────────┐
│                                 │
│   about   privacy   contact     │
│                                 │
│  ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─      │
│             about         │     │
│  │                              │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘     │
│  ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─      │
│             privacy       │     │
│  │                              │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘     │
│  ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─      │
│             contact       │     │
│  │                              │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘     │
│                                 │
└─────────────────────────────────┘

When the user clicks on any of the links – about, privacy, contact – then the respective panel becomes visible and the URL in the browser bar changes to reflect the state with the help of history.pushState(). So far so good.
┌─────────────────────────────────┐
│      https://server/about       │
└─────────────────────────────────┘
┌─────────────────────────────────┐
│                                 │
│   about   privacy   contact     │
│                                 │
│  ┌────────────────────────┐     │
│  │          about         │     │
│  │                        │     │
│  └────────────────────────┘     │
│  ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─      │
│             privacy       │     │
│  │                              │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘     │
│  ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─      │
│             contact       │     │
│  │                              │
│   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘     │
│                                 │
└─────────────────────────────────┘

Now the tricky part, where I need some help – I send this URL to someone as a link. That user clicks on the link and I want the web page to open up with the correct panel visible. The problem is, any logic I implement to perform this has to be in the page, and the page has to be loaded, and for the page to be loaded, it has to exist on the server. However, there is no about.html on the server. There is only a single page with the panels that are hidden and made visible on demand. How do I do this? (see update below)
Of course, one way would be to simply have copies of my page named as about.html and privacy.html but surely, I can do this much more cleverly, can't I?
How?
Update: so, with the magic of Unix, I can create a symbolic link ln -s index.html about.html (index.html is my actual, existing web page while about.html is the page that doesn't exist but has to look like it does) and this does work. When I ask the browser to load about.html, it doesn't know any better and loads the page that the web server sends. So, this is the solution, I guess. Any gotchas I've got to watch out for?


text:
Q: multiselect, set default selected values How can I set selected values for a multiselect within my controller?
This is my code so far
    class Blog_Form_Post extends Zend_Form
    {
        public function init()
        {
    ...
            $this->addElement('multiselect', 'categories', array(
                'label'      => 'Categories:',
                'required'   => false,
            ));
    ...

            $form = new Blog_Form_Post();
            $categories = new Blog_Model_DbTable_Categories();
            $categories = $categories->fetchAll();
            foreach ($categories as $category)
            {
// Some of the categories needs to selected by default
                $form->getElement('categories')->addMultiOption($category->ID, $category->name);

        }

Edit to be more clear. I am taking the example from Aron Rotteveel
$multi->setMultiOptions(array(
    'foo' => 'Foo',
    'bar' => 'Bar',
    'baz' => 'Baz',
    'bat' => 'Bat',
));

I want Foo and Bar to be selected while Baz and Bat should be unselected when the form is rendered. IE
<select name="categories[]" id="categories" multiple="multiple">
    <option selected="selected" value="foo">foo</option>
    <option selected="selected"value="bar">bar</option>
    <option value="baz">baz</option>
    <option value="bat">bat</option>
</select>

A: I usually use setDefaults() on the form - you can also use setValue() on the element, but you set a multi-select's "selected options" as an array of selected id's (just like it returns for a value).
$categories = // model funciton to get selected categories for this entry.
$selected=array();
foreach ($categories as $category)
{
  $selected[] = $category->ID;
}
$form->setDefaults(array('categories' => $selected));

A: You can pass an array of values to setValue().
The values in the array should correspond to the keys passed when setting the multiOptions.
$multi->setMultiOptions(array(
    'foo' => 'Foo',
    'bar' => 'Bar',
    'baz' => 'Baz',
    'bat' => 'Bat',
));

$multi->setValue(array('foo', 'bar'));

From the ZF manual:

To mark checked items, you need to
  pass an array of values to setValue().

A: If you prefer to pass the options by array rather than using discrete elements, you can also do this:
$this->addElement('select', 'element_name', array(
  'label'=>'Element Label',
  'value'=> array('value_name'=>'Value Label',
  'multiOptions' => array(
      'value_name'=>'Value Label',
      'value_name_2'=>'Value Label 2',
      'value_name_3'=>'Value Label 3',
));

The important part is the 'value' key of the $options array.
This will cause the first element to be selected.


text:
Q: C++ - values not getting set correctly in for loop I am trying to set the values for the 2nd and 3rd corners on three objects of class triangle.  If done explicitly, this looks like this:
triangle_mesh[0].set_vector_point2(vector_anchors[1]);
triangle_mesh[1].set_vector_point3(vector_anchors[1]);
triangle_mesh[1].set_vector_point2(vector_anchors[2]);
triangle_mesh[2].set_vector_point3(vector_anchors[2]);
triangle_mesh[2].set_vector_point2(vector_anchors[3]);
triangle_mesh[0].set_vector_point3(vector_anchors[3]);

and this works!  Printing these triangles, I get (n.b. the first corner has already been set - this is not an issue):
triangle0 is ( 0, 0, -1) (1, 0, 0) (-0.5, -0.866025, 0)
triangle1 is ( 0, 0, -1) (-0.5, 0.866025, 0) (1, 0, 0)
triangle2 is ( 0, 0, -1) (-0.5, -0.866025, 0) (-0.5, 0.866025, 0)

Firstly, though, this is ugly, and secondly it must generalise to cases where I have more than three triangles to set up.  My code for this is:
for (int longitude = 0; longitude < num_longitudes; longitude++){
  SurfaceVector current_anchor = vector_anchors[1 + longitude];
    triangle_mesh[longitude].set_vector_point2(current_anchor);
    triangle_mesh[(longitude + 1) % num_longitudes].set_vector_point3(current_anchor);
}

*n.b. num_longitudes is 3*
I've checked everything I can think of, but now when I print out my triangles I get:
triangle0 is ( 0, 0, -1) (-0.5, -0.866025, 0) (-0.5, -0.866025, 0)
triangle1 is ( 0, 0, -1) (-0.5, -0.866025, 0) (-0.5, -0.866025, 0)
triangle2 is ( 0, 0, -1) (-0.5, -0.866025, 0) (-0.5, -0.866025, 0)

Does anyone have any idea what could be going wrong?!
EDIT
The vector_point variables on the triangle are pointers, and are set like:
void set_vector_point1(SurfaceVector vector_point) { vector_point1 = &vector_point; }

A: There lies your problem:
void set_vector_point1(SurfaceVector vector_point) { vector_point1 = &vector_point; }

You are pointing to a temporary (vector_point ceases to exist once the function call completes). Change it so you copy SurfaceVector properly.

A: I'd change:
void set_vector_point1(SurfaceVector vector_point) { vector_point1 = &vector_point; }

to
void set_vector_point1(SurfaceVector& vector_point) { vector_point1 = &vector_point; }

Or something like that.
In the current version vector_point will be a copy of whatever you pass, and will no longer exist after, you're storing a pointer to an object that no longer exists.
In the second one, vector_point is a reference to a longer lived object external to the function. Storing a pointer to that is fine as the object will still be there when you use the pointer.
The trick is to make sure the object lives longer than all the pointers to it.
ADDITION:
Thanks @Nim in the below comment:
Also in the for loop where the line is:
SurfaceVector current_anchor = vector_anchors[1 + longitude];

That should probable be a reference too .. at the moment it too is a copy. That way you'll be editing the actual objects in the array, rather than playing around with copies and throwing them away. So I would change that line to:
SurfaceVector& current_anchor = vector_anchors[1 + longitude];


text:
Q: UITextView becomes unselectable when using textstorage with textcontainer in iOS I am trying to display NSAttributedString to UITextView. I have used NSTextStorage, NSLayoutManager and NSTextContainer. But what happens is UITextView becomes unselectable. When i try to select , i can't find any selection or copy - paste options.
I have given textview.selectable=YES
I have used multiple textviews with same textstorage. Is that the reason for this problem ?? Or do I have to enable anything else ???

A: solved that issue myself !!!!
I believe its the problem when we use same storage and different UITextViews ie. splitting content to different textviews. I didnt find any solution for that.
I solved it by omitting storage, container, & layout manager and by implementing the same features by  other way.


text:
Q: Unable to cast object of type 'System.String' to type 'Microsoft.SharePoint.SPFieldUserValue' I want to get the user value from the Person or Group column in code behind.
My code is:
List<string> manager = GeneralMethods.GetUsers((SPFieldUserValueCollection)item[FieldNames.Manager]);
List<string> owner = GeneralMethods.GetUsers((SPFieldUserValueCollection)item[FieldNames.ProjectOwner]);

The method code is:
        public static List<string> GetUsers(SPFieldUserValueCollection users)
    {
        List<string> listUsers = new List<string>();

        if (users.Count != 0)
        {
            foreach (SPFieldUserValue field in users)
            {
                SPUser user = field.User;
                listUsers.Add(user.LoginName);
            }
        }

        return listUsers;
    }

My problem is that manager assigned successfully but when the control comes to owner then the above mentioned error is thrown. Here the item[FieldNames.ProjectOwner]) is the person or group column which accepts single value only.
What am I missing?

A: I wouldn't cast the field directly in a SPFieldUserValueCollection. Try this:
public List<string> GetUser(string fieldName, SPListItem item)
{
    List<string> listUsers = new List<string>();
    string strUserColl = item[fieldName].ToString();
    if (strUserColl != null)
    {
        SPFieldUserValueCollection usercollection = new SPFieldUserValueCollection(web, strUserColl);
        if (usercollection != null)
        {
            foreach (SPFieldUserValue userValue in usercollection)
            {
                 SPUser user = userValue.User;
                 listUsers.Add(user.LoginName);
            }
        }
    }
    return listUsers;
}

If you want to initialize a SPFieldUserValueCollection object that is bases on a field value, you should use this constructor. See Msdn: SPFieldUserValueCollection(SPWeb,string)

A: Verify that user.LoginName for the project owner returns a string in format ID;#USERACCOUNT. E.g., 34;#domain\user. ID being the Id of the user in this site collection's hidden User Information List.
If it only has a single value, you probably cannot cast it to a collection.

A: Can you give this code a try. I haven't tested it though:
UPDATE
Perhaps there is no value in the field. Check for the null condition as shown below:
SPFieldUserValue owner = item[FieldNames.ProjectOwner] as SPFieldUserValue;
if (null != owner)
{
   SPUser user = owner.User;
   string ownerLogin = user.LoginName
}


text:
Q: Swift variable not holding value or resetting itself somehow I am trying to keep score in a game which has different point values associated with different things. The user has to touch things in the game to get the points. However the score is not being calculated accurately.
I have determined that the score associated which each element in the game is being stored properly in a variable called ballValue. The variable currentScore is used to hold the score and then I'm using a SKLabelNode to display the value of currentScore.
currentScore is initialized with a value of 0 and is updated with its current value plus ballValue when a user touches a ball.
Update to show code and context
class ChallengeScene: SKScene, GKGameCenterControllerDelegate {

    // MARK: Ball Data
    var randomBallType : Int = 0
    var ballValue : Int = 0

    // MARK: HUD
    var scoreLabel = SKLabelNode(fontNamed: "Impact")
    var timeLabel = SKLabelNode(fontNamed: "Impact")

    var currentScore : Int = 0 {
        didSet {
            self.scoreLabel.text = "\(self.currentScore)"
            GameHandler.sharedInstance.score = currentScore
        }
    }

    // MARK: Initial Setup
    func createHUD() {
    ... UNRELATED HUD STUFF...
        currentScore = 0
    }

    // MARK: Gameplay Setup
    func createBall(forTrack track: Int) {
        setupTracks()

        randomBallType = GKRandomSource.sharedRandom().nextInt(upperBound: 9)

        switch randomBallType {
        case 0:
            player = SKSpriteNode(imageNamed: "blueOne")
            ballSpeed = 0.008
            ballValue = 1
        case 1:
            player = SKSpriteNode(imageNamed: "minusThree")
            ballSpeed = 0.008
            ballValue = -3
        case 2:
            player = SKSpriteNode(imageNamed: "minusFive")
            ballSpeed = 0.008
            ballValue = -5
        case 3:
            player = SKSpriteNode(imageNamed: "purpleThree")
            ballSpeed = 0.008
            ballValue = 3
        case 4:
            player = SKSpriteNode(imageNamed: "greenFive")
            ballSpeed = 0.008
            ballValue = 5
        case 5:
            player = SKSpriteNode(imageNamed: "blackTen")
            ballSpeed = 0.008
            ballValue = 10
        default:
            player = SKSpriteNode(imageNamed: "blueOne")
            ballSpeed = 0.008
            ballValue = 1
        }

        player?.name = "BALL"
        player?.size = CGSize(width: 100, height: 100)
        player?.physicsBody?.linearDamping = 0

        ...UNRELATED BALL STUFF...

        self.addChild(player!)
    }

    // MARK: Overrides
    override func didMove(to view: SKView) {

        createHUD()
        launchGameTimer()

        self.run(SKAction.repeatForever(SKAction.sequence([SKAction.run {
            self.createBall(forTrack: self.track)
            }, SKAction.wait(forDuration: 1)])))

    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let location = touch.location(in: self)
            let node = self.nodes(at: location).first

            if node?.name == "BALL" {
                currentScore = currentScore + ballValue
                node?.removeFromParent()
            }
        }

    }

    override func update(_ currentTime: TimeInterval) {

        // GAME TIMER RELATED STUFF

    }
}

I think I know where the problem happens (in the touches override), I just don't understand why it is happening. If you could help in anyway that would be awesome

A: You have a single ballValue property. Every time you spawn a new ball, you set ballValue as appropriate for that newly-created ball. What about all the other existing balls? A touch on any of them will also be worth that same ballValue.
When a ball is touched, you need to know the proper value for the touched ball, which may be different than the value of the most-recently-created ball. What you probably want to do is create a subclass of SKSpriteNode that represents a ball, and holds its own value:
class BallNode: SKSpriteNode {
    let value: Int

    init(imageName: String, speed: CGFloat, value: Int) {
        let texture = SKTexture(imageNamed: imageName)
        self.value = value
        super.init(texture: texture, color: .init(white: 1, alpha: 0), size: texture.size())
        self.speed = speed
    }

    required init(coder decoder: NSCoder) { fatalError() }
}

Create the balls like this:
func createBall(forTrack track: Int) {

//        setupTracks()
    randomBallType = GKRandomSource.sharedRandom().nextInt(upperBound: 9)

    let ball: BallNode
    switch randomBallType {
    case 0: ball = BallNode(imageNamed: "blueOne", speed: 0.008, value: 1)
    case 1: ball = BallNode(imageNamed: "minusThree", speed: 0.008, value: -3)
    case 2: ball = BallNode(imageNamed: "minusFive", speed: 0.008, value: -5)
    // etc.
    }

    ball.name = "BALL"
    ball.size = CGSize(width: 100, height: 100)
    ball.physicsBody?.linearDamping = 0

    // ...UNRELATED BALL STUFF...

    self.addChild(ball)
}

Then, to handle a touch, use the touched ball's value to update the score:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: self)
        if let ball = self.nodes(at: location).flatMap({ $0 as? BallNode }).first {
            currentScore += ball.value
            ball.removeFromParent()
        }
    }
}


text:
Q: "Expect" usage and subjunctive in English Can I write

*

*"We expect from you that by the end of the program you would have learned to…"

or

*"We expect from you that by the end of the program you will learn to…"

Thanks everybody. It seems that keeping the infinitive in the best By the end of the program we expect you to have learned _______ and then infinitive, Practical English Usage Michael Swan

A: The former is correct, however, the latter is incorrect.
Having said "you will learn to" subsequent to saying "by the end of the program" is not correct, as you have rendered the former phrase dependent on the latter and therefore it can precede the latter. Saying, "by the end..." specifies the following action should have already been completed therefore must be in the past tense. You could, however, say, "we expect from you that by the end of the program you will have learned to...."


text:
Q: SQL server table locking and unlocking issue I have a very interesting problem.
I have a table where I have data, like this:
DVDSerialNumbers(ID, Create_Date, SerialNumber, CategoryID)
My application generates serial numbers for DVD's and I have a SQL command like this (issued by my application):
ExecuteQuery("select top {0} SerialNumber from DVDSerialNumbers where CategoryID = {1};" &
"delete from DVDSerialNumbers where ID in (select top{0} ID from DVDSerialNumber where " &
 "CategoryID = {1});", n, CategoryID)

ExecuteQuery returns the result of my select query but the delete command is executed too.
Basically I get no more than n SerialNumbers which have the given CategoryID and I delete their rows.
However, here I have a concurency problem.
If the code above runs twice in the same time, it's possible that the results will be the same, however, the idea is to get a given SerialNumber from the table only once.
How can I make instance B to wait for instance A to finish this command? Should I lock the table? Or should I lock some rows? Or is there a better solution?
Thanks in advance for your help.

A: You need READPAST, UPDLOCK, ROWLOCK hints. See this for more: SQL Server Process Queue Race Condition
Then you'd need a transaction for the SELECT/DELETE. Instead, you can do this in one statement with an OUTPUT clause
ExecuteQuery("delete top ({0})
                  DVDSerialNumbers WITH (READPAST, UPDLOCK, ROWLOCK)
              OUTPUT DELETED.SerialNumber
              where CategoryID = {1}" &
                , n, CategoryID)


text:
Q: Why doesn't my oData response have navigation properties If you look at the following sample oData feed you'll see included navigation properties for 'child' items to tell you which URL to follow:

http://services.odata.org/OData/OData.svc/Suppliers?$format=json

For example supplier 0 has a navigation property to products.
This links to a list of products for that supplier.

http://services.odata.org/OData/OData.svc/Suppliers(0)/Products?$format=json

I'm trying to do the same with ODataConventionModelBuilder and EntitySetController<Product> so that when I request oData/Product(0) it will show me the 'features' for the product:
I create my model like this (based on GetImplicitEdmModel sample)
     // odata
     ODataModelBuilder modelBuilder = new ODataConventionModelBuilder();
     modelBuilder.EntitySet<RRStoreDB.Models.Product>("Product");
     modelBuilder.EntitySet<RRStoreDB.Models.ProductFeature>("ProductFeature");

     Microsoft.Data.Edm.IEdmModel model = modelBuilder.GetEdmModel();
     config.Routes.MapODataRoute("ODataRoute", "odata", model);

I create a controller for WebAPI :
public class  ProductController : EntitySetController<Product, int>
{
    RRStoreDBContext _db = new RRStoreDBContext();

    [Queryable]
    public override IQueryable<DProduct> Get()
    {
        return _db.Products.AsQueryable();
    }

    public ICollection<ProductFeature> GetProductFeatures(int key)
    {
        Product product = _db.Products.FirstOrDefault(p => p.ProductId == key);
        if (product == null)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
        return product.ProductFeatures;
    }
}

When I actually call the URL for my child property it works and gives me the correct list of features :
 /oData/Products(18)/ProductFeatures

However I would have expected a navigation property in /oData/Products(18) pointing to this.
What do I need to do to get this to appear. This article says it's automatic but I'm not seeing them:

The ODataConventionModelBuilder, which is generally recommended over
  the ODataModelBuilder, will automatically infer inheritance
  hierarchies in the absence of explicit configuration. Then once the
  hierarchy is inferred, it will also infer properties and navigation
  properties too. This allows you to write less code, focusing on where
  you deviate from our conventions.

A: I think the problem is that you are asking for application/json. application/json in web API OData points to json light which is the latest OData json representation aimed at reducing response payload sizes and trimming the un-necessary/redundant metadata from the response. For comparison, try getting the url ~/oData/Products(18) with accept header application/json;odata=verbose.
Now, the idea behind json light is that if a link can be calculated because the link follows conventions, it will not be put in the response. The navigation link /oData/Products(18)/ProductFeatures is a perfect example of that. It follows OData uri conventions.
OData json light has 3 modes, minimalmetadata (the default), fullmetadata and nometadata. The names are themselves explanatory. If you want the link to be on the wire, send the request with accept header application/json;odata=fullmetadata.
Refer to this document to understand more about json light.