text:
Q: How to manage pytests' `tests` folder name collision with jupyter extensions I'm in the process of writing unit tests for my software.
I wrote some helpers for my tests. For convenience I would like to use them in a jupyter notebook.
When I try to import them inside of the notebook though, I get an error.
from tests import helpers

->
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-12-d8ba72c24738> in <module>
----> 1 from tests.helpers import some_helper

ModuleNotFoundError: No module named 'tests.helpers'

Digging a little, I found out that importing tests actually imports this folder as a module:
 '/my_project_path/.venv/lib/python3.8/site-packages/IPython/extensions/tests'

The folder contains test_autoreload.py and test_storemagic.py, which are tests for extensions I use.
Here's my question, how do I properly manage this conflict? I would like to keep those extension installed, and I would like to keep the name tests for my folder, as it is the convention when working with pytest.
I installed those extensions with pip. Did I miss an option to ignore the tests when installing or something?
Thanks! :)

A: Not really a solution but some hints here in case they help you:
I was having the same issue today and getting a bit crazy. Not in jupyter but int the ipyton shell. As jupyter uses ipython I guess it will be the same issue.
IPython has a module called tests
within the IPython/extensions folder, and this folder is added is added to the search path when using ipython instead of python.
This are my paths from a python shell (using sys.path):
['',
 '/usr/local/lib/python37.zip',
 '/usr/local/lib/python3.7',
 '/usr/local/lib/python3.7/lib-dynload',
 '/usr/local/lib/python3.7/site-packages']

And the ones from an ipython shell:
['/usr/local/bin',
 '/usr/local/lib/python37.zip',
 '/usr/local/lib/python3.7',
 '/usr/local/lib/python3.7/lib-dynload',
 '',
 '/usr/local/lib/python3.7/site-packages',
 '/usr/local/lib/python3.7/site-packages/IPython/extensions',
 '/home/dmontaner/.ipython']

So, if your are in iptyhon or in a notebook and you import tests or from tests import something, the interpreter will search in:
'/usr/local/lib/python3.7/site-packages/IPython/extensions'

So far all is as expected. But I also had as you my own tests module in the same directory where my ipython session was running. What should happen then is that my own tests module should be imported first. But it was not and I had the same error as you.
If I would remove the 'IPython/extensions' from the path doing sys.path.remove(.../IPython/extensions') then I was able to import my own module.
I did uninstall ipyton and ipython_genutils and, using python -m pytest in the command line (on a .py file, not a notebook) I was still having a slightly similar issue this time about dash trying to load the IPython. The weird thing is that in my project I am not using dash but flask and dash is not a dependency of pytest anyway I think.
So, I uninstalled ipyton, ipython_genutils, dash and plotly and then I could run pytest importing from my own tests module.
I reinstalled the 4 libraries again and the problem was solved! And now I can import from my tests module even from within a jupyter notebook.
I guess the message is that there is some buggy setup or dependency among all those libraries (and may be some others). Try to reinstall latest versions or recreate your virtual environment in case it helps.
Sorry that I could not figure out what was the exact problem... but I hope this helps you.

A: The long-term fix for these kind of naming conflicts is to put all your code, including your test code, into a project package, such that you imports look like
import my_project.tests.helpers instead of import tests.helpers.
By choosing a unique name for your project, you define your own namespace and avoid naming conflicts.


text:
Q: User Profiles email property not getting updated in SharePoint We have SharePoint 2013 on-premise site, where users from "ABC" AD domain are accessing the site. Now some of the users got new account and email on "XYZ" domain, but still they are part of "ABC" domain to access our site but email has been terminated.
Now our AD administrator changed there email from name@abc.com to name@xyz.com in our AD "ABC". But this email is not getting updated in SharePoint User profile and still it shows old email id. And hence no mail goes to them.
This issue is occuring for existing users only. If any new users get added and they put email id as name@xyz.com it is comhing in sharepoint.

A: This is due to the site collection users list, which is where this info is stored.  There are two timer jobs that control this:

"User Profile Service Application Name" - User Profile to SharePoint Full Synchronization
"User Profile Service Application Name" - User Profile to SharePoint Quick Synchronization
Where "User Profile Service Application Name" is the name of the user profile service application.  The full runs hourly, the quick every 5 minutes.  They require information about the user to be correct in the user profile store.  I would be that is where your issue lies.  The reason it works for new users added is because people picker is resolving the user info real-time from AD and not the user profile service application.  Then once you select them and they login to the site, they are added to site collection users.  Once they are added to the site collections users, that info is used instead.  You can view the site collection users by looking a group id 0 on the site collection (easiest way to do this is open a group, then change the ID to 0 in the URL, and press enter of course).
A fix outside of user profile service application is deleting the users from the site collection users list and adding them again (slow, tedious and you need to make sure you add them to the right group(s) again).

A: Profiles are first imported via User Profile Synchronization which is part of the User Profile Service Application. Then, a scheduled timer job is supposed to sync the latest updated profile data to each site collection.
Each site collection stores a copy of the user profile information in it's User list. I believe if a user logs in and the user's profile information is not in the user list, it is added to the list with data pulled from the Service App profile database or AD.
You can manually run the "stsadm -o sync" command to tell SharePoint to run the synchronization script that synchronizes the site collection user list data with the user profile data from the shared services provider.
Note: If you continue to have issues, it is possible to delete the individual user's profile information for the particular site. However, not recommended.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Passenger process already running? but its not Trying to start passenger standalone with passenger start -p 80 and it's saying its already running but when i do a passenger stop -p 80i getAccording to the PID file '/var/crm/tmp/pids/passenger.80.pid', Phusion Passenger Standalone doesn't seem to be running.
But it clearly is not because when i try stop it, it says its not running and i cant access it from the web
[root@technetium crm]# passenger start -p 80
*** ERROR ***
The address 0.0.0.0:80 is already in use by another process, perhaps another
Phusion Passenger Standalone instance.

If you want to run this Phusion Passenger Standalone instance on another port,
use the -p option, like this:

  passenger start -p 81

A: try running lsof or netstat -tlnp | grep 80 to determine which application is using port 80. Once you have that figured out you can do something like ps -elf to kill that process.


text:
Q: Reducing SQL code in ms access using a loop I want to automize a SQL query in MS Access. I am new to vba and it would be great if someone can help me with my problem:
I need to generate a list for my company with each employee who has worked for a specific team. Each team gets a list that includes the working hours that have been done for a specific project. Here is the sql-code for one team:
SELECT
    Sum(b.Stunden) AS Gesamtstunden,
    b.Mitarbeiter, b.Leistungen.Kostengefäss_ID,
    Team.Teamleader, b.Positionen.Position_ID, b.Positionen.Art
FROM
    (SELECT *
     FROM
          (SELECT *
           FROM Leistungen
           INNER JOIN Kostengefässe ON Leistungen.Kostengefäss_ID = Kostengefässe.Kostengefäss_ID) AS a
     INNER JOIN
         Positionen ON a.Position_ID = Positionen.Position_ID) AS b
INNER JOIN
    Team ON b.Team_ID = Team.Team_ID
WHERE
    (((b.Mitarbeiter) = 'HBI') AND (Team.Team_ID) = '2_RR1')
GROUP BY
    b.Mitarbeiter, b.Leistungen.Kostengefäss_ID, Team.Teamleader,
    b.Positionen.Position_ID, b.Positionen.Art

UNION

SELECT
    Sum(b.Stunden) AS Gesamtstunden,
    b.Mitarbeiter, b.Leistungen.Kostengefäss_ID, Team.Teamleader,
    b.Positionen.Position_ID, b.Positionen.Art
FROM
    (SELECT *
     FROM
         (SELECT *
          FROM Leistungen
          INNER JOIN Kostengefässe ON Leistungen.Kostengefäss_ID = Kostengefässe.Kostengefäss_ID) AS a
     INNER JOIN
         Positionen ON a.Position_ID = Positionen.Position_ID) AS b
INNER JOIN
    Team ON b.Team_ID = Team.Team_ID
WHERE
    (((b.Mitarbeiter) = 'LBR') AND (Team.Team_ID) = '2_RR1')
GROUP BY
    b.Mitarbeiter, b.Leistungen.Kostengefäss_ID, Team.Teamleader,
    b.Positionen.Position_ID, b.Positionen.Art

UNION

SELECT
    Sum(b.Stunden) AS Gesamtstunden,
    b.Mitarbeiter, b.Leistungen.Kostengefäss_ID, Team.Teamleader,
    b.Positionen.Position_ID, b.Positionen.Art
FROM
    (SELECT *
     FROM
         (SELECT *
          FROM Leistungen
          INNER JOIN Kostengefässe ON Leistungen.Kostengefäss_ID = Kostengefässe.Kostengefäss_ID) AS a
     INNER JOIN
         Positionen ON a.Position_ID = Positionen.Position_ID) AS b
INNER JOIN
    Team ON b.Team_ID = Team.Team_ID
WHERE
    (((b.Mitarbeiter) = 'PJO') AND (Team.Team_ID) = '2_RR1')
GROUP BY
    b.Mitarbeiter, b.Leistungen.Kostengefäss_ID, Team.Teamleader,
    b.Positionen.Position_ID, b.Positionen.Art

As you can see, I have multiple queries which I unite using the UNION. I want to reduce these queries using a loop for one single sql with the employee as a variable and loop through all employees. Any ideas?

A: You can simply use the IN condition instead of '='.
SELECT Sum(b.Stunden) AS Gesamtstunden, b.Mitarbeiter, b.Leistungen.Kostengefäss_ID, Team.Teamleader, b.Positionen.Position_ID, b.Positionen.Art
FROM (SELECT * FROM (SELECT * FROM Leistungen INNER JOIN Kostengefässe ON Leistungen.Kostengefäss_ID = Kostengefässe.Kostengefäss_ID)  AS a INNER JOIN Positionen ON a.Position_ID = Positionen.Position_ID)  AS b INNER JOIN Team ON b.Team_ID = Team.Team_ID
WHERE (((b.Mitarbeiter) in('HBI','LBR','PJO')) And (Team.Team_ID)='2_RR1')
GROUP BY b.Mitarbeiter, b.Leistungen.Kostengefäss_ID, Team.Teamleader, b.Positionen.Position_ID, b.Positionen.Art

Your code was hard to read, so I hope I saw all the differences between those 3 queries ('HBI','LBR','PJO')?
BTW - you use a lot of unnecessary '()'


text:
Q: PNG Graphics won't display in LaTeX I have trouble with graphics in LaTeX. I am using Kil under ubuntu.
I first tried including .png images, then got the classic no bounding box error.
When I switched to .eps, I got no errors but no images in the input!
Included graphics package:
 \usepackage{graphicx}

And used a simple:
\includegraphics{figures/arch2.eps}

A: you must include the package \usepackage{epstopdf}

A: This error is normal if you use latex for conversion, so I'm almost sure you're not using pdftex for conversion, as you should if you want to insert  figures other than eps.


text:
Q: Is there a way to get the SOQL behind a report? I have a (reasonably) Year on Year analysis summary report that I use in Salesforce and I would like to create this report in SOQL or at least create the SOQL equivelant to return the same results, short of building the SOQL statement myself, I want to know is there a way of finding the SOQL behind any particular report in Salesforce?

A: There is no way to obtained this, I doubt even Salesforce actually uses SOQL inside the reporting engine. To get a better developer perspective on the report definition you could use the Force.com IDE tool to download the report (which uses the Metadata API). I've heard of some off platform solutions using this information to parse the report and generate queries SOQL (though its doubtful all report definitions can be supported via SOQL). In the future we will see the advent of the Analytics API (first from REST, then Apex) that will allow an API into the reporting engine!


text:
Q: Extracting data from JSON column defined as String A table has a ports column (defined as VARCHAR) which has the following data:

[{u'position': 1, u'macAddress': u'00:8C:FA:C1:7C:88'}, {u'position':
2, u'macAddress': u'00:8C:FA:5E:98:81'}]

I want to extract the data from just the macAddress fields into separate rows. I tried to flatten the data in Snowflake but it is not working as the column is not defined as VARIANT and the the fields have a 'u' in front of them (this is my guess).
00:8C:FA:C3:7C:84
00:5C:FA:7E:98:87

Could someone please help with the requirement.

A: The provided JSON is not a valid JSON but it is possible to treat it as one with text operations and PARSE_JSON:
SELECT s.value:macAddress::TEXT AS macAddress
FROM t
,LATERAL FLATTEN(INPUT => PARSE_JSON(REPLACE(REPLACE(col, 'u''', ''''), '''', '"')))
                 AS s;

For input:
CREATE OR REPLACE TABLE t(col TEXT)
AS
SELECT $$[{u'position': 1, u'macAddress': u'00:8C:FA:C1:7C:88'}, {u'position': 2, u'macAddress': u'00:8C:FA:5E:98:81'}]$$;

Output:


text:
Q: Repmat function in matlab I have been through a bunch of questions about the Repeat function in MatLab, but I can't figure out how this process work.
I am trying to translate it into R, but my problem is that I do not know how the function manipulates the data.
The code is part of a process to make a pairs trading strategy, where the code takes in a vector of FALSE/TRUE expressions.
The code is:
% initialize positions array
positions=NaN(length(tday), 2);

% long entries
positions(shorts, :)=repmat([-1 1], [length(find(shorts)) 1]);

where shorts is the vector of TRUE/FALSE expressions.
Hope you can help.

A: repmat repeats the matrix you give him [dim1 dim2 dim3,...] times. What your code does is:
1.-length(find(shorts)): gets the amount of "trues" in shorts.
e.g:
shorts=[1 0 0 0 1 0]
length(find(shorts))
ans = 2

2.-repmat([-1 1], [length(find(shorts)) 1]); repeats the [-1 1] [length(find(shorts)) 1] times.
continuation of e.g.:
repmat([-1 1], [length(find(shorts)) 1]);
ans=[-1 1
     -1 1];

3.- positions(shorts, :)= saves the given matrix in the given indexes. (NOTE!: only works if shorts is of type logical).
continuation of e.g.:
At this point, if you haven't omit anything, positions should be a 6x2 NaN matrix. the indexing will fill the true positions of shorts with the [-1 1] matrix. so after this, positions will be:
positions=[-1 1
           NaN NaN
           NaN NaN
           NaN NaN
           -1 1
           NaN NaN]

Hope it helps

A: The MATLAB repmat function replicates and tiles the array. The syntax is
B = repmat(A,n)

where A is the input array and n specifies how to tile the array. If n is a vector [n1,n2] - as in your case - then A is replicated n1 times in rows and n2 times in columns. E.g.
A = [ 1 2 ; 3 4]
B = repmat(A,[2,3])

B =           |           |
     1     2     1     2     1     2
     3     4     3     4     3     4   __
     1     2     1     2     1     2
     3     4     3     4     3     4

(the lines are only to illustrate how A gets tiled)
In your case, repmat replicates the vector [-1, 1] for each non-zero element of shorts. You thus set each row of positions, whos corresponding entry in shorts is not zero, to [-1,1]. All other rows will stay NaN.
For example if
shorts = [1; 0; 1; 1; 0];

then your code will create
positions =
          -1    1
          NaN   NaN
          -1    1
          -1    1
          NaN   NaN

I hope this helps you to clarify the effect of repmat. If not, feel free to ask.


text:
Q: Unexpected behavior of matplotlib.patches upon window resizing I am working on a Python 3.4 application for displaying power spectral density graphs for EEG signals. I want to superimpose color patches on the graphs to indicate standard frequency bands for delta, theta, alpha, beta and gamma.
The skeleton program below shows how a graph appears in a popup window when the Display button is pressed. Everything is fine when resizing the first popup. The problem occurs when resizing a second popup window (by clicking on the Display button a second time). Then, color patches appear at incorrect locations and do not correspond to the indicated frequency bands.
import tkinter as tk
from tkinter import BOTH, TOP, Y
from tkinter import ttk
from tkinter import Frame
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg

# The following is used for psd semi-log graphs only
XMIN = 0 # minimum frequency
XMAX = 55 # maximum frequency
YMIN = 0.1 # minimum PSD value
YMAX = 100 # maximum PSD value
lblY = YMAX - 30

band_patches = [
    patches.Rectangle((XMIN, YMIN), 4, YMAX, facecolor="blue", alpha=0.2),
    patches.Rectangle((4, YMIN), 4, YMAX, facecolor="cyan", alpha=0.2),
    patches.Rectangle((8, YMIN), 4, YMAX, facecolor="green", alpha=0.2),
    patches.Rectangle((12, YMIN), 18, YMAX, facecolor="orange", alpha=0.2),
    patches.Rectangle((30, YMIN), XMAX-30, YMAX, facecolor="magenta", alpha=0.2),
]

class PV(ttk.Frame):

    def __init__(self, name='demo'):
        ttk.Frame.__init__(self, name=name)
        self.pack(expand=Y, fill=BOTH)
        self.master.title('Demo')
        self._create_viewer_panel()

    def _create_viewer_panel(self):
        viewerPanel = Frame(self, name='pv')
        viewerPanel.pack(side=TOP, fill=BOTH, expand=Y)
        # create the notebook
        nb = ttk.Notebook(viewerPanel, name='notebook')
        nb.enable_traversal()
        nb.pack(fill=BOTH, expand=Y, padx=2, pady=3)
        self._create_UI_tab(nb)  #NEW

    def _create_UI_tab(self, nb):
        # frame to hold contentx
        self.frame = ttk.Frame(nb, height='10i', width='8i', name='main')
        btn0 = ttk.Button(self.frame, text='Display', width='25', command=self.draw_psd)
        btn0.grid(row=0, column=1)
        # add to notebook (underline = index for short-cut character)
        nb.add(self.frame, text='Main', underline=0, padding=2)

    def draw_psd(self):
        popup = tk.Tk()
        popup.geometry('720x480') # Set dimensions of popup window to 800x500 pixels
        popup.wm_title("Power Spectral Density")
        p = plt.figure()
        self.ax = plt.subplot(111)

        box = self.ax.get_position()
        self.ax.set_position([box.x0, box.y0, box.width, box.height*0.95])

        self.ax.set_yscale('log')
        self.ax.set_xscale('linear')
        plt.xlabel('Frequency (Hz)')
        plt.xlim(XMIN, XMAX)
        plt.ylim(YMIN, YMAX)
        for ptch in band_patches:
            self.ax.add_patch(ptch)
        self.ax.annotate('delta', xy=(2,lblY), fontsize=10, color=None, horizontalalignment='center')
        self.ax.annotate('theta', xy=(6,lblY), fontsize=10, color=None, horizontalalignment='center')
        self.ax.annotate('alpha', xy=(10,lblY), fontsize=10, color=None, horizontalalignment='center')
        self.ax.annotate('beta', xy=(21,lblY), fontsize=10, color=None, horizontalalignment='center')
        self.ax.annotate('gamma', xy=(42,lblY), fontsize=10, color=None, horizontalalignment='center')

        plt.show()

        canvas = FigureCanvasTkAgg(p, master=popup)
        canvas.show()
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        toolbar = NavigationToolbar2TkAgg(canvas, popup)
        toolbar.update()
        canvas._tkcanvas.pack(side=tk.TOP, expand=1)

        popup.mainloop()
        return None

if __name__ == '__main__':
    PV().mainloop()

I suspect that it's a problem with initializing coordinates but I'm at a loss as to how to fix it. Any suggestions?

A: It looks like you have to redefine the patches for each new plot - in order
for their "transforms" to work properly.
You should only have one Tk instance per application. For secondary windows
use Toplevel.
Also, when you're embedding matplotlib into a tkinter application, it's
best to avoid the so-called "pyplot interface" - plt.show() etc. Instead,
use the matplotlib API explicitly: plt.xlabel(...) -> ax.set_xlabel(...)
import tkinter as tk
from tkinter import BOTH, TOP, Y
from tkinter import ttk
from tkinter import Frame, Toplevel
##import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg

XMIN = 0 # minimum frequency
XMAX = 55 # maximum frequency
YMIN = 0.1 # minimum PSD value
YMAX = 100 # maximum PSD value
lblY = YMAX - 30

##band_patches = [
##    patches.Rectangle((XMIN, YMIN), 4, YMAX, facecolor="blue", alpha=0.2),
##    patches.Rectangle((4, YMIN), 4, YMAX, facecolor="cyan", alpha=0.2),
##    patches.Rectangle((8, YMIN), 4, YMAX, facecolor="green", alpha=0.2),
##    patches.Rectangle((12, YMIN), 18, YMAX, facecolor="orange", alpha=0.2),
##    patches.Rectangle((30, YMIN), XMAX-30, YMAX, facecolor="magenta", alpha=0.2),
##]

class WinPsd(Toplevel):
    def __init__(self, master, cnf={}, **kw):
        Toplevel.__init__(self, master, **kw)
        self._create_plot()

    def _create_plot(self):
        self.fig = Figure()
        self.ax = self.fig.add_subplot(111)

        ax = self.ax
        box = ax.get_position()
        ax.set_position([box.x0, box.y0, box.width, box.height*0.95])

        ax.set_yscale('log')
        ax.set_xscale('linear')

        ax.set_xlabel('Frequency (Hz)')
        ax.set_xlim(XMIN, XMAX)
        ax.set_ylim(YMIN, YMAX)

        band_patches = [
                        patches.Rectangle((XMIN, YMIN), 4, YMAX,
                                          facecolor="blue", alpha=0.2
                                          ),
                        patches.Rectangle((4, YMIN), 4, YMAX,
                                          facecolor="cyan", alpha=0.2
                                          ),
                        patches.Rectangle((8, YMIN), 4, YMAX,
                                          facecolor="green", alpha=0.2
                                          ),
                        patches.Rectangle((12, YMIN), 18, YMAX,
                                          facecolor="orange", alpha=0.2
                                          ),
                        patches.Rectangle((30, YMIN), XMAX-30, YMAX,
                                          facecolor="magenta", alpha=0.2
                                          ),
                       ]

        for ptch in band_patches:
            ax.add_patch(ptch)
        ax.annotate('delta', xy=(2,lblY), fontsize=10, color=None, horizontalalignment='center')
        ax.annotate('theta', xy=(6,lblY), fontsize=10, color=None, horizontalalignment='center')
        ax.annotate('alpha', xy=(10,lblY), fontsize=10, color=None, horizontalalignment='center')
        ax.annotate('beta', xy=(21,lblY), fontsize=10, color=None, horizontalalignment='center')
        ax.annotate('gamma', xy=(42,lblY), fontsize=10, color=None, horizontalalignment='center')

        xdata,ydata = [],[]
        self.line, = ax.plot(xdata, ydata)

        canvas = FigureCanvasTkAgg(self.fig, master=self)

        toolbar = NavigationToolbar2TkAgg(canvas, self)
        toolbar.update()
        canvas._tkcanvas.pack(fill='both', expand=1)
        canvas.show()

    def draw(self, xdata, ydata):
        self.line.set_xdata(xdata)
        self.line.set_ydata(ydata)
        self.fig.canvas.draw()

class WinMain(tk.Tk):
    def __init__(self, name='demo', **kw):
        tk.Tk.__init__(self, **kw)
        self.title(name)
        self._create_viewer_panel()

    def _create_viewer_panel(self):
        viewerPanel = ttk.Frame(self, name='pv')
        viewerPanel.pack(side=TOP, fill=BOTH, expand=Y)
        nb = ttk.Notebook(viewerPanel, name='notebook')
        nb.enable_traversal()
        nb.pack(fill=BOTH, expand=Y, padx=2, pady=3)
        self._create_UI_tab(nb)

    def _create_UI_tab(self, nb):
        self.frame = ttk.Frame(nb, height='10i', width='8i', name='main')
        btn0 = ttk.Button(self.frame, text='Display', width='25', command=self.show_psd)
        btn0.grid(row=0, column=1)
        nb.add(self.frame, text='Main', underline=0, padding=2)

    def show_psd(self):
        xdata,ydata = [range(50)],[range(50)] #get some data from somewhere
        popup = WinPsd(self)
        popup.wm_title("Power Spectral Density")
        popup.draw(xdata, ydata)

if __name__ == '__main__':
    WinMain().mainloop()


text:
Q: How is the storage associated with std::future allocated? One way to get a std::future is through std::async:
int foo()
{
  return 42;
}

...

std::future<int> x = std::async(foo);

In this example, how is the storage for x's asynchronous state allocated, and which thread (if more than one thread is involved) is responsible for performing the allocation? Moreover, does a client of std::async have any control over the allocation?
For context, I see that one of the constructors of std::promise may receive an allocator, but it's not clear to me if it is possible to customize the allocation of the std::future at the level of std::async.

A: The memory is allocated by the thread that calls std::async, and you have no control over how it is done. Typically it will be done by some variant of new __internal_state_type, but there is no guarantee; it may use malloc, or an allocator specifically chosen for the purpose.
From 30.6.8p3 [futures.async]:

"Effects: The first function behaves the same as a call to the second function with a policy argument of launch::async | launch::deferred and the same arguments for F and Args. The second function creates a shared state that is associated with the returned future object. ..."

The "first function" is the overload without a launch policy, whilst the second is the overload with a launch policy.
In the case of std::launch::deferred, there is no other thread, so everything must happen on the calling thread. In the case of std::launch::async, 30.6.8p3 goes on to say:

— if policy & launch::async is non-zero — calls INVOKE (DECAY_COPY (std::forward<F>(f)), DECAY_COPY (std::forward<Args>(args))...) (20.8.2, 30.3.1.2) as if in a new thread of execution represented by a thread object with the calls to DECAY_COPY () being evaluated in the thread that called async. ...

I've added the emphasis. Since the copy of the function and arguments has to happen in the calling thread, this essentially requires that the shared state is allocated by the calling thread.
Of course, you could write an implementation that started the new thread, waited for it to allocate the state, and then returned a future that referenced that, but why would you?

A: Just judging from the mere arguments of std::async there seems to be no way to control the allocation of the internal std::promise and it can therefore just use anything, though likely the std::allocator. Though I guess in theory it is unspecified, it is likely the shared state is allocated inside the calling thread. I haven't found any explicit information in the standard about this matter. In the end std::async is a very specialized facility for easy asynchronous invocation, so you don't have to think if there actually is a std::promise anywhere.
For more direct control about the behaviour of an asynchronous call there is also std::packaged_task, which indeed has an allocator argument. But from the mere standard quote it is not perfectly clear if this allocator is just used to allocate storage for the function (since std::packaged_task is kind of a special std::function) or if it is also used to allocate the shared state of the internal std::promise, though it seems likely:
30.6.9.1 [futures.task.members]:

Effects: constructs a new packaged_task object with a shared state and
  initializes the object's stored task with std::forward<F>(f). The
  constructors that take an Allocator argument use it to allocate memory
  needed to store the internal data structures.

Well, it doesn't even say there is a std::promise underneath (likewise for std::async), it could just be an undefined type connectable to a std::future.
So if it is indeed not specified how std::packaged_task allocates its internal shared state, your best bet might be to implement your own facilities for asynchronous function invocation. Considering that, simply spoken, a std::packaged_task is just a std::function bundled with a std::promise and std::async just starts a std::packaged_task in a new thread (well, except when it doesn't), this shouldn't be too much of a problem.
But indeed this might be an oversight in the specification. Whereas allocation control doesn't really fit to std::async, the explanation of std::packaged_task and its use of allocators might be a bit clearer. But this may also be intentional, so the std::packaged_task is free to use whatever it wants and doesn't even need a std::promise internally.
EDIT: Reading it again, I think the above standard quote indeed says, that the std::packaged_task's shared state is allocated using the provided allocator, since it is part of the "internal data structures", whatever those are (there doesn't need to be an actual std::promise, though). So I think std::packaged_task should be enough for having explicit control of the shared state of an asynchronous task's std::future.


text:
Q: India do or does? In pics: India celebrates Rakhi with fervour
Or In pics: India celebrate Rakhi with fervour
which is correct?

A: In these sentences, India is an example of synechdoche, where a word (India) is used to represent something with a greater scope (all of the people in India).
Although it represents a group of people, the word India is a singular noun, and so the verb must take the appropriate form for a singular noun. The correct version is therefore:

India celebrates Rakhi with fervour


text:
Q: What is the purpose of MemoryCache in MVC? I'm a bit confused on the proper usage of MemoryCache.
Should/can it be used to load static information to save on repeated calls?
Should/can it be used to persist data on a view across several action methods?
I have an instance where I don't want to use the data store to populate and persist the data across my view.  I started using the MemoryCache which works fine, however I'm starting to question if that was the correct approach.
My concerns was what happens if I have several users on the same page using the same MemoryCache?

A: First of all, MemoryCache is part of the System.Runtime.Caching namespace. It can be used by MVC applications, but it is not limited to MVC applications.

NOTE: There is also a System.Web.Caching namespace (much older) that can only be used with the ASP.NET framework (including MVC).

Should/can it be used to load static information to save on repeated calls?

Yes.

Should/can it be used to persist data on a view across several action methods?

Yes. If your views use the same data it can. Or if you have data that is on your _Layout.cshtml page that needs caching, it could be done in a global filter.

what happens if I have several users on the same page using the same MemoryCache?

Caching is shared between all users by default. It is specifically meant for keeping data in memory so it doesn't have to be fetched from the database on every request (for example, a list of state names on a checkout page for populating a dropdown for all users).
It is also a good idea to cache data that changes frequently for a second or two to prevent a flood of concurrent requests from being a denial-of-service attack on your database.
Caching depends on a unique key. It is possible to store individual user information in the cache by making the user's name or ID part of the key.
var key = "MyFavoriteItems-" + this.User.Identity.Name;

Warning: This method works only if you have a single web server. It won't scale to multiple web servers. Session state (which is meant for individual user memory storage) is a more scalable approach. However, session state is not always worth the tradeoffs.

Typical Caching Pattern
Note that although MemoryCache is thread-safe, using it in conjunction with a database call can make the operation cross threads. Without locking, it is possible that you might get several queries to the database to reload the cache when it expires.
So, you should use a double-checked locking pattern to ensure only one thread makes it through to reload the cache from the database.
Let's say you have a list that is wasteful to get on every request because every user will need the list when they get to a specific page.
public IEnumerable<StateOrProvinceDto> GetStateOrProvinceList(string country)
{
    // Query the database to get the data...
}

To cache the result of this query, you can add another method with a double-checked locking pattern and use it to call your original method.

NOTE: A common approach is to use the decorator pattern to make the caching seamless to your API.

private ObjectCache _cache = MemoryCache.Default;
private object _lock = new object();

// NOTE: The country parameter would typically be a database key type,
// (normally int or Guid) but you could still use it to build a unique key using `.ToString()`.
public IEnumerable<StateOrProvinceDto> GetCachedStateOrProvinceList(string country)
{
    // Key can be any string, but it must be both
    // unique across the cache and deterministic
    // for this function.
    var key = "GetCachedStateList" + country;

    // Try to get the object from the cache
    var stateOrProvinceList = _cache[key] as IEnumerable<StateOrProvinceDto>;

    // Check whether the value exists
    if (stateOrProvinceList == null)
    {
        lock (_lock)
        {
            // Try to get the object from the cache again
           stateOrProvinceList = _cache[key] as IEnumerable<StateOrProvinceDto>;

            // Double-check that another thread did
            // not call the DB already and load the cache
            if (stateOrProvinceList == null)
            {
                // Get the list from the DB
                stateOrProvinceList = GetStateOrProvinceList()

                // Add the list to the cache
                _cache.Set(key, stateOrProvinceList, DateTimeOffset.Now.AddMinutes(5));
            }
        }
    }

    // Return the cached list
    return stateOrProvinceList;
}

So, you call the GetCachedStateOrProvinceList and it will automatically get the list from the cache and if it is not cached will automatically load the list from the database into the cache. Only 1 thread will be allowed to call the database, the rest will wait until the cache is populated and then return the list from the cache once available.
Note also that the list of states or provinces for each country will be cached individually.


text:
Q: Plotting (beta) curves in R I have used the following code to plot a beta curve:
p <- seq(0, 1, length=100)
plot(p, dbeta(p, 5, 7), ylab="density", type="l", col=4)

I wanted to plot two curves on the same graph and so repeated the second line using different numerical values in place of the 5 and 7. This resulted in the second curve being printed on a different graph (i.e. I got two separate graphs). Could anyone explain how to get both curves on the same graph?

A: A solution with ggplot:
library(ggplot2)

p= as.data.frame(seq(0,6,length=100))

ggplot(p) +
  stat_function(fun = function(p) dbeta(p, 5, 7), color = "red", size = 1) +
  xlab("beta curve")


text:
Q: Cannot read property 'value' of undefined in angular I am a beginner in Angular.
html form :
    <mat-form-field class = "tp-full-width" style="padding-left: 20px;">
      <input #equiId formControlName="equiId" matInput placeholder = "Equipment Code" value = "">
    </mat-form-field>

and button with code :
<mat-card-actions >
          <button mat-raised-button color="accent" type="button" style="width:200px;"
          (click)="add_equi(equiId.value)">control value</button>
</mat-card-actions>

and in ts file :
this.formGroupContent=new FormGroup({
      equiId:new FormControl()
)}

add_equi(equiId){
    console.log(equiId);
}

the problem is that when equiId has a value, console print that value. But when equiId is empty I receive an error :

Cannot read property 'value' of undefined in angular

I want to receive a message when equiId control is empty.

A: Try to use the Elvis operator (?) so that you can avoid the error in console..
<button mat-raised-button color="accent" type="button" style="width:200px;"
          (click)="add_equi(equiId?.value)">control value</button>

A: You are using the reactive forms so try to using its properties, like:
add_equi() {
    console.log(this.formGroupContent.controls.equiId.value);
  }

Remove #equiId from your input element and use properties of your form, for more info about reactive forms check out this link : Reactive forms


text:
Q: Path Display in Label Are there any automatic methods for trimming a path string in .NET?
For example:
C:\Documents and Settings\nick\My Documents\Tests\demo data\demo data.emx

becomes
C:\Documents...\demo data.emx

It would be particularly cool if this were built into the Label class, and I seem to recall it is--can't find it though!

A: Use TextRenderer.DrawText with TextFormatFlags.PathEllipsis flag
void label_Paint(object sender, PaintEventArgs e)
{
  Label label = (Label)sender;
  TextRenderer.DrawText(e.Graphics, label.Text, label.Font, label.ClientRectangle, label.ForeColor, TextFormatFlags.PathEllipsis);
}

Your code is 95% there. The only
  problem is that the trimmed text is
  drawn on top of the text which is
  already on the label.

Yes thanks, I was aware of that. My intention was only to demonstrate use of DrawText method. I didn't know whether you want to manually create event for each label or just  override OnPaint() method in inherited label. Thanks for sharing your final solution though.

A: @ lubos hasko Your code is 95% there.  The only problem is that the trimmed text is drawn on top of the text which is already on the label.  This is easily solved:
    Label label = (Label)sender;
    using (SolidBrush b = new SolidBrush(label.BackColor))
        e.Graphics.FillRectangle(b, label.ClientRectangle);
    TextRenderer.DrawText(
        e.Graphics,
        label.Text,
        label.Font,
        label.ClientRectangle,
        label.ForeColor,
        TextFormatFlags.PathEllipsis);

A: Not hard to write yourself though:
    public static string TrimPath(string path)
    {
        int someArbitaryNumber = 10;
        string directory = Path.GetDirectoryName(path);
        string fileName = Path.GetFileName(path);
        if (directory.Length > someArbitaryNumber)
        {
            return String.Format(@"{0}...\{1}",
                directory.Substring(0, someArbitaryNumber), fileName);
        }
        else
        {
            return path;
        }
    }

I guess you could even add it as an extension method.

A: What you are thinking on the label is that it will put ... if it is longer than the width (not set to auto size), but that would be
c:\Documents and Settings\nick\My Doc...

If there is support, it would probably be on the Path class in System.IO

A: You could use the System.IO.Path.GetFileName method and append that string to a shortened System.IO.Path.GetDirectoryName string.

A: Next code works for folders. I'm using it to display a download path!
        public static string TrimPath(string path) {
        string shortenedPath = "";
        string[] pathParts = path.Split('\\');
        for (int i = 0; i < pathParts.Length-1; i++) {
            string part = pathParts[i];
            if (pathParts.Length-2 != i) {
                if (part.Length > 5) { //If folder name length is bigger than 5 chars
                    shortenedPath += "..\\";
                }
                else {
                    shortenedPath += part+"\\";
                }
            }
            else {
                shortenedPath += part+"\\";
            }

        }
        return shortenedPath;
    }

Example:
Input:
C:\Users\Sandra\Desktop\Proyectos de programación\Prototype\ServerClient\test
output:
C:\Users\..\..\..\..\..\test\


text:
Q: DocuSign for Salesforce Automatic Reminders I have "send with docuSign" button on opportunity and need to send opportunity details as PDF with docuSign.
Also we have send reminder based on one date field on opportunity.
So suppose if i sent document today with docuSign and if date field say 3 days after document send date , i have to send the reminder to recipient.
Remainder should send based on date field whatever date it is.

A: Assuming you're using minimum automation, this is a fairly straightforward task.
The DocuSign managed package installs an object called "DocuSign Status". This object has a lookup to the opportunity that you will take advantage of.
Create a process builder for this object that fires when it's created and each time it is edited to meet criteria.
This PB should use a time based action to fire a pre-made email alert to the specified user if the "status" field is not "completed" by the reminder date.
Here are some documents that might help you:

*

*Email Alert Actions

*Process Builder Trailhead

*DocuSign Admin Documentation
Advanced
I just completed a POC for a completely automated DocuSign send using their Rest API in Salesforce. You're fairly limited in what you can do using the method above. For instance, your reminder email will not be able to contain a link to the document to be signed meaning if the end user for some reason loses the original email they will have to request a new document from you.
I'd recommend a seniored SF developer or a consulting service for a more advanced integration.


text:
Q: How can I turn off jtable cell selection through mouse presses and drags I am wanting to use a JTable but with a different cell selection method rather than clicking in the cells.  I am using the glasspane to allow users to draw a rectangle and am discovering what cells are contained in the rectangle to select.  But I am only wanting to select a cell if it is totally within the rectangle.  For example, imagine a simple 3 x 3 table.  The user my want to select the middle cell (1,1).  I want them to be able to click in the first cell 0,0 and drag down to cell 2,2 drawing the rectangle for selection.  But I don't want cells 0,0 or 2,2 selected.  Or get all 9 selected, for that matter.  This is a simplified example.  Drawing the rectangle might actually encompass cells from more than one table on the screen.
I looked into implementing the ListSelectionModel interface, but don't really want to try and rewrite that.  While experimenting I saw that setSelectionInterval() in the model was being called like crazy (for every single mouse movement) as I click and dragged around in the table.  What I would really like is to find a simple way to turn off whatever listener/mechanism is on the table that makes the calls to the SelectionModel, while keeping the model in place.  I'd still want it to report isSelectedIndex() for example.  I would tell the model what intervals are selected.
I figured that somewhere there's a mouse input adapter inherently built into JTables?  I'd like to turn it off if possible.
Thanks,
BBB

A: For a generic / text-based question, you get a generic, text-based response. :) Start by uninstalling the MouseListeners installed on the table by default:
MouseListener[] listeners = myTable.getMouseListeners();
for (MouseListener l : listeners)
{
    myTable.removeMouseListener(l);
}

Then, add your own MouseListener to the table (use MouseAdapter if you want) and override the "mousePressed" / "mouseReleased" methods to record the points where the drag began, and drag ended. Determine the enclosing rectangle and call:
setRowSelectionInterval(#, #)
setColumnSelectionInterval(#,#)

to select one (or more) cells.


text:
Q: Basic examples of functions in Hörmander class The Hörmander class $S_{\rho,\delta}^m$ (with $\rho,\delta\in[0,1]$) consists of smooth functions $p(x,\xi)$ with
$$|D_x^\beta D_\xi^\alpha p(x,\xi)|\leq C_{\alpha\beta}(1+|\xi|^2)^{(m-\rho|\alpha|+\delta|\beta|)/2}.$$
I'm a newcomer to pseudodifferential calculus so my question is: what are the basic examples to have in mind when thinking about this class? Relatedly, why is this class a natural thing to consider?
The only example apparent to me is that if
$$p(x,\xi)=\sum_{|\alpha|\leq k} a_\alpha(x)\xi^\alpha$$
with $a_\alpha\in C_c^\infty$, then $p\in S_{0,\delta}^m$ for any $\delta\geq 0.$

A: I don't know if the following example is nontrivial enough for you, but I'll let you decide that. Let $\psi$ be a Schwartz function such that $\widehat{\psi}$ has support in the annulus $\{2^{-1/2}\leq|\xi|\leq 2^{1/2}\}$. Consider the symbol $a$ given by
$$a(x,\xi)=\sum_{j=1}^{\infty}a_{j}(x)\widehat{\psi}(2^{-j}\xi), \tag{1}$$
where the $a_{j}$ are $C^{\infty}$ functions with uniformly bounded derivatives. Set $\psi_{j}$ so that $\widehat{\psi_{j}}=\psi(2^{-j}\cdot)$. You can check that $\widehat{\psi_{j}}$ is supported in the annulus $\{2^{j-1/2}\leq|\xi|\leq 2^{j+1/2}\}$, and therefore for each $\xi$, at most one term in (1) is nonzero. It is evident that $a\in C^{\infty}(\mathbb{R}^{n}\times\mathbb{R}^{n})$. And when $2^{j-1/2}\leq|\xi|\leq 2^{j+1/2}$, $j\geq 1$, we have that
$$|\partial_{x}^{\alpha}\partial_{\xi}^{\beta}a(x,\xi)|\leq C_{\alpha}2^{-j|\beta|}\|\partial^{\beta}\widehat{\psi}\|_{\infty}\leq C_{\alpha\beta}(1+|\xi|^{2})^{-|\beta|/2},\quad\forall \xi\in\mathbb{R}^{n}$$
Lastly, we note that $a(x,\xi)$ vanishes for $|\xi|<2^{-1/2}$.
One source of motivation for considering the Hörmander class of symbols is because they generalize space multipliers and Fourier multipliers, which give rise to $L^{2}$-bounded operators. In the latter case, we have the Hörmander-Mikhlin multiplier theorem which gives conditions for a sufficiently smooth function on $\mathbb{R}^{n}\setminus\{0\}$ function $m(\xi)$ to yield an $L^{p}$-bounded operator for $1<p<\infty$. More precisely, it gives conditions for the associated operator to be a Calderón-Zygmund operator.
On this last point, certain subclasses of symbols give rise to Calderón-Zygmund operators. The standard symbol class $S_{1,0}^{0}$ is such an example; this is precisely the Calderón-Vaillancourt theorem. I'm sorry I can't say more; I'm still incredibly new to the subject as well.


text:
Q: Changing CSS attributes I use Waypoints.js (http://imakewebthings.com/waypoints/api/waypoint/ -- no-framework dependency).
Now I want to change CSS attributes on waypoints. What would be the best way to handle my code in a modular way?
HTML:

<button class="menu"></button>

JS:
var waypoint = new Waypoint({

    element: document.getElementById('direction-waypoint'),
    handler: function(direction) {
        if (direction == 'down') {
            document.getElementById("header").setAttribute("style", "position: fixed;");
            document.getElementById("header").style.backgroundColor = "white";
            document.getElementById("menu").getElementsByTagName("li")[0].setAttribute("style", "background-color: #999;");
            document.getElementById("menu").getElementsByTagName("li")[1].setAttribute("style", "background-color: #999;");
            document.getElementById("menu").getElementsByTagName("li")[2].setAttribute("style", "background-color: #999;");

        } else {
            document.getElementById("header").setAttribute("style", "position: absolute;");
            document.getElementById("menu").getElementsByTagName("li")[0].setAttribute("style", "background-color: default;");
            document.getElementById("menu").getElementsByTagName("li")[1].setAttribute("style", "background-color: default;");
            document.getElementById("menu").getElementsByTagName("li")[2].setAttribute("style", "background-color: default;");

        }
    }

});

A: You do it like this.
var waypoint = new Waypoint({

    element: document.getElementById('direction-waypoint'),
    handler: function(direction) {

    var headerElem = document.getElementById("header"),
    menuElem = document.getElementById("menu");

        if (direction == 'down') {
            )

    headerElem.style.position = 'fixed';
    headerElem.style.background-color = 'white';

    menuElem.children[0].style.background-color = '#999';
     menuElem.children[1].style.background-color = '#999';
            menuElem.children[2].style.background-color =  '#999';

        } else {

     headerElem.style.position = 'absolute';

     menuElem.children[0].style.background-color = '';
     menuElem.children[1].style.background-color = '';
    menuElem.children[2].style.background-color = '';

        }
    }

});

If you do a console.dir you can see all of the elements properties. It a good way to evaluate things when your using vanilla JavaScript.
var headerElem = document.getElementById("header");

console.dir(headerElem);


text:
Q: Fragment orientation always portrait I restricted the activity orientation change via
android:screenOrientation="portrait"

But a fragment is attached to this activity.
How can I restrict the fragment from changing its orientation?
Because it's looking odd in landscape, therefore I want it to be always in portrait mode.


text:
Q: Using a  ScrollViewer in a ContextMenu.MenuItem DataTemplate I've spent a lot of time trying to understand and to implement something that looks easy.
In my WP7 application, I have a button that displays a context menu after a long tap. As this context menu is bound to a list, the number of items can be huge. Until now, I haven't been able to add a scroll viewer around my data template. But I have tested that if the data template was not there, it should work fine.
Here is my XAML:
<toolkit:ContextMenuService.ContextMenu>
    <toolkit:ContextMenu ItemsSource="{Binding}">
       <toolkit:ContextMenu.ItemTemplate>
          <DataTemplate >
             <toolkit:MenuItem Header="{Binding Path=Name}" Click="MenuItem_Click"/>
           </DataTemplate>
        </toolkit:ContextMenu.ItemTemplate>
    </toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>

I tried to add a ScrollViewer almost everywhere (before the tag: <toolkit:ContextMenuService.ContextMenu>, before the tag <toolkit:ContextMenu ItemsSource="{Binding}">,...) but nothing works
I also tried to use an attached property in my tag:
<toolkit:ContextMenu ItemsSource="{Binding}" ScrollViewer.VerticalScrollBarVisibility="Visible">

but it doesn't work either.
But if I don't use a data template like:
<toolkit:ContextMenuService.ContextMenu>
    <toolkit:ContextMenu>
        <ScrollViewer>
            <stackPanel>
                <toolkit:MenuItem Header="Item1"/>
                <toolkit:MenuItem Header="Item2"/>
                <toolkit:MenuItem Header="Item3"/>
                <toolkit:MenuItem Header="Item4"/>
            </stackPanel>
        </ScrollViewer>
    </toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>

it works fine.
Did I miss something?

A: You will want to put your ScrollViewer in the Template and a StackPanel in your ItemsPanelTemplate, so something like this:
<toolkit:ContextMenuService.ContextMenu>
    <toolkit:ContextMenu ItemsSource="{Binding}">
        <toolkit:ContextMenu.Template>
            <ControlTemplate TargetType="toolkit:ContextMenu">
                <Border>
                    <ScrollViewer>
                        <ItemsPresenter/>
                    </ScrollViewer>
                </Border>
            </ControlTemplate>
        </toolkit:ContextMenu.Template>
        <toolkit:ContextMenu.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel />
            </ItemsPanelTemplate>
        </toolkit:ContextMenu.ItemsPanel>
        <toolkit:ContextMenu.ItemTemplate>
          <DataTemplate >
             <toolkit:MenuItem Header="{Binding Path=Name}" Click="MenuItem_Click"/>
           </DataTemplate>
        </toolkit:ContextMenu.ItemTemplate>
    </toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>


text:
Q: Using the ANCESTOR function on a DATE dimension Here is my script:
WITH MEMBER [Date].[Date - Calendar Month].[2MthPrev] AS
    (
    ANCESTOR(
        CLOSINGPERIOD([Date].[Date - Calendar Month].[Calendar Month]),
        2
    ))
SELECT
    NON EMPTY
    {
        [Date].[Date - Calendar Month].[2MthPrev]
    }
    ON ROWS,
    NON EMPTY
        [Measures].[Revenue]
    ON COLUMNS
FROM [OurCube]

The query runs with no error but the result pane is empty.
I've attempted to create a custom member in the [Date - Calendar Month] hierarchy that is two months previous to the last month in the hierarchy's level [Calendar Month]. So if the last loaded month in the cube is July 2013 then I'd hope that [2MthPrev] would show the results from May 2013.
I believe the problem is with the custom member [2MthPrev] and its use of ANCESTOR - how is this fixed?

A: Not sure to understand the query but assuming [Calendar Month] is having at most 2 levels (ALL + months) I guess you're asking for something like :
[a-month].parent.parent = [all].parent = null

[2MthPrev] is a scalar value and not a member; if you want to debug to sth like:
with [2MthPrev] as ancestor( ... ).uniqueName

Hope that helps.

A: This query returns 2 months prior from the last populated date for the given measure group. You may have to fiddle with it to make a calculated member. The second argument in tail is optional.  If you don't include it, the default value is 1.
So I'm returning the item that is 2 prior to (lag) the first item (Item(0)) of the set which includes the last month  (tail) from the set of months for which there are values in the Measure Group (exists clause).
select {Tail(Exists([Date].[Date - Calendar Month].[Calendar Month].members, , "Measure Group Name")).Item(0).lag(2)} on 0
 from [OurCube]


text:
Q: Test of node.js method using knex with sqlite3 never stops What I want to do
I'm trying to test a node.js function which uses knex.
Instead of just mocking knex, I think it's interesting to actually run the test on an in-memory database, which makes this test not strictly unitary, but it's, to me, the only useful way to test a repository class.
It's also the most voted answer here: https://stackoverflow.com/a/32749601/1187067
What I use in my test

*

*A simplified book repository bookRepo.js based on knex

*A test bookRepo.test.js injecting a knex connection based on SQLite3.

Problem
The database is well initialize, the test succeeds and the afterEach() function is well invoked, but the process never ends which is particularly problematic for pipelines.
The only way I found to stop the process is to call knex.destroy() in both bookRepo.js and bookRepo.test.js, but it is not possible to destroy knex because it won't be possible to use it more than once.
Thanks for helping!
Code
bookRepo.js
const knex = require('connection'); // dependency not injected in constructor

const TABLE = 'books';

class BookRepo {
  constructor() {
    this.knex = knex;
  }

  static getTable() {
    return TABLE;
  }

  async getTitleById(id) {
    const book = await this.knex(TABLE)
      .select('title')
      .where('id', id)
      .first();

    return book.title;
  }
}

module.exports = BookRepo;

bookRepo.test.js
const { assert } = require('chai');
const mock = require('mock-require');
const {
  describe,
  it,
  before,
  after,
  beforeEach,
  afterEach,
} = require('mocha');

const sqliteConf = {
  client: 'sqlite3',
  connection: {
    filename: ':memory:',
  },
  useNullAsDefault: true,
};
const knex = require('knex')(sqliteConf);

const booksTable = BookRepo.getTable();
const BOOK_1 = {
  id: 1,
  title: 'Batman',
};

let bookRepo;

describe('getTitleById', () => {
  before(() => {
    // To use sqlite3 in the tested module, replace knexfile (required by connections)
    mock('../knexfile', {
      development: sqliteConf,
    });

    // as knex is not injected in constructor, we need to require BookRepo after having mocked knexfile.
    const BookRepo = require('../bookRepo');
    bookRepo = new BookRepo();
  });

  after(() => {
    mock.stopAll();
    knex.destroy(); // destroys only the connection of the test, not in bookRepo
  });

  /**
   * We initialize the SQLite database before each test (create table and insert)
   */
  beforeEach(async () => {
    // drop table
    await knex.schema.dropTableIfExists(booksTable);

    // create table
    await knex.schema.createTable(booksTable, (table) => {
      table.integer('id');
      table.string('title');
    });

    // Insertion
    await knex.transaction((t) => knex(booksTable)
      .transacting(t)
      .insert(BOOK_1)
      .then(t.commit)
      .catch(t.rollback))
      .catch((e) => {
        console.error(e);
        throw new Error('failed to insert test data');
      });
  });

  /**
   * We drop the SQLite table after each test
   */
  afterEach(async () => {
    await knex.schema.dropTableIfExists(booksTable); // table well dropped
  });

  it('returns the title of the given book', async () => {
    const bookRepo = new BookRepo();

    const expectedTitle = BOOK_1.title;
    const retrievedTitle = await bookRepo.getTitleById(BOOK_1.id);

    assert.equal(retrievedTitle, expectedTitle); // OK
  });
});

package.json
…
dependencies": {
    "knex": "^0.20.1",
 },
  "devDependencies": {
    "chai": "latest",
    "mocha": "^6.2.2",
    "sqlite3": "latest",
  }
}

A: Since you're using mocha, it seems best to use Mocha's after hook and call destroy from there. Likewise, you could instantiate Knex in before. I can't think of a reason you would need to call destroy in your non-test code.


text:
Q: MySQL date comparison function In my table dates are stored in the format "2010-08-26 09:00:00" so yyyy-mm-dd. I'd like to select all fields that have a date field that is "today", so between 2010-08-26 00:00:01 and 2010-08-26 23:59:59.
Just using larger and smaller than operators does not work, does MySQL have some built in date comparison functions that can do this?
EDIT: I should have mentioned dates are stored as datetime fields

A: ... WHERE DATE(field)=CURDATE()

or
... WHERE DATE(field)=CURRENT_DATE

or
... WHERE DATE(field)=CURRENT_DATE()

Pick one!

A: I'd suggest [...] WHERE DATEDIFF(CURDATE(),date_field) = 0 [...]

A: use function DATE()
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date

A: Just a recommendation for the future: storing a date in a varchar column is almost always a very bad idea.

A: Using the DATE() function you should be able to construct a value for comparison:
DATE(2010-08-26 12:13:24)

will return just the date section for you ie. 2010-08-26.


text:
Q: What is the value of y in $x\left(\tan\left(\sqrt{x^{2}+y^{2}}\right)\right)-y=0$ What is the value of y in, $$x\left(\tan\left(\sqrt{x^{2}+y^{2}}\right)\right)-y=0$$, and in general how would you solve, sin(x+y)=sqrt(y), for y?

A: If you use polar coordinates $x=r \cos(t)$, $y=r \sin(t)$, you end with the equation
$$r \tan (r) \cos (t)=r \sin (t)$$ the only non-trivial solution being $r=t$ which gives the equation of a spiral.
Otherwise, let $x=k y$ and, for a given value of $k$, you would have
$$y=\frac{\cot ^{-1}(k)}{\sqrt{k^2+1}}$$


text:
Q: Replacing an existing hex value with another in an external file with Java I'm currently trying to make a program that edits the hex values in a 'PAK file' (e.g file.pak). I've currently got the hex values I need to edit but I just don't know how. Here's what I'm trying to do:
Opens file.pak file -> Finds first hex value and replaces it with the second -> Saves file -> Ends
If anyone could help, that would be great. Thank you!


text:
Q: Jira using GitHUB instead of Git My understanding is that GitHUB adds functionality to Git that Jira also adds. So what's the point of connecting Jira to GitHUB instead of to Git directly?
It seems my question is difficult to understand. Let me ask differently. Why would it be better to install Jira with GitHUB as opposed to Jira with Git
Further clarification: It is not part of the question if a Jira/Git integration without GitHUB exists or not.

A: git is a version control system, while Github is a service that allows for hosting your projects online, adds a graphical user interface to git, and allows you to collaborate with other users

A: JIRA is used to track issues, bugs, improvements in form of tickets. It's used in agile methodologies.
git(local) and github(global) are used for version control.
Connecting JIRA to github allows you to automatically reference JIRA tickets in git commits.
For example JIRA issue is "issue111". You mention it in git commit:
"issue111 initial commit". Then if you check issue111 in JIRA you will see in Development section: 1 branch, 1 commit etc. links which you can click to see the commit


text:
Q: queueing and batching requests using java I want to use some mechanism to do something like this - I have a application server getting request to process orders. One request can have one order or two orders. To process the order the application will need to make a call to outside vendor, vendor can process at the most 5 orders at a time. I want to create a component that will batch maximum up to 5 orders if available and fire one request to the vendor and then when I get the response re-distribute the reponse to the appropriate request. The component would wait, say, 2 seconds before firing a batch request ones the first request arrives.
I thought of using JMS but in JMS a consumer will process the message (order) as soon as it arrives and a consumer processes one message at a time. I am thinking of usinga regular queue (ArrayBlockingQueue) and batch up the orders before firing using a ScheduledTimerTask. Does anybody have any ideas - Thanks in advance.

A: Most of what you describe can be done with Apache Camel. It can be configured to throttle, to batch, and forward request.
The Aggregator does what "max wait for X messages and then forward request"

A: There is nothing stopping you from using JMS. Just set a timeout on the operation that fetches from your queue, and when you have 5 messages or a timeout, you process the batch.


text:
Q: How to use navigator onchange event in RxJS stream Here I am trying to write a nice observable to get navigator permissions. The problem is that it updates the status with onchange event. I tried to use FromEvent, but it doesn't look neat. Any nice ideas how to implement it?
getState$(name: PermissionName): Observable<PermissionState> {
  return from(this.navigator.permissions.query({ name })).pipe(
    map((permissionStatus: PermissionStatus) => {
      // How to use onchange callback into stream
      permissionStatus.onchange = function() {
        console.log('permission state has changed to ', this.state);
      };
      return permissionStatus.state
    })
  );
}

After a bit of playing I found that this is possible solution
getState(name: PermissionName): Observable<PermissionState> {
  return from(this.navigator.permissions.query({ name })).pipe(
    mergeMap((permissionStatus: PermissionStatus) => {
      return fromEvent(permissionStatus, 'change').pipe(
        map(event => event?.target?.['state'] as PermissionState),
        startWith(permissionStatus.state)
      );
    })
  )
}

And yet wanna fount a better one

A: You need to use a subject to subscribe to the event. The query only returns a Promise. An observable created from a promise will only return a single value (or an error).
Iterating from what you came up with, here is an improvement
const getState = (name: PermissionName): Observable<PermissionState> => {
  return from(navigator.permissions.query({ name })).pipe(
    switchMap((permissionStatus: PermissionStatus) => {
      return fromEvent(permissionStatus, 'change').pipe(
        map(() => permissionStatus.state),
        startWith(permissionStatus.state)
      );
    })
  );
};


text:
Q: Condicion ternaria ¿Cómo puedo aplicar una condición ternaria en la siguiente línea ?
comm.Parameters.Add(new OracleParameter(":TRES", item.respuesta3));

Este es su contenido:

En caso de que sea 0 guarde un vacío, de lo contrario todo normal ya que, al seguir me da una exception:

"Value does not fall within the expected range."

A: No está del todo claro tu pregunta, creo haberla entendido bien. Te recomiendo que antes de realizar una pregunta la leas en voz alta, y trates de explicarla a otra persona. Eso ayuda a ver si es claro lo que preguntas.
comm.Parameters.Add(new OracleParameter(":TRES", item.respuesta3 == 0 ? "" : item.respuesta3));

Si necesitas realizar una codicion ternaria, podrías probar en vez de poner la variable, reemplazarla por el condicional.
Hace mucho no programo en C#, espero recordar bien el léxico.

A: Podrias hacer algo como esto
string respuesta3 = item.respuesta3.Count == 0 ? "" : item.respuesta3;
comm.Parameters.Add(new OracleParameter(":TRES", respuesta3));

usando el if en linea
?: operator (C# reference)


text:
Q: Proper indendation with backslash line continuations in python-mode.el I like to use python-mode.el and (gnu) emacs for editing my python files.  If I use parentheses for multiline continuations, indentation works as I expect.  For example,
foo_long_long_long_long = (
    bar_long_long_long_long[
        (x_long_long_long_long == X) &
        (y_long_long_long_long == Y)])

is just the way I like it.
On the other hand, if I use a backslash for continuations, a single indentation is created and all subsequent lines stop using the extra indentation logic.  Below the third and fourth lines fail to have any extra indentation
foo_long_long_long_long = \
    bar_long_long_long_long[
    (x_long_long_long_long == X) &
    (y_long_long_long_long == Y)]

Does anyone know how to fix python-mode.el (5.1.0) so that backslash continuations indent the same as parenthesis continuations?

EDIT: Although I'm happy to just use parens all day long (python is after all, rather lisp like...), I collaborate with others who use backslash continuations.  Emacs messes up the indentation when I press TAB, which I often do as a reflex.  It'd be nice to be able to edit their files and have emacs keep all its indentation smarts when working with backslash line continuations.

A: Don't use blackslash continuations.

A: This got Bug lp:629916,  fixed in https://launchpad.net/python-mode


text:
Q: ORM: Sequelize: Add Not Equal Constraint for Two Columns I have a following table. I don't want user to follow himself so I want to add a CHECK constraint.

For example, if this is inserted, I want database to throw an error.
{
   userID: 1,
   followingID: 1,
}

I can check with Javascript if userID and followingID are equal but I want database to check it.
My MYSQL version is 8.0.17 so I think it is possible to create this constraint with SQL. How can I add this constraint with Sequelize?

A: There is two solution
1. Using Model wise validation and adding check constraint in database manually:
Model wise validation:
const FollowingModel = sequelize.define("following", {
     userId: {
          type: Sequelize.INTEGER,
          // .. other configuration like `allowNull`
     },
     followingId: {
          type: Sequelize.INTEGER,
          // .. other configuration like `allowNull`
     }
}, {
    validate: {
         userShouldNotFollowSelf : function() {
             if(this.userId === this.followingId) {
                 throw Error("User should not follow self") // Use any custom error class if your application has such class.
             }
         }
    }
}

Beware this will allow you create entry in database which does not maintain this constraint.
It is just ORM's application layer check that, this application won't allow any entry where userId and followingId is not same.
Mysql database layer check constraint.
CREATE TABLE `following`
(
  `userId` INT NOT NULL,
  `followingId` INT NOT NULL,
  CONSTRAINT `no_self_following` CHECK (`userId` <> `followingId`)
  -- other properties and foreign key constraints.
);

It will ensure that, no such entry inserted where userId and followingId is same.
2. Declaring constraint in sequelize query interface.
This require to declare your model using query interfaces addConstraint as follows
sequelize.getQueryInterface().addConstraint("following", ['userId'], {
    type: 'check',
    name: "no_self_following"
    where: {
        userId: {
            [Sequelize.Op.ne]: Sequelize.col("followingId")
        }
    }
});

Run this while all database model is been synced correctly. It will add database level constraint.
Which one to use ?
Approach #1 is more efficient. It is checking within the application without going into the database call, Makes your database less busy.


text:
Q: Wronskian of a fundamental set of solutions (instead of the dot above, i used ' and ", am I correct in thinking that these are equivalent?)
Consider the system of equations,
$$x'_1=x_2$$
$$x'_2=-q(t)x_1-p(t)x_2$$
where $q(t)$ and $p(t)$ are continuous functions on all of the real numbers. Find an expression for the Wronskian of a fundamental set of solutions.
I know what a wronskian is,  $W(t)=detM(t)$ but I guess I am confused about how to find the fundamental set of solutions.
I was looking at a similar example in the book but I couldn't quite follow it either:
The Euler differential equation with nonconstant coefficients $t^2y"-2ty'+2y=0$ has 2 solutions $y^1(t)=t$ and $y^2(t)=t^2$. (now i realize this might be obvious, but is the superscript number just symbolizing "first" solution and "second" solution, not actually squaring?) This second order differential equation corresponds to the first-order system of differential equations $x'_1=x_2$ and $x'_2=\frac{2}{t^2}x_1+\frac{2}{t}x_2$ (so I don't understand how they got these equations?)
The preceding scalar solutions correspond to the vector solutions $x^1(t)=(t,1)^T$ and $x^2(t)=(t^2,2t)^T$ (what is this T?? and how did they get these answers?)

A: Yes, there are two solutions, $y_1(t)$ and $y_2(t)$.
$T$ = Transpose
To write the DEQ as a system of first order equations, we let:
$x_1 =y $, so:
$$x_1' = y' = x_2$$
$$x_2' = y'' = \dfrac{2 y'}{t} - \dfrac{2 y }{t^2} = - \dfrac{2 x_1}{t^2} + \dfrac{2 x_2}{t} $$
To solve the Euler-Cauchy equation, we let:
$$y = t^m \implies y' = m t^{m-1} \implies y'' = m(m-1)t^{m-2}$$
Substituting this into the DEQ, yields:
$$(m^2-3m+2)t^m = 0 \implies m^2 - 3m + 2 = 0 \implies m_1 = 1, m_2 = 2$$
Thus, we have two solutions:
$$y = y_1(t) + y_2(t) = c_1 t + c_2 t^2$$


text:
Q: Caret train() mlp missing values I'm trying to train a multi layer perceptron for non linear regression on a dataset but it keeps giving me this error :
Warning message:
In nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,  :
  There were missing values in resampled performance measures.

I tried doing it again with a R dataset to see if my data was the problem but I keep getting the error and i have no idea why.
I already tried adding or removing tuneGrid, trControl, even linOut.
It will always give me constant results for some reasons.
    library(datasets)
    library(MASS)
    library(caret)
    DP = caret::createDataPartition(Boston$medv, p=0.75, list = F)

    train = Boston[DP,]
    test = Boston[-DP,]
    colnames(train) = colnames(Boston)
    colnames(test) = colnames(Boston)

    mlp = caret::train(medv ~., data = Boston, method = "mlp", trControl = trainControl(method = "cv", number = 3),
                       tuneGrid = expand.grid(size = 1:3), linOut = T, metric = "RMSE")

    Yp = caret::predict.train(mlp, test[,1:13])


text:
Q: Callback uri not opening in google api installed application I am writing a small desktop application in java with the google fusion tables java client using oauth2. I am able to get the browser to open so the user can log in to his/her google account, but after logging in the application crashes giving me this exception:
Please open the following address in your browser:
  https://accounts.google.com/o/oauth2/auth?client_id=611708255166-npbqbne71spdn8fa1tfsegbl2msi8lsk.apps.googleusercontent.com&redirect_uri=http://localhost:63909/Callback&response_type=code&scope=https://www.googleapis.com/auth/fusiontables
Attempting to open that address in the default browser now...
2013-08-21 11:27:28.076:WARN::/Callback?code=4/V8EpwmnrtF48VjXerABWDPZNyllS.ov1iLPSii_IVshQV0ieZDAps5vxCgQI
java.lang.NoSuchMethodError: javax.servlet.http.HttpServletResponse.flushBuffer()V
    at com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver$CallbackHandler.handle(LocalServerReceiver.java:220)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:326)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
    at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:928)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:549)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
    at org.mortbay.jetty.bio.SocketConnector$Connection.run(SocketConnector.java:228)
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)

So it seems like the callback uri is not working. I do not want my call back uri to point to any website since this is a desktop application, but I want to somehow go back to my application to let the user know that the call to fusion tables has finished.

A: At the risk of stating the obvious, the error is "java.lang.NoSuchMethodError: javax.servlet.http.HttpServletResponse.flushBuffer"
If I look at the LocalServerReceiver.java:220 class at https://code.google.com/p/google-oauth-java-client/source/browse/google-oauth-client-jetty/src/main/java/com/google/api/client/extensions/jetty/auth/oauth2/LocalServerReceiver.java?r=2c0510b314d24701810aa277f5d803a4368b2e20
line 220 is blank.
So I would double check your library versions.
Also check your classpath to see where javax.servlet.http.HttpServletResponse is being found.


text:
Q: Nancy: configure per-request MaxJsonLength and other json serialization settings I would like Nancy's Json serialization to behave as usual for a certain set of requests.
For other (very particular!) requests, usually for diagnostic purpose, I'd like to be able to get very specific settings, such as MaxJsonLength set to int.MaxValue.
The only way I found to change the default behavior is to set the static value of Nancy.Json.JsonSettings.MaxJsonLength (as described, for example, in https://stackoverflow.com/a/45046722/1288109 ). The drawback of this solution is that the setting is applied to all calls (something I'd like to avoid!).
(I also would like to avoid "dirty" tricks such as temporary change the values of Nancy.Json.JsonSettings, restore them at the end of the call and invent weird fancy stuff to prevent unexpected behaviors for calls processed at the same time)
So: is it possible to change Nancy's Json serialization settings PER-REQUEST? How?


text:
Q: NDSolve unable to solve system of PDEs I'm trying to solve a set of PDEs and am running into problems. The system is defined by:

As can be seen, there are two dynamical equations for $\rho$ and $\phi$, but the equation for $v$ has no time derivative on it. I take Dirichlet boundary conditions for all variables, $\rho(x=-L) = \rho(x=L) = \rho_0$, $\phi(x=-L) = 1, \phi(x=L) = 0$ and $V(x=-L)=v(x=L)=0$. Initial conditions are $\rho(x, t=0)= \rho_0$, $\phi(x, t=0)$ is a sigmoid function going from 1 to 0 and $V(x, t=0)=0$.
Somehow, NDSolve is unable to solve this system under certain conditions. In that case, when I run NDSolve it seems to generate an infinite loop and never terminates, while using up a lot of CPU/memory on my PC.
For reference, here is the current working code thanks to @Alex Trounev (sorry for the poor formatting):
kA := 1/τ ((ρdA - ρ[x, t])/ρdA);
kB := 1/τ ((ρdB - ρ[x, t])/ρdB);
e := (eM (1 - ϕ[x, t]) + eO ϕ[x, t]) ;
kD := α e; params = {ρdA -> 0.3, ρdB ->
   1, ρh -> 1, τ -> 0.5,
  D1 -> 0.01, η -> 0.1, ξ -> 0.1, kF -> 1, z -> 1,
  e0 -> 1, α -> 0, eM -> 1, eO -> 1,
  fc -> 0, χ -> 1, κ ->
   1}; tmax = 1; L = 1; iv = {ρ[x,
     0] == (Tanh[8 x] + 1)/2 (ρdA - ρdB) + ρdB, ϕ[
     x, 0] == (1 - Tanh[8 x])/2, v[x, 0] == 0} /.
  params; bc = {ρ[-L,
     t] == (Tanh[-8 L] + 1)/
       2 (ρdA - ρdB) + ρdB, ρ[L,
     t] == (Tanh[8 L] + 1)/
       2 (ρdA - ρdB) + ρdB, ϕ[-L,
     t] == (1 + Tanh[8 L])/2, ϕ[L, t] == (1 - Tanh[8 L])/2,
   v[-L, t] == 0, v[L, t] == 0} /. params;
PDEsys = {D[ρ[x, t], t] +
     D[ρ[x, t] (v[x, t]),
      x] == (kA (1 - ϕ[x, t]) + kB ϕ[x, t]) ρ[x, t],
   D[ϕ[x, t], t] + (v[x, t]) D[ϕ[x, t], x] ==
    D1 D [ϕ[x, t], {x, 2}] +
     z D1 D[ρ[x, t],
       x] D[ϕ[x, t], x]/ρ[x, t] + (kB - kA + kF) ϕ[x,
       t] (1 - ϕ[x, t]) +
     kD (1 - ϕ[x, t]), η D[v[x, t], {x, 2}] - ξ v[x,
       t] == e D[ρ[x, t], x]/ρ[x, t] +
     D[e, x] Log[ρ[x, t]/ρh]};
vars = {ρ, ϕ, v}
fullsys = Simplify@Join[PDEsys /. params, bc, iv];
ndsol = NDSolve[fullsys, vars, {x, -L, L}, {t, 0, tmax},
  Method -> {"EquationSimplification" -> "Residual",
    "IndexReduction" -> Automatic}]

Now I'm simplifying a few conditions, and the question is how to get it working when eM is not equal to eO, and when alpha is not equal to zero.

A: There are exist range of parameters where NDSolve getting solution, for example,
params = {kA -> .1, kB -> 1, D1 -> .1, \[Eta] -> 1, \[Xi] -> 1,
  kD -> 1, kF -> .5,
  z -> 1}; rh0 = 1; tmax = 1; L = 1; iv = {\[Rho][x, 0] ==
   rh0, \[Phi][x, 0] == (1 - Tanh[8 x])/2,
  v[x, 0] == 0}; bc = {\[Rho][-L, t] == rh0, \[Rho][L, t] ==
   rh0, \[Phi][-L, t] == (1 + Tanh[8 L])/2, \[Phi][L,
    t] == (1 - Tanh[8 L])/2, v[-L, t] == 0, v[L, t] == 0};

PDEsys = {D[\[Rho][x, t], t] +
     D[\[Rho][x, t] (v[x, t]),
      x] == (kA (1 - \[Phi][x, t]) + kB \[Phi][x, t]) \[Rho][x, t],
   D[\[Phi][x, t], t] + (v[x, t]) D[\[Phi][x, t], x] ==
    D1 D[\[Phi][x, t], {x, 2}] +
     z D1 D[\[Rho][x, t],
       x] D[\[Phi][x, t], x]/\[Rho][x, t] + (kB - kA + kF) \[Phi][x,
       t] (1 - \[Phi][x, t]) +
     kD, \[Eta] D[v[x, t], {x, 2}] - \[Xi] v[x, t] ==
    D[\[Rho][x, t], x]/\[Rho][x, t]};
vars = {\[Rho], \[Phi], v}
fullsys = Join[PDEsys /. params, bc, iv];

ndsol = NDSolve[fullsys, vars, {x, -L, L}, {t, 0, tmax},
  Method -> {"EquationSimplification" -> "Residual",
    "IndexReduction" -> Automatic}]

Visualization
{Plot3D[\[Rho][x, t] /. ndsol[[1]], {x, -L, L}, {t, 0, tmax},
  Mesh -> None, ColorFunction -> "Rainbow", AxesLabel -> Automatic,
  PlotLabel -> "\[Rho]"],
 Plot3D[\[Phi][x, t] /. ndsol[[1]], {x, -L, L}, {t, 0, tmax},
  Mesh -> None, ColorFunction -> "Rainbow", AxesLabel -> Automatic,
  PlotLabel -> "\[Phi]"],
 Plot3D[v[x, t] /. ndsol[[1]], {x, -L, L}, {t, 0, tmax}, Mesh -> None,
   ColorFunction -> "Rainbow", AxesLabel -> Automatic,
  PlotLabel -> "v"]}


text:
Q: Useradd with given password I would like to add new user without needed any interaction, so with specified password. I have tried command above:
useradd -m -p user -s /bin/bash user

So it should be a user with password user, but I can't login via SSH.

A: Read the man page.  The argument to -p is not the plaintext password:

-p, --password PASSWORD
The encrypted password, as returned by crypt(3). The default is to disable the password.

and it would be an extremely dangerous command if it were.  There is no easy way to do what you want, because what you want is dangerous.
Edit: I understand that you feel your circumstances justify this loss of security, and you might be right: but there is no way for the passwd command to know what you're thinking.
If you're sure you don't mind this loss of security, you could do
echo fr00zalgn3t | passwd --stdin user

to set the initial password to the echoed string, but if you do this, you should also do
chage -d 0 user

immediately after, to require that the password be changed on first login.  You should also ensure that your shell history is cleared after doing this, so the passwords used aren't sitting in a permanent record on-disc.  And you should not, ever, use the username as an initial password, no matter how low-end you feel the system is.


text:
Q: how to identify files modified/touched by chef recipe I would like to find the files on chef client that was touched/modified/created by chef sever.
chef-client -l debug command give lot of output.

A: Try knife-lastrun.
It gives you a list of all modified resources.

A: Actually in Chef 11.8.2 info (not debug) logs is very clear stated what resources were not touched. They have (up to date) written besides them. Also, if you have log output to console and not into file, then the changed resources will be in green.

A: If you configure and install a report handler as part of your chef-client run, you can get a list of updated resources (i.e what changed) as well as other goodies that you might find useful.
The report() function called in a report handler gets passed a run_status object which contains, among other thing:

*

*node, The node on which the chef-client run occurred.

*all_resources, A list of all resources that are included in the resource_collection property for the current chef-client run.

*updated_resources, A list of resources that were marked as updated as a result of the chef-client run.

A: If you want to list the modified resources in the context of chef, you can install the chef-handler-updated-resources:
$ gem install chef-handler-updated-resources

Then appending following code into your /etc/chef/client.rb like:
require 'chef/handler/updated_resources'

updated_resources_handler = SimpleReport::UpdatedResources.new
report_handlers << updated_resources_handler

However, if you do want to list the opened file descriptor underneath chef resources, low level information is required out of the chef-client process because of ruby garbage collection. Assume the chef-client runs on linux OS, you can use directory /proc/$pid/fd to list all opened file descriptor by given process with a pid. So you can write a custom chef handler with this report method:
def report
  Chef::Log.info "File opened by this chef client run:"
  %x( ls /proc/#{Process.pid}/fd -lh | awk '{print $11}').split("\n").uniq!.each {|fd| Chef::Log.info "  #{fd.to_s}"}
end

A: In 2018 the "easiest" way to do this is to run with -F min which should reduce the output when running chef-client -W or chef-client to only a limit set of characters depending on the state of each resource, with a nice summary at the end of only actually/potentially changed resources.
According to a blog post from a couple years ago, you should be able to edit the client.rb and add verbose_logging false and log_level :info to reduce the clutter but I didn't have much luck with that. https://www.frankmitchell.org/2013/04/shush-chef/


text:
Q: C# .Net Framework WPF: How can I do POST call and save login Baerer key? I used following POST request in my C# WPF project: https://stackoverflow.com/a/8091963/17283265 . So i'm getting user login Bearer id and i want to save it (I use localstorage to save it like redux in reactjs). Same pages requre to authenticate. I didn't find a good solution for this. Here is my code.
            using (var wb = new WebClient())
            {
                string Useremail = Login_email.Text;
                string Userpassword = Pass_password.Text;

                var data = new NameValueCollection();
                data["application_id"] = "22233sasdsa1123asdasxzczx";
                data["email"] = Useremail;
                data["password"] = Userpassword;

                var response = wb.UploadValues("https://example.com/user/api/logins?", "POST", data);
                string responseInString = Encoding.UTF8.GetString(response);
                test.Content = responseInString;
            }

I'm getting response from server. No problem with API POST.

A: You can serialize your response and save it as a text file.
It can be accessed at anytime or place in your application.
Here is a simple demo that just collects the html from the front page of Bing.
The html source is now serialized and saved to file that can be accessed anywhere by the sample app.
Ensure your program can read and write to the file without elevated permissions when deploying (AppData folder etc). Local testing is fine. Here is code you can drop into a new Console app for testing purposes.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

   namespace SerializeObject
{
    class Program
    {
        static void Main(string[] args)
        {
            //ensure you delete StorageFile.txt if you encounter errors or change structure of MyObject
            GetInternetString("http://www.bing.com");
        }

        private static void GetInternetString(string url)
        {
            using (var wb = new WebClient())
            {
                var response = wb.DownloadString(url);
                Serialize(response);
            }
        }

        private static void Serialize(string webPageContent)
        {
            try
            {
                MyObject saveThis = new MyObject(webPageContent);
                IFormatter formatter = new BinaryFormatter();
                using (Stream stream = new FileStream("StorageFile.txt", FileMode.Append, FileAccess.Write))
                {
                    formatter.Serialize(stream, saveThis);
                    stream.Close();
                }

                Deserialize();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\r" + ex.StackTrace);
            }
        }

        private static void Deserialize()
        {
            try
            {
                //change this to your specific use
                var lstSessionProjectFilesTrimsSaveThis = new List<MyObject>();
                using (var fileStream = new FileStream("StorageFile.txt", FileMode.Open))
                {
                    var bFormatter = new BinaryFormatter();
                    while (fileStream.Position != fileStream.Length)
                    {
                        //change this to your specific use
                        lstSessionProjectFilesTrimsSaveThis.Add((MyObject)bFormatter.Deserialize(fileStream));
                    }
                }

                foreach (var VARIABLE in lstSessionProjectFilesTrimsSaveThis)
                {
                    Console.WriteLine(VARIABLE.WebPageContent);
                }

                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\n" + ex.StackTrace);
            }
        }

[Serializable] //mandatory to have this declaration
    public class MyObject
    {
        public MyObject(string webPageContent)
        {
            WebPageContent = webPageContent;
        }

        public string WebPageContent { get; set; }
    }
}
}


text:
Q: android/view/View$OnUnhandleKeyListener (Error) Estoy creando un menu que esta construido por un Toolbar, pero me sale un error android/view/View$OnUnhandleKeyListener, tampoco consigo ver la parte del Design
Este es el codigo del Menu
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".Principal_Activity">

    <item
        android:id="@+id/menubtn"
        android:icon="@drawable/menu"
        android:title="menulogo"
        android:visible="true"
        app:showAsAction="always" >

        <menu xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools">
            <item
                android:id="@+id/perfil"
                android:layout_height="match_parent"
                android:title="@string/perfil"
                android:visible="true" />

            <item
                android:id="@+id/exit"
                android:layout_height="match_parent"
                android:title="@string/logout"
                android:visible="true" />
        </menu>

    </item>

</menu>

Este es el codigo del ToolBar:

>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="55dp"
    android:gravity="left"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/imageView5"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginBottom="5dp"
        android:layout_weight="1"
        app:srcCompat="@drawable/logomark"
        android:contentDescription="TODO" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="73dp"
        android:layout_height="match_parent"
        android:layout_marginTop="4dp"
        android:layout_weight="5"
        android:gravity="bottom|center"
        android:padding="7dp"
        android:text="PhotoGO"
        android:textColor="#FAFAFA"
        android:textSize="20sp"
        android:textStyle="bold|italic"
        app:fontFamily="@font/calligraffitti" />

    <Space
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="2" />

</LinearLayout>

Asi se ve la parte del Design  del Tollbar:

Y este es el Error:

Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.julio.photogo">
    <uses-permission
        android:name="android.permission.GET_ACCOUNTS"
        android:maxSdkVersion="22"/>
        <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />

    <application

        android:name=".LogApp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:hardwareAccelerated="false"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.NoActionBar"
        >
        <meta-data android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id"/>
        <meta-data
            android:name="preloaded_fonts"
            android:resource="@array/preloaded_fonts" />

        <activity android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name" />
        <activity
            android:name="com.facebook.CustomTabActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="@string/fb_login_protocol_scheme" />
            </intent-filter>
        </activity>

        <activity
            android:name=".Main_Activity"
            android:label="@string/app_name" >

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".Register_Activity"></activity>

        <activity android:name=".SingIn_Activity"></activity>

        <activity android:name=".Principal_Activity"></activity>

        <activity android:name=".Camera_Activity"></activity>

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>

    </application>

</manifest>