text:
Q: Python - How to add parametric line from data on top of contour plot I have some problems trying to fit together two different plots. On the one hand, I have a contour plot
On the other hand, I have a 1D plot
My goal is to basically get a path on top of the contour following the values from the line plot. Physically, the not all variables from the contour plot are available. For example, at a0=0 I would start at point (0,0) and then I would get a path to (0.5,1.6) for a0=0.8.
Problem is I don't fully know how to combine both data. Here is the code for the contour:
r_field=np.linspace(0,2.0,21)   ##squeezed bath
n_field=np.linspace(0,0.5,21)  ## thermal bath
n_index=0
for Nth in n_field:
    r_index=0
    for r in r_field:
        N = Nth * (np.cosh(r)**2 + np.sinh(r)**2) + np.sinh(r)**2
        M =np.cosh(r) * np.sinh(r) * np.exp(-1j * theta) * (2 * Nth + 1)
        L=(N+1)*L1+(N+1)*L2+N*L1_d+N*L2_d+M*(Lm+Lm_d)
        msol=solve_ivp(Master, [min(t_span),max(t_span)] , rho_in , t_eval= t_span)
        #purity_field[r_index,n_index]=np.real(msol.y[:,-1].reshape(4,4).dot(msol.y[:,-1].reshape(4,4)).trace())
        concurrence_field[r_index,n_index]=Concurrence(msol.y[:,-1])
        r_index+=1
    print(n_index)
    n_index+=1
xlist = r_field
ylist = n_field
X, Y = np.meshgrid(xlist, ylist)
Z = concurrence_field.transpose()
fig,ax=plt.subplots(1,1)
cp = ax.contourf(X, Y, Z,levels=np.linspace(0.0,np.max(concurrence_field),19),cmap='coolwarm')
fig.colorbar(cp)
ax.set_title(r'Concurrence two qubits in a squeezed thermal reservoir at $\gamma=%s$'% (gamma1))
ax.set_xlabel(r'$r_{sq}$', fontsize='20')
ax.set_ylabel(r'$n_{th}$', fontsize='20')
plt.show()

and for the line plot
a_0_list=np.linspace(0.0,0.8,100)
eta=0.1

rsq_fp=np.zeros(len(a_0_list),dtype=np.float64)
nth_fp=np.zeros(len(a_0_list),dtype=np.float64)

i=0
for a_0 in a_0_list:
    nth_fp[i]=4*np.sqrt(det(eta,a_0))-1/2
    rsq_fp[i]=np.arctanh(X1X2(eta,a_0)/XX(eta,a_0))/2.0
    i+=1
plt.plot(a_0_list,nth_fp,label=r'$n_{th}$')
plt.plot(a_0_list,rsq_fp,label=r'$r_{sq}$')
plt.grid()
plt.legend(fontsize='15')
plt.xlabel(r'$<a_{0}>$',fontsize='20')
plt.show();

where I have skipped a few unnecessary lines of code.
A bit of guidance would be appreciated. It would also be great if I could label some discrete points along the path, placing the corresponding a0 value.
Thanks,


text:
Q: Pdo Exception (Mysql) no me detecta errores personalizados Estoy haciendo un mantenimiento en PHP (PDO) a una tabla mediante un Store Procedure (Mysql)  en una determinada situación lanzo una excepción desde el Mysql de la siguiente Manera:
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='Cheque cobrado, no se puede anular.';

en PHP ejecuto la sentencia de esta forma:
try {
    ....................
    ....................
    ....................
    $stmt->execute();
    }
    catch (PDOException $e) {
        echo "Error en la Ejecucion: ".$e->getMessage();
    }

Cabe recalcar que seteada la conexión con el atributo PDO::ATTR_ERRMODE-> PDO::ERRMODE_EXCEPTION y me captura los errores usuales de MYSQL pero con los errores personalizados no he tenido suerte.
ya he probado en consola y desde VB.net y el procedimiento si devuelve el mensaje de error.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Share in-app purchase IDs across premium and free versions of iPhone apps? We're releasing free and paid versions of our app. Both versions contain the same in-app purchase elements.
As far as we know, we cannot reuse the same IAP IDs in both apps. Even though the virtual good is the same in both as well as the code for processing a transaction, we need to use distinct IDs.
The default solution is to set a flag and then process the orders differently based on whether it's a free or paid version, but we're wondering if there is a better way where we can somehow share the same IAP IDs across both.

A: The easiest solution is to have a single version of your application with an in-app purchase to switch between paid and unpaid modes. You could also use your own server to keep track of the purchases, where users create and login to accounts to transfer purchases.
Is there a pressing reason to have separate paid and unpaid versions?


text:
Q: Eliminating Multiple If Statements For Pulling A Specific Object Property Model:
public class ServiceHours
{
    public int Id { get; set; }
    ...
    public TimeSpan? Monday { get; set; }
    public TimeSpan? Tuesday { get; set; }
    public TimeSpan? Wednesday { get; set; }
    public TimeSpan? Thursday { get; set; }
    public TimeSpan? Friday { get; set; }
    public TimeSpan? Saturday { get; set; }
    public TimeSpan? Sunday { get; set; }
}

I'm currently iterating through a list of "service hour" objects (they can hold an optional start time for 1 or multiple days of the week). I want to be able to dynamically grab the value that corresponds to the DayOfWeek enum from a DateTime object.
This works but isn't very elegant
var today = DateTime.Today.DayOfWeek;

foreach (var item in myItems)
{
    var time = new TimeSpan?();

    if (today == DayOfWeek.Monday)
        time = item.Monday;
    else if (today == DayOfWeek.Tuesday)
        time = item.Tuesday;
    else if (today == DayOfWeek.Wednesday)
        time = item.Wednesday;
    else if (today == DayOfWeek.Thursday)
        time = item.Thursday;
    else if (today == DayOfWeek.Friday)
        time = item.Friday;
    else if (today == DayOfWeek.Saturday)
        time = item.Saturday;
    else if (today == DayOfWeek.Sunday)
        time = item.Sunday;

    ...
}

UPDATE:
I ended up using reflection at the time, but this was a very poor, naive design to begin with and this question should've been posted to Code Review anyways - This question should be disregarded, just adding this notice in case any others come along. Thanks to those who attempted to help out regardless of the terrible question!

A: If you are able to modify the class of the object that makes up your objectList variable, then try using a Dictionary<DayOfWeek, TimeSpan?> in that class. DayOfWeek would be the key and TimeSpan? would be the value. This would simplify the class as well as eliminate the long if-else logic.
Also, if I'm not mistaken, this method would also be faster than using reflection and wouldn't rely on the property names of your object to be spelled exactly the same of the days of the week in DayOfWeek (if you needed to refactor for some reason in the future).
Here is an example:
static void Main(string[] args)
{
    List<WeekObject> weekObjs = new List<WeekObject>();

    foreach (var obj in weekObjs)
    {
        SaveTime(obj.ID, obj.weekDictionary[DateTime.Today.DayOfWeek]);
    }
}

class WeekObject
{
    public int ID { get; set; }
    public Dictionary<DayOfWeek, TimeSpan?> weekDictionary { get; set; } = new Dictionary<DayOfWeek, TimeSpan?>();

    public WeekObject ()
    {
        // Initialize dictionary here if you'd like
        weekDictionary.Add(DayOfWeek.Sunday, null);
    }
}

public static void SaveTime(int ID, TimeSpan? timeSpan)
{
    // Your code here
}

A: Something like this probably (did not compiled this code though)
object.GetType().GetProperty(today.DayOfWeek.ToSring()).GetValue(object)

use reflection to get property value,with only condition that DayOfWeek enum member has to have exact name of the property present in object type.


text:
Q: Error when using DownloadString from a website using powershell When executing the code below to get a value for a web server I get this error.
I have read some possible solutions that involve changing setting on the web server it's self but this is not an option for me because I don't own the server.
Error

Exception calling "DownloadString" with "1" argument(s): "The server
  committed a protocol violation. Section=ResponseStatusLine" At
  C:\get.ps1:28 char:60
  + $ramPage = (New-Object System.Net.WebClient).DownloadString <<<< ("http://" + $server + "/RAM/" + $evalRAMStars)
      + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : DotNetMethodException

Powershell Code
Function Get-Performance(){
$CPU = Get-WmiObject win32_processor | Measure-Object -property LoadPercentage -Average | Select Average

$SystemInfo = Get-WmiObject -Class Win32_OperatingSystem | Select-Object Name, TotalVisibleMemorySize, FreePhysicalMemory
$perRam = (($SystemInfo.FreePhysicalMemory/1MB) / ($systeminfo.totalvisiblememorysize/1MB)) * 100
$perRam = 100 - $perRam

Write-host ("CPU:  " + $CPU.Average + "%")
Write-host ("Ram:  " + $perRam + "%")

$CPUStars = $CPU.Average / 10
$RAMStars = $perRam /10

if($CPUStars -lt 1){$CPUStars = 1}

Write-host ("{0:N0}" -f $CPUStars)
Write-host ("{0:N0}" -f $RAMStars)

$evalCPUStars = "{0:N0}" -f $CPUStars
$evalRAMStars = "{0:N0}" -f $RAMStars

$server = "10.0.0.188"

#this will get our page for later
$cpuPage = (New-Object System.Net.WebClient).DownloadString("http://" + $server + "/CPU/" + $evalCPUStars)
$ramPage = (New-Object System.Net.WebClient).DownloadString("http://" + $server + "/RAM/" + $evalRAMStars)
Write-host("http://" + $server + "/CPU/" + $evalCPUStars)
Write-host("http://" + $server + "/RAM/" + $evalRAMStars)
}

While($x -ne 0)
{
    Get-Performance
    Start-Sleep -s 10   #this will run the powershell script every 10 seconds.
}

A: The value of $evalRAMStars is probably causing the unsafe header parsing to block the message.  Check that its value is valid. Otherwise, see The server committed a protocol violation. Section=ResponseStatusLine ERROR for more solutions.


text:
Q: Laravel: Update data without select file again I have a table called projects with this fields:
TABLE INFORMATION
id, slug, order, public, pathheader and pathhome.
CREATE VIEW
The form to store the data looks like this:

        <form  enctype="multipart/form-data" id="myFormProject" name="myFormProject">
         <input type="hidden" name="_token" value="{{ Session::token() }}">

            Slug:
            <input type="text" id="slug" name="slug" placeholder="ejemplo-de-slug" class="form-control form-control-sm">

                      <input type="file" name="pathheader" id="pathheader"  class="form-control-file" aria-describedby="fileHelp" style="display:none;">

                      <input type="file" name="pathhome" id="pathhome" class="form-control-file" aria-describedby="fileHelp" style="display:none;">

                      <input type="button" name="" value="Seleccionar header" id="browse_file" class="btn btn-danger form-control">

                      <input type="button" name="" value="Seleccionar home" id="browse_file2" class="btn btn-danger form-control">

            <input type="submit" value="Crear Proyecto" id="createprojectsubmit" class="btn btn-danger btn-md">

        </form>

FUNCTION TO SAVE THE DATA
And the function looks like this:
 public function storeProject(Request $request)
        {

        $project = new Project();
        $project->slug = $request->input("slug");
        //$project->order = $request->input("order");
        $project->order = DB::table('projects')
                      ->where('order', DB::raw("(select max(`order`) from projects)"))
                      ->first()
                      ->order + 1;
        $project->public = 0;
        $project->pathheader = $request->file('pathheader');
        $project->pathhome = $request->file('pathhome');

        \Storage::disk('projects')->makeDirectory($project->slug);
        \Storage::disk('projects')->putFileAs($project->slug,$project->pathheader,'header.jpg');
        \Storage::disk('projects')->putFileAs($project->slug,$project->pathhome,'home.jpg');
        $project->save();
        }

This works really good, and save me values like: /tmp/phQX0ddm in pathheader and pathhome.
VIEW TO UPDATE THE DATA

                Slug
                  <textarea type="text" class="form-control form-control-sm" id="slug" name="slug" rows="1" required style="resize:none;">{{$project->slug}}</textarea>

                      Order
                      <textarea type="number" class="form-control form-control-sm" id="order" name="order" rows="1">{{$project->order}}</textarea>

                Public
                <textarea type="text" class="form-control form-control-sm" id="public" name="public" value="" rows="1">{{$project->public}}</textarea>

                      @if (Storage::disk('projects')->has($project->slug))
                      slug.'/header.jpg') }}" id="img" class="img" style="width:100%;height:200px;background-color:#ccc;border:2px solid gray;">
                      @else

                      @endif
                      <input type="file" name="pathheader" id="pathheader" class="form-control-file" aria-describedby="fileHelp" style="display:none;">

                      @if (Storage::disk('projects')->has($project->slug))
                      slug.'/home.jpg') }}" id="img" class="img" style="width:100%;height:200px;background-color:#ccc;border:2px solid gray;">
                      @else

                      @endif
                      <input type="file" name="pathhome" id="pathhome" class="form-control-file" aria-describedby="fileHelp" style="display:none;">

                      <input type="button" name="" value="Seleccionar header" id="browse_file" class="btn btn-danger form-control">

                      <input type="button" name="" value="Seleccionar home" id="browse_file2" class="btn btn-danger form-control">

FUNCTION TO UPDATE THE DATA
public function updateProject(Request $request, $id)

//Actualizar la informacion de un trabajador
    {
        $project = Project::find($id);
        $project->slug = $request->input('slug');
        $project->order = $request->input('order');
        $project->public = $request->input('public');
        if($request->hasFile('pathheader')){
            $project->pathheader = $request->file('pathheader');
            \Storage::disk('projects')->putFileAs($project->slug,$project->pathheader,'header.jpg');
        }
        $project->pathheader = Project::find($id)->pathheader;
        if($request->hasFile('pathhome')){
            $project->pathhome = $request->file('pathhome');
            \Storage::disk('projects')->putFileAs($project->slug,$project->pathhome,'home.jpg');
        }
        $project->pathhome = Project::find($id)->pathhome;
        $project->save();
    }

The problem is, if I don't select again the file when I update the data, image isn't loaded.
How can I fix this? My first idea was take the value of pathhome and pathheader and put it on function controller to update the data again with same values, but doesn't work.
I hope someone can help me, I will be really really appreciated.

A: You can use the Project model like:
$pathheader = Project::find($id)->pathheader;

A: I think you should try this :
$project->pathheader = DB::table('projects')
                            ->where('id',$id)
                            ->where('pathheader',  DB::raw("(select pathheader from projects)"))
                            ->first();

Hope this work for you !!!

A: You can try this query
$pathheader = DB::table('projects')->select('pathheader')->where('id','=',$id)->first();

I think this is what you seeking for


text:
Q: Acessar site na SMARTTV Olá,
Desenvolvi um sistema web em php/html/css(Bootstrap) e abrir normal em vários dispositivos pc, notebooks, tablets, celulares porém em TV's Smart, que é o foco do sistema, não ficou legal não reconhece altura dos elementos, a tag svg não apareceu, enfim um série de bugs.
Alguém já passou por isso?

A: Existe uma lista de tv's que o html5 é suportado:
LG WebOS 2016   WebOS
Samsung Smart TV 2015   Tizen
Panasonic Viera 2015    Firefox OS
GoogleTV    Chrome 11
Confira se sua tv esta nas suportadas, além de possuir notas para cada tv em seu suporte. Apenas estas conseguiram interpretar bem um site como o seu.
Fonte: https://html5test.com/results/other.html


text:
Q: Name of a post-apocalyptic book I can remember some details about the plot but not the title or author name.

*

*The story is recent (it was published after 2000)

*The apocalypse was caused by a mutated species of wasp called slavers

A: The book is called Invasive Species by Joseph Wallace. The wasps are actually called thieves - I thought they were called slavers because the sequel is called Slavemaker.


text:
Q: RHEL (say 5.6, kernel 2.6.18-238) with dual IP address (IPv4v6) So I have a SERVER that that utilizes RHEL's (assume 5.6) underlying kernel for setting up TCP connections and other networking aspects. My deployment need requires that the SERVER have dual IP address, an IPv4 and an IPv6 address. The SERVER interacts with two entities, one on the left having an IPv6 address and one on the right having an IPv4 address (as shown in the figure below). The left entity sends a message M to the SERVER over a TCP/IPv6 socket. The same message M needs to be delivered to the right entity by the SERVER over a TCP/IPv4 socket.
My questions:

*

*Does RHEL 5.6 allow this? I am assuming yes, but would request any issues I would need to be aware of from configuration perspective.

*Any limitation from process/thread standpoint? I believe the IPv6 thread/process that manages the connection needs to communicate with the IPv4 thread/process? How complicated is that?

*Any impacts to scalability with respect to number of TCP connections either side of the IP interface (IPv4 and v6)?

Thank you!

A: If it's a simple IPv6-to-IPv4 translator, this could be done through IPTables and a translation rule. Or alternately, funnel it through something like stunnel if you really need the network connection to terminate on the server.

A: RHEL 5 (and it's siblings like CentOS) have quite poor IPv6 support, particularly in the kernel's connection tracking.
As mentioned, you need to configure either a NAT64 [1] or application proxy to relay the message. AFAIK, RHEL 5 does not have any tools to do that.
[1] http://en.wikipedia.org/wiki/NAT64

A: NAT64 can cause MTU problems. Proxy software is a better solution. Haproxy is one I can recommend. You will need to install some software to make this work. I don't think RHEL5 has a recent enough haproxy package.
PS: Keep an eye on the ISOC Deploy360 website. A whitepaper on exactly this issue will be published soon.


text:
Q: $\mathring{M}$, $\overline{M}$ and $\partial M$ of $M = \bigcup_{k=1}^\infty \big[\frac{1}{k+1}, \frac{k}{k+1} \big] \subset \mathbb{R}$ How can one find out the interior $\mathring{M}$, the closure $\overline{M}$ and the boundary $\partial M$ of this set?
$$M = \bigcup_{k=1}^\infty \big[\frac{1}{k+1}, \frac{k}{k+1} \big] \subset \mathbb{R}$$
I don't even know how to draw this region in the plane..

A: Hint:
Rewrite each interval in the form
$$\biggl[\frac1{n+1},1-\frac 1{n+1}\biggr].$$

A: By construction we have $[\frac{1}{k+1} , \frac{k}{k+1}] \subset (0,1)$. Thus $M\subset (0,1)$. Let $x\in (0,1)$. There exists  $k\in \Bbb N$ such that $\frac{1}{k+1} \leq x \le 1 - \frac 1 {k+1} = \frac{k}{k+1}$. Therefore $x \in M$.
It follows that $M = (0,1)$. Thus $\overline{M} = [0,1]$, $\text{interior}(M) = (0,1)$, $\partial M = \{0,1\}$


text:
Q: The value of $\int_C \bar{z}dz$? What is the value of $\int_C \bar{z}dz$ from $z=0$ to $z=4+2\pi i$ along the curve $C$ given by $z=t^2+it$?

A: Hint: parametrize it.
$$\bar{z}=t^2-it,~~~dz=(2t+i)dt$$
where $t$ is from $0$ to $2$
There should be a typo in your OP, from $z=0$ to $z=4+2i$


text:
Q: How to pass "unknown" object as parameter and use it's original object type to deserialize I am working on building a re-usable function to deserialize a JSON string.
The JSON deserialization routines need an object type(jsonTestObject). This all works as expected.
  // serialize json to object

  jsonTestObject testO = new jsonTestObject();
  testO = Newtonsoft.Json.JsonConvert.DeserializeObject<jsonTestObject>(jsonString);

When I try to wrap this in a re-usable function to deserialize "any" object type I send, I run into issues. I am not sure how to pass the object type as a parameter to the function as I cant strongly type it.
I want to send "any" object type to my function and cast the result to my desired object type (As I will know what object type I am expecting when making the call.)
I don't want to hardcode a separate function for all classes that I want to serialize/deserialize.
Here is what I have that is not working...
    JSONdeserialize(string jSONstring,Type t)
    {
        object newObject;

        // deserialize object based on the original object type that was passed in.
        newObject = JsonConvert.DeserializeObject<t>(jSONstring); //ERROR LINE

        return newObject;
    }

jsonTestObject jsonObject = new jsonTestObject();
object o = JSONdeserialize(jsonString, jsonObject.GetType());

jsonObject = (jsonTestObject)o;

ERROR: "'t' is a variable but is used like a type"

A: newObject = JsonConvert.DeserializeObject(jSONstring, t);

A: The code can be written in both the way.
public void JSONdeserialize<T>(string jSONstring)
{
   return JsonConvert.DeserializeObject<T>(jSONstring);
}

jsonTestObject jsonObject = new jsonTestObject();
object o = JSONdeserialize<jsonTestObject>(jsonString);

jsonObject = (jsonTestObject)o;

or
public void JSONdeserialize(string jSONstring, Type type)
{
   return JsonConvert.DeserializeObject(jSONstring, type);
}

jsonTestObject jsonObject = new jsonTestObject();
object o = JSONdeserialize(jsonString, typeof(jsonTestObject));

jsonObject = (jsonTestObject)o;


text:
Q: How does stress change through a bar that sharply increases in diameter? I am looking to analyse the stress through the following bar:

The bar is of circular cross section, homogeneous in material, that is of a certain diameter on one half, and a large diameter on the other half. You can consider it as two bars of different diameters welded together, with the centrelines of both bars collinear. Uniform normal tensile stresses act on both ends of the bar such that equilibrium is satisfied.
Specifically, I would like to know which physical principles are required to mathematically determine the distribution of axial stress acting on the cross-section of the bar at all points along the bar.
Intuitively, one might say the stress is uniform along the length of the bar, as the stresses at both ends must be uniform. However, I argue otherwise, especially if you look at the middle of the bar where the diameter steps up.
I would agree the stress in the part of the bar with the smaller diameter is uniform, but the stress distribution begins to change gradually as soon as you reach the point the diameter changes.
In the half of the bar with larger diameter: near the point of change in diameter, I believe the stress is distributed such that the stress is concentrated in the centre of the bar. I believe this as the annular face on the half of the bar with large diameter is unstressed. Then, as you move near the end of the thicker half, the stress distribution starts to become more uniform. It is almost as though you take a cylinder filled with water, and you instantly increase the diameter of the cylinder, and the water changes shape to accommodate the shape of the wide cylinder, reaching uniform depth.
The following diagrams helps to illustrate my intuitive understanding of the stress distribution:

Is this intuitive understanding correct/plausible? Can it be verified mathematically? What principles can be employed? For example, in analysing bending beams, you make use of the principle of equilibrium, Hooke's Law, and the geometric deformation assumption that plane sections in beams remain plane after deforming. Can a similar list of principles be used in this question? (So far, equilibrium and Hooke's Law springs to mind).
Thanks in advance!

A: It's hard to do this one analytically, but that's why we have computers. I used a commercial FEM package to set up your problem and simulate steel with some dummy loading conditions.
Your intuition is basically correct away from the corner. Indeed, the stress is uniform far from the corner, and it only has interesting behavior close to the feature. However, You're not quite right about how the stress is distributed at the interface. The corner creates a singularity in the stress field that is best described with a picture. The first picture shows contours of the axial component of the stress. Don't worry about the actual values of stress. These are dependent on the loading, and will simply scale with the applied traction.

To get a more quantitative view of how the stress changes at different cross-sections, I created a few plots starting at the top in the thick section and moving down into the thin section. The plots are the axial stress (normalized by the far-field stress in the thick section) vs the x-position. As you can see in the third plot from the bottom, the stress at the corner is much higher than the stress in the bulk. Successively refining the mesh would reveal that this is, in fact, a true singularity, so the stress would go to $\infty$ if the mesh size $\Delta x \rightarrow 0$.
Note, it's not surprising that the small-diameter mean stress is ~4 since this was a 3D calculation of a cylindrical body and the ratio of the $D_{big}/D_{small} = 2$.

A: The water analogy is good but think of the water as force and not stress.   Equilibrium applies to forces, not stresses and, essentially, what flows in at one end emerges at the other end.   In Mechanics 1, you'd simply divide the force in each constant-area element by its area to get the average stress in the element.
However, as @Tyler's FEA shows, this simple analysis won't tell you what's going on close to the change of section.   If you don't have access to FEA, there are analytic solutions and reference books, e.g Roark's Formulas for Stress and Strain for the stress concentration factor as a function of the radius of the corner.


text:
Q: Can't locate a file using a regular expression in NLTK I am fairly new to programming and NLTK and have been following a text book to get started. I am having trouble getting the Regular Expression r'.*.pos' to work in Python 2.7 (Mac). I am following a set of examples in the book, Python Text Processing with NLTK 2.0 Cookbook, chapter 3. I think the code is meant to find all files named pos (or with the extension "pos" I'm not entirely sure.
Below is the code:
reader = TaggedCorpusReader('/Users/mattmatters22/Desktop/pos',r'.*\.pos')
reader.words()

Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    reader.words()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nltk/corpus/reader/tagged.py", line 82, in words
    for (fileid, enc) in self.abspaths(fileids, True)])
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nltk/corpus/reader/util.py", line 421, in concat
    raise ValueError('concat() expects at least one object!')
ValueError: concat() expects at least one object!

A: r'.*\.pos'

means match ".pos" with maybe something before (the .* part).
But this can not be found in "/Users/mattmatters22/Desktop/pos". Could this cause your problem?
Try it without the dot r'.*pos' and see if you get the same error or a result.

A: Try reader = TaggedCorpusReader('/Users/mattmatters22/Desktop/pos',['brown.pos'])
If that doesn't work, then brown.pos must not be in /Users/mattmatters22/Desktop/pos

A: The code in nltk book assumes that the corpus is named brown.pos, which is not the case and doing a help(TaggedCorpusReader) and looking at its init function explains to me that I need to give two arguments - path and filename or regex which can be used to compute filename.
I tried the following on my linux system and it works. Hopefully code is self-explanatory:
    >>> import nltk
    >>> nltk.corpus.brown.fileids()
    [u'ca01', u'ca02', u'ca03' ..]
    >>> nltk.corpus.brown.abspath('ca01')
    FileSystemPathPointer(u'/home/<username>/nltk_data/corpora/brown/ca01')
    >>> reader = TaggedCorpusReader('/home/<username>/nltk_data/corpora/brown/', 'ca01')
    >>> reader.words()
    [u'The', u'Fulton', u'County', u'Grand', u'Jury', ...]

After this, instead of using explicit file name, you can substitute your own regex.


text:
Q: Python listing all files in a directory and write it in a file in python Below is the code i am which i tried, I am new to python, could someone let me know what shall i do
#opening a 'Newfile' to write in

file_list=open('file_list.txt','w')
#taking the list of file which i have to write in file
list_files = os.system("ls -1 /amxusers7/inf/aimsys/netabp6/ALL_SCRIPTS/VOICE")
#trying to write in a Newfile
file_list.writelines(list_files)

I am getting error:
Traceback (most recent call last):
 File "testPuneet.py", line 30, in ?
file_list.writelines(list_files)
TypeError: writelines() requires an iterable argument

A: On Unix, os.system returns the exit code of the process you invoked. So, os.system("ls") will give you an integer, not a list of files.
Instead, use the subprocess module. The check_output method will give you the values that are printed to the screen.
import subprocess
result_of_ls = subprocess.check_output(["ls", "-l", "/amxusers7/inf/aimsys/netabp6/ALL_SCRIPTS/VOICE"])

As an example gives:

total 75032\n-rw-rw-r--  1 user  user         0 Jun  3 22:04 122.txt\n-rw-rw-r--  1 user  user         0 Jun  3 22:04 154.txt\n-r--------  1 user  user      8666 Mar 29 22:11 2731_74814450810_2074865_n.jpg\n-rw-rw-r--  1 user  user    111872 May 30 21:40 3065397482_cd8b581c9a.jpg\n-rw-rw-r--  1 user  user     24661 Jun 18 13:11 375585_782393371042_1430263587_n.jpg\n

Taking the single string returned by check_output and turning it into a list of filenames is left as an exercise to the reader.

A: If you are using Python, you might as well do it the Python way:
import os
with open('file_list.txt','w') as file_list:
    list_files = os.listdir('/amxusers7/inf/aimsys/netabp6/ALL_SCRIPTS/VOICE')
    file_list.write('\n'.join(list_files))


text:
Q: Does the chance of catching a Pokémon change with each throw? In GamePress's article about Catch Mechanics, they describe how the capture chance is calculated for each ball thrown.  At the end of the article they say this...

Catch Success and Failure
Finally, the server generates a Random Number between 0% and 100.0%. If Final Capture Chance is greater than this random number, the Pokémon is caught. If Final Capture Rate is less than this random number, the Pokémon breaks out and possibly flees.

How the capture rate is calculated is explained well in article, however, what I don't understand is when the Random Number is chosen.  Is a value chosen with each throw, each encounter, each spawn?
So basically, I can modify the Final Capture Chance by giving a Razz Berry, throwing a different type of ball, and/or throwing the ball when the target circle is smaller/larger.  But if the Random Number is 100%, and it never changes for that Pokémon. Then I don't have much chance of ever catching the Pokémon.  However, if the Random Number changes with every throw, then I always have a chance to catch it with the next ball (assuming it doesn't run away).

A: The Random Number is generated once for each throw, the chance of catching a Pokémon does not change with each throw, except with things that explicitly do so like the Razz Berry.

A: Based on the quote you provided, where it says:

If Final Capture Rate is less than this random number, the Pokemon breaks out and possibly flees.

This indicates that this random number must be generated for each throw.
Many times now, I have attempted to capture Pokemon with Pokeballs, getting Great or Excellent throws, then failing, but then throwing a Pokeball with no accuracy bonus, and catching the Pokemon. If the random number did not change with each throw, these cases would be impossible.

A: It's pretty much like two dices.
You have a fixed capture rate based on the Pokémon species and its level, the ball you're throwing at it and whether or not a Razz Berry effect is applied. This value will not change, if you keep using Razz Berries (if used at all) and the same Pokéballs.
However, it is increased by throwing curve balls and/or landing nice/great/excellent throws.
The sum of that is your Final Capture Rate, the first dice on the table. So basically the chance changes by what you do. And only by that. If you land the same throws with the same balls the chance will not change. Ever. (For that particular Pokémon that is.)
The random number is your other dice. With each throw you roll your 2nd dice, and if it's higher (or equal)... Gotcha. Regardless of the amount of rolls the first dice will still lie there, only affected by the variable bonuses.
So it would be like this:
You throw the ball...

*

*Thrown ball hits the Pokémon

*Pokémon rolls its dice (capture rate + bonuses = Final Capture Rate = first dice)

*You roll your dice (random number = second dice)

*If you land a greater (or equal) roll the Pokémon is yours, otherwise it breaks out and you start over again (unless it flees).


text:
Q: How to increment value of global variable in assembly in linux I am going through the assembly implementation of AES algorithm to understand, how sbox and lookup table are implemented/accessed.
Theoretically I know, AES uses 10 rounds when key length=128bits.
There is one part where one loop of 200 lines of code (representation of AES rounds) is executed.
_x86_64_AES_decrypt_compact:

.Ldec_loop_compact:

xorl    0(%r15),%eax
xorl    4(%r15),%ebx
xorl    8(%r15),%ecx
xorl    12(%r15),%edx
leaq    16(%r15),%r15
.
.
.
xorl    %r12d,%ecx
movq    256(%r14),%r13
xorl    %r8d,%ebx
xorl    %r11d,%edx

jmp .Ldec_loop_compact

I want to increase a global variable's (i.e. round_var) value by 1 every time one round of AES is completed.
So at the end of AES operation on 1 block (16bytes), the variable's value will be 10 and
at the end of AES operation on 2 block (2x16bytes), the variable's value will be 20.
.globl round_var
round_var:
.long 0

_x86_64_AES_decrypt_compact:

.Ldec_loop_compact:
.
.
.
;increase round_var by 1
.
.
.
jmp .Ldec_loop_compact

To increase round_var by 1 , I tried following approaches
64bit :
        movq    round_var(%rip), %rax
        addq    $1, %rax
        movq    %rax, round_var(%rip)

32bit :
        movl    round_var(%rip), %eax
        addl    $1, %eax
        movl    %eax, round_var(%rip)

As all of eax,ebx,ecx,edx are used inside that loop, I just added those lines before the updation of %eax (or %rax) register so it won't effect AES operation.
After addition of those lines, I am successfully able to execute following commands to build customized openssl. It means the lines are added at correct place during compile/assemble time.
make
sudo make install

However, I got segmentation fault while trying to perform AES decryption operation. This indicates something went wrong at those lines codes at runtime.
I suspect %rip of movl    round_var(%rip), %eax is causing this segmentation fault.
It will be great if anyone help me to resolve the above issue or to increment the global variable round_var by 1 using assembly instruction ?
I am using Ubuntu-16.04 , Intel(R) Core(TM) i5-7200U CPU @ 2.50GHz and Openssl-1.0.2n
Thanks in advance.

A: Static variables should be placed in the .data section.  To do this, write:
        .data                 # enter the data section
        .align 4              # align to four bytes
var:    .long 1234            # assemble a 32 bit word with value 1234

you might also want to specify the following to aid debugging:
        .type var,@object     # var refers to an object
        .size var,4           # var occupies 4 bytes of storage

If the variable initially has the value zero, you can optionally place it in the .bss section to save space in the binary.  The .bss section does not occupy space in the binary and is filled with zeroes at runtime.
        .bss                  # enter the bss section
        .align 4              # align to four bytes
var:    .space 4              # allocate four bytes for var

Similarly to the previous approach, you might also want to specify symbol size and type for better debugging.
As a shorthand for this, you may write
        .lcomm var,4          # align four bytes in .bss for var

A third option is defining the variable as a common symbol.  This causes all variables with the same name from other translation units to be merged with this one and is useful for creating global variables.  Simply write
        .comm var,4           # defines var to be a common symbol of size 4


text:
Q: how to fill a table for chart javascript? I want to complete this table with a loop but it generates an error you can help me.
Morris.Area({
    element: 'graph-area',
    behaveLikeLine: true,
    gridEnabled: false,
    gridLineColor: '#dddddd',
    axes: true,
    fillOpacity:.7,
    data: [
    for( var i=1;i<10;i++)
    {
        {period: '2010 Q1',  itouch: i},

    }

    ],
    lineColors:['#E67A77','#D9DD81','#79D1CF'],
    xkey: 'period',
    ykeys: ['iphone', 'ipad', 'itouch'],
    labels: ['iPhone', 'iPad', 'iPod Touch'],
    pointSize: 0,
    lineWidth: 0,
    hideHover: 'auto'

});

A: Use intermediate variable like:
var myData = [];
for( var i=1;i<10;i++){
  myData.push({period: '2010 Q1',  itouch: i});
}

Morris.Area({
    element: 'graph-area',
    behaveLikeLine: true,
    gridEnabled: false,
    gridLineColor: '#dddddd',
    axes: true,
    fillOpacity:.7,
    data: myData,
    lineColors:['#E67A77','#D9DD81','#79D1CF'],
    xkey: 'period',
    ykeys: ['iphone', 'ipad', 'itouch'],
    labels: ['iPhone', 'iPad', 'iPod Touch'],
    pointSize: 0,
    lineWidth: 0,
    hideHover: 'auto'
});


text:
Q: Почему не работает программа, если в подключаемом файле две строки? Всем доброго вечера!
Возник вопрос в проге. Если в подключаемом файле одна строка, все работает, но если их 2 и более, то прога уже ложится. Ошибку выдает в splite, я так понимаю, что надо заменять enter пробел. Может, кто подскажет, как это сделать? Заранее спасибо!
$number_a = Read-Host "Enter a ";
$number_b = Read-Host "Enter b ";
$sum = 0;
$razn = 0;
$string = Get-Content d:\учёба\СПО\SPO_lab1\input.txt;
$array = $string.split(" ");
for ($i = 0; $i -lt $array.length; $i++){

    if ([int]$array[$i] -le $number_a ) {
        $razn = $number_a - [int]$array[$i];
    }
    else {
        $razn = $array[$i] - $number_a;
    }
    if ($razn -le $number_b) {
        $sum = $sum + $razn
    }
    $razn = 0;
}

$file = 'd:\учёба\СПО\SPO_lab1\res.txt'
$issetFile = Test-Path $file;
if ($issetFile){
    $sum | Out-File $file -Force;
    echo "Done! Result is $sum";
}else{
    echo 'File not found`n. File res.txt is created!';
    New-Item -Path $file -ItemType "file";
    $sum | Out-File $file -Force;
    echo "Done! Result is $sum";
}

A: Самый простой метод — разбивать по пробелам и концам строк.
Для этого передайте несколько аргументов в split.
$array = $string.split(' `n');

По поводу того, почему программа не работала: у вас, как вы правильно заметили в вопросе, не было разбиения по концам строк, и некоторые элементы в  $array содержали посередине конец строки! При этом попытка преобразовать в число ([int]$array[$i]) приводила к падению.


text:
Q: AD return 8009030C: LdapErr: DSID-0C09043E, comment: AcceptSecurityContext error, data 0, vece I use Java's LdapContext to authenticate to one AD server. It works well on Windows7 home basic,enterprise, professional version.But AD throws resultcode 49 when the client is running on Windows7 ultimate and Vista ultimate.
What's wrong with these two operating system?
And how I fix that?

A: Error 49 is invalid credentials.
It's a common mistake to use Windows logon name (e.g. JohnS) instead of LDAP DN (e.g. cn=John Smith, ou=Users, dc=example, dc=com). AD may also accept user principal name e.g. johns@example.com.


text:
Q: fleqn option makes math internal mode (inner) not detected The following MWE points out that, without fleqn class option, math internal mode is detected ("i" and "o") but, as soon as fleqn class option is enabled, this mode is not detected anymore ("i" and "i").
Do you see what's going on?
\documentclass
%[fleqn]
{article}
%
\newcommand{\test}{%
  \relax%
  \ifinner%
  i%
  \else%
  o%
  \fi%
}
%
\begin{document}
$\test$
%
\begin{equation}
  \test
\end{equation}
\end{document}

A: \ifinner does not really test anything useful in math mode whether or not fleqn is used.
If you want to distinguish displaystyle then unfortunately you need to use \mathchoice.
The following produces t inline and d in display whether or not the [fleqn] option is used.
\documentclass
[fleqn]
{article}
%
\newcommand{\test}{%
\mathchoice
{\displaystyle d}%
{\textstyle t}%
{\scriptstyle s}%
{\scriptscriptstyle 2}%
}
%
\begin{document}
$\test$
%
\begin{equation}
  \test
\end{equation}
\end{document}


text:
Q: Recursively building an XML tree using dom4j without duplicate code for the root node I am serializing a tree structure to XML data.
My tree looks like
Company
  Department
    Employee
    Employee

My desired root node is Company, so the XML would look something like
<?xml version="1.0" encoding="UTF-8"?>
<Company>
  <Department>
    <Employee>
       ...
    </Employee>
  </Department>
</Company>

After looking at the examples, I've decided I'll write it like this
public void writeNodes(Element root, NodeBase node) throws XMLStreamException
{
    Element elmt = root.addElement(node.getName());
    for (NodeBase child : node.getChildren())
    {
        writeNodes(child);
    }
}

public void makeXML(NodeCompany root, String filename)
{
    try {
        document = DocumentHelper.createDocument();
        writeNodes(???, root);
        writeFile(document, filename);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

I want my root node to be used as the root, but I don't want to write duplicate code to treat the root node separately from its children.
Since there will ever only be a single Company node in my tree, I can perform an explicit check in my writeNodes method to skip any company nodes, but that doesn't look nice.
Is there a way to complete this code without duplicating any code?

A: Hy,
for me the method writeNodes is unnecessary, you can do this:
public void makeXML(Element rootElement, String filename) {
    try {

        //you must detach it for you can add it in the new document after
        Element rootElementCopied = (Element) rootElement.clone();

        Document document = DocumentHelper.createDocument();

        document.add(rootElementCopied);

        writeFile(document, filename);
    }
    catch (Exception e){
        e.printStackTrace();
    }
}


text:
Q: Find the series solution for the ODE $x^2y''(x)-3y(x) = 0$
Find the series solution for the ODE  $x^2y''(x)-3y(x) = 0$

I assume $y(x) = \sum{a_nx^n}$ then substitute in the equation and get
$$\sum_{n=0}^{\infty} ({a_nn(n-1) - 3a_n)x^n}=0$$
When I equate the coefficients I get $a_i = 0$ for all i
Then I tried to put $y(x) =x^\alpha \sum{a_nx^n}$ but I still can't get a solution.
Can someone help? Thanks

A: Your second attempt should have led you to a solution.  If you try $ y (x)=x^\alpha $, you get $\alpha^2-\alpha-3=0$, i.e. $\alpha=\frac {1\pm\sqrt {13}} 2$. This gives you two linearly independent solutions.


text:
Q: Trouble scraping Div class with same class Ids with Xpath
https://www.maplesford.com/new-Warsaw-2022-Ford-Escape-SEL-1FMCU9H97NUB34573
body_style = response.xpath(".//div[@class='vdp-info-media vdp-body-style']/text()").get()

My issue is I can't seem to drop the levels down to pull the body style. stuck at /text() don't know how to pull the body style.

A: You're looking for:
body_style = response.xpath("//li[@class='vdp-info media vdp-body-style']//h3/text()").get()

Check Scrapy docs here


text:
Q: Do Android apps force the use of SSL 3? In light of the recent POODLE vulnerability, the servers that I talk to in my Android app are disabling SSL 3.
The code where I make my HTTP requests looks something like this
AndroidHttpClient c = AndroidHttpClient.newInstance("My Client/1.0");

try {
    SyncBasicHttpContext httpcontext = getHttpContext();
    HttpResponse jsonResponse = c.execute(request, httpcontext);
    Status status = jsonResponse.getStatus();
} catch (Exception e) {
    // ...etc
}

Is there anything I will need to do to my code to continue to be able to talk to the severs?


text:
Q: Getting "UNIQUE constraint failed" exception using Ormlite createOrUpdate() method I have several calls throughout my app where tables in my database are updated through calls to .createOrUpdate()
The documentation suggests from this calls:

This is a convenience method for creating an item in the database if it does not
  exist. The id is extracted from the data parameter and a query-by-id
  is made on the database. If a row in the database with the same id
  exists then all of the columns in the database will be updated from
  the fields in the data parameter. If the id is null (or 0 or some
  other default value) or doesn't exist in the database then the object
  will be created in the database. This also means that your data item
  must have an id field defined.

My understanding is then that, when calling createOrUpdate(), the underlying code should be calling "insert" if the Database doesn't contain the row and "update" if the row exists.
What seems to be happening is that the underlying code is calling "insert" when the row already exists causing the exception.
Does anybody know why this is happening or how to avoid it?
Exception below:
java.lang.RuntimeException: java.sql.SQLException: Unable to run insert stmt on object
    Feed(id=126275579_organisations-email_58284484, type=organisations-email, category=1, msg=
Body
, regarding=Bobby Castle, subject=Subject, createdTs=2016-01-04T09:59:27+00:00, completed=0, read=0, starred=0, archived=0, remoteAttachments=[], localAttachments=null, authorId=250008275, authorName=Live Regression Test, authorImg=null): INSERT INTO `feed` (`id` ,`type` ,`category` ,`msg` ,`regarding` ,`subject` ,`createdTs` ,`completed` ,`read` ,`starred` ,`archived` ,`authorId` ,`authorName` ,`authorImg` ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)
     at com.j256.ormlite.dao.RuntimeExceptionDao.createOrUpdate(RuntimeExceptionDao.java:252)
     at uk.co.test.test.data.orm.models.Feed.createOrUpdate(Feed.java:81)
     at uk.co.test.test.interactors.server.CategoryInteractor$6.onSuccessfulResponse(CategoryInteractor.java:308)
     at uk.co.test.test.interactors.server.CategoryInteractor$6.onSuccessfulResponse(CategoryInteractor.java:290)
     at uk.co.test.test.interactors.common.StandardCallbackRunnable.checkStandardResponse(StandardCallbackRunnable.java:27)
     at uk.co.test.test.interactors.common.StandardCallbackRunnable.checkStandardResponse(StandardCallbackRunnable.java:12)
     at uk.co.test.test.interactors.common.CallbackRunnable.success(CallbackRunnable.java:127)
     at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45)
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
     at java.lang.Thread.run(Thread.java:818)
Caused by: java.sql.SQLException: Unable to run insert stmt on object Feed(id=126275579_organisations-email_58284484, type=organisations-email, category=1, msg=
Body
, regarding=Bobby Castle, subject=Subject, createdTs=2016-01-04T09:59:27+00:00, completed=0, read=0, starred=0, archived=0, remoteAttachments=[], localAttachments=null, authorId=250008275, authorName=Live Regression Test, authorImg=null): INSERT INTO `feed` (`id` ,`type` ,`category` ,`msg` ,`regarding` ,`subject` ,`createdTs` ,`completed` ,`read` ,`starred` ,`archived` ,`authorId` ,`authorName` ,`authorImg` ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)
     at com.j256.ormlite.misc.SqlExceptionUtil.create(SqlExceptionUtil.java:22)
     at com.j256.ormlite.stmt.mapped.MappedCreate.insert(MappedCreate.java:135)
     at com.j256.ormlite.stmt.StatementExecutor.create(StatementExecutor.java:450)
     at com.j256.ormlite.dao.BaseDaoImpl.create(BaseDaoImpl.java:310)
     at com.j256.ormlite.dao.BaseDaoImpl.createOrUpdate(BaseDaoImpl.java:336)
     at com.j256.ormlite.dao.RuntimeExceptionDao.createOrUpdate(RuntimeExceptionDao.java:249)
     at uk.co.test.test.data.orm.models.Feed.createOrUpdate(Feed.java:81)
     at uk.co.test.test.interactors.server.CategoryInteractor$6.onSuccessfulResponse(CategoryInteractor.java:308)
     at uk.co.test.test.interactors.server.CategoryInteractor$6.onSuccessfulResponse(CategoryInteractor.java:290)
     at uk.co.test.test.interactors.common.StandardCallbackRunnable.checkStandardResponse(StandardCallbackRunnable.java:27)
     at uk.co.test.test.interactors.common.StandardCallbackRunnable.checkStandardResponse(StandardCallbackRunnable.java:12)
     at uk.co.test.test.interactors.common.CallbackRunnable.success(CallbackRunnable.java:127)
     at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45)
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
     at java.lang.Thread.run(Thread.java:818)
Caused by: java.sql.SQLException: inserting to database failed: INSERT INTO `feed` (`id` ,`type` ,`category` ,`msg` ,`regarding` ,`subject` ,`createdTs` ,`completed` ,`read` ,`starred` ,`archived` ,`authorId` ,`authorName` ,`authorImg` ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)
     at com.j256.ormlite.misc.SqlExceptionUtil.create(SqlExceptionUtil.java:22)
     at com.j256.ormlite.android.AndroidDatabaseConnection.insert(AndroidDatabaseConnection.java:169)
     at com.j256.ormlite.stmt.mapped.MappedCreate.insert(MappedCreate.java:91)
     at com.j256.ormlite.stmt.StatementExecutor.create(StatementExecutor.java:450)
     at com.j256.ormlite.dao.BaseDaoImpl.create(BaseDaoImpl.java:310)
     at com.j256.ormlite.dao.BaseDaoImpl.createOrUpdate(BaseDaoImpl.java:336)
     at com.j256.ormlite.dao.RuntimeExceptionDao.createOrUpdate(RuntimeExceptionDao.java:249)
     at uk.co.test.test.data.orm.models.Feed.createOrUpdate(Feed.java:81)
     at uk.co.test.test.interactors.server.CategoryInteractor$6.onSuccessfulResponse(CategoryInteractor.java:308)
     at uk.co.test.test.interactors.server.CategoryInteractor$6.onSuccessfulResponse(CategoryInteractor.java:290)
     at uk.co.test.test.interactors.common.StandardCallbackRunnable.checkStandardResponse(StandardCallbackRunnable.java:27)
     at uk.co.test.test.interactors.common.StandardCallbackRunnable.checkStandardResponse(StandardCallbackRunnable.java:12)
     at uk.co.test.test.interactors.common.CallbackRunnable.success(CallbackRunnable.java:127)
     at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45)
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
     at java.lang.Thread.run(Thread.java:818)
Caused by: android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: feed.id (code 1555)
     at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
     at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
     at android.

A:
My understanding is then that, when calling createOrUpdate(), the underlying code should be calling "insert" if the Database doesn't contain the row and "update" if the row exists.

This is true however the operation is not (and cannot be) atomic because multiple database calls are being made to accomplish it.  There is no locking that is done in the DAO method – although maybe there should be.
If we look at the BaseDaoImpl.createOrUpdate(...) code you can see that it does:

*

*Extract the ID from the entity in question.

*Looks it up in the database to see if it exists.

*Calls update(...) if it exists otherwise create().

Because there are multiple calls to the database going on, then there are race conditions if multiple threads are executing this method at the same time.

at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)

Right, if you are using this DAO method with threads (and createIfNotExists(...) which also does 2 database calls) then I would do so within a synchronized block:
synchronized (dao) {
    status = dao.createOrUpdate(...);
}


text:
Q: How to accept a pdf file from server in ember Consider the below URL:

http://localhost:4200/abc/secured/rest/name/166

This URL returns a PDF file from the server. Code is done to successfully trigger the service URL and get the response code as 200.
What code should be written in ember to capture the PDF file and prompt a save as window to the User for saving the PDF file in local machine.

A: You can try ember-pdfjs,
https://github.com/mysterlune/ember-pdfjs
And provide the URL as the src for the pdf-document which can be used to render the pdf inside a template.
In the same page you can provide a link like below which provide an download attribute (HTML5 attribute, not support by ledgacy browser)
Download Your File

Code above will let the browser download the file instead of open it for viewing.

A: execute this code in button click action handler.
 let link = document.createElement('a');
 link.href = 'http://localhost:4200/abc/secured/rest/name/166';
 link.target = '_blank';
 link.click();


text:
Q: ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate the subclass I'm newbie to Rails.
I have two models Category and Product as follows:-
class Category < ActiveRecord::Base
 attr_accessible :type

 has_many :products
end

class Product < ActiveRecord::Base
 attr_accessible :category_id, :color, :price, :title

 belongs_to :category
end

And my schema.rb is as follows:-
ActiveRecord::Schema.define(:version => 20130725220046) do

create_table "categories", :force => true do |t|
    t.string   "type"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  create_table "products", :force => true do |t|
    t.integer  "category_id"
    t.decimal  "price",       :precision => 10, :scale => 0
    t.string   "title"
    t.string   "color"
    t.datetime "created_at",                                 :null => false
    t.datetime "updated_at",                                 :null => false
  end

end

In Rails console I created two products with two products with the Product.create command
[#<Product id: 1, category_id: 1, price: 500, title: "shirt", color: "blue", `created_at: "2013-07-25 22:04:54", updated_at: "2013-07-25 22:04:54">, #<Product id: 2, category_id: 1, price: 600, title: "tees", color: "black", created_at: "2013-07-25 22:05:17", updated_at: "2013-07-25 22:05:17">]`

And created two Categories with the Category.create command in console
<Category id: 1, type: "clothing", created_at: "2013-07-25 22:03:54", updated_at: "2013-07-25 22:03:54"><Category id: 2, type: "footwear", created_at: "2013-07-25 22:04:02", updated_at: "2013-07-25 22:04:02">

Now, Product.all works fine but Category.all gives

ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate the subclass: 'clothing'. This error is raised because the column 'type' is reserved for storing the class in case of inheritance. Please rename this column if you didn't intend it to be used for storing the inheritance class or overwrite Category.inheritance_column to use another column for that information.

What's wrong in there? I want to make a relationship between Category and Product like
a category has_many products and products belongs_to a category.

A: You can set inside your model self.inheritance_column = :_sti_disabled (or some other name) if you are not using STI for current AR model

A: if anyone is actually trying to pull off STI, try adding a new class that inherits from the parent, and the error message in question should go away.
class YourSubclass < Category
end

A: If you found this question because you encountered the same error, and you are actually using Rails STI, but got the error because you were trying to rename the inherited subclasses, it's probably because you have old data in the type column and forgot to update it. Then this rake task might help:
update_category_type_column_with_new_subclass_names.rake
# This will be run when running `rake categories:update_type_column_with_new_subclass_names`
namespace :categories do
  desc 'Run through the categories with values in the type column and rename those according to the new subclass names: CategorySubclass1 -> CategorySubclass1NewName, CategorySubclass2 -> CategorySubclass2NewName, and CategorySubclass3 -> CategorySubclass3NewName . Run this rake task without arguments.'
  task update_type_column_with_new_subclass_names: :environment do
    Category.inheritance_column = :_type_disabled # to avoid getting error when using the type column: "ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate the subclass: 'CategorySubclass1'"
    categories = Category.where("type <> '' AND type IS NOT NULL")
    categories.each do |a|
        begin
            case a.type
            when 'CategorySubclass1'
                a.type = 'CategorySubclass1NewName'
                a.save!
            when 'CategorySubclass2'
                a.type = 'CategorySubclass2NewName'
                a.save!
            when 'CategorySubclass3'
                a.type = 'CategorySubclass3NewName'
                a.save!
            end
        rescue StandardError => e
            puts '---'
            puts 'Error trying to set :type for category with :'
            puts 'id and url: '
            puts ' ' + a.id.to_s
            puts ' ' + a.type
            puts 'Error message: '
            puts e.message
            puts '---'
        end
    end
    Category.inheritance_column = :type # switch on the Rails STI after you've made your updates to the DB columns
  end
end

A: Try using inheritance_column, then type will no longer be reserved:
class Category < ActiveRecord::Base
 self.inheritance_column = :foo
 attr_accessible :type

 has_many :products
end

class Product < ActiveRecord::Base
 attr_accessible :category_id, :color, :price, :title

 belongs_to :category
end

A: Just came across this post while trying to find a solution to my own problem with this type reserve word so maybe this can help someone else.
Changing the name of the column isn't an easy solution for me because I'm working on a existing complete system migrating to active record from mongodb.
I found adding self.inheritance_column = :_type_disabled to the model with the offending column name fixed the error which I found here.

Disable STI
I had to add "self.inheritance_column" as opposed to simply
  "inheritance_column" to get this to work. Code example
class MyModel < ActiveRecord::Base   # disable STI
  self.inheritance_column = :_type_disabled end

I know that we're not using any inheritance so I think it's fine for me to do this but I don't know what other implications there could be because of it. If anyone else has any opinions on this I'd be interested to know.
If you can just change the column name and avoid doing this then that's a much better solution I'm sure.

A: type is restricted word, you can't use it as a column name in ActiveRecord models (unless you're doing STI).


text:
Q: How can i get and display all value without undefined value from mongodb? How can i get and display all value without undefined value from mongodb?
app.post('/add_teacher',(req,res)=>{
    const name = req.body.name;
    const biography = req.body.biography;
  teacherCollection.insertOne({name,biography})
         .then(result =>{
           console.log(result);
             res.send(result.insertedCount>0);
        })
    })

app.get('/get_all_teacher', (req, res) =>{

  teacherCollection.find()
  .toArray((err, course) =>{
   res.send(course);
  })
})

suppose,i give a value for name but don't give value for biography.so the value of biography will be "undefined".now i want to get nothing where value is "undefined" .I have used mongodb
https://i.stack.imgur.com/39qHH.jpg

A: In javascript when you want to access a key from an object and the key is not exists in object it return undefiend
const biography = req.body.biography; // return undefiend if not exists

if you want null value or a default value when the key is not exists, this code will help you
const biography = req.body.biography || null; // return null if not exists

const biography = req.body.biography || ''; // return empty string if not exists


text:
Q: Get param from URL with c# send to angular side I would like to send an optional parameter to the url of my app to use as a
placeholder for one of my text boxes. I've tried a couple of different
approaches and cant seem to get any of them to get the param from the URL
in my c# code and pass it to my angular. Any help would be greatly
appreciated!
*I tried using //import { ActivatedRoute, Params } from '@angular/router';
but, it keeps giving me this issue. ("no provider for ActivatedRoute")
which im okay with not using I would rather get it from my c# code so I can
do some minor manipulation on it and then send the param to my angular if
possible.
C# controller
   [Route("api/[controller]")]
   public class PasswordController : Controller
   {
       private readonly AppSettings _options;

       public PasswordController(IOptions<AppSettings> optionsAccessor)
       {
           _options = optionsAccessor.Value;

       }

       /// <summary>
       /// Returns the ClientSettings object as a JSON string
       /// </summary>

       [HttpGet]
       public IActionResult Get([FromQuery]string emp)
       {
           //I get nothing on this...
           var x = HttpContext.Request.Query["emp"].ToString();
               Response.Headers.Add("x-emp-name", x);
           return Json(_options.ClientSettings);
       }

Change-pass.ts
import { Title } from '@angular/platform-browser';
import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { MatSnackBar, MatDialog } from '@angular/material';
import { FormControl, FormGroup, Validators } from '@angular/forms';
//import { ActivatedRoute, Params } from '@angular/router';
import ViewOptions from '../models/view-options.model';
import Alerts from '../models/alerts.model';
import Recaptcha from '../models/recaptcha.model';
import ChangePasswordForm from '../models/change-password-form.model';
import Result from '../models/result-data.model';
import PasswordModel from '../models/password.model';
import DialogOverview from '../dialog/app.dialog'

import PasswordValidator from '../helpers/passwordValidator';
import PasswordStrength from '../helpers/passwordStrength';

import 'rxjs/add/operator/map';

const emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-
zA-Z0-9-]+)*$/;

@Component({
 selector: 'app-root',
 templateUrl: './change-password.html',
 styleUrls: ['./app.change-password.css']
})
export default class ChangePasswordComponent implements OnInit {
 // Form Controls
 FormGroup = new FormGroup({
   username: new FormControl('', [Validators.required, Validators.pattern
(emailRegex)]),
   currentPassword: new FormControl('', [Validators.required]),
   newPassword: new FormControl('', [Validators.required]),
   newPasswordVerify: new FormControl('', [Validators.required])
 }, PasswordValidator.MatchPassword);
 // Variables
 ViewOptions: ViewOptions;
 ResultData: Result;
 Loading: boolean = false;
 ErrorAlertMessage: string = '';
 FormData: PasswordModel;
 color: string = 'warn';
 value: number = 0;

 constructor(private http: Http, private snackBar: MatSnackBar,
   private titleService: Title, public dialog: MatDialog) {
   this.FormData = new PasswordModel;
   this.ViewOptions = new ViewOptions;
   this.ViewOptions.alerts = new Alerts;
   this.ViewOptions.recaptcha = new Recaptcha;
   this.ViewOptions.changePasswordForm = new ChangePasswordForm;

   this.FormGroup.valueChanges.subscribe(data => {
     if (data.newPassword != null)
       this.changeProgressBar(PasswordStrength.measureStrength
(data.newPassword));
   });
 }

 ngOnInit(): void {
    // If I set this it works needs to be dynamic and from the URL
    this.GetData("TestUser");
 }

private GetData(queryParam: string): void {
     this.FormData.Username = queryParam;
     this.http.get('api/password?emp='+ queryParam).subscribe(values => {
     this.ViewOptions = values.json();
     this.titleService.setTitle(this.ViewOptions.changePasswordTitle + " -
" + this.ViewOptions.applicationTitle);

     if (this.ViewOptions.recaptcha.isEnabled) {
       this.FormGroup.addControl('reCaptcha', new FormControl('',
[Validators.required]));
       const sp = document.createElement('script');
       sp.type = 'text/javascript';
       sp.async = true;
       sp.defer = true;
       sp.src =
'https://www.google.com/recaptcha/api.js?onload=vcRecaptchaApiLoaded&render=explicit&hl='
+ this.ViewOptions.recaptcha.languageCode;
     }
   });
 }

change-pass.html
                           <input matInput [(ngModel)]="FormData.Username"
formControlName="username" name="Username" type="email" required
placeholder="{{ViewOptions.changePasswordForm.usernamePlaceholder}}">

A: Try the following
import {ActivatedRoute} from '@angular/router';
......
export default class ChangePasswordComponent implements OnInit{
.......
//define the ActivatedRoute instance on your constructor
constructor(.......
             private route: ActivatedRoute)

........
 ngOnInit(){
  let paramValue;
        this.route.queryParams.subscribe((params)=>{
   paramValue = params['paramName'];
});

console.log(paramValue); // this should contain your URL parameter
}
.....
}


text:
Q: Xcode API and Documentation in a seperate window? When i open up the reference with cmd + shift + 0, the window opens up in in the same window as my code, but i like to tab back and forth between things. Is there a way to have it in a seperate window or something like that?

A: Try the menu item instead of the shortcut key-combo. I always get a separate window when I use the menu item.


text:
Q: looping with range in Go Correct me if I'm wrong, there are only 3 types of loops in Go.
Type1 (The most basic type, with a single condition):
for i <= 3 {...}
Type2 (Classical for-loop)
for j := 7; j <= 9; j++ {...}
Type3 (infinite loop rely on break)
for {...break}
Then I come across this for loop that sums the value from array
nums := []int{2, 3, 4}
sum := 0
for _, num := range nums {
    sum += num
}
fmt.Println("sum:", sum)//"sum: 9"

Is the above for-loop to be considered Type1 where it automatically applies <= and range of nums as max value? Can I in any way change the value? maybe I need two extra loops? Can we apply something like range + 2?

A: From Effective Go:

The Go for loop is similar to—but not the same as—C's. It unifies for and while and there is no do-while. There are three forms, only one of which has semicolons.
// Like a C for
for init; condition; post { }

// Like a C while
for condition { }

// Like a C for(;;)
for { }

It continues:

If you're looping over an array, slice, string, or map, or reading from a channel, a range clause can manage the loop.
for key, value := range oldMap {
        newMap[key] = value
}

From this I think of range loops as a for condition { } loop, where the condition (such as it is) is that the variables being designated as the values of the array/slice/string/map/chan are not nil, though in practice even explicitly nil values work
for _, v := range []interface{}{nil, nil, nil, nil} {
    // will still iterate four times
}

In reality it might be more useful to think of Go's for loop as a contextual combination of a C-style for init; condition; post loop, a classical while loop, and a more modern foreach loop.

A: Type1 will work almost like while in other languages. Since there is no while in go language it uses for in that case.
Type2 is the classic for loop like in other languages as you have also stated.
Type3 is used to range over various data structures like arrays, slice, maps

range on arrays and slices provides both the index and value for each
  entry like the example you have given

nums := []int{2, 3, 4}
sum := 0
for _, num := range nums {
    sum += num
}
fmt.Println("sum:", sum)//"sum: 9"

range on map iterates over key/value pairs.

kvs := map[string]string{"a": "apple", "b": "banana"}
for k, v := range kvs {
    fmt.Printf("%s -> %s\n", k, v)
}

range on strings iterates over Unicode code points. The first value is
  the starting byte index of the rune and the second the rune itself.

for i, c := range "go" {
    fmt.Println(i, c)
}

For more information, Check Go by example website for usage of range


text:
Q: Take 2: When/Why are these equal? This didn't go right the first time, so I'm going to drastically rephrase the query.
As per this previous question, I am wondering if the two series $$\frac{f(a)+f(b)}{2}\frac{(b-a)}{1!}+\frac{f'(a)-f'(b)}{2}\frac{(b-a)^2}{2!}+\frac{f''(a)+f''(b)}{2}\frac{(b-a)^3}{3!}+\cdots$$
and $$\frac{f(a)+f(b)}{2}\frac{(b-a)}{1!}+\frac{f'(a)-f'(b)}{2^2}\frac{(b-a)^2}{2!}+\frac{f''(a)+f''(b)}{2^3}\frac{(b-a)^3}{3!}+\cdots$$ could possibly be equal. The only difference is the powers of $2$ in the denominator.
NOTE: the numerator is $f^{(k)}(a)+(-1)^kf^{(k)}(b)$ in general.

A: The identity you give is quite pretty! Yes they are equal.
Let
$$\phi(t) = \sum_{n \ge 0}\frac{(b-a)^{n+1}}{(n+1)!}
\left( f^{(n)}(a) \cdot t^{n+1} + f^{(n)}(b) \cdot (-1)^n (1-t)^{n+1}\right).$$
The first series in question is $\frac12(\phi(1)+\phi(0))$ and the second is $\phi(\frac12)$. The "why" is that these are equal because, in fact, $\phi$ is constant:
$$\phi(t) = \int_a^bf(x) \, dx$$
for all $0 \le t \le 1$. The proof is by splitting the integral into two as
$$\int_a^bf(x) \, dx = \int_a^{a(1-t)+bt}f(x) \, dx + \int_{a(1-t)+bt}^bf(x) \, dx$$
and evaluating the first by expanding $f$ as a power series about $a$ and the second by expanding $f$ as a power series about $b$. You will get $\phi(t)$ as the result.
Specifically, the "when" is the condition that the power series expansions
$$f(x) = f(a)+f'(a)(x-a)+\frac{1}{2!}f''(a)(x-a)^2+\cdots$$
and
$$f(x) = f(b)+f'(b)(x-b)+\frac{1}{2!}f''(b)(x-b)^2+\cdots$$
are valid for all $x \in [a,b]$.
At the risk of sounding totally banal, I've basically just briefly rehashed (and slightly generalized) the derivation you linked to $-$ that post in itself already gives the proof.

A: Alright, here's another explanation.
The idea is that when you're dealing with an analytic function, if you know $f(a), f'(a), f''(a), ...$, then you already have all the information about $f$. If you also happen to know $f(b), f'(b), f''(b), ...$, well that information is totally redundant. Since
$$f(x) = f(a)+f'(a)\cdot(x-a)+\frac{1}{2!}f''(a)\cdot(x-a)^2+\cdots
= \sum_n \frac{f^{(n)}(a)}{n!}(x-a)^n$$
and
$$f^{(n)}(x) =
    f^{(n)}(a) +
    f^{(n+1)}(a)\cdot(x-a) +
    \frac{1}{2!}f^{(n+2)}(a)\cdot(x-a)^2 +
    \cdots =
  \sum_m \frac{f^{(m)}(a)}{(m-n)!}(x-a)^{m-n},$$
just go into the series in question and substitute away all instances of $f^{(n)}(b)$. Then find the coefficient of $f^{(N)}(a)$ for each $N$; you'll find that you get $\frac{(b-a)^{N+1}}{(N+1)!}$ as the coefficient in both cases.

Are you prepared for gory details? Are you sure you really want to see gory details?
So the first series in question is
$$\sum_{n \ge 0}\frac{(b-a)^{n+1}}{(n+1)!}
\left( f^{(n)}(a) \cdot \frac12 + f^{(n)}(b) \cdot (-1)^n \cdot\frac12\right).$$
Now do the substitution to get
$$\sum_{n \ge 0}\frac{(b-a)^{n+1}}{(n+1)!}
\left( \frac12 f^{(n)}(a) + \frac12 (-1)^n
    \sum_m \frac{f^{(m)}(a)}{(m-n)!}(b-a)^{m-n}
\right).$$
The coefficient of $f^{(N)}(a)$ in this
$$  \frac12 \frac{(b-a)^{N+1}}{(N+1)!} +
    \frac12 (-1)^0 \frac{(b-a)^{0+1}}{(0+1)!} \frac{(b-a)^{N-0}}{(N-0)!} +
    \frac12 (-1)^1 \frac{(b-a)^{1+1}}{(1+1)!} \frac{(b-a)^{N-1}}{(N-1)!} +
    \cdots +
    \frac12 (-1)^N \frac{(b-a)^{N+1}}{(N+1)!} \frac{(b-a)^{N-N}}{(N-N)!}
$$
which can be rewritten as
$$  \frac12 \frac{(b-a)^{N+1}}{(N+1)!}
    \left(
        1 +
        (-1)^0 \binom{N+1}{1} +
        \cdots +
        (-1)^N \binom{N+1}{N+1}
    \right)
.$$
Apply the binomial coefficient identity (i.e. just the binomial theorem)
$$  (-1)^0 \binom{c}{0} +
    (-1)^1 \binom{c}{1} +
    \cdots +
    (-1)^c \binom{c}{c}
  = (1-1)^c
  = 0
$$
to get $\frac{(b-a)^{N+1}}{(N+1)!}$ as promised.

I'll leave out the details of the other verification; you my dear reader can fill them in as an exercise. To briefly sketch it: at the last step you'll get
$$  \frac{(b-a)^{N+1}}{(N+1)!}
    \left(
        \frac{1}{2^{N+1}} +
        \frac{(-1)^0}{2^1}\binom{N+1}{1} +
        \frac{(-1)^1}{2^2} \binom{N+1}{2} +
        \cdots +
        \frac{(-1)^N}{2^{N+1}} \binom{N+1}{N+1}
    \right)
$$
and another binomial coefficient identity will bring you to $\frac{(b-a)^{N+1}}{(N+1)!}$.

So there it is. Hey, it wasn't actually so bad. I'd say the other proof is more intuitive, since it actually explains what the two series in question represent. This derivation is more straightforward, in the sense that it requires no real creative leaps.

A: Denote a primitive of $f$ by $F$ and add ${1\over2}\bigl(F(a)-F(b)\bigr)$ to both series. Then the first series becomes
$$\eqalign{{1\over2}\sum_{k=0}^\infty \bigl(F^{(k)}(a)-(-1)^kF^{(k)}(b)\bigr){(b-a)^k\over k!}&={1\over2}\sum_{k=0}^\infty F^{(k)}(a){(b-a)^k\over k!}
-{1\over2}\sum_{k=0}^\infty F^{(k)}(b){(a-b)^k\over k!}\cr
&={1\over2}\bigl(F(b)-F(a)\bigr)\ ,\cr}$$
and similarly the second series becomes
$$-{1\over2}\bigl(F(a)-F(b)\bigr)+\sum_{k=0}^\infty \bigl(F^{(k)}(a)-(-1)^k F^{(k)}(b)\bigr)\>{\bigl({b-a\over2}\bigr)^k\over k!}$$
$$={1\over2}\bigl(F(b)-F(a)\bigr)+F\left({a+b\over2}\right)-F\left({a+b\over2}\right)={1\over2}\bigl(F(b)-F(a)\bigr)\ .$$


text:
Q: Find $\alpha$ if AB = 2HM
My progress
I haven't made much progress. I figured out the angles but all the equations are equivalent. I think some additional straight will be needed.
I plotted H, D midpoint of AB, so AD = DB = x. Therefore:
$\triangle ADH (isosceles) \triangle DHB (isosceles)...$
(Answer: $\alpha =18ô$

A:
Let point $D$ be midpoint of $AB$, $AD=BD$
Draw $HD$, then $HD=AD=BD=HM$
Draw $DM$, then $\triangle HDM$  is an isosceles with $HD=HM$
$DM \parallel AG$, since $AD=BD$ and $BM=MG$ (Midpoint Theorem)
$\angle AMD= \angle MAG= \alpha$, then $\angle HDM=\angle AMD = \alpha$
$\angle DHA =2\alpha$ (exterior angle of triangle $HDM$)
$\angle DAH =\angle DHA =2\alpha$ $(AD=DH)$
$5\alpha =90$ (in triangle ABH)
$\alpha=18$

A: Join D to M and mark intersection of DM and BH as F. we have:
$DM||AC\Rightarrow \angle FMH=\angle MAF=\alpha$
Triangle DHM is isosceles so:
$\angle HDF=\alpha$
$\angle DFH=90+\alpha$
So: $\angle DHB=180-(90+\alpha+\alpha)=90-2\alpha$
Triangle BDH is isosceles and we have:
$\angle DBH=\angle DHB$
So:
$3\alpha=90--2\alpha\Rightarrow \alpha=18^o $


text:
Q: Setting up a download of data already in the Javascript data model Some Javascript on a page gets a large wad of data from a server. At some point, I'd like to allow the user to click to download this data in, say, a format digestible to Excel.
My belief is that this will require the data to be on the server and re-fetched by the browser, but I am hoping that there's something I'm missing, and that there's some way for Javascript to get the browser to offer the 'save as' dialog to save away some content generated righ there.

A: The data URI method is probably the most direct. Although there are alternatives, for example, https://github.com/dcneiner/Downloadify achieves this with flash. pimvdb's comment links to his nice HTML5 implementation.


text:
Q: how to get value selected by user in SumoSelect? I have a drop down of various countries, and I have an array of objects representing the information of each country. I've implemented the dropdown through sumoselect. What I want is-
Depending on what value is clicked by the user, I want to fetch the data of that particular country from the array and display it.
For eg, If I select New Zealand from the drop down, then I want to see the data of new-zealand.  How can I do it? Thanks in advance!

$(document).ready(function () {
            var countryData={"usa":
              "The U.S. is a country of 50 states covering a vast swath of North America, with Alaska in the northwest and Hawaii extending the nation's presence into the Pacific Ocean. Major Atlantic Coast cities are New York, a global finance and culture center, and capital Washington, DC. Midwestern metropolis Chicago is known for influential architecture and on the west coast, Los Angeles' Hollywood is famed for filmmaking.",
              "india": "India is a vast South Asian country with diverse terrain – from Himalayan peaks to Indian Ocean coastline – and history reaching back 5 millennia. In the north, Mughal Empire landmarks include Delhi's Red Fort complex and massive Jama Masjid mosque, plus Agra's iconic Taj Mahal mausoleum. Pilgrims bathe in the Ganges in Varanasi, and Rishikesh is a yoga centre and base for Himalayan trekking." ,
              "england" : "England, birthplace of Shakespeare and The Beatles, is a country in the British Isles bordering Scotland and Wales. The capital, London, on the River Thames, is home of Parliament, Big Ben and the 11th-century Tower of London. It's also a multicultural, modern hub for the arts and business. Other large cities are Manchester, Birmingham, Liverpool, Bristol and the university centres of Oxford and Cambridge.",
              "new-zealand": "New Zealand is a country in the southwestern Pacific Ocean consisting of 2 main islands, both marked by volcanoes and glaciation. Capital Wellington, on the North Island, is home to Te Papa Tongarewa, the expansive national museum. Wellington's dramatic Mt. Victoria, along with the South Island's Fiordland and Southern Lakes, stood in for mythical Middle Earth in Peter Jackson's 'Lord of the Rings' films.",
              "russia": "Russia, the world's largest nation, borders European and Asian countries as well as the Pacific and Arctic oceans. Its landscape ranges from tundra and forests to subtropical beaches. It's famous for Moscow's Bolshoi and St. Petersburg's Mariinsky ballet companies. St. Petersburg, founded by Russian leader Peter the Great, has the baroque Winter Palace, now housing part of the State Hermitage Museum's art collection."
              };
            $('.countries').SumoSelect();
     });
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery.sumoselect/3.0.2/sumoselect.min.css">

<select class="countries">
<option value="usa">USA</option>
<option value="india">India</option>
<option value="england">England</option>
<option value="new-zealand">New Zealand</option>
<option value="russia">Russia</option>
</select>

A: You can use change event with SumoSelect to access the selected value.

$(document).ready(function () {
  var countryData={"usa":
    "The U.S. is a country of 50 states covering a vast swath of North America, with Alaska in the northwest and Hawaii extending the nation's presence into the Pacific Ocean. Major Atlantic Coast cities are New York, a global finance and culture center, and capital Washington, DC. Midwestern metropolis Chicago is known for influential architecture and on the west coast, Los Angeles' Hollywood is famed for filmmaking.",
    "india": "India is a vast South Asian country with diverse terrain – from Himalayan peaks to Indian Ocean coastline – and history reaching back 5 millennia. In the north, Mughal Empire landmarks include Delhi's Red Fort complex and massive Jama Masjid mosque, plus Agra's iconic Taj Mahal mausoleum. Pilgrims bathe in the Ganges in Varanasi, and Rishikesh is a yoga centre and base for Himalayan trekking." ,
    "england" : "England, birthplace of Shakespeare and The Beatles, is a country in the British Isles bordering Scotland and Wales. The capital, London, on the River Thames, is home of Parliament, Big Ben and the 11th-century Tower of London. It's also a multicultural, modern hub for the arts and business. Other large cities are Manchester, Birmingham, Liverpool, Bristol and the university centres of Oxford and Cambridge.",
    "new-zealand": "New Zealand is a country in the southwestern Pacific Ocean consisting of 2 main islands, both marked by volcanoes and glaciation. Capital Wellington, on the North Island, is home to Te Papa Tongarewa, the expansive national museum. Wellington's dramatic Mt. Victoria, along with the South Island's Fiordland and Southern Lakes, stood in for mythical Middle Earth in Peter Jackson's 'Lord of the Rings' films.",
    "russia": "Russia, the world's largest nation, borders European and Asian countries as well as the Pacific and Arctic oceans. Its landscape ranges from tundra and forests to subtropical beaches. It's famous for Moscow's Bolshoi and St. Petersburg's Mariinsky ballet companies. St. Petersburg, founded by Russian leader Peter the Great, has the baroque Winter Palace, now housing part of the State Hermitage Museum's art collection."
    };
  var mySelect = $('select.countries').SumoSelect();
  $('select.countries').on('change', function() {
    $('#countryInfo').text(countryData[mySelect.value]);
  })
});

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery.sumoselect/3.0.2/sumoselect.min.css">
<select class="countries">
<option value="usa">USA</option>
<option value="india">India</option>
<option value="england">England</option>
<option value="new-zealand">New Zealand</option>
<option value="russia">Russia</option>
</select>


text:
Q: Stub geocoder with address_components in rspec i try to write rspec to test some code work with gem Geocoder. With location is a Geocoder::Result::Google object, my code like :
address = location.address_components_of_type(:sublocality_level_1).first&.dig('long_name')

and i implement stub a point like (refer here ) :
```ruby
Geocoder.configure(lookup: :test)
Geocoder::Lookup::Test.set_default_stub(
  [
    {
      'latitude'     => 35.6691084,
      'longitude'    => 139.6009546,
      'address'      => 'Address',
      'state'        => 'State',
      'city'         => 'City',
      'types'        => ['political'],
      'address_components' => [
        {
          'types' => ['sublocality_level_1'],
          'long_name' => 'level_1',
        }
      ]
    },
  ]
)

i try to byebug when run rspec and check, i get :
(byebug) location.class
Geocoder::Result::Test
(byebug) location.address_components
[{"types"=>["sublocality_level_1"], "long_name"=>"level_1"}]
(byebug) location.respond_to?(:address_components_of_type)
false

location.respond_to?(:address_components_of_type) return false, and i can't call location.address_components_of_type(:sublocality_level_1).first&.dig('long_name') as my expect.
location when run rspec is a Geocoder::Result::Test object
so, can you help me to resolve this issue? many thanks

Geocoder version: 1.4.3
Rails version: 5.0.2


text:
Q: compress vector in (inverse of rep) I need to decompose a vector into a series of x and repeat, I am not really sure what the proper term for this is. It is the inverse of the rep function. So a vector
[1,2,2,2,2,1,1,1,1,1,2,2] -> [1x1, 4x2, 5x1, 2x2]

I wrote a little function to do this, but I am sure there must be a more native way:
invrep <- function(y){
  numy <- as.numeric(y);
  newpoints <- which(c(T,diff(numy) != 0));
  x <- y[newpoints];
  times <- diff(c(newpoints, length(numy)+1));
  return(list(x=x, times=times));
}

myvec <- factor(floor(runif(50,0,3)), levels=0:2, labels=c("blue", "yellow", "red"));
myrep <- invrep(myvec);
identical(myvec, rep(myrep$x, myrep$times));

A: The rle function should do the trick:
> x <- c(1,2,2,2,2,1,1,1,1,1,2,2)
> y <- rle(x)
> y
Run Length Encoding
  lengths: int [1:4] 1 4 5 2
  values : num [1:4] 1 2 1 2
> inverse.rle(y)
 [1] 1 2 2 2 2 1 1 1 1 1 2 2
> rep(y$values, y$lengths)
 [1] 1 2 2 2 2 1 1 1 1 1 2 2

UPDATE As @TylerRinker commented, use as.character on factors:
myvec <- factor(sample.int(3,50,TRUE), levels=1:3, labels=c("blue", "yellow", "red"))
x <- rle(as.character(myvec))
y <- inverse.rle(x)


text:
Q: Plotting graph and data with PSTricks: Wrong scaling Consider the following code:
\documentclass{article}

\usepackage{pst-plot}

\begin{document}

% options
\psset{
  xunit = 5,
  yunit = 50
}
% constants.
\def\masse{0.183276667}  % kg
\def\kraft{0.0278661}    % N
\def\bKonst{0.012}       % kg/s
\def\omegaKonst{12.1278} % s^(-1)
% function
\def\amplitude(#1){\kraft/(\omegaKonst*\masse*sqrt(\omegaKonst^2*(#1)^4+(\bKonst^2/\masse^2-2*\omegaKonst^2)*(#1)^2+\omegaKonst^2))}
% data
\readdata{\resonans}{data-resonans.txt}
% plot
\begin{pspicture}(-0.21,-0.011)(1.83,0.191)
  \psaxes[
    dx = 0.2,
    Dx = 0.2,
    dy = 0.02,
    Dy = 0.005,
    comma
  ]{->}(0,0)(1.5,0.09)[$\omega_{\textup{SHB}}/\omega_{\textup{d}}$,0][$A$~(m),90]
  \listplot[
    plotstyle = dots,
    dotstyle = o,
    fillcolor = red
  ]{\resonans}
  \psplot[
    algebraic,
    plotpoints = 1000,
    linecolor = blue
  ]{0}{1.5}{\amplitude(x)}
\end{pspicture}

\end{document}

How do I get the same output as the following?

The data can be downloaded from http://gupl.dk/705814/.

A: \documentclass{article}

\usepackage{pst-plot}
\usepackage{filecontents}

\begin{filecontents*}{data.dat}
[[0.6005832177,0.00371],[0.6618893637,0.00388],[0.7123448644,0.00246],[0.7324185582,0.00266],[0.7861292525,0.00328],[0.8523181889,0.00451],[0.9109116735,0.00647],[0.9282727060,0.00760],[0.9906639165,0.0114],[1.025928514,0.0152],[1.051970063,0.0222],[1.079096676,0.0131],[1.105138225,0.00865],[1.149625870,0.00549],[1.170242096,0.00455],[1.220155065,0.00336],[1.256504727,0.00267],[1.351990405,0.00184]]
\end{filecontents*}
\begin{document}

% options
\psset{
  xunit = 5,
  yunit = 200
}
% constants.
\def\masse{0.183276667}  % kg
\def\kraft{0.0278661}    % N
\def\bKonst{0.13831}       % kg/s
\def\omegaKonst{12.1278} % s^(-1)
% function
\def\amplitude{\kraft/(\omegaKonst*\masse)/%
  sqrt(\omegaKonst^2*x^4+(\bKonst^2/\masse^2-2*\omegaKonst^2)*x^2+\omegaKonst^2)}
% data
% plot
\begin{pspicture}(-0.21,-0.011)(1.83,0.021)
  \psaxes[
    Dx = 0.4,
    Dy = 0.005,
    comma
  ]{->}(0,0)(1.5,0.02)[$\omega_{\textup{SHB}}/\omega_{\textup{d}}$,0][$A$~(m),90]
\readdata{\resonans}{data.dat}
  \listplot[
    plotstyle = dots,
    dotstyle = o,
    fillcolor = red
  ]{\resonans}
  \psplot[
    algebraic,
    plotpoints = 5000,
    linecolor = blue,
    yMaxValue=0.08
  ]{0}{1.5}{\amplitude}
\end{pspicture}

\end{document}

And here the solution with values:
\documentclass{article}
\usepackage{pst-plot}
\usepackage{filecontents}

\begin{filecontents*}{data.dat}
[[0.6005832177,0.00371],[0.6618893637,0.00388],[0.7123448644,0.00246],[0.7324185582,0.00266],[0.7861292525,0.00328],[0.8523181889,0.00451],[0.9109116735,0.00647],[0.9282727060,0.00760],[0.9906639165,0.0114],[1.025928514,0.0152],[1.051970063,0.0222],[1.079096676,0.0131],[1.105138225,0.00865],[1.149625870,0.00549],[1.170242096,0.00455],[1.220155065,0.00336],[1.256504727,0.00267],[1.351990405,0.00184]]
\end{filecontents*}
\begin{document}

% options
\psset{
  xunit = 5,
  yunit = 200
}
% function
\def\amplitude{0.0125368/sqrt(147.084-293.598*x^2+147.084*x^4)}
% data
% plot
\begin{pspicture}(-0.21,-0.011)(1.83,0.03)
  \psaxes[
    Dx = 0.4,
    Dy = 0.005,
    dy=0.01,
    comma
  ]{->}(0,0)(1.5,0.03)[$\omega_{\textup{SHB}}/\omega_{\textup{d}}$,0][$A$~(m),90]
\readdata{\resonans}{data.dat}
  \listplot[
    plotstyle = dots,
    dotstyle = o,
    fillcolor = red
  ]{\resonans}
  \psplot[
    algebraic,
    plotpoints = 5000,
    linecolor = blue,
  ]{0}{1.5}{\amplitude}
\end{pspicture}

\end{document}


text:
Q: Is there any easy way to convert multipart/form data to an array in NodeJS? I am trying some input to get post data as array in Sails/nodeJS;
When I try with this way then get data as array perfectly.
<input type="text" class="form-control" name="answer[1][txt]">
 <input type="text" class="form-control" name="answer[1][img]">
 <input type="text" class="form-control" name="answer[2][txt]">
 <input type="text" class="form-control" name="answer[2][img]">

Output:
answer:[ { txt: 'ans 1', img: 'yes' }, { txt: 'ans 2', img: 'yes' } ]

But when I use enctype(enctype="multipart/form-data") attribute in form then can not get data as previous method.
Output:
  'answer[0][txt]': 'ans 1', 'answer[0][img]': 'yes',
'answer[1][txt]': 'ans 2','answer[1][img]': 'yes',

I don't know what happened when I use enctype attribute. I want only first return output data with using enctype(multipart/form-data) attribute.
Thank You

A: You can create a new object from the currently returned object; use for..in loop to iterate object, match "txt" or "img" portion of property, set value to value of existing object

let data = {
  'answer[0][txt]': 'ans 1',
  'answer[0][img]': 'yes',
  'answer[1][txt]': 'ans 2',
  'answer[1][img]': 'yes'
};

let res = {
  answer: []
};

for (let prop in data) {
  res.answer.push({
    [prop.match(/txt|img/)[0]]: data[prop]
  })
}

console.log(res);


text:
Q: .jar works only on my computer, classnotfoundexception on others I'm building a java project on my Lubuntu computer and while it's working on my computer, when I'm trying to run it on a different one (Windows/Lubuntu) I'm getting

Exception in thread "main" java.lang.NoClassDefFoundError: geli/BasicApp
  .....
  ...
  ....
   ............
  ....
  Caused by: java.lang.ClassNotFoundException: geli.BasicApp

Here's the file structure -

At the beginning I've thought that it's because of the Linux and Windows path difference but testing it on my other Linux computer gave me the same error that I've got on my windows computer.
I have no clue for the solution and I'd really appreciate any help.
EDIT:
jar file from inside has the libs
Manefiest:

A: As you are using eclipse you can just follow these steps :
Right click the project -> Export -> Java -> Runnable jar file
If you want to manually resolve the issue follow the steps:

*

*Add all the dependant jars in a folder, say "dependencies". Place the folder in the same location of your actual jar

*Now add the the dependency entries in META-INF/MANIFEST.MF file of your jar as below
Class-Path: dependencies/dependency1.jar dependencies/dependency2.jar


text:
Q: Converting a regular json file to a parent-child hierarchical json as used by d3 flare.json I have a json file with the following structure:
  {
    "a": "b",
    "c": "d",
    "e": {
      "f": "g",
      "h": "i"
    }
  }

I would like it to have the following structure:
  {
    "name": "Root",
    "parent": "null",
    "children": [
      {
        "name": "a",
        "parent": "Root",
        "children": [
          {
            "name": "b",
            "parent": "a"
          }
        ]
      },
      {
        "name": "c",
        "parent": "Root",
        "children": [
          {
            "name": "d",
            "parent": "d"
          }
        ]
      },
      {
        "name": "e",
        "parent": "Root",
        "children": [
          {
            "name": "f",
            "parent": "e",
            "children": [
              {
                "name": "g",
                "parent": "f"
              },
              {
                "name": "h",
                "parent": "e",
                "children": [
                  {
                    "name": "i",
                    "parent": "h"
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  }

I would like to have a parent-children hierarchy relationship so that it would be easier to draw a collapsible-tree diagram with nodes.Please forgive if the indentation is not proper.

A: You could use a recursive approach by using the object and a parent value.
For getting the wanted style with Root element, you need to hand over a new object which follows the same building rule than the inner objects of the given data.

{
    Root: data[0]
}

const
    getObjects = (o, parent) =>
        o && typeof o === 'object'
            ? Object.entries(o).map(([name, v]) => ({ name, parent, children: getObjects(v, name) }))
            : [{ name: o, parent }];

var data = [{ a: "b", c: "d", e: { f: "g", h: "i" } }],
    result = getObjects({ Root: data[0] }, 'null');

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: Here's one possibility:

const treeify = (orig) => Object.entries(orig).map(
  ([k, v]) => (Object.assign({name: k}, typeof v == 'object'
    ? {children: treeify(v)}
    : {children: {name: v}}
  ))
)
const convert = (orig) => ({name: 'Root', children: treeify(orig)})

const orig = {"a": "b", "c": "d", "e": {"f": "g", "h": "i"}}

console.log(convert(orig))

treeify handles the heavy lifting, and convert is a simple wrapper that adds the Root node.  Note that there is no attempt to create parent nodes, as those, according to the comments, are not necessary.
Update
The clarity of the answer from Nina Scholz, which does supply a parent (I thought it would be much more difficult!) suggests an alternative to this version to also include it.  Even without the parents, I like this version of convert better:

const treeify = (orig, parent) => Object.entries(orig).map(
  ([k, v]) => (Object.assign({name: k, parent}, typeof v == 'object'
    ? {children: treeify(v, k)}
    : {children: {name: v, parent: k}}
  ))
)

const convert = (orig) => treeify({Root: orig}, 'null')[0]

const orig = {"a": "b", "c": "d", "e": {"f": "g", "h": "i"}}
console.log(convert(orig))


text:
Q: How do I remove a COM+ component from a COM+ application programmatically I am trying to automate a build, and the application uses COM+ applications with Components, and I need to figure out how to delete the component from the package using c#.  I am using the COMAdmin library, and have built out a collection of the applications, but i'm kinda stuck from there.  Any help would be appreciated.
Thanks!
public static void RemoveComponents()
    {
        COMAdminCatalog objCatalog = new COMAdminCatalog();
        string ApplicationName = "Comply Plus Web";

    }

A: I think you'd want System.EnterpriseServices.RegistrationHelper.UninstallAssembly().


text:
Q: How to remove TapStops location recursively using enumerateAttributes in iOS I've to show HTML data in UITextView, this HTML data sometimes contains nested tags for lists, which cause extra padding on device, I want to remove extra padding using swift side since padding from CSS doesn't seem to be working here. Here is how my code and sample data looks like
let mutableAttributedString = NSMutableAttributedString(attributedString: attributedQuestionMessage!)
    mutableAttributedString.enumerateAttributes(in: NSMakeRange(0, mutableAttributedString.length), options: []) { (attributes, range, stop) in
        let maybeParagraphStyles = attributes.filter {$0.key == NSAttributedStringKey.paragraphStyle }
        maybeParagraphStyles.forEach({ (style) in
            if let paragraphStyle = style.value as? NSParagraphStyle {
                let mutableParagraphStyle = paragraphStyle.mutableCopy() as! NSMutableParagraphStyle

                let modifiedTabStops = mutableParagraphStyle.tabStops.map {
                    NSTextTab(textAlignment: $0.alignment, location: $0.location - mutableParagraphStyle.defaultTabInterval, options: $0.options)
                }
                if modifiedTabStops.count > 0 {
                    mutableParagraphStyle.tabStops = modifiedTabStops
                }
                var mutableAttributes = attributes

                mutableAttributes[NSAttributedStringKey.paragraphStyle] = mutableParagraphStyle
                mutableAttributedString.removeAttribute(.paragraphStyle, range: range)
                mutableAttributedString.addAttribute(.paragraphStyle, value: mutableParagraphStyle, range: range)
            }
        })

    }
    textView.attributedText = mutableAttributedString

this works fine, but fails for when I've to display data like this

To make this more tangible, let's bring this concept to
the team level. What would you say are the aspirations for your
team?

What is the overall goal?

E.g., Increase customer
loyalty by 20% as measured by Repeat Customer Rate

What specific initiatives do you think would lead you to achieve
it?

E.g., Implement a loyalty
program that rewards customers each time they purchase a certain value
 of items

which show data like this, as you can see there is alignment issue & padding too, any suggestions ?

A: As you can see it's obvious in the code that I'm reducing NSTextTab by subtracting it defaultTabInterval from it, head indent of paragraphStyle is equivalent to in this case modifiedTabStops.last?.location, since I was changing the location of both tabs of NSTextTab, changing the headIndent solve my problem. Here is the solution.
    let mutableAttributedString = NSMutableAttributedString(attributedString: attributedQuestionMessage!)
    mutableAttributedString.enumerateAttributes(in: NSMakeRange(0, mutableAttributedString.length), options: []) { (attributes, range, stop) in
        let maybeParagraphStyles = attributes.filter {$0.key == NSAttributedStringKey.paragraphStyle }
        maybeParagraphStyles.forEach({ (style) in
            if let paragraphStyle = style.value as? NSParagraphStyle {
                let mutableParagraphStyle = paragraphStyle.mutableCopy() as! NSMutableParagraphStyle

                let modifiedTabStops = mutableParagraphStyle.tabStops.map {
                    NSTextTab(textAlignment: $0.alignment, location: $0.location - mutableParagraphStyle.defaultTabInterval, options: $0.options)
                }

                if modifiedTabStops.count > 0 &&  mutableParagraphStyle.headIndent > mutableParagraphStyle.defaultTabInterval {
                    if let location = modifiedTabStops.last?.location {
                        mutableParagraphStyle.headIndent = location
                    }
                    mutableParagraphStyle.tabStops = modifiedTabStops
                }
                var mutableAttributes = attributes
                mutableAttributes[NSAttributedStringKey.paragraphStyle] = mutableParagraphStyle
                mutableAttributedString.removeAttribute(.paragraphStyle, range: range)
                mutableAttributedString.addAttribute(.paragraphStyle, value: mutableParagraphStyle, range: range)
            }
        })

    }


text:
Q: 200%+ width page, how to make an object stay fix centered I'm making a one page web site with horizontal scrolling and undefined width, and I'd like to know how to keep my logo and navigation centered in all time at the top.

A: You can try, margin-left:auto; margin-right:auto