text:
Q: Slow For Each Element in Array Loop with Instr I need to check if values (approx 10.000 insecure passwords) stored in a one-dimensional array occur in a TextBox and display a warning if necessary.
But due to the constant checking after each keystroke the input into the TextBox is very delayed.
Does anyone know a faster way to do this?
Greetings Ronny
'ForbiddenPasswords = one-dimensional array
Private Sub txtAdminPassword_Change()
Dim VarDat As Variant

For Each VarDat In ForbiddenPasswords
    If InStr(1, LCase(txtAdminPassword.Text), VarDat) > 0 Then
        lblInsecureWarning.Visible = True
        Exit For
    End If
Next
End Sub

A: Rather than loading the list of banned passwords in an array and searching through it to find if it exists, consider using a table to store the (lower case) passwords. You can then open a recordset based on the text entered, and see if it returns any records. Something like:
Function fCheckBannedPWD(strPWD As String) As Boolean
'   returns true if the entered password is banned, otherwise false
    On Error GoTo E_Handle
    Dim db As DAO.Database
    Dim rsPWD As DAO.Recordset
    Dim strSQL As String
    Set db = CurrentDb
    strSQL = "SELECT BannedPWD FROM tblPWD WHERE InStr('" & LCase(strPWD) & "',BannedPWD)>0;"
    Set rsPWD = db.OpenRecordset(strSQL)
    If Not (rsPWD.BOF And rsPWD.EOF) Then
        fCheckBannedPWD = True
    End If
fExit:
    On Error Resume Next
    rsPWD.Close
    Set rsPWD = Nothing
    Set db = Nothing
    Exit Function
E_Handle:
    MsgBox Err.Description & vbCrLf & vbCrLf & "fCheckBannedPWD", vbOKOnly + vbCritical, "Error: " & Err.Number
    Resume fExit
End Function

Regards,

A: Arrays want to be iterated with For...Next; Object collections want to be iterated with For Each...Next. Using For Each to iterate a large array is going to be slower than it needs to be.
Converting 10K strings to lowercase is also taking a toll on performance.
Using InStr is verifying whether the password contains the forbidden password, not whether it is one of them: assuming you mean to check if the user's password exists in the forbidden passwords list, you don't need InStr.
If you want to stick with an array, use For...Next to iterate it, and specify Option Compare Text to have the = operator treat "string" the same as "STRING" (default is Option Compare Database in Access, which matches your database settings - in all other hosts it's Option Compare Binary, which is case-sensitive).
But you shouldn't need to iterate any array. Assuming the 10K strings are all unique, you can have them added to a keyed Collection, and then you can instantly know if the user's password is in the collection by trying to add the user's password to the collection:
Private Function IsForbiddenPassword(ByVal Value As String) As Boolean
'assuming a ForbiddenPasswords global collection exists
    On Error Resume Next
    ForbiddenPasswords.Add Value, Value 'if the key already exists, an error is raised
    If Err.Number <> 0 Then
        'key already exists: password is forbidden
        IsForbiddenPassword = True
    Else
        '.Add was successful, password is not forbidden (gotta remove it now!)
        ForbiddenPasswords.Remove Value
    End If
    On Error GoTo 0
End Function

Alternatively, use a Scripting.Dictionary and its Exists method, which returns True if a given key already exists:
Private Sub txtAdminPassword_Change()
    'where ForbiddenPasswords is a Dictionary instance keyed with the passwords:
    lblInsecureWarning.Visible = ForbiddenPasswords.Exists(Value)
End Sub

A: Try the next way, please:

*

*Create a Private variable on top of the module (in the declarations area):

Private objExcel As Object

*Copy the next function code:

Function passExists(strPass As String, arr) As Boolean
   Dim lPath As String
   lPath = UCase(strPass)
   passExists = Not IsError(objExcel.Application.match(lPath, arr, 0))
End Function

*It can be checked in the next way:

Sub checkPasswordInArray()
 Dim ForbiddenPasswords, boolMatch As Boolean, strPass As String
   If objExcel Is Nothing Then Set objExcel = CreateObject("Excel.Application")
   ForbiddenPasswords = Split("pass1,pass2,pass3", ",")
   strPass = "Pass2" 'txtAdminPassword.Text
   Debug.Print passExists(strPass, ForbiddenPasswords)
End Sub

In order to be very fast, objExcel must not be created each time you need to use the function, but you must take care to quit after using it...

A: Just to be complete, 2 additions to the propositions found.

*

*txtAdminPassword.Text LIKE vardat & "*" is about 6x faster than
InStr(1, LCase(txtAdminPassword.Text), VarDat) > 0

*for even better perf with your array,  you can use Filter:
Dim strSubNames As Variant
strSubNames = Filter(forbiddenPasswords, txtAdminPassword.Text)


text:
Q: How can I maintain the order of column from database to Dundas The sequence of columns when coming to dundas gets changed.
is there any way to retain order.
I am using Dundas Dashboard V5. The virtual table is getting data from a stored procedure and I am using dataset into data grid for dashboard. The data from the table is in a sequence which retains till virtual table but gets changed from dataset.
Also last few columns returned pivoted data of two year whose month are dynamic and are in sequence
Eg:
PIVOT(MAX(AmountCurrency)
      FOR [Month] IN ([Sep2015], [Oct2015], [Dec2015], [Feb2016], [Mar2016], [Apr2016], [Jun2016], [Jul2016], [Oct2016], [Dec2016]
     )) AS MNamePivot

Now two problems which I am facing are:

*

*The sequence of months which I create in the stored procedure should be retained in dashboard like mm/yy chronologically

*The month do get change dynamically so the dashboard should show the changed month(At the moment it is showing Old Cached data).
Let me know if this make sense and is there any solution to it.
Thanks for your time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как отправить на контроллер все строки из foreach Есть у меня View которая отображает определенные данные. Я хочу добавить checkbox для каждой строки и передать это все в контроллер.
@model List<PlumbingCalculation>

<form method="post" asp-action="IncludeCalculationSelectData" asp-controller="Plumbing" asp-route-id="@ViewBag.Id">

                @{foreach (PlumbingCalculation item in Model)
                    {

                                <input type="checkbox" value="true" name="col" />
                                <input type="hidden" value="false" name="col" />

                                <input type="hidden"  name="col" asp-for="@item.CalculationName" />
                                @item.CalculationName

                    }
                }

        <input type="submit" class="btn btn-default" value="Далее" />
    </form>

На View выводит 3 элемента.
Модель:
public class PlumbingCalculation
    {
        public int PlumbingCalculationId { get; set; }
        public int PlumbingMainId { get; set; }
        public string CalculationName { get; set; }
        //
        [NotMapped]
        public bool isChecked { get; set; }

        public PlumbingMain PlumbingMain { get; set; }
    }

Но я не понимаю, как передать коллекцию в контроллер.
Я пробовал так:
 [HttpPost]
        public IActionResult IncludeCalculationSelectData(int id, List<PlumbingCalculation> col)
        {
                     ViewBag.count = names.Count();
                     return View("test");
        }

Количество : 0

A: У меня так и не получилось передать коллекцию объектов целиком, я
исправил параметр name в input и передал в контроллер каждый imput как отдельную коллекцию:
@{foreach (PlumbingCalculation item in Model)
                    {

                                <input type="checkbox" value="true" name="checkbox" />
                                <input type="hidden" value="false" name="checkbox" />

                                <input type="hidden"  name="CalculationName" asp-for="@item.CalculationName" />
                                @item.CalculationName

                    }
                }

Контроллер:
[HttpPost]
        public IActionResult IncludeCalculationSelectData(int id, List<bool> checkbox, List<string> CalculationName )
        {
                     ViewBag.count = CaclulationName.Count();
                     return View("test");
        }

На выходе я получил свои 3 элемента. Возможно кто-то найдет более приемлемое решение. Был бы рад услышать.

A: Через создание контекста данных в Entity Framework
    public class BookContext : DbContext {
        public DbSet<PlumbingCalculation> plumbingCalculation { get; set; }
    }

Создаете в контроллере экземпляр контекста и передаете через ViewBag в методе действия


text:
Q: How to use the Adobe Acrobat JavaScript SDK to save the pdf from the browser? Adobe Acrobat allows us to insert JS in the pdf:
if (app.alert("Do you want to save the pdf?", 2, 3) === 4) {
    // Save the pdf.
}

I tried: app.save(), app.execCommand("Save"), but both failed.
Is it possible that using the Adobe Acrobat JavaScript SDK to trigger the save action inside of the browser?


text:
Q: WARNING: autodoc: failed to import module 'upload_data_to_server' from module 'manual'; I'm trying to document a Django project using Sphinx's autodoc extension. I have two main problems:

*

*It's documenting excessivelly in some modules (importing documentation that I don't want from django)

*It's not documenting one of the packages at all.

Here is my django tree:
|main_app
|   core
|      migrations
|      static
|      templates
|      consumers.py
|      forms.py
|      models.py
|      routing.py
|      serializers.py
|      urls.py
|      views.py
|   main_app
|      asgi.py
|      settings.py
|      urls.py
|      wsgi.py
|   manual
|      upload_data_to_server.py
|   manage.py
|   docs
|      _build
|      _static
|      _templates
|      conf.py
|      index.rst
|      make.bat
|      Makefile

The docs file is the one I created to host the files created by sphinx-quickstart. Then, I changed the conf.py file adding this lines:
import os
import sys
import django
sys.path.insert(0, os.path.abspath('..'))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main_app.settings")
django.setup()

extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon']

And I changed index.rst adding modules:
Welcome to yourProject's documentation!
====================================

.. toctree::
   :maxdepth: 2
   :caption: Contents:

   modules

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

I executed sphinx-apidoc -o . .. and ./make html. I get something similar to what I want, but as I said before, I get too many comments for django files, and no comments at all for the manual package.
I'm using this manual package for things outside of django, like uploading some data from some excel to a database on a server. So it does not follow django settings. But how can I specify this to sphinx? I get this error when ./make html:
WARNING: autodoc: failed to import module 'upload_data_to_server' from module 'manual';

Do I need to add some new path into conf.py?
In the other hand, how can I 'clean' or edit the comments created by autodoc manually?


text:
Q: How to change the color of operators and methods in vim? Recently I've been trying to create my own color scheme for vim. I've been mostly just writing in-file, referencing Vivify for hi syntax calls and another site for RGB color codes. After changing most of the color scheme, and creating something that I'm happy with, I noticed that you can't change the color of operators (i.e. +, -, =, || etc.) or the color of methods (e.g. object.method()), as both of these fall under the keyword Normal. Being a java programmer, and having used only the NetBeans IDE up to this point, it's kind of tough not to have any differentiation between objects and their methods. As such I was hoping someone would know of a work-around, or a way to color such forms of syntax not normally changeable via pre-reserved keywords.
Here's the relevant color scheme:

A: Create a file $HOME/.vim/after/syntax/java.vim with:
" highlight operators
syntax match _Operator "[-+&|<>=!\/~.,;:*%&^?()\[\]{}]"

" highlight methods
syntax match _Paren "?=(" contains=cParen,cCppParen
syntax match _memberFunc "\.\s*\w\+\s*(\@=" contains=_Operator,_Paren

" colors
hi _memberFunc guifg=#00FF00 guibg=NONE gui=none
hi _Operator guifg=#FF0000 guibg=NONE gui=none

" to resolve conflict with comment markers
syntax region _Comment start="\/\*" end="\*\/"
syntax match _Comment "\/\/.*$"
hi link _Comment Comment


text:
Q: VideoView - ship video files with app I want to play a mp4 file in an Activity using the VideoView. But I want to somehow have the mp4 saved in my app itself, just like images can be saved under R.drawable. So, the video ships with the app. Is there a way to do it?

A: Yes, you can store them in res/raw/ and access with openRawResource(), from docs (emphasis is mine):

Access to Original Files
While uncommon, you might need access your original files and directories. If you do, then saving your files in res/ won't work for you, because the only way to read a resource from res/ is with the resource ID. Instead, you can save your resources in the assets/ directory.
Files saved in the assets/ directory are not given a resource ID, so you can't reference them through the R class or from XML resources. Instead, you can query files in the assets/ directory like a normal file system and read raw data using AssetManager.
However, if all you require is the ability to read raw data (such as a video or audio file), then save the file in the res/raw/ directory and read a stream of bytes using openRawResource().


text:
Q: How to draw circle count down in pygame? I am working on game in python and I want make the power countdown like in "Mobile Legends". But for this I need to draw not full circle, for example:
I know that I can animate all count down as images but maybe there is siplest way? Can pygame do somthing like this?


text:
Q: Does BigQuery support regular expressions flags? I want to do a case insensitive REGEX_MATCH and I'm not sure if I can use flags.

A: BigQuery uses re2 for regular expressions, and re2 does support flags.
For example, to do a case insensitive match:
SELECT REGEXP_MATCH('TomatoPotato', r'TOpo')
false

SELECT REGEXP_MATCH('TomatoPotato', r'(?:TOpo)')
false

SELECT REGEXP_MATCH('TomatoPotato', r'(?i:TOpo)')
true


text:
Q: I would like to develop function related to QRCode reader. Is there anyway I can debug by Simulator Can I debug my program for QRcode reader with cn1 simulator without a camera?
The simulator doesn't include a camera to scan QRcode. How do I debug my program for QRCode reading?

A: Currently we don't support that. Notice that you can use the isSimulator() method (in CN and Display) to create a special case that lets you add a manual way to test the QR code.
E.g. instead of showing a scan button just add a text field and paste in the text matching the QR code content. Then use that to invoke the rest of your code.


text:
Q: Annular segment in 3D I would like to plot a segment of a circular annulus in three dimensions with constant thickness (like a thick washer, but through some limited ranges of angle).  This shows the shape:
RegionPlot3D[
 (5 < Sqrt[x^2 + y^2] < 6 && 5 < z < 6 && 0 < ArcTan[x, y] < .5) ,
 {x, -10, 10}, {y, -10, 10}, {z, -10, 10},
 Mesh -> None,
 PlotPoints -> 100,
 PlotStyle -> Directive[Opacity[0.5], Red]]

However, this requires an extremely high number of PlotPoints (which will be undesirable in my full figure, containing many dozens of such shapes).  Moreover I would like to retain the thin edge lines and impose Opacity[], colors, and so forth, as can be applied in all Graphics3D primitives such as Cylinder[].
I could work with Regions, such as this start:
Region[
 RegionDifference[Cylinder[{{0, 0, 0}, {0, 0, 1}}, 1],
  Cylinder[{{0, 0, 0}, {0, 0, 1}}, 1/2]]]

but here too I won't get the thin edge lines and opportunity to adjust the overall opacity and color as I seek.
In two dimensions, there is a perfect graphics element:
Graphics[{Opacity[0.5], Orange, Annulus[{0, 0}, {1/2, 1}, {0, .3}]}]

What I'm seeking would be called Annulus3D.  In the absence of such a 3D primitive, how shall I plot what I seek?

Just to show the final result (using the linked code from @kglr, below):

A: You can use RegionProduct:
rp = RegionProduct[Annulus[{0, 0}, {1/2, 1}, {0, .3}], Line[{{0}, {1/10}}]];

Region[rp]

An alternative approach: Modify the trick in this answer to add a location parameter:
ClearAll[annulus3D]
annulus3D[ctr_, {θ1_, θ2_}, {r1_, r2_}, {z1_, z2_}] :=
   Translate[
     ChartElementData["CylindricalSector3D"][{{θ1, θ2}, {r1, r2}, {z1, z2}}, 1],
     ctr]

Example:
Graphics3D[{EdgeForm[{Thick, Gray}],
  Opacity[.5, Red], annulus3D[{1, 1, .5}, {Pi/3, 2 Pi/3}, {.5, 1}, {0, .6}],
  Opacity[.5, Blue], annulus3D[{0, 0, 0}, {Pi/4, 3 Pi/2}, {.25, 1.5}, {.5, .75}]},
 Axes -> True, BoxRatios -> 1, AxesOrigin -> {0, 0, 0}]


text:
Q: Vector valued function How can I determine if a function lies within the span of a vector valued function?
For an example does $\begin{bmatrix} 2\\ 1\end{bmatrix}$ lie in the span of:
$$a(x) = \begin{bmatrix} 1\\ x\end{bmatrix}$$
$$b(x) = \begin{bmatrix} x\\ 1\end{bmatrix}$$
$$c(x) = \begin{bmatrix} x\\ 2x\end{bmatrix}$$

A: You could approach this problem in an unorganized brute force sort of way like: Suppose $$[2\;1]^T = r[1\;x]^T+s[x\;1]^T+t[x\;2x]^T.$$ This leads to equations: $2=r+sx+tx$ and $1=rx+s+t2x$. Thus $2=r+(s+t)x$ and $1=s+(r+2t)x$. So (equating coefficients) one has $2=r$, $0=s+t$, $1=s$, and $0=r+2t$. Therefore, $r=2$, $s=1$, and $t=-1$. Thus "Yes" $[2\;1]^T=2a(x)+b(x)-c(x)$.
Instead a coordinate approach is a bit more organized (although a little clunkier). Such an approach would be more successful (than brute force) if dealing with a larger problem.
The collection of all functions $\{f:\mathbb{R}\to\mathbb{R}^{2\times 1}\}$ form an infinite dimensional vector space. But your functions lie in a finite dimensional subspace, for example: $W = \left\{ \begin{bmatrix} ax+b\\cx+d \end{bmatrix} \;:\; a,b,c,d \in \mathbb{R} \right\}$. By choosing a basis like $$\beta=\left\{\begin{bmatrix} 1\\0 \end{bmatrix},\begin{bmatrix} x\\0 \end{bmatrix},\begin{bmatrix} 0\\1 \end{bmatrix},\begin{bmatrix} 0\\x \end{bmatrix}\right\}$$
we can write everything in coordinates. So
$$ \left[ \begin{bmatrix} 2\\1 \end{bmatrix} \right]_\beta = \begin{bmatrix} 2 \\ 0 \\ 1 \\ 0 \end{bmatrix} \quad
\left[ \begin{bmatrix} 1\\x \end{bmatrix} \right]_\beta = \begin{bmatrix} 1 \\ 0 \\ 0 \\ 1 \end{bmatrix} \quad
\left[ \begin{bmatrix} x\\1 \end{bmatrix} \right]_\beta = \begin{bmatrix} 0 \\ 1 \\ 1 \\ 0 \end{bmatrix} \quad
\left[ \begin{bmatrix} x\\2x \end{bmatrix} \right]_\beta = \begin{bmatrix} 0 \\ 1 \\ 0 \\ 2 \end{bmatrix}$$.
Then asking if $[2\;1]^T$ is in the span of $\{a(x),b(x),c(x)\}$ amounts to asking if the final column of the following matrix lies in the span of the first three columns (i.e. is the final column a non-pivot column?):
$$ \begin{bmatrix} 1 & 0 & 0 & : & 2 \\ 0 & 1 & 1 & : & 0 \\ 0 & 1 & 0 & : & 1 \\ 1 & 0 & 2 & : & 0 \end{bmatrix}$$
This matrix row reduces to
$$ \begin{bmatrix} 1 & 0 & 0 & : & 2 \\ 0 & 1 & 0 & : & 1 \\ 0 & 0 & 1 & : & -1 \\ 0 & 0 & 0 & : & 0 \end{bmatrix}$$
So the final column is not a pivot column and thus $[1\;2]^T$ lies in the span of $\{a(x),b(x),c(x)\}$. Moreover, the RREF tells us that the desired linear combination is $2a(x)+b(x)-c(x)$ (as before).

A: Maybe you mean to ask,
Does the point $(2,1)$ fall on the line parametrized by $a(x),b(x)$ or $c(x)$ if any?
$$ a(x) = (2,1)=(1,x) \ \ \Rightarrow \ \ 2=1, 1=x $$
$$ b(x) = (2,1)=(x,1) \ \ \Rightarrow \ \ 2=x, 1=1 $$
$$ c(x) = (2,1)=(x,2x) \ \ \Rightarrow \ \ 2=x, 1=2x $$
Obviously $2=1$ is hard to solve, the equation for $b(x)$ shows $b(2)=(2,1)$ and the equation for $c(x)$ gives $x=2$ and $x=1/2$ which is a contradiction. Only $b$ contains $(2,1)$ in its image.
Following Bill's suggestion: you could find $c_1,c_2,c_3$ such that
$$ (2,1) = c_1(1,x)+c_2(x,1)+c_3(x,2x) $$
This equation has to hold for all $x$ if $(2,1)$ is in the span of $a,b,c$ as vector-valued functions.


text:
Q: SQL query for multiple where clause I have a table named tbl_transactions with columns

*

*Category (string)

*for_month (string)

*Vehicle_No (string)

*amount (float)
As shown below in the
.
Is it possible to get the total amount for each month and the result should be category wise something like

A: You can use the conditional aggregation as follows:
SELECT CATEGORY,
       SUM(CASE WHEN FOR_MONTH = 'April' THEN AMOUNT END) AS APRIL_AMOUNT,
       SUM(CASE WHEN FOR_MONTH = 'May' THEN AMOUNT END) AS MAY_AMOUNT,
       SUM(CASE WHEN FOR_MONTH = 'June' THEN AMOUNT END) AS JUNE_AMOUNT
 FROM YOUR_tABLE T
WHERE FOR_MONTH IN ('April', 'May', 'June')
 GROUP BY CATEGORY

A: Using PIVOT
DECLARE @t TABLE(Cat VARCHAR(MAX), Mon VARCHAR(MAX),Amt INT)

INSERT INTO @T VALUES('Registration','April',850),
('Registration','April',450),
('Registration','April',295)

SELECT Cat,  [April] AS [Total Amt in Apr],
      [May] AS [Total Amt in May],
    [June] AS [Total Amt in June]FROM
(
 SELECT
    Cat,
    Mon,
    Amt
FROM
   @T
) t
PIVOT(
SUM(Amt)
FOR Mon IN (
    [April],
    [May],
    [June]
  )
) AS pivot_table;

Results:
Cat            Total Amt in Apr   Total Amt in May  Total Amt in June
Registration    1595               NULL              NULL


text:
Q: Redirect users in first login to a dynamic link I'm using a Gravity Forms user registration to handle registration processes, and I use Gravity Forms custom post type + wp resume manager to let the user submit some fields in his resume within the registration process. The user registers, fills some fields, and these fields he put are mapped to his resume fields. The resume is just a post.

Here's my problem:
Now the user is registered and has posted his resume and filled some of the fields, I want to redirect him on the first login to the resume edit page to fill the rest of fields.
Here's a sample link:
http://mydomainname/complete-your-resume/?action=edit&resume_id=7038
The resume is a custom post type; the name of the post type is resume and "7038" is the resume post_id.
I already know how to redirect users in first login, but what I don't know is how to do the following:

*

*How to redirect them to "their" resume-post edit page (the above link).

*Redirect them based in their role. I want to redirect only users who have role "candidates".

*If there a way to prevent them to navigate anywhere until they fill all the fields and save the post/resume.

I will highly appreciate any help of these points above. Thanks in advance.

A: 1) GF will save the Form entry ID in the wp_usermeta table for the registered user, so you can grab all the entry(submitted) data and I believe the resume ID too
$entry = get_user_meta( get_current_user_id(), 'entry_id', true );

Then you can get the entry data using the "get_entry" method from the PHP API wrapper class as described in the docs:
https://www.gravityhelp.com/documentation/article/web-api/#php-wrapper
See: https://github.com/rocketgenius/webapiclient/blob/master/includes/class-gf-web-api-wrapper.php#L230
Or:
https://www.gravityhelp.com/documentation/article/api-functions/#get_entry
Also, you can hook to the GF post created or user activated actions and store the POST ID for that user in the wp_usermeta table, not sure but I believe the post created addon may have a hook for that.
2) See: https://wordpress.stackexchange.com/a/5048/60079
3) You can add a hidden field to the form, save it as user meta and update the value if they complete the resume using the "gform_post_submission" GF hook.
I don't like the idea of forcing users to complete the resume, instead, I'll go for a site wide notification. Anyway, you can hook the wp init and always redirect the user to the desired page and hide the navigation on that one too.


text:
Q: Solving the equation $y+xy^2-e^{xy}=0$ to form $y=f(x)$. I need help by this question. Problem I don't know where to start by solving such a questions.
Can the equation $y+xy^2-e^{xy}=0$ in a neighbourhood of $(x_0,y_0)$ with $x_0=0$ and suitable $y_0$ be brought to the form $y= f(x)$? If yes, what is $f^\prime(0)$?

A: To answer your second part you can determine the derivative when $x=0$.
Note when $x=0$ we get:
$$y+0\times y^2-e^{0\times y}=0$$
$$y-1=0$$
$$y=1$$
Then to find the derivative at the point $(0,1)$ you can implicitly differentiate your original expression:
$$y'+y^2+2xyy'-e^{xy}(y+xy')=0$$
Substituting in $x=0$ and $y=1$ gives:
$$y'+1-e^0=0$$
$$y'=0$$
Edit:
For reference here is what the graph looks like.


text:
Q: Error in Deserialization I am implementing a simple serialization and deserialization program, but I am getting an error during deserialization, as segmentation fault(core dumped).
I am using '|' as a delimiter, to retrieve the data. I think I am making a mistake while putting the data back into the member variable.
I will be trying to send the data over a socket as the next step
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 100

typedef struct Frame
{
    char p[MAX];
    char q[MAX];
    char r[MAX];

}frame;

void serial(char [] , frame*);
void deserial(char [], frame*);

int main ()
{
    char buffer [MAX];

    int  i = 0;

    frame* packet1;
    frame* packet2;

    char temp[sizeof(frame)];

    strcpy(packet1->p, "1234");
    strcpy(packet1->q, "qwerty");
    strcpy(packet1->r, "abcdef");
    serial( temp, packet1);

    deserial( temp, packet2);
    return 0 ;
}

void serial ( char temp[], frame * packet1)
{
    char* p = temp;
    int len ;
    int i=0;

    len = strlen (packet1->p);
    while ( i<len)
    {
        *p = packet1->p[i];
         p++;
         i++;
    }
    strcat(p,"|");
    p++;
    i  = 0;
    len = strlen (packet1->q);
    while ( i<len)
    {
        *p = packet1->q[i];
         p++;
         i++;
    }
    strcat(p,"|");
    p++;
    i  = 0;
    len = strlen (packet1->r);
    while ( i<len)
    {
        *p = packet1->r[i];
         p++;
         i++;
    }
    strcat(p,"|");
    return;
}

void deserial ( char temp[], frame *packet2)
{
    char *str = temp;
    int i= 0 ;
    char delimit[]="|";
    printf("\n");
    while (*str!='|')
    {
        printf ("%c\n", *str);
        packet2->p[i] = *str;  //error here
        str++;
        i++;
    }
}

A: You have an issue with this code
frame* packet1;   // This is a pointer and it is uninitialized
frame* packet2;

char temp[sizeof(frame)];

strcpy(packet1->p, "1234");  // Use of uninitialized pointer

Did you want to do
frame packet1;
frame packet2;

char temp[sizeof(frame)];

strcpy(packet1.p, "1234");
...
serial( temp, &packet1);

Further - when you do
strcat(p,"|");

p is pointing to some uninitialized memory so it isn't a string and strcat will (likely) fail. Instead do:
*p = '|';

A: strcpy(packet1->p, "1234");

Here you are dereferencing a pointer which points to nowhere.You have to allocate memory first.
frame* packet1 = malloc(sizeof(*packet1 ));


text:
Q: How to set headers in Cordova InAppBrowser? In an app I'm building using the ionic framework (based on Cordova) I'm using the Cordova InAppBrowser to visit a url, but I want to set custom headers for that request. I've read over the readme and some other sites, but I can't find anything.
Does anybody know how I can set headers in the Cordova InAppBrowser? All tips are welcome!

A: As far as I now know this could not be done. So I opted for an alternative solution in which I gave the params via the url. I could do this because I also controlled the url which I wanted to open. So it worked, but it wasn't ideal.
Anyway, maybe this can help other people.


text:
Q: Jquery html/css: Creating drop shadow on fixed pos header that appears and disappears when scrollling new to jquery here but I'm trying to learn some different stuff that's been done on websites I frequent.
One such case that I can't figure out, is how to create a drop shadow for a fixed positioned header, so that when you scroll a drop shadow appears under the header and then disappears when you aren't scrolling anything. Here's the website I frequent that uses this technique  www.thisisluckyme.com
It doesn't seem too complex but I can't find much to go off of when trying to make this. Any help or insight into how its down would be very appreciated!

A: Pretty simple. You just bind an event handler to the window's scroll event, and check the position of the fixed header's top. If it's not 0, add the shadow. If it is 0, remove the 0.
Working example: http://jsfiddle.net/3cRe5/
the JS:
var header = $('.header');

$(window).scroll(function(e){
    if(header.offset().top !== 0){
        if(!header.hasClass('shadow')){
            header.addClass('shadow');
        }
    }else{
        header.removeClass('shadow');
    }
});


text:
Q: Tensorboard Error - NameError: name 'tensorboard' is not defined I am now learning tensorflow but am unable to get tensorboard to work. I tried the simple program below with no luck. The program works before I use the tensorboard code but when I use the tensorboard code I get the following error:
NameError: name 'tensorboard' is not defined

Please any assistance is apppreciated.
import tensorflow as tf

a = tf.constant(5, name="input_a")
b = tf.constant(3, name="input_a")
c = tf.multiply(a,b, name="mul_c")
d = tf.add(a,b, name="add_d")
e = tf.add(c,d, name="add_e")

sess = tf.Session()
sess.run(e)
output = sess.run(e)

writer = tf.summary.FileWriter('/tmp/newtest', graph=sess.graph)

print(sess.run(e))

tensorboard --logdir /tmp/newtest

A: I believe this is already 'answered', but, to give a sample of what I did, regarding this, and I hope it helps you or others.
This is just covering ending overhead of triggering & showing tensorboard.
import subprocess
import webbrowser
import time

logLocation = 'tflearn_logs'

print("\r\nWould you like to see the visual results (y/N)? ", end='', flush=True)
answer = input()
if answer.strip().lower() == "y":
    port = str(8018)
    print("Starting Tensorboard to visualize... ")
    process = subprocess.Popen(['tensorboard', "--logdir='" + logLocation + "'", '--port=' + port])

    # Wait for a few seconds, give the tensorboard a headstart
    time.sleep(5)

    print("Opening Tensorboard webpage... ")
    url = 'http://127.0.0.1:' + port + '/'
    # Path differs per OS (Windows, Linux, iOS)
    chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
    webbrowser.get(chrome_path).open(url)

print("Press enter to quit... ", end='', flush=True)
answer = input()
if process is not None:
    process.kill()


text:
Q: How to save all version of a modified file with minimum cost on a database I recently got  database for my website and was suprised to see how expensive it was for the amount of space they gave me (only 500 mb for sql2005). The database is used to store data such as posts or articles submitted by members.
the problem: I would like to be able to save not only the final version of a user post, but also all possible modification that occurred since he posted it. How can I save these modifications in the database without having to store the whole post several time with different version numbers? my concern is that the size of the database might grow too fast and reach the 500mb limit.
Any ideas?

A: How often do you need to retrieve the previous posts? How large are they?
You can compress the data before inserting into the database but this will increase retrieval time.
You could store the diff of the posts but this requires iterating through each post and applying the diff to recreate the history.
You should determine the number of articles/edits that you expect so that you can determine how many you can store within your limit.
If articles are large and previous versions not commonly accessed then just store the articles as files and store the header information in the database.


text:
Q: Generating Functions Interpretation - Expanding around other points? Generating functions are incredibly useful for solving all kinds of combinatorial problems. Whenever they are used, though, the generating function is always expanded around $x=0$ to obtain the series. Why is this the case? Is there a combinatorial use/interpretation of a 'generating function' expanded around other points on the line (or the complex plane)?

A: Good question! For one thing, any power series  $$f(x) = \sum_n a_n (x-a)^n$$ may be converted into a power series based around $0$ by taking $$g(x) = f(x+a) = \sum_n a_n x^n.$$ and power series of this form are more convenient to work with.  For example, we frequently want to multiply generating functions, but how should we interpret a product of power series of the form
$$\left(\sum_n a_n (x-a)^n\right)\left( \sum_n b_n (x-b)^n\right)?$$  It's not clear whether we should expand it as a power series in $(x-a)$ or $(x-b)$, and it might not be possible to do either.
In combinatorics we usually use only formal power series, which means roughly that we do not want to consider issues of convergence.  For example, it's sometimes useful to consider a power series such as $$f(x) = \sum_{n=1}^\infty n!x^n$$ which only converges at $x=0$.  Here we don't think of $f(x)$ as a function.  It's just "a clothesline on which we hang up a sequence of numbers for display", to quote Wilf in the free downloadable book generatingfunctionology.  It doesn't make such to evaluate such a power series at a number such as $x=1$, but we can still add, multiply, and perform other operations with such power series and it's often meaningful combinatorially to do so. In this case it's not clear what it would mean to expand $f(x)$ as a power series around a point $a\neq0$.
Even in the case when $f(x)$ can be expanded around any point, you may not get integer coefficients.  For example, take the exponential function $$f(x) = e^x = \sum_{n=0}^\infty \frac{1}{n!}x^n$$ which is frequently useful as an exponential generating function.  If we expand $f(x)$ around $a=1$ we get  $$f(x) = \sum_{n=0}^\infty \frac{e}{n!} (x-1)^n$$ and the number $e = 2.718\cdots$ does not have any direct combinatorial significance.


text:
Q: RowEditor Data Validation in ExtJS 4 I´ve designed an application based on the MVC Pattern. So I also defined my proxies, fields and validators in my model. Here for example is a model for a list of countries:
Model
Ext.define('LT.model.Country',{

    extend: 'Ext.data.Model',
    fields: [{name: 'id',type: 'int'},
             {name: 'name', type: 'string'},
    ],

    validations: [
        {type: 'length', field: 'name', min: 2}
    ],

    proxy: {
        type: 'rest',
        url: '/country',
        reader: {
            type: 'json'
        },
        writer: {
            type: 'json'
        }
   }
});

And here is the store for using this model:
Store:
Ext.define('LT.store.Country', {
    extend: 'LT.base.store.Base',
    model:  'LT.model.Country'
});

The store is shown in a Grid Panel, where i use the RowEditor Plugin to enable adding and editing rows directly in grid view
Grid Panel:
    Ext.define('LT.view.country.List' ,{
    extend: 'Ext.grid.Panel',
    alias : 'widget.country-list',
    plugins: [
        Ext.create('Ext.grid.plugin.RowEditing', {
            clicksToEdit: 2,
            clicksToMoveEditor: 1
        })
    ],
    store : 'Country',

    columns: [
            {header: 'ID',  dataIndex: 'id', width: 50},
            {header: 'Name', dataIndex: 'name', flex: 3, editor: 'textfield'},

    ],
    tbar: [{
        xtype: 'button',
        action: 'add',
        text: 'Add'
    },{
        xtype: 'button',
        action: 'delete',
        text: 'Delete'
    }]

});

My problem now is, that the Validation Errors are not show if you edit data in grid view. If the data doesn´t match the validation criterias, then it´s not submitted to the proxy (which is fine), but the user also doesn´t get an error message, that the inserted data is invalid.
I found some (not really beautiful) workarounds - but maybe anyone knows another solution to add validation functionality to rowediting in extjs?
Thanks in advance & cheers,
Michael

A: Integrating Ext.grid.panel validation and Ext.data.Model.validations
The above response talks about the approach that you can follow


text:
Q: Adding background color to polygons in KML files I'm working a on a new project which requires me to extract data from www.wikimapia.com
in the form of KML files. I then need to display the said files on google maps. There doesn't seem to be much information on wikimapia on the Internet.
My aim to style the polygons and fill in a CSS equivalent background-color.
At the moment I only have the outline of the boundary showing up.
Thank you very much fellow stackoverflowers :)

A: The simplest way to style Polygons from KML is to use the KML styling for polygons PolyStyle. That would involve changing the KML.
Another option would be to import your KML files into FusionTables, and use a FusionTablesLayer to display them on a Google Maps API v3 map.  You can style the polygons with the FusionTables User Interface or dynamically using javascript (if you have less than 5 styles)
More information
A third option (if your KML is not very complicated would be to use a third party parser like geoxml3 or geoxml-v3 to parse the KML to native Google Maps API v3 objects and style those the normal way with the API.


text:
Q: CircleCI parallel Cypress against multiple environments I'm currently using CircleCI to run my Cypress test suite against a single environment. The CircleCI config specifies the following:
docker:
      - image: cypress/base:10
    parallelism: 16
    steps:
      - *quick_attach
      - restore_cache:
          key: dependency-cache-{{ checksum "yarn.lock" }}-v2
      - run:
          name: Run Cypress Tests
          command: >
            CYPRESS_BRANCH=$CIRCLE_BRANCH
            CYPRESS_SOURCE=CircleCI
            CYPRESS_RECORD_KEY=$CYPRESS_RECORD_KEY
            /bin/bash ./scripts/cypress_run_circleci_all.sh

Inside cypress_run_circleci_all.sh, I have a hashmap and loop over it.
#!/bin/bash
set -e

declare -A environments
environments[dev]="https://dev.mydomain.com"
environments[qa]="https://qa.mydomain.com"

##  loop through the all environments
for env_name in ${!environments[@]}
do
    TAGS="all-envs-test,${env_name}"
    CYPRESS_baseUrl=${environments[$env_name]} \
    yarn cypress:run:desktop --record \
    --group Desktop \
    --parallel \
    --tag \"$TAGS\" || true
    echo "sleeping 60s"
    sleep 60
done

Everything works as expected for the first environment, but the second environment always finishes very quickly. I'm guessing there's something about running multiple cypress commands as part of the parallel command that's breaking things, but I'm unsure what.
Any suggestions on what I'm doing wrong, and what I could do to acheive what I want (running cypress tests sequentially against multiple environments, with each run against an environment running in parallel).

A: The Cypress Real World App is a payment application to demonstrate real-world usage of Cypress testing methods, patterns, and workflows.  It contains a CircleCI config to run tests against Windows and Linux and uses the ci-build-id parameter for the Cypress CircleCI Orb to link the builds in the Cypress Dashboard


text:
Q: What properties make a good barrier for microwave (oven) radiation? Suppose I have plenty of food I want to heat (which will provide load) in the microwave, and one item I don't want to heat. What properties would make a material a a good shield, to reduce or prevent heating of that item? I know metal can work as a barrier in the form of a Faraday cage, but that there are also potential issues with arcing. Presumably some kind of smoothly flexible metal mesh would be a good candidate - what properties would it need to be effective? (For example, we might consider mesh spacing, wire diameter, and the choice of metal.)
(Note: this is based on this question, which was recently migrated over to Seasoned Advice (food and cooking), but I think that it could really use physics expertise, so this is a rephrased version, addressing the complaints I saw leading to that question's migration.)

A: The answer is this: You will need to cover the item you don't want to heat with a conducting material, creating a so called Faraday's cage, which is connected to an earth potential equal to the potential of the metal casing of the microwave oven.
The reason for this is threefold: The covering material needs to be a conductor, because conductors have the property that free charges can move free without significant resistance inside it. Because of this, the electric field inside the conductor is zero, for elsewise charges would move due to the electric field. But they move themselves in such a position that they cancel out the fiel again. Now, because the electric field inside the conductor material is zero, is also has to be zero in cavities of the conductor. For if it would not be zero inside the conductor, one could move electrons through a loop partially through the cavity, and partially through the conductor. The path integral through this closed loop would then be non zero. In onther words, one could generate energy without costs, obviously in contradiction to the law of conservation of energy. Therefore, wrapping an item in conducting material creates a so called Faraday's cage, whereby the electric field through the wrapped item is zero.
Now this is what we want, because the microwave oven heats items with the use of electric field waves. So, shielding the item off from electric fields, also shields it from heating.
However, charges inside the conductor start moving because of the electric field waves. This can create a potential difference with the shielding material of the casing of the microwave oven. It is because of this difference that arcing could occur. That is why you will also need te connect the conductive wrapping to the earth potential of the metal casing.


text:
Q: Calculate cumulatve growth/drawdown from local min/max I'm learning R (and its application to trading tasks via quantmod lib) and looking through the community pretty regularly to get a lot of new knowledge and tricks from here. My impression about R in general and quantmod lib in particular - it's awesome.
At this point I need help of seasoned R users. I'm using timeseries downloaded via getSymbols and I need to calculate cumulative growth/drawdown from local minimum/maximum respectively.
I can solve my task using FOR cycles as well as I can do necessary modelling in MS Excel, but I want to figure out more simple solution that does not require FOR cycles and that is more "native" in R.
Example.
Input data:
20121121    79810
20121122    79100
20121123    80045
20121126    81020
20121127    80200
20121128    81350
20121129    81010
20121130    80550
20121203    80780
20121204    81700
20121205    83705
20121206    83350
20121207    83800
20121210    85385

Result:
            CLOSE   Cumulative gr/dd
20121121    79810   N/A
20121122    79100   0.58%
20121123    80045   1.55%
20121126    81020   2.37%
20121127    80200   -0.10%
20121128    81350   0.06%
20121129    81010   -0.76%
20121130    80550   -0.82%
20121203    80780   0.73%
20121204    81700   3.78%
20121205    83705   5.19%
20121206    83350   -1.50%
20121207    83800   1.67%
20121210    85385   2.22%

A: The calculation is already in the tseries package as function maxdrawdown. Here is the beginning of its example:
mxdrwdR> # Toy example
mxdrwdR> x <- c(1:10, 9:7, 8:14, 13:8, 9:20)

mxdrwdR> mdd <- maxdrawdown(x)

mxdrwdR> mdd
$maxdrawdown
[1] 6

$from
[1] 20

$to
[1] 26

Turning this into percentages is pretty easy -- look at the (short) code of the function itself.

A: To complement Dirk's answer, the PerformanceAnalytics package has various drawdown options. Here is an excerpt from some of my code, that also shows the growth calculation (and sharpe ratio, as a bonus):
#x is an xts object containing OHLC data
profit=ROC(x$Close)
growth=sum(na.omit(profit)),
equity=exp(sum(na.omit(profit))),
sharpe=as.vector(SharpeRatio.annualized(profit)),
maxDrawdown=maxDrawdown(profit)

A: Finally, I've managed to solve it. Dirk and Darren, many thanks for your comments - the "maxdrawdown" function from PerformanceAnalytics package was not exactly what I needed, but this made me paying attention to PerformanceAnalytics and make some search through this site and the Internet. The findDrawdowns function from the same package that was close to my need, but anyway was not exacly what I was looking for (it needs the last high to be updated to start calculating new drawdown, while I need even local maxima and minima to be taken into account). Making further trials-and-errors, I made my own code that solves my task without FOR cycles. :) Here is the code. As a bonus - it returns vector with number of bars of constant growing/falling of the asset. I'll be happy if anyone can advise how to improve it.
library(rusquant)
library(quantmod)
library(tseries)

na.zero <- function(x) {
  tmp <- x
  tmp[is.na(tmp)] <- 0

  return(tmp)
}

my.cumulative.grdd <- function(asset) {
  # creating list for temporary data
  tmp <- list()
  #
  #   tmp$asset.lag <- na.locf(lag(asset), fromLast=TRUE)

  # calculating ROC for the asset + getting ROC shifted by 1 element to the left and to the right
  # to compare ROC[i] and ROC[i+1] and ROC[i-1]
  tmp$asset.roc <- na.zero(ROC(asset))
  tmp$asset.roc.lag <- na.zero(lag(tmp$asset.roc))
  tmp$asset.roc.lag1 <- na.locf(lag(tmp$asset.roc, k=-1))

  # calculating indices of consequent growth/drawdown waves start and end
  tmp$indexfrom <- sapply(index(tmp$asset.roc[sign(tmp$asset.roc) * sign(tmp$asset.roc.lag) <= 0]), function(i) which(index(tmp$asset.roc) == i), simplify=TRUE)
  tmp$indexto <- c(sapply(index(tmp$asset.roc[sign(tmp$asset.roc) * sign(tmp$asset.roc.lag1) <= 0]), function(i) which(index(tmp$asset.roc.lag1) == i), simplify=TRUE), length(index(tmp$asset.roc)))

  # this is necessary to work around ROC[1] = 1
  tmp$indexfrom <- tmp$indexfrom[-2]
  tmp$indexto <- tmp$indexto[-1]

  # calculating dates of waves start/end based on indices
  tmp$datesfrom <- (sapply(tmp$indexfrom, FUN=function(x) format(index(asset)[x])))
  tmp$datesto <- (sapply(tmp$indexto, FUN=function(x) format(index(asset)[x])))
  tmp$dates <- apply(cbind(tmp$indexfrom, tmp$indexto), 2, FUN=function(x) format(index(asset)[x]))

  # merging dates for selection (i.e. "2012-01-02::2012-01-05") and calculation of cumulative product
  tmp$txtdates <- paste(tmp$datesfrom, tmp$datesto, sep="::")
  # extracting consequent growth/drawdowns
  tmp$drawdowns.sequences <- lapply(tmp$txtdates, function(i) tmp$asset.roc[i])
  # calculating cumulative products for extracted sub-series
  tmp$drawdowns.sequences.cumprods <- lapply(tmp$drawdowns.sequences, function(x) cumprod(1+x)-1)

  # generating final result
  result <- list()
  result$len <- tmp$indexto - tmp$indexfrom + 1
  result$cumgrdd <- xts(unlist(tmp$drawdowns.sequences.cumprods), index(tmp$asset.roc))

  return(result)
}

# let's test
getSymbols("SPY", from="2012-01-01")
spy.cl <- Cl(SPY)
spy.grdd <- my.cumulative.grdd(spy.cl)
spy.grdd

A: you can use zig zag points to find the peaks and valleys and then calculate percent decrease/increase. for example
    s <- get(getSymbols('goog'))["2012::"]
    z <- ZigZag(s[,2:3],10,percent=TRUE)
    # 10 in this example is the sensitivity to changes.
    # if you want to use closing prices use s instad of s[,2:3]

    # extract the extreme points
    z <- rbind(z[findPeaks(z)-1],z[findValleys(z)-1])
    # calculate the difference
    names(z) <- c("zig")
    z$PercentChange <- ((z - Lag(z)) / z) * 100

hope it helps


text:
Q: Randomly distributing values across multiple rows in a data frame I have two data frames.
DF1 contains unique ID's which are assigned to an area and a count of how many people are in each ID. (the COUNT column).
DF2 contains how many more or less people need to be assigned an area (the CHANGE column).
Is there an efficient way of, in the case of Area A for example, adding the extra 24 people from CHANGE column in DF2 to the COUNT column in DF1 randomly across the rows assigned to Area A.
Thank you.
DF1 <- data.frame(matrix(0, nrow=20, ncol=3))
DF1[,1] <- 1:20
DF1[,2] <- rep(c("A","B","C","D"), each=5)
DF1[,3] <- sample(10:30,20,rep=TRUE)
colnames(DF1) <- c("ID","AREA","COUNT")

DF2 <- data.frame(matrix(0, nrow=4, ncol=2))
DF2[,1] <- c("A","B","C","D")
DF2[,2] <- c(24,-17,-1,5)
colnames(DF2) <- c("AREA","CHANGE")

EDIT:
This is my current solution. However, my actual dataset contains thousands of rows and takes a few hours to complete. Hence why I am after a more efficient way of achieving the same goal.
for (i in 1:length(unique(DF2[,1]))){
DF_Area <- unique(DF1[,2])
DF1_Subset <- with(DF1, DF1[AREA == DF_Area[i],])
DF2_Row <- DF2[DF2$AREA %in% DF_Area[i],]

if(DF2_Row$CHANGE!=0){
DF1_Update <- as.data.frame(DF1_Subset$COUNT)

if(DF2_Row$CHANGE>=0){ALLOCATION_VALUE <- 1}else{ALLOCATION_VALUE <- -1}

for (GG in 1:abs(DF2_Row$CHANGE)){
DF1_Update_Row <- sample(which(DF1_Update > 0),1)
DF1_Update[DF1_Update_Row, ] <- DF1_Update[DF1_Update_Row, ] + ALLOCATION_VALUE}

DF1_Subset$COUNT <- DF1_Update[,1]
DF1$COUNT[match(DF1$ID, DF1_Subset$ID, nomatch = 0) != 0] <- DF1_Subset$COUNT[match(DF1$ID, DF1_Subset$ID, nomatch = 0)]}}

A: This does work for any number of area and with any ID number but it can give a negative count if too much people are removed in an ID
library(data.table)

DF1 <- as.data.table(DF1,key="ID")
DF1$AREA <- as.factor(DF1$AREA)  #to change area as level
dt_all <-NULL

for (i in levels(DF1$AREA)) {

  if (DF2[DF2$AREA == i,]$CHANGE != 0) {
    bool_pos <- (DF2[DF2$AREA == i,]$CHANGE > 0) #to know to add or remove from count

    ID <- sample(1:(length(DF1[AREA == i,]$ID)),abs(DF2[DF2$AREA == i,]$CHANGE), rep=TRUE)
    ID <- DF1[AREA == i,]$ID[ID] # select random id for each value in change
    df_temp <- as.data.table(table(ID),key="ID")
    df_temp$ID <- as.integer(df_temp$ID)
    if (!bool_pos) {
      df_temp$N <- (df_temp$N)*-1
    }

    dt_all <- rbind(dt_all,df_temp )
  }
}

DF1 <- merge(DF1, dt_all,all.x=TRUE, by="ID")
DF1[is.na(N), N:=0]
DF1[, COUNT:=COUNT+N]
DF1[,N:=NULL]
dt_all <-NULL

A: This should also work (where the random numbers are generated each time by dividing the total CHANGE into equal intervals from which each of the remaining numbers are to be generated). Also, use split instead of subsetting inside loop, it will be faster.
set.seed(100)
do.call(rbind, lapply(split(DF1, DF1$AREA),
       function(x) {
         tot <- DF2[DF2$AREA == unique(x[,'AREA']),]$CHANGE # total change needed
         n <- nrow(x)
         nums <- rep(0, n)
         part.tot <- 0
         for (i in 1:(n-1)) {
           lb <- min(0, tot-part.tot)
           ub <- max(0, tot-part.tot)
           nums[i] <- round(runif(1, lb, ub)/(n-i+1)) # divide the remaining CHANGE into (n-i+1) equal parts
           part.tot <- part.tot + nums[i]
         }
         nums[n] <- tot - part.tot # assign the remaining to the last element
         x['COUNT'] <- x['COUNT'] + nums
         x
       }))

      ID AREA COUNT
#A.1   1    A    14
#A.2   2    A    30
#A.3   3    A    32
#A.4   4    A    27
#A.5   5    A    34
#B.6   6    B    27
#B.7   7    B    23
#B.8   8    B    18
#B.9   9    B    19
#B.10 10    B     5
#C.11 11    C    15
#C.12 12    C    19
#C.13 13    C    11
#C.14 14    C    19
#C.15 15    C    10
#D.16 16    D    30
#D.17 17    D    26
#D.18 18    D    19
#D.19 19    D    15
#D.20 20    D    20


text:
Q: svn commit operation error
Possible Duplicate:
Internet connection Drops during an SVN commit

I changed a code on my local machine and want to commit it to the SVN server. If during commit operation there will occur an error then the code will not be commited at all or the code until the error will be commited?

A: No, if there's an error during a commit, nothing in that commit operation will be sent to the server. So if you try to commit 5 files and there's an error after file #2, none of the 5 files will be committed.


text:
Q: 404 vs 204 on GET, PUT, DELETE Methods If a request want to get/delete/update to a resource which isn't exist, what do you prefer to return? 204 or 404?
Sample: api/blog/{id} can take that requests: GET, DELETE, PUT and api/blog can take GET and POST.
GET: api/blog returns list of blogs, GET: api/blog/{id} returns single blog,PUT: api/blog/{id} updates single blog and DELETE: api/blog/{id} deletes single blog.

A: In my opinion the distinction that matters is whether the request ends up successfully or not.
So generally in most of the cases 404 is the way to go.
I would recommend so, because the HTTP response codes are grouped by, let's say, result. source

*

*Informational responses (100–199)

*Successful responses (200–299)

*Redirects (300–399)

*Client errors (400–499)

*Server errors (500–599)

For example, the process can be like this:

*

*The client attempts to DELETE an entity.

*The entity is not there.

*This situation can be considered a client error, since deletion of nonexistent entity is being attempted

On 204 again cited from MDN:

The HTTP 204 No Content success status response code indicates that a
request has succeeded, but that the client doesn't need to navigate
away from its current page.
This might be used, for example, when implementing "save and continue
editing" functionality for a wiki site. In this case an PUT request
would be used to save the page, and the 204 No Content response would
be sent to indicate that the editor should not be replaced by some
other page.

A:
If a request want to get/delete/update to a resource which isn't exist, what do you prefer to return? 204 or 404?

"It depends."
If the payload in the response is "a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition", then I'm going to use a 4xx Client Error status code.  In the case where I want to draw attention to the target-uri of the request, then I'm going to use 404 Not Found.
On the other hand, if the payload in the response is a representation of the resource, or a representation of a status of a successful action, then I'm going to use some 2xx Successful status code, usually 200 OK.
In particular, if that payload is zero bytes long, I'm normally going to use 200 with Content-Length: 0 rather than 204 No Content.  204 I reserve for those cases where I really want the user agent to stay with the same view.  See also 205 Reset Content.
(Part of the lesson here - don't try to guess the meaning of a status code from the accompanying reason phrase.  Read the definition.)

Whether or not a resource has a "current representation" at any given time is a "resource design" concern.  It can make sense to say that this document has a representation even though we've never talked about it before.  Maybe that representation is zero bytes long, maybe it has some default representation, like a government form with a bunch of blanks to be filled in later.
For example, a report of activity during some time period might have a current representation even though the time period described by the report is in the future.

404 in response to PUT or DELETE is weird.
PUT is semantically close to UPSERT, it's strange to object that you couldn't find a current representation of the resource when I'm asking you to replace it with the representation provided in the payload.
Similarly, DELETE is about decoupling a resource from its implementation.  Why report that you can't do it when it has already been done?


text:
Q: Algo falla al setear el parametro en la consulta Estoy haciendo uan consulta en hibernate y me da un error al hacerla y creo que es un rerror al setear el parametro.
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Could not locate ordinal parameter [1], expecting one of []
    at org.hibernate.query.internal.ParameterMetadataImpl.getOrdinalParameterDescriptor(ParameterMetadataImpl.java:154)
    at org.hibernate.query.internal.ParameterMetadataImpl.getQueryParameter(ParameterMetadataImpl.java:204)
    at org.hibernate.query.internal.QueryParameterBindingsImpl.getBinding(QueryParameterBindingsImpl.java:182)
    at org.hibernate.query.internal.AbstractProducedQuery.setParameter(AbstractProducedQuery.java:507)
    at org.hibernate.query.internal.NativeQueryImpl.setParameter(NativeQueryImpl.java:613)
    at org.hibernate.query.internal.NativeQueryImpl.setParameter(NativeQueryImpl.java:62)

Esta es mi consulta
public static ArrayList CiudadesDeUnPais(short id) {
        short p = id;
        String nombreCiudad;
        ArrayList<String> nCiudades = new ArrayList();
        Session sesion = NewHibernateUtil.getSessionFactory().openSession();
        org.hibernate.Transaction tr = sesion.beginTransaction();
        Query consulta = sesion.createNativeQuery("SELECT city FROM City where country_id =:id", City.class).setParameter(id, p);
        nCiudades = (ArrayList<String>) consulta.getResultList();
        return nCiudades;
    }

A: Prueba a pasar el nombre del parámetro:
Query consulta = sesion.createNativeQuery("SELECT city FROM City where country_id =:id", City.class)
    .setParameter("id", p, Hibernate.INTEGER);

Otra opción es pasar el parámetro por posición, pero es más robusto pasarlo por nombre, por si la query evoluciona:
....setParameter(0, p);

Para más información: https://docs.jboss.org/hibernate/orm/3.2/api/org/hibernate/Query.html#setParameter(java.lang.String,%20java.lang.Object)


text:
Q: MySQL Fulltext separate digits and letters? Lets say we have 'ABCD1234EF' word in text. Now to find it, I have to match exact word. The goal is to find it by 'ABCD1234EF', 'ABCD', '1234' or 'EF' strings. NOT by 'CD12' or anything like it. Parameter 'ft_min_word_len' is  set to 1.
It's only option to create second column and store splited values there? Could it be done by MySQL?
I have found something on MySQL site http://dev.mysql.com/doc/refman/5.1/en/full-text-plugins.html. But it brings more questions than it solves.

*

*does it replace original mysql parser?

*how to compile it on Windows machine?

A: I think the easiest route would be splitting your input string into three separate columns with SQL (based on something like this perhaps,).
Writting your own fulltext plugin essentially moves this logic to a lower with uncertain added value (reference):

The main parsing function, simple_parser_parse(), acts as a replacement for the built-in full-text parser, so it needs to split text into words and pass each word to the server.

This also answers your first bullet question: this procedure replaces the full-text parser (not the SQL parser, if this was your question).
The MySQL compilation instructions provide Windows-specific steps.


text:
Q: Have trouble getting the toggle status from api & check it with status data I have a toggle button with titles that is setting data to send to server.
And it is getting api data like what it is posted to server.
I want to check the if there is a similar item id in api data with rules then get its status and replace it with what it is right now.
But i get this error changedStatus is not defined
I would appreciate if someone can help me with it.
Link to my code in sandbox
https://codesandbox.io/s/vuex-todo-list-forked-4kui26
    <input type="checkbox" v-model="Rule.params.value" />

     Rules: [
    {
      item_id: 144,
      title: "_00_Init_Initialization",
      params: {
        value: false,
      },
    },
    {
      item_id: 145,
      title: "_Init_AppsInitialization",
      params: {
        value: false,
      },
    },
    {
      item_id: 146,
      title: "_02_Global_Generic",
      params: {
        value: false,
      },
    },
    {
      item_id: 147,
      title: "_02_Global_Generic",
      params: {
        value: false,
      },
    },
    {
      item_id: 148,
      title: "02_Global_Generic",
      params: {
        value: false,
      },
    },
    {
      item_id: 149,
      title: "Global_Generic",
      params: {
        value: false,
      },
    },
  ],
  apiData: [
    {
      item_id: 144,
      params: {
        value: true,
      },
    },
    {
      item_id: 145,
      params: {
        value: false,
      },
    },
    {
      item_id: 146,
      params: {
        value: true,
      },
    },
    {
      item_id: 147,
      params: {
        value: true,
      },
    },
    {
      item_id: 148,
      params: {
        value: false,
      },
    },
    {
      item_id: 149,
      params: {
        value: false,
      },
    },
  ],

in methods
 mounted() {
   console.log("mounted");
   this.checkStatus();
  },
 methods: {
   checkStatus() {
     this.Rules.map((rule) => {
     this.apiData.map((data) => {
      const status = this.apiData.find(
        (data) => rule.item_id == data.item_id
      );
      if (status.params.value == true) {
        const changedStatus = this.Rules.find(
          (data) => status.item_id == data.item_id
        );
        changedStatus.params.value = true
      } else {
        changedStatus.params.value = false
      }
    });
  });
},

A: Try to define changedStatus outside of the condition:
methods: {
  checkStatus() {
    this.Rules.map((rule) => {
    this.apiData.map((data) => {
    const status = this.apiData.find(
      (data) => rule.item_id == data.item_id
    );
    const changedStatus = this.Rules.find(
      (data) => status.item_id == data.item_id
    );
    status.params.value == true ?
      changedStatus.params.value = true :
      changedStatus.params.value = false
    }
  });
});


text:
Q: Populate Repeater after TextBox is cleared I have a standard repeater, which is populated with a default list of images in code-behind:
Repeater.DataSource = ImageList;
Repeater.DataBind();

I have a TextBox, for which I use this script to clear it, whenever you click on it:
$(function () {
    $('input[type=text]').focus(function () {
        $(this).val('');
    });
});

The DataSource for my Repeater might change from time to time and I want to bind the above default ImageList to it whenever the TextBox is cleared. I couldn't think of any solution, so I'm grateful for any advice.

A: Add next method to your code behind:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static int BindRepeater(int justparam)
{
    int result = 0;
    Repeater.DataSource = ImageList;
    Repeater.DataBind();
    return result;
}

And jquery to your design page:
$(document).ready(function(){
    $('#textboxid').change(function(){
        if ($('#textboxid').value == '')
            BindRepeat();
    }

    function BindRepeat(){
        $.ajax({
                type: "POST",
                url: "YourPagesName.aspx/BindRepeater",
                data: "{justparam: '2'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert('Works');
                },
                error: function (data) {
                    alert('Error');
                }
            });
    }
}

Hope it helps you


text:
Q: Multiple nested views in UI-Router degrading performance I am using UI-Router for my ionic application, which follows the following structure

*

*Main

*

*Sales - View

*

*District - tab

*Area - tab

*Station - tab

*Filter - tab

*Inventory - view

*

*District - tab

*Area - tab

*Station - tab

*Filter - tab

*Sourcing - view

*

*Station - tab

*Filter - tab

But when I switch views in the app then it loads filter tab and any of the remain tabs (filter & district, filter & area or filter & station). Filter tab will always be in view while you can switch between district, area and station. Now the problem is that when I switch my views i.e. From sales to inventory or inventory to sourcing, It is taking huge amount of time. I tested it in iPad Air, Samsung tab 3, still the same issue. It doesn't happen when I switch tabs.
I want to enhance the performance of the app by speeding up the time that takes to switch the view. Any help will be appreciated.
Thanks


text:
Q: Missing saved files after updating iPod to iOS 5 I updated my iPod to iOS 5 and all my apps and their save files are missing. I backed them up to my computer but can not find them.
How do I restore the backup?

A: Backups are managed by iTunes, there's no need for you to know where the actual files are (This is the beauty about Apple things).
To restore your backup connect your iPad, right click it in iTunes' sidebar and select restore from backup (Sometimes it helps to restore from backup twice).


text:
Q: Variadic template function rvalue parameters silently moved C++ to the function The following code compiles and prints: move move. I would prefer that it didn't compile since merge takes rvalue references and I don't move t1 and t2 to it.
class A {
   public:
    A() = default;
    A(const A& other) { std::cout << "copy "; };
    A(A&& other) { std::cout << "move "; };
};

template <typename... TupleType>
auto merge(TupleType&&... tuples) {
    return std::tuple_cat(std::move(tuples)...);
}
int main() {
    std::tuple<int> t1{1};
    std::tuple<A> t2{A()};
    auto t3 = merge(t1, t2);
}

I'm not sure what happens here and why. Furthermore, I think this behavior is dangerous: I have no move in the call to merge, but t1 and t2 are moved from.
Why is this allowed and how can I make merge take only rvalue references?

A: For why is this possible, See Reference_collapsing.
Now If you want to prevent your function from accepting lvalues, you can use the following code
#include <tuple>
#include <iostream>

class A {
public:
    A()  = default;
    A(const A& other) { std::cout << "\ncopy "; }
    A(A&& other)noexcept { std::cout << "\nmove "; }
};
template <typename... TupleType>
auto merge(TupleType&... tuples) = delete;

template <typename... TupleType>
auto merge(TupleType&&... tuples) {
    return std::tuple_cat(std::forward<TupleType>(tuples)...);
}

int main() {
    std::tuple<int> t1{1};
    std::tuple<A> t2{A()};
    // auto t3 = merge(t1, t2);//won't compile

    //compiles and gives the desired behavior move move
    auto t4 = merge(std::make_tuple(1), std::make_tuple(A{}));
}

Live


text:
Q: How to find the range of a cannon ball? A cannon is positioned with a direction of 60 degrees between the ground and itself. (Sorry, again, for my poor English. I hope you understood that sentence.).
The shooting velocity is $800{\text{m}\over \sec}$. What is its range?
I didn't really understand this question. Am I asked how further the cannon ball will go before it descends? Because if so, I should I find the highest point the cannon ball get? Should I do it by differentiating?
I would truly appreciate your assistance.

A: In the simplest model, you are working in two dimensions, with the system of equations:
$$\frac{d^2 y}{dt^2} = -g \\
\frac{d^2 x}{dt^2} = 0 \\
y(0)=0,y'(0)=\sin(\theta) s \\
x(0)=0,x'(0)=\cos(\theta) s
$$
where $g>0$ is acceleration due to gravity, $\theta$ is the angle of the initial velocity, and $s$ is the initial speed. Note that this model assumes no friction. When you solve you find
$$y(t)=-\frac{1}{2} gt^2 + \sin(\theta) s t \\
x(t)=\cos(\theta) s t.$$
Now the range of the ball is the horizontal distance it travels before hitting the ground, i.e. the value of $x$ when $y=0$. Can you find this using these equations?

A: In projectile motion, you need to concern yourself with the two components of displacement:
$$x=x_0 + v_x t + \frac{1}{2}a_x t^2$$
$$y=y_0 + v_y t + \frac{1}{2}a_y t^2$$
If we place the cannon at the origin, then $(x_0,y_0) = (0,0)$. Furthermore, there is no acceleration in the $x$ direction if we neglect things like air resistance. Then $a_x = 0$. The acceleration in the $y$ direction is due to gravity $a_y = -g$.
$$x=v_x t$$
$$y=v_y t - \frac{1}{2}g t^2$$
We need to find the range. That is, we need to find the displacement in $x$ that occurs when the cannonball hits the ground, or when $y=0$.
$$x=v_x t$$
$$0=v_y t - \frac{1}{2}g t^2$$
The velocity can be broken up into components with trigonometry.
$$v_x = 800\cos60^\circ m/s$$
$$v_y = 800\sin60^\circ m/s$$
Using this information, solve for $t$ when the cannonball hits the ground. Then use that time to calculate displacement in $x$.


text:
Q: What is the use of the `prepare` argument in the createSlice function of Redix Toolkit? I'm following the Redux tutorial from redux site, and in Part 8, when writing a reducer to handle todos they do the following:
const todosSlice = createSlice({
  name: 'todos',
  initialState,
  reducers: {
    //...
    todoColorSelected: {
      reducer(state, action) {
        const { color, todoId } = action.payload
        state.entities[todoId].color = color
      },
      prepare(todoId, color) {
        return {
          payload: { todoId, color }
        }
      }
    },
    //...
  }
})

They make use of the prepare function; however, I wrote that code without knowing the existence of the prepare function as follows (only using the reducer) and it works as well.
const todosSlice = createSlice({
  name: 'todos',
  initialState,
  reducers: {
    //...
    todoColorSelected: {
      const { color, todoId } = action.payload
      state.entities[todoId].color = color
    },
    //...
  }
})

So why do we need in this case the prepare function? or is it just a simple example where it makes no difference?

A: It's a helper to run code before action.payload is handled by a reducer, you can transform the payload etc. https://redux-toolkit.js.org/api/createAction#using-prepare-callbacks-to-customize-action-contents


text:
Q: Snorby Setup-RedCloth error I am trying to install Snorby (obviously) and am continuously running into errors with this same gem.  Each time I attempt to do sudo bundle install in the snorby directory, I get the following error:
Installing RedCloth (4.2.9) with native extensions /usr/local/lib/site_ruby/1.9.1/rubygems/installer.rb:556:in `rescue in block in build_extensions': ERROR: Failed to build gem native extension. (Gem::Installer::ExtensionBuildError)
    /usr/bin/ruby1.9.1 extconf.rb

/usr/local/lib/site_ruby/1.9.1/rubygems/custom_require.rb:36:in require': cannot load such file -- mkmf (LoadError)
    from /usr/local/lib/site_ruby/1.9.1/rubygems/custom_require.rb:36:inrequire'
    from extconf.rb:1:in `'
I have tried everything I have seen and know.  I have tried to install a previous version of it.  I have tried gem upate.  I have tried sudo gem install Redcloth -v .  It then tells me the same continuous error.  Failed to build gem native extension.  Nothing is working.  All help is much appreciated!

A: I found the issue finally!  For those of you struggling, search no more.  All you have to do is download the dev package by doing:
sudo apt-get install ruby1.9.1-dev


text:
Q: Set text in a label This should be super simple but I can't for the life of me seem to get it to just set the text of a label at run time. It throws "1120: Access of undefined property lbl_param"
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx"
               width="398" height="85" minWidth="398" minHeight="85">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <s:Label id="lbl_param" x="19" y="10" width="105" height="29" text="Paramaters: "/>

    <fx:Script>
        <![CDATA[
            lbl_param.text = "test113";
        ]]>
    </fx:Script>
</s:Application>

A: Your code to set the lbl_param.text should be in a method:   The only code in a script block you can run outside of a method is a class import or a variable definition.  This sample puts the code in a initialize event hander:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx"
               width="398" height="85" minWidth="398" minHeight="85" initialize="init()">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <s:Label id="lbl_param" x="19" y="10" width="105" height="29" text="Paramaters: "/>

    <fx:Script>
        <![CDATA[
           public function init():void{
            lbl_param.text = "test113";
           }
        ]]>
    </fx:Script></s:Application>

Disclaimer: I wrote this code in the browser and it may not be "compiler" perfect.


text:
Q: How do I fix my if statement I wrote a program where the user inputs a date to find some stock information.
I used a series of if statements so the program can look up the type of info they want. There are 10 different types of info the user can look up: "open", "high", "low", "close", "volume", "changed", "percent change", "adjusted closing", "trade value", "trade volume".
The problem is that when information doesn't exist for that type of info, the program doesn't work.
Here is the error that comes up:
lookup.rb:75:in `<main>': undefined method `[]' for nil:NilClass (NoMethodError)

This is is one of my if statements:
if input == "open"
  if data[1] != nil
    puts "The open of your stock is: " +  data[1]
  else
    puts "Sorry, but that value wasn't recorded"
  end
end

Let me know of you need the rest of the program.

A: You could do something like
if data && data[1] != nil

which will check if data exists before it tries to access the data[1] element

A: Without the rest of the code, this just looks like you're using data when it's nil.  If this is the case, just don't do that.
Something like this may help:
if input == "open" && !data.nil?
    if data[1] != nil
        puts "The open of your stock is: " +  data[1]
    else
        puts "Sorry, but that value wasn't recorded"
    end
end

But there's likely a better solution if we had your code to look at.


text:
Q: Is it possible to make a diagonal pinstripe like this in CSS? Is it possible using only CSS (and no images) a background like the blue one in the following photo? If so, how?

fiddle: https://jsfiddle.net/hd74keqq/
.striped-blue { background: #3777BB; padding: 20px;}
  .striped-blue p { color: #FFF; }

A: Maybe its help you :)
CSS:
div {
  width: 100%;
  height:900px;
  background: repeating-linear-gradient(
  -55deg,
  #3777BB,
  #3777BB 1px,
  #3072B8 1px,
  #3072B8 6px
);
}

It is partially similar.
Demo

You can play with the properties to accommodate your need.
div {
  width: 100%;
  height:900px;
  background: repeating-linear-gradient(
  -40deg,
  #3777BB,
  #3777BB 1px,
  #3072B8 1px,
  #3072B8 4.9px
);
}

Demo

Edit: Here you have more information of repeating-linear-gradient
Formal Syntax:
repeating-linear-gradient(  [ <angle> | to <side-or-corner> ,]? <color-stop> [, <color-stop>]+ )

More info


text:
Q: Kendo Dropdown list - remote data binding I have local service and I want bind data to dropdown list. When my dd list downloads data got me error

Uncaught SyntaxError: Unexpected token:

Any Idea how fix that ?
My JSON:
{"Data":{"Data":[{"__type":"EType:#DataAccessLayer.Entities","Id":1,"Name":"Zamestnanec"},{"__type":"EType:#DataAccessLayer.Entities","Id":2,"Name":"Manažér"}]},"Valid":true}

my kendo ddl:
$("#types").kendoDropDownList({
            dataTextField: "Data.Data.Name",
            dataValueField: "Data.Data.Id",
            dataSource: {
                transport: {
                    read: {
                        dataType: "jsonp",
                        url: "http://localhost:3992/MyService.svc/GetRoleTypes",
                    }
                }
            }
        });

A: you have to parse the response before dropdown can use it, you can parse response using schema option in data source, like this :
$("#types").kendoDropDownList({
    dataTextField: "Name",
    dataValueField: "Id",
    dataSource: {
        transport: {
            read: {
                dataType: "jsonp",
                url: "http://localhost:3992/MyService.svc/GetRoleTypes"
            }
        },
        schema: {
            data: function (response) {
                return response.Data.Data;
            }
        }
    }
});

and done forget to change dataTextField and dataValueField also as shown above


text:
Q: Why Is My Wordpress Page.php Not Redirecting? I bought a site and migrated the files to my hosting, and I have a page that is not redirecting properly. This is the page:
http://www.flatshoesforwomen.net/home.php
It should redirect to the link on the page but it's not doing so. There are a few other pages that are doing the same thing. Can anyone explain the fix to a non-programmer? Thanks in advance!

A: Change your home.php file. The part before the <body> tag currently looks like
<html> <head>  <title>Foot Pain And Its Types</title>

You want to insert instructions for the browser to go somewhere else after a few seconds. You also want to properly close the <head> tag. So replace the above with:
<html>
<head>
    <title>Foot Pain And Its Types</title>
    <META http-equiv="refresh" content="5;URL=http://www.flatshoesforwomen.net/">
</head>

You can change 5 with 3 if you want redirection after 3 seconds.  The rest of the page, from the opening <body> tag, can stay the same.


text:
Q: Poem about aliens observing cars on highway? I read a poem way back in elementary school in the 70's that described the observations of aliens watching cars on a highway and concluding that cars were the inhabitants of earth.
They described the "creatures" as moving on black "tapes" with white lines (highways) and having "guts" that were visible through clear panels in their fronts. (Human drivers viewed through the windshields).
The first time it was read to me as a kid, I didn't get at all that they were looking at cars and I've always wanted to go back and re-read it!
Does this strike a chord with anyone? I think the title might have had the word Highway in it...I never read the titles of anything.

A: Southbound on the Freeway by May Swenson

The creatures of this star
are made of metal and glass.
Through the transparent parts
you can see their guts.
Their feet are round and roll
on diagrams of long
measuring tapes, dark
with white lines.

This is just a partial quote (not the beginning, but close to it), to convince you that is probably the poem you look for. The full poem is on the link I provide.


text:
Q: pass radio button value I am using this javascript code for passing radio button value from one page to another.
This javascript code is using for-loop and I  want to use infinite loop in my programming.
 <script langauge="javascript">
   function getresult(){
 for(i=0; i<5; i++)
  {
    if(document.forms[0].elements[i].checked)
    {
       var the_value = document.forms[0].elements[i].value;
    }
 }
 self.opener.Add_Define.OPRID.value=the_value;
 window.close();
}
</script>

How can I do this without a loop?

A: Add this path in header like how do we include js file (you can also put this file locally)
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">

</script>

And then use following code in your script. where "myradiobutton" is the name of your radio button.
var the_value=$('input[name="myradiobutton"]:radio:checked').val();


text:
Q: How do I interpret this two variables function? I've only taken math courses that have one independent variable in them (no calculus 2 yet), so I'm stumped trying to understand what's going on here:
f(y1, y2) = {3y1,  0 ≤ y2 ≤ y1 ≤ 1;     0, elsewhere}
Especially for this domain (is it even a domain?) what's going on here?
0 ≤ y2 ≤ y1 ≤ 1

What does the y2 ≤ y1 mean? Does it mean on the y1y2 plane, all points where y2 ≤ y1 takes on the function 3y1, and all points where y2 > y1 takes the 0 value? If so, would
0 ≤ y2 = y1 ≤ 1

mean that all points in the square (0,0) (1,0) (1,1) (0,1) takes on the function 3y1?

A: You have:
$$f(x,y)=\begin{cases} 3x, \ 0\le y\le x\le 1 \\ 0, \ elsewhere \end{cases}.$$
Note that $y\le x$ is the region below and on the line $y=x$. Once the borders $0$ and $1$ are placed, the region is constrained to the triangle with the vertices: $(0,0), (1,0), (1,1)$.


text:
Q: Content-dependent templates/partials with moustache.js I'd like to use moustache.js to render the following JSON structure:
[
  {type:'img', src:'some_url'},
  {type:'text', text:'lorem ipsum ...'},
  {type:'link', href:'some_url', label:'click here'},
  //  more entries ...
]

I'd like to render each item depending on type: img should br rendered as , text as
{{text}}
, etc. Is that possible with moustache.js or should I roll my own templating system? If it's possible, how would the template look like and how must I extend the JSON structure that it works as a moustache view?

A: Yes that's absolutely possible.
You could do something like
{{#myarray}} {{! loop through array}}
{{#src}} {{! if you have src it must be an img}}

{{/src}}
{{#text}} {{! if you have text is must be a paragraph}}

{{text}}{{/p}}
{{/text}}
{{#href}}} {{! if you have an href is must be an anchor}}
  {{label}}
{{/href}}
{{/myarray}}

No reason to extend the json at all, as long as the fields are unique to a certain type of output. You can just check if the field exists, and then if it does it must be output in a certain way.
The other thing you can do instead of having a 'type' field is have the json set with various flags to base you're template on (e.g. 'is_image: true', 'is_anchor: true', etc).


text:
Q: Can't show a MapContainer I resurrected a CN1 project (already published) and tried to make it run in the simulator under Netbeans 11 (running on OpenJdK 11). However the project kept crashing.
I updated the CN1 Google Maps extension, refreshed the libs, but the problem remained.
So I created a new CN1 project (bare bones with Java 8 project UNticked since it is a Java 11 project) to see if it crashed or not. Actually it showed the "Hi" Form. But then I added a MapContainer like I used to :
public void start() {
    if(current != null){

        current.show();
        return;
    }

    MapContainer map = new MapContainer("myJAvascriptKey");

    Form hi = new Form("Hi World");
    hi.setLayout(new BorderLayout());
    hi.add(BorderLayout.CENTER,map);
    hi.show();
}

And the simulator keeps crashing :
Retina Scale: 1.0
   Rendering frame took too long 163 milliseconds
   [JS Console] Here I am !!!
   Rendering frame took too long 207 milliseconds
   #
   # A fatal error has been detected by the Java Runtime Environment:
   #
   #  SIGSEGV (0xb) at pc=0x00007f66f5c69762, pid=13967, tid=14053
   #
   # JRE version: OpenJDK Runtime Environment (11.0.4+11) (build 11.0.4+11-post-Debian-1bpo91)
   # Java VM: OpenJDK 64-Bit Server VM (11.0.4+11-post-Debian-1bpo91, mixed mode, sharing, tiered, compressed oops, g1 gc, linux-amd64)
   # Problematic frame:
   # V  [libjvm.so+0x89a762]

The Google Map extension version is 42. What should I do to make everything work as before ?
Any help appreciated,

A: Change the JDK on your project to JDK8.  There is a bug in JavaFX right now that is causing crashes with the web view when run on JDK 11.


text:
Q: How to get the last element in a list in R I want to get the every last element in a list. I have found that by using sapply function, the first element can be obtained.
sapply(a,`[`,1)

However, I don't actually understantd what is the meaning of [, and how to get the last element in a similar way. This code doesn't work.
sapply(a,`]`,1)

A: By using the length of a list/vector:
a[length(a)]

For the last "n"th element:
a[length(a)-n+1]

Example:
a[length(a)-1] #the 2nd last element
a[length(a)-2] #the 3rd last element
a[length(a)-8] #the 9th last element

A: I came here with the same question, and saw that the answer must have been overlooked, but for me @akrun as usual had the answer that worked for me. So in the absence of a correct answer it is:
sapply(a, tail, 1)

A: If I get your query correctly, it could simply be :
tail(a, n = 1)


text:
Q: How to add service reference from customer's private network
I need to develop a service client application in C#. The service is hosted on customer's local network which I have no access. So I cannot use Add Service Reference option to create service proxy.
The customer gave me only the XML Soap declarations of their service. It looks like the following:
 <?xml version="1.0" encoding="UTF-8" ?>
- <!--  Published by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is Oracle JAX-WS 2.1.5.
  -->
- <!--  Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is Oracle JAX-WS 2.1.5.
  -->
- <definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://helios.tedas.gov.tr/im" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://helios.tedas.gov.tr/im" name="IletisimModulu">
- <types>

It is just the head of XML, I am not putting the full XML because of its size. I think this is what we would see if we navigate to service url from explorer (http://mywebservice/Service?WSDL).
So now, how can I create service proxy from this XML document that they gave me?

A:
So I cannot use Add Service Reference option to create service proxy.

You can paste a file path there as well as an URL. See also How can I consume a WCF service using a local WSDL file?.


text:
Q: Transformation of Random Variable results in strange CDF I'm trying to transform a RV according to $Y=X^{-a}$ with $a>0$ and X being uniformly distributed in $[0,A]$:
$
F_X(x) = \begin{cases}0 & x<0 \\ x/A & 0\leq x \leq A \\ 1  &x>A\end{cases}
$
I tried using the 'CDF'-method, here is what I got:
step 1:
$
F_Y(y) = Pr( Y \leq y ) = Pr( X^{-a} \leq y ) = 1 - Pr( x \leq Y^{-1/a} ) = 1 - F_X( Y^{-1/a} )
$
which gives me:
step2:
$
F_Y(y) =  \begin{cases} 1 & y^{-1/a}<0 \\ 1-y^{-1/a}/A & 0\leq y^{-1/a} \leq A \\ 0  &y^{-1/a}>A\end{cases}
$
and then results in:
step 3:
$
F_Y(y) = \begin{cases}1 & y<0 \\ 1-y^{-1/a}/A & y \geq A^{-a} \\ 0  & 0 \leq y \leq A^{-a} \end{cases}
$
and thus $F_Y(-\infty)=1$ and $F_Y(\infty)=1$
So this is wrong, but where is my mistake?

A: The problem is with inequality manipulation, which is on the tricky side.  For the cdf of $Y$, we want $\Pr(X^{-a}\le y)$.
We separate out the case $y\le 0$, although there is no need to. If $y\le 0$, we have $\Pr(Y\le y)=0$.
Now we deal with positive $y$. We have $X^{-a}\le y$ precisely if $\frac{1}{X^a}\le y$. This is the case if $X^a\ge y^{-1}$, or equivalently if $X\ge y^{-1/a}$.
If $y^{-1/a} \ge A$, then $\Pr(X\ge y^{-1/a})=0$. So if $y$ is positive and $y\le A^{-a}$, then $F_Y(y)=0$.
Putting things together with the case $y\le 0$, we get that $F_Y(y)=0$ if $y\le A^{-a}$.
Now look at $y\gt A^{-a}$. In that case,
$$F_Y(y)=\Pr(X\ge y^{-1/a})=\frac{A-y^{-1/a}}{A}.$$
Note that this approaches $1$ as $y\to\infty$, as it should.  The density function of $Y$ "lives" on the interval $(A^{-a},\infty)$.


text:
Q: Run PHP from within TPL I am trying to modify a module TPL file and face some difficulties.
I have a dropdown list and want to run an SQL query when the user selects an item from the list.
So far I have tried to run a PHP file through Ajax in order to run the query but without any success.
I have seen various examples but can't understand how it should be done.
Nevertheless here is what I have done so far.
This is the code I use on the TPL file:
<select id="statusSelect" onChange="updateStatus({$order.id_order|escape:'html':'UTF-8'})">
<option value="1"> test1 </option>
<option value="2"> test2 </option>
<option value="3"> test3 </option>
</select>

This is the JS function I use to call the PHP file, through Ajax:
<script type="text/javascript">
    function updateStatus(order_id_sent)
    {
    //TEST
    //alert(document.getElementsByTagName("option")[selectedIndex].value + " " + order_id_sent);
    $.ajax({
    url: 'setStatus.php',
    type: 'get',
    data: 'ajax=true',
    success: function()
    {
    alert("It worked");
    }
    });
    }
    </script>

And here is my setStatus.php file which I want to call:
<?php
include_once('../../../../../config/config.inc.php');
include_once('../../../../../init.php');
public function doStuff()
{
echo "alert('test');";
return 1;
}
if ($_GET['ajax'])
{
echo function doStuff();
}
?>

A: use
$( document ).ready(function() {
  $("#statusSelect").change(function(){
      statusUpdate($(this).val());
  });
}

in your code the name of the function is statusUpdate and in the select you call updateStatus
i wish this can help you

A: Finally I've got a solution for the problem, by using the following script to run the PHP file.
It seems that I had to import the JQuery from google-apis and use {literal} before and after my script.
Here is the updated javascript:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
{literal}
<script type="text/javascript">
    function setStatus(order_id_sent)
    {
        var selectedIndex = document.getElementById("statusSelect").selectedIndex;
        // test
        // alert(document.getElementsByTagName("option")[selectedIndex].value + " " + order_id_sent);
        var data = document.getElementsByTagName("option")[selectedIndex].value + "-" + order_id_sent;
        $.ajax({
            data: data,
            type: "post",
            url: "setStatus.php>",
            success: function(data){
            alert("data sent" + data);
            }
        });
    }
</script>
{/literal}

And here is my PHP file, which is not complete yet but the point was to run the query and now it works properly.
<?php
include_once('../../../../../config/config.inc.php');
include_once('../../../../../init.php');
include_once('../../../../../classes/Db.php');

if(isset($_REQUEST))
{
    error_reporting(E_ALL && ~E_NOTICE);
    $words = explode('-', $_POST['data']);
    //add code to update db
}
?>


text:
Q: Open an Excel sheet from PowerPoint I am using Office 2010 and I want to open a specific Excel from a PowerPoint slide. The PowerPoint slide should look the following:
On the slide I have an object or a link and when I click on that, the desired Excel sheet opens.
I tried to open it via the option: Insert>Object>Microsoft Excel Worksheet this basically gives me a new Excel sheet.
Any recommendations how to accomplish that?

A: Try Insert>Object>Create from file browse your file and tick the Display as icon box (FYI: Display as icon isn't available to be clicked until you have selected a file)


text:
Q: What files except LICENSE is a good practice to add to your gem repo? I wrote gem and published it to github (ex - https://github.com/randx/six)
I added LICENSE file.
I often see VERSION file in other repo - whats the goal?
Any other files should I add?

A: Chapter 8 of "Ruby Best Practices" by Greg Brown exclusively deals with properly maintaining Ruby projects, including directory layout, files you should include etc. The book is legally available online here:
http://majesticseacreature.com/rbp-book/pdfs/rbp_1-0.pdf

A: I always love a good README. It's much easier to read a well explained README than browse the automatically generated RDoc manual. The README should explain what the gem does and how to use it, with example code and even some advanced examples can be included towards the end of the README.
Another essential file is a history or CHANGES file. This file should contain an explanation of the major changes between releases. It does not need to include nitty gritty details, but should include enough information so that someone upgrading from version x to version y can quickly see what's new (so you can asses the benefits of upgrading) and what has changed (so you can asses the potential impacts an upgrade has on your current code).
Too many times I see projects where the CHANGES file is missing, and you're left pretty much in the dark about what has changed when you run an upgrade.

A: From my perspective each GitHub project (based on your question you have a repo there) should have:

*

*Integration with CI servers (Travis CI, Circle CI, etc)

*.github folder with issue/pull requests templates (example https://github.com/zold-io/zold/tree/master/.github)

*.gitingore to avoid accidentally committed temporal/local files

*.gitattributes for custom Git repo configuration (more https://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes and https://git-scm.com/docs/gitattributes)

*.rubycop.yml

*Add the following badges to your readme.md

*

* version of your ruby gem

* license details

* commit activity per year to hightlight the status of the project

* More about HoC here https://www.yegor256.com/2014/11/14/hits-of-code.html

*
 the status of the latest builds

* the status of dependencies (obsolte or not)

*
show the vulnurabilities count(if any) for the dependencies

*

 as code quality badges

Projects from the examples above:

*

*https://github.com/dgroup/docker-unittests (java)

*https://github.com/mattbrictson/gem (ruby)