text:
Q: Issue with temp table and insert into statement in VBA (ADODB query) I use VBA and the ADODB to query against a SQL Server server and having trouble with INSERT INTO statement in the following string:
StrQuery = "INSERT INTO #temp_ImprtSampVol Values ('RBM','Care: Admin',28)," & _
" ('RRA','Care: Quality',29)"

The error message is "Incorrect syntax near ','. I'm sure something is wrong with the above statement but I'm struggling to figure our what might be wrong.
I would like to insert the following values into the table (it does work perfectly in SQL):
INSERT INTO #temp_ImprtSampVol
VALUES
('RBM','Care: Admin',28),
('RBM','Care: Exit',31),
('RBM','Care: Other',22),
('RRA','Care: Quality',29),
('RRA','Care: Finance',37),

My code is as follows:
Sub VBAFromSQL()
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=HIDDEN_Outputs;Data Source=HIDDEN;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False"

cnn.Open ConnectionString
cnn.CommandTimeout = 900

StrQuery = "IF OBJECT_ID('tempdb..#temp_MthToDt') IS NOT NULL drop table
#temp_MthToDt" & _
" IF OBJECT_ID('tempdb..#temp_ImprtSampVol') IS NOT NULL drop table
#temp_ImprtSampVol" & _
" IF OBJECT_ID('tempdb..#temp_T1') IS NOT NULL drop table #temp_T2AuditData"

StrQuery = "DECLARE @Last_Day_Loaded VARCHAR(30) = '2018-10-03';" & _
" DECLARE @Start_of_Sample VARCHAR(30) = '2018-10-03';" & _
" DECLARE @End_of_Sample VARCHAR(30) = '2018-10-03';" & _
" DECLARE @Days_Data_so_far INT = 03;" & _
" DECLARE @First_Day_Month VARCHAR(30) = '2018-10-01';" & _
" DECLARE @Working_Days_in_Month INT = 23;" & _
" DECLARE @Days_in_Month INT = 31;" & _
" DECLARE @BBE_Sample_Minimum INT = 10;" & _
" DECLARE @BBE_Sample_adjustment_multiplier decimal(5,2) = 1.0;"

StrQuery = "CREATE TABLE #temp_ImprtSampVol (" & _
" CIS VARCHAR(10) NOT NULL," & _
" RD VARCHAR(40) NOT NULL," & _
" Sample_to_send INT NOT NULL );"

StrQuery = "INSERT INTO #temp_ImprtSampVol Values ('RBM','Care: Admin',28)," & _
" ('RRA','Care: Quality',29)"

rst.Open StrQuery, cnn
Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

Can you please advise how to rectify this? Thanks in advance.

A: As Sean Lange commented an insert statement doesn't return anything usefull but a confirmation of the query result state, so it errors or not.
According to the sql-code, I assume you are querying against a SQL-Server and having no access to a DB with necessary access rights to it you are using the tempdb :-) fair enough.
But, the problem in your code is that only the last part starting from the last
StrQry, namely the one with your "Insert into..." until "Sheets(1).Range...." has any effect. The other previous StrQry assignments are simply overwritten by the last one.
Your problem with these many continuations can be worked around by simply removing them where possible according to the T-SQL-syntax and make long lines as the SQL-Server handles the codelines on its own.
So, the code may look like this
Sub VBAFromSQL()
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=HIDDEN_Outputs;Data Source=HIDDEN;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False"

cnn.Open ConnectionString
cnn.CommandTimeout = 900

StrQuery = "IF OBJECT_ID('tempdb..#temp_MthToDt') IS NOT NULL drop table #temp_MthToDt; IF OBJECT_ID('tempdb..#temp_ImprtSampVol') IS NOT NULL drop table #temp_ImprtSampVol; IF OBJECT_ID('tempdb..#temp_T1') IS NOT NULL drop table #temp_T2AuditData; DECLARE @Last_Day_Loaded VARCHAR(30) = '2018-10-03', @Start_of_Sample VARCHAR(30) = '2018-10-03',@End_of_Sample VARCHAR(30) = '2018-10-03', @Days_Data_so_far INT = 03,@First_Day_Month VARCHAR(30) = '2018-10-01',@Working_Days_in_Month INT = 23,@Days_in_Month INT = 31,@BBE_Sample_Minimum INT = 10,@BBE_Sample_adjustment_multiplier decimal(5,2) = 1.0; CREATE TABLE #temp_ImprtSampVol (CIS VARCHAR(10) NOT NULL,RD VARCHAR(40) NOT NULL,Sample_to_send INT NOT NULL );INSERT INTO #temp_ImprtSampVol Values ('RBM','Care: Admin',28),('RRA','Care: Quality',29);"

rst.Open StrQuery, cnn
Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

What is not clear to me is what you expected from the insert statement to be delivered and shown in A2 of Sheet1.
If you wanted to show the the inserted lines you have to append either
;select * from #temp_ImprtSampVol;

or
output inserted.*;

at the end of the StrQry.
Mind the missing ";" in front of "output" as it belongs to the insert statement.

A: Excuse me. I had to be more precise with this.
Before attaching the last mentioned parts you have to remove the ";" at the end of the statement in your StrQry = ... .
So it the looks like this:
StrQry = "... ;INSERT INTO #temp_ImprtSampVol Values ('RBM','Care: Admin',28),('RRA','Care: Quality',29) output inserted.*;"

or
StrQry = "... ;INSERT INTO #temp_ImprtSampVol Values ('RBM','Care: Admin',28),('RRA','Care: Quality',29);select * from #temp_ImprtSampVol;"

I'm wondering why you are dropping these other tables that have never been used anyhow and why there are declared all this variables, but I think you want to extend the query. Be advised, even this way has it's limitations and you might better ask your DBA for some space with let's say, a small database where you can create SPs on your own. :-)


text:
Q: Sum values using Arrays and INDEX I have the following sample sheet:
1/A B       C   D   E   F   G   H   I   J
2
3   Points  8   4   2   1
4
5   Values  1   2   3   4   4   3   1   2

I'm trying to sum the 'Points' based upon the array index from the 'Values'.
My expected result from this is: 30
Here is my formula:
{=SUM(INDEX($C$3:$F$3,1,C5:J5))}

For some reason though, this only returns the first value of the array, rather than the entire sum.
To clarify, the C# version would be something like:
var points = new int[] { 8, 4, 2, 1 };
var values = new int[] { 2, 4, 3, 1, 2, 4, 2 };

var result = (from v in values
              select points[v - 1]).Sum(); // -1 as '4' will crash, but in Excel '4' is fine

Edit: Adding further clarifying example
Another example to clarify:
Points is the array. The 'values' represents the index of the array to sum.
The example above is the same as:
=SUM(8, 4, 2, 1, 1, 2, 8, 4)

A: INDEX will never take its row or column parameters from arrays and then perform multiple times within one array formula contained in one cell. For this OFFSET will be needed.
Either
{=SUM(N(OFFSET($C$3,,C5:J5-1)))}

as an array formula.
Or
=SUMPRODUCT(N(OFFSET($C$3,,C5:J5-1)))

as an implicit array formula without the need for [Ctrl]+[Shift]+[Enter].

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retrieving the US Postal Zip code for a street address using Python What is the most efficient way one would go about retrieving the U.S. Postal zip code for a street address using Python? Is this something that is even possible?
Preferably, something that includes a local database as oppose to a remote API call of some sort.
Thanks in advance for any help one may be able to offer.

A: May be a start:
The Zip Code Database Project
googlemaps – Google Maps and Local Search APIs in Python
GoogleMaps.geocode(query, sensor='false', oe='utf8', ll='', spn='', gl='')

Given a string address query, return a dictionary of information
  about that location, including its
  latitude and longitude.
    Interesting bits:

>>> gmaps = GoogleMaps(api_key)
>>> address = '350 Fifth Avenue New York, NY'
>>> result = gmaps.geocode(address)
>>> placemark = result['Placemark'][0]
>>> lng, lat = placemark['Point']['coordinates'][0:2]
# Note these are backwards from usual
>>> print lat, lng
40.6721118 -73.9838823
>>> details = placemark['AddressDetails']['Country']['AdministrativeArea']
>>> street = details['Locality']['Thoroughfare']['ThoroughfareName']
>>> city = details['Locality']['LocalityName']
>>> state = details['AdministrativeAreaName']
>>> zipcode = details['Locality']['PostalCode']['PostalCodeNumber']
>>> print ', '.join((street, city, state, zipcode))
350 5th Ave, Brooklyn, NY, 11215

A: A more reliable way is to use a robust address verification service that is using current USPS address data.  In full disclosure, I work for SmartyStreets, an address verification software company which provides just such a service.  Here's a simple example that illustrates how to use the service:
https://github.com/smartystreets/LiveAddressSamples/blob/master/python/street-address.py
As you can see from the sample, this service provides the full 9-digit ZIP Code along with all other address components as well as some metadata about the address.


text:
Q: Question about the definition of the composition of relations I am slightly confused about following definition:

Suppose R is a relation from A to B and S is a relation from B to C.
  Then the composition of S and R is the relation S ◦ R from A to C
  defined as follows:
  $$S \circ R = \{(a,c) \in A \times C \mid \exists b \in B((a,b) \in R
\text{ and } (b,c) \in S\}$$

I struggle to explain my question in words, hence I will give you an example to show where I'm confused.
Case 1
Suppose
$A = \{a_1,a_2,a_3\}$, $B = \{b_1,b_2,b_3\}$, $C = \{c_1,c_2,c_3\}$
$R$ is a relation from $A$ to $B$, and $D$ is a relation from $B$ to $C$
$R = \{(a_1,b_1)\}$ and $D = \{(b_1,c_3)\}$
I'm pretty sure that in this case, $R \circ D = \{(a_1,c_3)\}$
But now consider slightly different example:
Case 2
$A = \{a_1,a_2,a_3\}$, $B = \{b_1,b_2,b_3\}$, $C = \{c_1,c_2,c_3\}$
$R$ is a relation from $A$ to $B$, and $D$ is a relation from $B$ to $C$
$R = \{(a_1,b_2)\}$ and $D = \{(b_1,c_3)\}$ (Note that each subsets of $R$ and $D$ now have $b$'s with different indices)
In this case, is $R \circ D = \{(a_1,c_3)\}$ or $R \circ D = \emptyset$ ?

A: Note that your definition is understand by right to left:
First you take $(a, \color{red}b) \in R$ and if $( \color{red}b,c) \in S$, then add $(a,c)$ to $S \circ R$
So your computation in case 1 is wrong!, since $(\color{red}{c_3}, ?) \notin R $
For case 2, it is empty!

Note that a relation from $A$ to $C$ is any subset of $A \times C$, so empty set is also a relation. See here

A: You are correct.
The composite relation is not always non-empty.
You have to have the range of $D$ to be a subset of the domain of $ R$ in order for  $RoD$ to be non-empty.


text:
Q: Markov chain as sum of iid random variables Suppose I have a sequence of iid random variable, $Z_i$ for $i=0,1,2,3...$ such that $$\Bbb P(Z_i=z)=
\begin{cases}
p, &\text{if  } z=1 \\
1-p, & \text{if  } z=0.
\end{cases}$$
Define $S_k=\sum^k_{i=0}Z_i$ and $\prod_n=\prod^k_{i=0}Z_i$ .
So I have to determine as an exercise in my textbook whether $X_n=S_n$ and $Y_n=\prod_n$ are markov chains.
What I tried to do is express $X_{n+1}$ in terms of $X_n$  and something only generated at time $n + 1$: $X_{n+1}=Z_{n+1}+ \sum^n_{i=0}Z_i$ from this I somehow can show that $X_n$ is markov? I'm not quite sure how to use $Z_i$'s probabilities. I'm stuck here, any help would be appreciated.
Edit:
I solved this using the reasoning in the commments below and I would like to check whether my reasoning is correct:
1) So since $X_{n+1}= X_n +Z_{n+1}$ , it follows that $X_{n+1}$ is Markov since the $ n+1$-th value depends not on any of $X_0,...,X_{n-1}$ . It only depends on $X_n$ and a random variable $Z_{n+1}$ independent of  $X_0,...,X_{n-1}$.
This I kind of don't understand myself. Why is $X_{n+1}= X_n +Z_{n+1}$ independent of $X_0,...,X_{n-1}$ ? Isn't $X_n=X_{n-1} + Z_n$?(And if we iterate this to $X_1$ then we could say that $X_{n+1}$ is equal to $X_0 + Z_1 +...+Z_n+Z_{n+1}$ so this means that it does depend on those values?
For example what if I take that $Z_0,...,Z_n=(0,....,0)$  and hence $X_{n+1}$ would be equal to $0$ or $1$ but what if I choose $Z_0$ to be $1$ then the sum would be $1$ or $2$ ? So this means that it is dependent of $X_0...X_{n-1}$? Am I missing something here? Also, since the exercise gives probabilities with which $Z_i$ takes value $\{0,1\}$ , how are we supposed to use these?
2) It's markov for the same reason as 1)
I have the same doubts about the second one. What if $Z_0$ is equal to $0$? Then the whole product is equal $0$? And if $Z_0$ is 1 and all others are $1$ then it will be $1$ or $0$(depending on the $Z_{n+1}$-th value)? So this again is dependent of the preceeding values? Could someone please explain me if these answers are correct and explain why my reasoning is wrong, and maybe intuitively explain why these are Markov's. I would really like to understand this intuitively.
Also, if possible, could someone please say whether 3) $X_n= S_0+...+S_n$ and 4) $X_n= (S_n,S_0+...+S_n)$ are Markov.
I'm also interested in how could I prove these answers rigourously by definition which is if  $\Bbb P(X_{n+1}=x_{n+1} | X_0=x_0,...,X_n=x_n)= \Bbb P(X_{n+1}=x_{n+1} | X_n=x_n)$ then $X_{n+1}$ is Markov

A: I think you are somehow mixing independence and conditional independence.
The idea is not that $X_{n+1}$ is independent from $X_0 ... X_{n-1}$, but that it is conditionally independent given $X_n$.
This simply means that, once you know the value of $X_n$, the previous values $X_0...X_{n-1}$ are irrelevant for the distribution of $X_{n+1}$. Taking your example, let us assume that $X_n = 5$. Now, when we want to predict the value of $X_{n+1}$, knowing the values of $X_0...X_{n-1},Z_0...Z_{n-1}$ is completely irrelevant. Nothing changes in your prediction if $X_{n-1}=4$ or $X_{n-1}=5$, once you know that $X_n = 5$.

Now:
$$\mathbb{P}(X_{n+1}=x_{n+1}|X_0=x_0,...,X_n=x_n)$$
$$\mathbb{P}( \sum_0^{n+1}Z_i =x_{n+1}|X_0=x_0,...,X_n=x_n)$$
$$\mathbb{P}( X_n + Z_{n+1} =x_{n+1}|X_0=x_0,...,X_n=x_n)$$
$$\mathbb{P}( Z_{n+1} =x_{n+1}-x_n|X_0=x_0,...,X_n=x_n)$$
$$\mathbb{P}( Z_{n+1} =x_{n+1}-x_n|X_n=x_n)$$
$$\mathbb{P}( X_{n+1} =x_{n+1}|X_n=x_n)$$
We were able to remove the conditioning on all $X_i$ for i smaller than $n$ because our probability is only a function of $Z_{n+1}$ (which is independent from them as a consequence of its independence from all $Z_i$), and of $x_n$ which is a given value.

This gives you a Markov Chain with infinite states, where every state has a transition probability of $p$ to the next state (+1) and $1-p$ to itself.
The same reasoning applies to $\Pi_n$. This will instead only have two states ${0,1}$. State $0$ is an attractor, so it has transition probability $p=1$ to itself, while from state $1$ has probability $p$ of transition to itself, and probability $1-p$ of going to state $0$.

Now, (3) is NOT a Markov chain.
$$\mathbb{P}(X_{n+1}=x_{n+1}|X_0=x_0...X_n=x_n)$$
$$\mathbb{P}(X_n + S_n+Z_{n+1}|X_0=x_0 ... X_n=x_n)$$
Here, however, we have no way of knowing the value of $S_n$ just by $X_n$. Knowing for example that $X_n=10$ would simply mean that $\sum_0^nS_i=10$, but we cannot infer the value of $S_n$ without peeking at the previous "history". Therefore, the markovian property does not hold.
(4), on the other hand, is a Markov Chain (I will use $(x,y)$ notation since now $X$ is multivariate).
$$\mathbb{P}(X_{n+1}=(x_{n+1},y_{n+1})|X_0=(x_{0},y_{0})...X_n=(x_{n},y_{n}))$$
$$\mathbb{P}((S_{n+1},\sum_0^{n+1}S_i)=(x_{n+1},y_{n+1})|X_0=(x_{0},y_{0})...X_n=(x_{n},y_{n}))$$
$$\mathbb{P}((S_{n}+Z_{n+1},\sum_0^{n}S_i+S_{n}+Z_{n+1})=(x_{n+1},y_{n+1})|X_0=(x_{0},y_{0})...X_n=(x_{n},y_{n}))$$
$$\mathbb{P}((x_{n}+Z_{n+1},y_n+x_{n}+Z_{n+1})=(x_{n+1},y_{n+1})|X_0=(x_{0},y_{0})...X_n=(x_{n},y_{n}))$$
Again, this is only a function of $Z_{n+1}$ (which is independent of previous $S_i$) and of $(x_n,y_n)$, and we can therefore remove conditioning on previous values as they are redundant.
$$\mathbb{P}((x_{n}+Z_{n+1},y_n+x_{n}+Z_{n+1})=(x_{n+1},y_{n+1})|X_n=(x_{n},y_{n}))$$
$$\mathbb{P}(X_{n+1}=(x_{n+1},y_{n+1})|X_n=(x_{n},y_{n}))$$
Which makes it Markovian.
I hope the logical passages are clear enough, otherwise let me know!


text:
Q: Locking User account created under Windows Authentication in SQL Server As per my project requirement i need to lock a user in SQL Server(Which is created using Windows Authentication). Is there any way to do this?
For example: For a SQL login if you try to login using wrong Password more than 3 or 4 attempts, then that account gets locked out. User cannot login to SQL Server using this username. I want to check this using Users created under windows authenntication
Thanks for the help
Santhosh

A: You need to keep two things apart:

*

*on a server-level, you have users that have a login - this gives them the ability to connect to that SQL Server at all. You can disable a login using:
ALTER LOGIN (name) DISABLE

Doing so prevents that user from logging into the database server alltogether - he (or she) cannot access anything on that database server anymore

*on a per-database level, those logins might be granted access to the database - this is done by creating a user (based on that login) for that database, and assigning that user certain permissions. You can't really disable a user in a database - you just have to drop that user
USE (database)
DROP USER (name)

You can always re-create that user from his login in that database using
USE (database)
CREATE USER (name) WITH LOGIN = (login name)


text:
Q: How to change the size of the text inside the Buttons? Can someone help me with this issue? I spent 1d searching on the web for a decent answer but found nothing!
'''
Created on 20 gen 2020

@author: ruben
'''
from tkinter import *
import os
import random
from _sqlite3 import Row
import math
from lib2to3.pgen2.token import OP

op = "suca"
num1 = 234
num2 = 0
#CalculatorGui
gui = Tk()
gui.geometry("320x427")
gui.title("Calculator")

#ScientificCalculator
#def RAD():

#TextArea
text = Text(gui, height='5', width='30')
text.grid(row=0, column=0, columnspan=5, ipadx=37)
#Buttons
n1 = Button(gui, text='1', fg='black', bg='grey', height='5', width='10', command=press1)
n1.grid(row=1, column=0)

gui.mainloop()

This is only 5% of all the code. I just need to change the size of the text inside the button n1 = Button(gui, text='1', size?

A: Changing the font size of a widget can be done using the font configure option, either when creating the widget or using the widget's config method. The font can be provided using a tuple or a string that contains the name of the font, and optionally a size and style.
n1 = Button(gui, text='1', font=('FontName', 16, 'style'))
n1 = Button(gui, text='1', font='FontName 16 style')
n1.config(font=('FontName', 16, 'style'))
n1.config(font='FontName 16 style')

Above are four options that all accomplish the same thing. To change the size of the text like this, you are required to provide a font name before you provide a text size. This means that if you want your button's text to match the text in other buttons, you'll need to know what font is being used. If you have manually set a font for the rest of the widgets already, use that one. But if you haven't set a font, you can determine the name of the default font using the button's cget() method.
n1 = Button(gui, text='1')
font = n1.cget('font')
n1.config(font=(font, 16))

More info on styling widgets here: https://effbot.org/tkinterbook/tkinter-widget-styling.htm

A: Use the font argument in the button call.
Button(gui, text='1', fg='black', bg='grey', height='5', width='10', command=press1, font=("Helvetica", 20, "bold"))


text:
Q: Process large file in chunks I have a large file which has two numbers per line and is sorted by the second column. I make a dictionary of lists keyed on the first column.
My code looks like
from collections import defaultdict
d = defaultdict(list)
for line in fin.readline():
    vals = line.split()
    d[vals[0]].append(vals[1])
process(d)

However the input file large is too large so d will not fit into memory.
To get round this I can in principle read in chunks of the file at a time but I need to make an overlap between the chunks so that process(d)  won't miss anything.
In pseudocode I could do the following.

*

*Read 100 lines creating the dictionary d.

*Process the  dictionary d

*Delete everything from  d that is not within 10 of the max value seen so far.

*Repeat but making sure we don't have more than 100 lines worth of data in d at any time.

Is there a nice way to do this in python?
Update.  More details of the problem. I will use d when reading in a second file of pairs where I will output the pair if depending on how many values there are in the list associated with the first value in d which are within 10.  The second file is also sorted by the second column.
Fake data.
Let's say we can fit 5 lines of data into memory and we need the overlap in values to be 5 as well.
1 1
2 1
1 6
7 6
1 16

So now d is {1:[1,6,16],2:[1],7:[6]}.
For the next chunk we only need to keep the last value (as 16-6 > 5). So we would set
d to be {1:[16]} and continue reading the next 4 lines.

A: Have you tried out the Pandas library, and in particular reading your data into a DataFrame then using groupby on the first column?
Pandas will let you do a lot of bulk operations effectively across your data, and you can read it in lazily if you want to.

A: You don't need default dict unless something strange is going on with the file, but you haven't mentioned what that is. Instead, use a list, which keeps your data in line order, that way you can process it using the appropriate slices thus:
d = []
for line in fin.readline():
    vals = line.split()
    d.append(vals)
    if not len(d)%100:
        process(d)
        d = d[90:]
process(d)

A: You could do this something like this:
n_process = 100
n_overlap = 10
data_chunk = []
for line in fin.readline():
    vals = line.split()
    data_chunk.append(vals)
    if len(data_chunk) == n_process:
        process(data_chunk)
        data_chunk = data_chunk[-n_overlap:]

When using a dictionary, data can be overwritten if multiple occurrences of numbers in the first column are present in a data sample. Also notice, that you need to use OrderedDict, since a dict does not have an order in python. However, in my opinion, OrderedDict is in most cases a sign of bad code design.
And by the way: we still don't know why you're trying to do this way…


text:
Q: Why am I getting a -3 on an AutoHotKey DllCall? I am attempting to use IBM's EHLLAPI to interface with their Personal Communicator terminal emulator. I point it to the location of the API, and specify the api name, as such:
hllapi(ByRef functionCode, ByRef data, ByRef length, ByRef returnCode)
{
  dllfunction := "C:\EHLAPI32.dll\HLLAPI"
  datatype := "Int *"
  rvalue := DllCall(dllfunction
                  , datatype, functionCode
                  , "Str"   , data
                  , datatype, length
                  , datatype, returnCode)
  If ErrorLevel
    MsgBox hllapi() returned %ErrorLevel%
  Return rvalue
}

However, it just returns -3, indicating:

-3: The specified DllFile could not be accessed. If no explicit path was specified for DllFile, the file must exist in the system's PATH or
  A_WorkingDir. This error might also occur if the user lacks permission
  to access the file.

I have checked the permissions, and there shouldn't be any issues there. I have also tried copying the dll to the root of my C:/ drive to avoid any access issues, and that did not fix it either. Why can't it find the file?

A: I finally discovered the problem. I am using 64 bit AutoHotkey, and the dll I am trying to use is 32-bit. Once I switched to 32-bit AutoHotkey, it was able to find the dll with no problems.


text:
Q: Single and double quote issue in SQL insert Please see the query below.
INSERT INTO pro VALUES ("260915",'Peel and Stick Floral Wall Art','Transform your tot's bedroom into a bright, burgeoning meadow with this set of oh-so-colorful wall art. Each unique flower, bird, butterfly, and swirly sun is a colorful creation of multilayered vinyl brimming with life and energy. How best to arrange them is entirely up to you--and your 12.2" x 15.4"','','Shipping',"790","110-m4jlgu36n",1.00,0,0,"0.00","70.00","http://.com/peel-and-stick-floral-wall-art.html","622")

Here I have single quote and double quote in same value which I want to insert in a column:
eg a) 12.2" x 15.4"
   b) Transform your tot's

Please suggest best solution.

A: When building the INSERT, use single quotes in the outside and the problem with double quotes is solved.
To fix the problem with single quotes, replace ' by ''.

A: why you don't escape your quotes? 12.2\" ?

A: Put everything inside single quote '
'12.2" x 15.4"<br>'

for string like this Transform your tot's you will have to escape it like
'Transform your tot\'s'

A: For T-SQL, to get a single quote in your data you just escape it with another (e.g. use two single quotes next to each other)  You don't need to worry about double quotes inside the string literals.
INSERT INTO foo VALUES ('qwerty''s: 25" sq.')

A: Use only single quote (') to surround the values. If a single quote is part of the value, type it in twice (that is the way to escape it).
E.g.
INSERT INTO TABLE VALUES ('12.2" x 15.4"', 'Transform your tot''s bedroom...');


text:
Q: return Object from Controller to another View in ASP.Net MVC I'm working on ASP.NET MVC ,
My application is to display list of menues in list box and when you click on any items another view will display list of submenues , and I have a problem is how to return Json to another view
 in the first of all the controller return view model object to view to display it on list box like the following
  return View(data);

where data is array of Strings , and I add an event to list box when selecting some item
@Html.Orubase().ListBox("list").RenderMode(RenderMode.Auto).IOS(c => c.ShowCorners(false)).BindDataSource(Model, map =>
{
    map.MapTo<string>(binding =>
    {
        binding.ItemDataBound((item, nd) =>
        {
            item.Text = nd;
        });
    });
}).OnItemSelect("select")

Where select is javascript function that call another function in controller
function select(event, d) {
       var index = d.selectedItemIndex;

       $.ajax({
           url: '@Url.Action("GetSubMenue", "Home")',
           type: 'GET',
           dataType: 'json',
           data:{ind:index},
           cache: false,

           success: function (data) {

           }
       });

Now GetSubMenue function will return the following object "data" that is another array of string
   return Json(data,JsonRequestBehavior.AllowGet);

now I want GetSubMenue function to return Json data object to another view to view it in  a new list
so, can you help me please

A: You may want to look at jquery templates. You can render a template out with your main view and then when you retrieve your sub menu populate the template with the json data.
Alternatively you could return a PartialView from the ajax call and manually replace the html in the document.


text:
Q: Angular new project vulnerabilities I've updated angular cli and created a new project, with routing and scss.
When I run npm install i see:

41 vulnerabilities (4 low, 37 moderate)

To address issues that do not require attention, run:
  npm audit fix

To address all issues (including breaking changes), run:
  npm audit fix --force

I used the first command npm audit fix and it showed me this:
up to date, audited 985 packages in 5s

90 packages are looking for funding
  run `npm fund` for details

# npm audit report

node-forge  <1.0.0
Prototype Pollution in node-forge debug API. - https://github.com/advisories/GHSA-5rrq-pxf6-6jx5
fix available via `npm audit fix --force`
Will install @angular-devkit/build-angular@0.1101.2, which is a breaking change
node_modules/node-forge
  selfsigned  >=1.1.1
  Depends on vulnerable versions of node-forge
  node_modules/selfsigned
    webpack-dev-server  >=2.5.0
    Depends on vulnerable versions of selfsigned
    node_modules/webpack-dev-server
      @angular-devkit/build-angular  *
      Depends on vulnerable versions of @angular-devkit/build-webpack
      Depends on vulnerable versions of postcss-preset-env
      Depends on vulnerable versions of resolve-url-loader
      Depends on vulnerable versions of webpack-dev-server
      node_modules/@angular-devkit/build-angular
      @angular-devkit/build-webpack  *
      Depends on vulnerable versions of webpack-dev-server
      node_modules/@angular-devkit/build-webpack

postcss  <8.2.13
Severity: moderate
Regular Expression Denial of Service in postcss - https://github.com/advisories/GHSA-566m-qj78-rww5
fix available via `npm audit fix --force`
Will install @angular-devkit/build-angular@0.1101.2, which is a breaking change
node_modules/autoprefixer/node_modules/postcss
node_modules/css-blank-pseudo/node_modules/postcss
node_modules/css-has-pseudo/node_modules/postcss
node_modules/css-prefers-color-scheme/node_modules/postcss
node_modules/postcss-attribute-case-insensitive/node_modules/postcss
node_modules/postcss-color-functional-notation/node_modules/postcss
node_modules/postcss-color-gray/node_modules/postcss
node_modules/postcss-color-hex-alpha/node_modules/postcss
node_modules/postcss-color-mod-function/node_modules/postcss
node_modules/postcss-color-rebeccapurple/node_modules/postcss
node_modules/postcss-custom-media/node_modules/postcss
node_modules/postcss-custom-properties/node_modules/postcss
node_modules/postcss-custom-selectors/node_modules/postcss
node_modules/postcss-dir-pseudo-class/node_modules/postcss
node_modules/postcss-double-position-gradients/node_modules/postcss
node_modules/postcss-env-function/node_modules/postcss
node_modules/postcss-focus-visible/node_modules/postcss
node_modules/postcss-focus-within/node_modules/postcss
node_modules/postcss-font-variant/node_modules/postcss
node_modules/postcss-gap-properties/node_modules/postcss
node_modules/postcss-image-set-function/node_modules/postcss
node_modules/postcss-initial/node_modules/postcss
node_modules/postcss-lab-function/node_modules/postcss
node_modules/postcss-logical/node_modules/postcss
node_modules/postcss-media-minmax/node_modules/postcss
node_modules/postcss-nesting/node_modules/postcss
node_modules/postcss-overflow-shorthand/node_modules/postcss
node_modules/postcss-page-break/node_modules/postcss
node_modules/postcss-place/node_modules/postcss
node_modules/postcss-preset-env/node_modules/postcss
node_modules/postcss-pseudo-class-any-link/node_modules/postcss
node_modules/postcss-replace-overflow-wrap/node_modules/postcss
node_modules/postcss-selector-matches/node_modules/postcss
node_modules/postcss-selector-not/node_modules/postcss
node_modules/resolve-url-loader/node_modules/postcss
  autoprefixer  1.0.20131222 - 9.8.8
  Depends on vulnerable versions of postcss
  node_modules/autoprefixer
    postcss-preset-env  <=7.0.0
    Depends on vulnerable versions of autoprefixer
    Depends on vulnerable versions of css-blank-pseudo
    Depends on vulnerable versions of css-prefers-color-scheme
    Depends on vulnerable versions of postcss
    Depends on vulnerable versions of postcss-color-gray
    Depends on vulnerable versions of postcss-color-mod-function
    Depends on vulnerable versions of postcss-double-position-gradients
    Depends on vulnerable versions of postcss-focus-visible
    Depends on vulnerable versions of postcss-focus-within
    Depends on vulnerable versions of postcss-initial
    Depends on vulnerable versions of postcss-page-break
    node_modules/postcss-preset-env
      @angular-devkit/build-angular  *
      Depends on vulnerable versions of @angular-devkit/build-webpack
      Depends on vulnerable versions of postcss-preset-env
      Depends on vulnerable versions of resolve-url-loader
      Depends on vulnerable versions of webpack-dev-server
      node_modules/@angular-devkit/build-angular
  css-blank-pseudo  <=1.0.0
  Depends on vulnerable versions of postcss
  node_modules/css-blank-pseudo
  css-has-pseudo  <=1.0.0
  Depends on vulnerable versions of postcss
  node_modules/css-has-pseudo
  css-prefers-color-scheme  <=4.0.0
  Depends on vulnerable versions of postcss
  node_modules/css-prefers-color-scheme
  postcss-attribute-case-insensitive  <=4.0.2
  Depends on vulnerable versions of postcss
  node_modules/postcss-attribute-case-insensitive
  postcss-color-functional-notation  <=3.0.2
  Depends on vulnerable versions of postcss
  node_modules/postcss-color-functional-notation
  postcss-color-gray  >=3.0.0
  Depends on vulnerable versions of postcss
  node_modules/postcss-color-gray
  postcss-color-hex-alpha  1.3.0 - 6.0.0
  Depends on vulnerable versions of postcss
  node_modules/postcss-color-hex-alpha
  postcss-color-mod-function  *
  Depends on vulnerable versions of postcss
  node_modules/postcss-color-mod-function
  postcss-color-rebeccapurple  1.2.0 - 6.0.0
  Depends on vulnerable versions of postcss
  node_modules/postcss-color-rebeccapurple
  postcss-custom-media  4.0.0 - 7.0.8
  Depends on vulnerable versions of postcss
  node_modules/postcss-custom-media
  postcss-custom-properties  3.3.0 - 10.0.0
  Depends on vulnerable versions of postcss
  node_modules/postcss-custom-properties
  postcss-custom-selectors  2.3.0 - 5.1.2
  Depends on vulnerable versions of postcss
  node_modules/postcss-custom-selectors
  postcss-dir-pseudo-class  <=5.0.0
  Depends on vulnerable versions of postcss
  node_modules/postcss-dir-pseudo-class
  postcss-double-position-gradients  <=2.0.0
  Depends on vulnerable versions of postcss
  node_modules/postcss-double-position-gradients
  postcss-env-function  <=3.0.0
  Depends on vulnerable versions of postcss
  node_modules/postcss-env-function
  postcss-focus-visible  <=5.0.0
  Depends on vulnerable versions of postcss
  node_modules/postcss-focus-visible
  postcss-focus-within  <=4.0.0
  Depends on vulnerable versions of postcss
  node_modules/postcss-focus-within
  postcss-font-variant  1.2.0 - 4.0.1
  Depends on vulnerable versions of postcss
  node_modules/postcss-font-variant
  postcss-gap-properties  <=2.0.0
  Depends on vulnerable versions of postcss
  node_modules/postcss-gap-properties
  postcss-image-set-function  <=3.0.1
  Depends on vulnerable versions of postcss
  node_modules/postcss-image-set-function
  postcss-initial  <=3.0.4
  Depends on vulnerable versions of postcss
  node_modules/postcss-initial
  postcss-lab-function  <=3.1.2
  Depends on vulnerable versions of postcss
  node_modules/postcss-lab-function
  postcss-logical  <=4.0.2
  Depends on vulnerable versions of postcss
  node_modules/postcss-logical
  postcss-media-minmax  1.2.0 - 4.0.0
  Depends on vulnerable versions of postcss
  node_modules/postcss-media-minmax
  postcss-nesting  <=7.0.1
  Depends on vulnerable versions of postcss
  node_modules/postcss-nesting
  postcss-overflow-shorthand  <=2.0.0
  Depends on vulnerable versions of postcss
  node_modules/postcss-overflow-shorthand
  postcss-page-break  <=2.0.0
  Depends on vulnerable versions of postcss
  node_modules/postcss-page-break
  postcss-place  <=5.0.0
  Depends on vulnerable versions of postcss
  node_modules/postcss-place
  postcss-pseudo-class-any-link  <=6.0.0
  Depends on vulnerable versions of postcss
  node_modules/postcss-pseudo-class-any-link
  postcss-replace-overflow-wrap  <=3.0.0
  Depends on vulnerable versions of postcss
  node_modules/postcss-replace-overflow-wrap
  postcss-selector-matches  *
  Depends on vulnerable versions of postcss
  node_modules/postcss-selector-matches
  postcss-selector-not  <=4.0.1
  Depends on vulnerable versions of postcss
  node_modules/postcss-selector-not
  resolve-url-loader  0.0.1-experiment-postcss || 3.0.0-alpha.1 - 4.0.0
  Depends on vulnerable versions of postcss
  node_modules/resolve-url-loader

After that i launched npm audit fix --force
And now i have

25 vulnerabilities (3 low, 15 moderate, 7 high)

To address issues that do not require attention, run:
  npm audit fix

To address all issues (including breaking changes), run:
  npm audit fix --force

Run `npm audit` for details.

And i also can't start the project
An unhandled exception occurred: require() of ES Module /Users/gboutte/Documents/my-project/node_modules/@angular/compiler-cli/bundles/index.js from /Users/gboutte/Documents/my-project/node_modules/@angular-devkit/build-angular/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js not supported.
Instead change the require of index.js in /Users/gboutte/Documents/my-project/node_modules/@angular-devkit/build-angular/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js to a dynamic import() which is available in all CommonJS modules.
See "/private/var/folders/yq/67x6zpfj695czhn4sqrwvxp40000gn/T/ng-h8zNpR/angular-errors.log" for further details.

Should i ignore theses error or is there a way to fix it ?
I saw the mention of postcss in the vulnerabilities, should i use something else than scss ?

A: Agreed with Will Alexander that we should probably just put up with these vulnerabilities for now and upgrade to a new Angular 13.x.x that patches them. On the plus side, these look like low-risk vulnerabilities for how most people use Angular (caveat: these are my best-guess; others please chime in if I'm missing something):

*

*node-forge looks like it's used to create self-signed SSL certificates for the local development server (usualy localhost:4200) when you run ng serve.

*postcss is used by build tools to parse and modify CSS (adding vendor prefixes, etc.) Not sure, but I think it's still used by Angular even if you're using CSS rather than SCSS.

So both of these are only being used in development and not deployed with a production build (where Prototype Pollution and RegEx DoS would be significant risks).
Also, the automated npm audit fix --force will probably cause more problems than it solves if you're using the current version of Angular (v13). It rolls back @angular-devkit/build-angular from 13.1.2 (for Angular v13) to 0.1101.2 (v11-lts, Long-Term Support for Angular v11). That mismatch between v11 build tools and v13 code is probably what's causing your unhandled exception when you try to run.
tl;dr: Develop in Angular without the npm audit fix (in this case!) since these vulnerabilities won't get deployed to production. Update to a newer Angular v13.x.x will hopefully clean up npm audit in the near future.

A: I'm afraid you just have to put up with the vulnerabilities. Angular has a very strict set of dependencies, and in changing the versions of those dependencies you've broken your app.
Make sure you keep updating your Angular project as often as is feasible, as the Angular team regularly update Angular's dependencies to mitigate these issues.


text:
Q: Getting province and city name of given point OpenStreetMap has many shapefiles for downloading, and with shp2pgsql we can import it to PostGIS

shp2pgsql -s SRID SHAPEFILE.shp SCHEMA.TABLE | psql -h HOST -d DATABASE -U USER

How can I get province and city name (or id) of a given point?
It is a little confusing for me! can someone explain more how can I do it? I just find some shape files here https://download.geofabrik.de/north-america/us.html and have no idea how to import just state/providence/city boundaries
Just tell me how to convert it to a minimal postgres table that contains type (state or city) , name of state/city and geometry of state/city
I know how can I use functions like ST_Contains to find city of given point


text:
Q: Balance BST tree manually I've done balancing of the tree(bst>avl) requested by hand and I wonder that it was really easy, so I am not sure whether I've done it correctly.
        a
       / \
      b  e3
     / \
    e1 e2
initial state is:
'a' is parent of 'b'(left) and 'e3'(right), 'b' is a parent of 'e1'(left) and 'e2'(right).
applying right rotation gives us:
        b
       / \
     e1   a
         / \
       e2   e3
'b' in place of 'a' with child 'e1' on the left and 'a' child on the right, 'a' gets 'e2' of 'b' on the left.
So the questions:

*

*If e1 is itself a subtree or node containing other elements, can I still do this rotation?

*2. If e2 and e3 are absent, can I still do this rotation?

example 11; 12;16
     16
     /
   13
  /
10

intial state: 16 is a parent of 13 and 13 is a parent of 10.
Can I do from it: 13 is a parent of 10(left) and 16(right)
I know it's simplistic, but theory often does not cover these thing assuming it's clear, well not for everyone.
Thanks for help,

A: Yes to everything, really. Think about the order property: left descendants < node and node < right descendants. Note how the rotation preserves this; compare a and b to e1, e2 and e3 before the rotation, and check the order and descendent relationships after the rotation. I'll let you ponder how before giving it away.


text:
Q: OpenCV: Assertion failed (src.checkVector(2, CV_32F) I'm currently trying to correct the perspective of an image within an UIImage extension.
When getPerspectiveTranform gets called I'm getting the following Asserting.
Error
OpenCV Error: Assertion failed (src.checkVector(2, CV_32F) == 4 && dst.checkVector(2, CV_32F) == 4) in getPerspectiveTransform, file /Volumes/build-storage/build/master_iOS-mac/opencv/modules/imgproc/src/imgwarp.cpp, line 6748
libc++abi.dylib: terminating with uncaught exception of type cv::Exception: /Volumes/build-storage/build/master_iOS-mac/opencv/modules/imgproc/src/imgwarp.cpp:6748: error: (-215) src.checkVector(2, CV_32F) == 4 && dst.checkVector(2, CV_32F) == 4 in function getPerspectiveTransform

Code
- (UIImage *)performPerspectiveCorrection {
    Mat src = [self genereateCVMat];
    Mat thr;
    cv::cvtColor(src, thr, CV_BGR2GRAY);

    cv::threshold(thr, thr, 70, 255, CV_THRESH_BINARY);

    std::vector< std::vector <cv::Point> > contours; // Vector for storing contour
    std::vector< cv::Vec4i > hierarchy;
    int largest_contour_index=0;
    int largest_area=0;

    cv::Mat dst(src.rows,src.cols, CV_8UC1, cv::Scalar::all(0)); //create destination image

    cv::findContours(thr.clone(), contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0)); // Find the contours in the image

    for (int i = 0; i< contours.size(); i++) {
        double a = cv::contourArea(contours[i], false); //  Find the area of contour
        if (a > largest_area){
            largest_area=a;
            largest_contour_index=i; //Store the index of largest contour
        }
    }

    cv::drawContours( dst,contours, largest_contour_index, cvScalar(255,255,255),CV_FILLED, 8, hierarchy );

    std::vector<std::vector<cv::Point> > contours_poly(1);
    approxPolyDP( cv::Mat(contours[largest_contour_index]), contours_poly[0],5, true );
    cv::Rect boundRect = cv::boundingRect(contours[largest_contour_index]);

    if(contours_poly[0].size() >= 4){
        std::vector<cv::Point> quad_pts;
        std::vector<cv::Point> squre_pts;

        quad_pts.push_back(cv::Point(contours_poly[0][0].x,contours_poly[0][0].y));
        quad_pts.push_back(cv::Point(contours_poly[0][1].x,contours_poly[0][1].y));
        quad_pts.push_back(cv::Point(contours_poly[0][3].x,contours_poly[0][3].y));
        quad_pts.push_back(cv::Point(contours_poly[0][2].x,contours_poly[0][2].y));

        squre_pts.push_back(cv::Point(boundRect.x,boundRect.y));
        squre_pts.push_back(cv::Point(boundRect.x,boundRect.y+boundRect.height));
        squre_pts.push_back(cv::Point(boundRect.x+boundRect.width,boundRect.y));
        squre_pts.push_back(cv::Point(boundRect.x+boundRect.width,boundRect.y+boundRect.height));

        Mat transmtx = getPerspectiveTransform(quad_pts, squre_pts);
        Mat transformed = Mat::zeros(src.rows, src.cols, CV_8UC3);
        warpPerspective(src, transformed, transmtx, src.size());

        return [UIImage imageByCVMat:transformed];
    }
    else {
        NSLog(@"Make sure that your are getting 4 corner using approxPolyDP...");
        return self;
    }
}

A: I know it's late but I confronted the same issue, so maybe it'll help anyone.
The error occours because src and dst in getPerspectiveTransform(src, dst); has to be type of vector<Point2f> not vector<Point>.
So it should be like:
std::vector<cv::Point2f> quad_pts;
std::vector<cv::Point2f> squre_pts;

quad_pts.push_back(cv::Point2f(contours_poly[0][0].x,contours_poly[0][0].y));

// etc.

squre_pts.push_back(cv::Point2f(boundRect.x,boundRect.y));

//etc.


text:
Q: Magento Security Scan : some of results are UNKNOWN I am trying magento's New Magento Security Scan and find out some of Unidentified Results.
Status of results are UNKNOWN.
How can i completely scan my website.

A: Unknown means we cannot determine the information, eg for PHP version the server might not be exposing this in the headers (which is actually good) or your admin panel might be in non-standard location (which is good too). It's recommended you manually verify those unknown results to double check eg that you use SSL for admin panel or using up to date PHP version as we cannot check this automatically.


text:
Q: Is it possible to pattern match on scala's akka ByteString? I'm implementing a self-defined TCP protocol with akka's tcp extention
Adopting the SimplisticHandler in tcp server example here
class SimplisticHandler extends Actor {
  import Tcp._
  def receive = {
    case Received(data) => sender() ! Write(data)
    case PeerClosed     => context stop self
  }
}

Under Received(data), is it possible to pattern match on the Byte sequence? As I understand it, there need to be an extractor defined in order for the pattern matching to work. There seems to be no unapply defined as per the documentation.
I want something like:
def receive = {
    case Received(data) =>
        val worker = getSomeWorkerActor
        worker ! data
  }

Then in children workers:
private[this] def commandA(cmd: ByteString) = println(cmd)
def receive = {
    // [warn] foo.scala:55: abstract type pattern Coll is unchecked since it is eliminated by erasure
    // [error] foo.scala:55: type mismatch;
    // [error]  found   : scala.collection.SeqLike[T,Coll]
    // [error]  required: akka.util.ByteString
    case 0x01 +: command => commandA(command)
    case 0x02 +: 0x03 +: command => commandB(command)
}

while keeping command as ByteString. If so how? Or what would be a recommended alternative?
I want to avoid decoding into String then compare against string if that's possible.
scala 2.11.8, akka 2.4.7

A: In a pattern matching construct, the type of the pattern is not infered from the right-hand side of the case clause, see also Pattern Matching Expressions. Therefore the parameter type of commandA and commandB is not considered. You have to match on ByteString first:
def receive = {
  case b: ByteString => b match {
    case 0x01 +: command => commandA(command)
    case 0x02 +: 0x03 +: command => commandB(command)
  }
}


text:
Q: Trying to find the XPATH I am trying to find the xpath of the 'lucidId' in this SOAP return:
 <SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://media.com/entities/lpedition" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <SOAP-ENV:Body>
       <ns1:detailFromPublicationDateResponse>
          <return SOAP-ENC:arrayType="ns1:Edition[2]" xsi:type="ns1:EditionArray">
             <item id="5267" status="" adsBundleStatus="" adsBundleSizeInBytes="" adsBundleUrl="" xsi:type="ns1:Edition" xmlns="http://lapresse.ca/entities/lpedition">
                <name>ARTS CINÉMA</name>
                <publishedAt>20170603</publishedAt>
                <sections>
                   <section id="22556" type="CAT" rank="1">
                      <typeCode>REG</typeCode>
                      <color>008591</color>
                      <name>ARTS CINÉMA</name>
                      <pages>
                         <page id="66972270" lucidId="3d84e764-c507-4f07-82c3-c6f9cab588eb|_0" pageNumberForEdition="" pageNumberForSection="1" type="" adsBundleStatus="" adsBundleSizeInBytes="0" adsBundleUrl="">
                            <navThumbnail url="http://lp-bo.lapresse.ca/api/5267/d8eb9c12f7b449dd80bf852832638ed7/thumbnail-nav">
                               <title>À la une</title>
                               <subTitle>ARTS</subTitle>
                            </navThumbnail>
                            <screenCapture url="http://lp-bo.lapresse.ca/api/5267/d8eb9c12f7b449dd80bf852832638ed7/thumbnail?lucidRank=0"/>
                            <ads/>
                            <pages/>
                            <articles/>
                            <slideshows/>
                         </page>

As soon as I put 'return' in my xpath, I am not getting anything
 /SOAP-ENV:Envelope/SOAP-ENV:Body/ns1:detailFromPublicationDateResponse/return

I have tried with various xpath tester, and I am not getting anything...
Would it have to do anything with the array?
It does work for the xpath when I am doing: //pages/page/@lucidId
But in my XSL file I am not able to bypass the return.
This is what I am trying to do:
 <xsl:template match="/SOAP-ENV:Envelope/SOAP-ENV:Body/ns1:detailFromPublicationDateResponse/return">
  <xsl:for-each select="item/sections/section/pages/page">
     <xsl:value-of select="@lucidId"/><xsl:text>;</xsl:text>

A: Everything from item down is in the default namespace http://lapresse.ca/entities/lpedition.
Try binding that namespace to a prefix in your XSLT and use it in your xpath.
In the example below, I bind the namespace to the prefix lp.
XSLT 1.0
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:ns1="http://media.com/entities/lpedition"
  xmlns:lp="http://lapresse.ca/entities/lpedition"
  exclude-result-prefixes="SOAP-ENV ns1 lp">
  <xsl:output indent="yes" omit-xml-declaration="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="/SOAP-ENV:Envelope/SOAP-ENV:Body/ns1:detailFromPublicationDateResponse/return">
    <xsl:for-each select="lp:item/lp:sections/lp:section/lp:pages/lp:page">
      <xsl:value-of select="@lucidId"/><xsl:text>;</xsl:text>
    </xsl:for-each>
  </xsl:template>

</xsl:stylesheet>

Output
3d84e764-c507-4f07-82c3-c6f9cab588eb|_0;

A: /*[local-name()='Envelope']/*[local-name()='Body']/*[local-name()='detailFromPublicationDateResponse']/*[local-name()='return']/*[local-name()='item']/*[local-name()='sections']/*[local-name()='section']/*[local-name()='pages']/*[local-name()='page']/@lucidId

or just
//*[local-name()='pages']/*[local-name()='page']/@lucidId


text:
Q: regex pattern ending sub group I could have the following strings:
Case 1:
VIR RECU 998721687978
DE: Mrs PAUL SMITH
564
MOTIF: ANY REASON

or case 2:
VIR RECU 998721687978
DE: Mrs PAUL SMITH
564

The "MOTIF: ..." part can be missing from the string
I am looking for a regex to isolate substring of the 2 precedents.
So far I have: ^VIR\sRECU\s(\d+)\nDE:\s(.*)(\nMOTIF:\s(.*)) that work for well for the case 1 but not for the case 2. If I had a question mark after the 'motif' capturing group like ^VIR\sRECU\s(\d+)\nDE:\s(.*)(\nMOTIF:\s(.*))? then this group is never isolated
I suppose the problem comes from the (.*) group, but cannot figure how to fix it.
Is it possible ? Or should I have 2 different regex, 1 for each case ?
I am using these regex on php with preg_math() function.
The results I want is 998721687978, Mrs PAUL SMITH
564 and ANY REASON values

A: You may use
^VIR\s+RECU\s+(\d+)\nDE:\s+([\s\S]*?)(\nMOTIF:\s+(.*))?$

See a regex test #1 and a regex test #2
Regex details

*

*^ - start of string

*VIR\s+RECU\s+ - VIR, 1+ whitespaces, RECU and again 1+ whitespaces

*(\d+) -  Group 1: one or more digits

*\nDE:  - a newline and DE: substring

*\s+ - 1+ whitespaces

*([\s\S]*?)  - Group 2: any 0+ chars, as few as possible

*(\nMOTIF:\s+(.*))? - an optional capturing group #3:

*

*\nMOTIF: - newline and MOTIF: string

*\s+ - 1+ whitespaces

*(.*)  - Group 4: any 0+ chars other than line break chars, as many as possible

*$ - end of string.


text:
Q: SIMULINK If-Else flow block and its effect on Embedded Code Generation I wish to use an if-else flow block (or a custom matlab function that does it) in SIMULINK and use embedded coder to generate code for it. I had previously encountered a problem with zero and one-based indexing with MATLAB function blocks used in SIMULINK. It seems that there is practically no way around it. How can I model a if-elseif logic in SIMULINK then?
I have tried to use switch and mux blocks but they are too messy and could result into misinterpretation of original flow logic that I am trying to implement.
My flow logic (PSEUDOCODE) is:
if (a<b) then
    p = x;
else if (a<c) then
    p = max(y, some_const_val);
else
    p = z;

Could someone please suggest a way?
KR,

A: Your pseudocode should work as a MATLAB Function block (which supports code generation for the subset of MATLAB function). I can't really see any issues with zero and one-based indexing??
For more complicated logic, Stateflow is a very powerful tool, but then it's an add-on so you need to fork out more money if you don't already have it. I agree though that, apart for very simple logic algorithms, a purely Simulink=blocks approach can become very quickly cumbersome.


text:
Q: How to show no analytic function with absolute value greater than negative power of absolute value z? I am taking an exam tomorrow on Complex Analysis, and this is a problem I have come across multiple times on old exams and I've been stumped.
"Show that there is no function f analytic on the punctured plane $\mathbb{C}-\{0\}$ that satisfies $$|f(z)| \ge \frac{1}{\sqrt{|z|}} \,\,\, \forall z \neq 0."$$
I probably tried a number of things back in June when I first saw it, but can't find my work on that right now. When I was going through again today, my initial approach was to assume by contradiction that there is such an f. I set $g(z)=f(1/z)$. Then g would have a pole at infinity. Bringing that information back to f, there's a pole at 0. Which I probably should have seen before doing that.
Then there's an entire function h and some integer n such that $f(z)=\frac{h(z)}{z^n}$. Right? So I was playing with h. From the inequality, $|h(z)| \ge |z|^{n-1/2}$. That doesn't look like a contradiction to me, but maybe I'm missing something.
I asked somebody who has passed this exam before, and they suggested setting $g(z)=\frac{1}{f(z)}$. That gives the inequality $|g(z)| \le \sqrt{|z|}$. Again, I look at singularities. Here, the only singularity is at infinity, the same as my other g. I feel like it's just giving the same information as my first attempt, and I am still seeing no contradiction.
I attempted to search for this on here, but couldn't find a way to formulate it that got me any relevant results through the search bar. If this is a repeat, just point me to the old one and trash mine.


text:
Q: What is required for the "required" attribute on HTML input elements to work? I have this component, using react, react-bootstrap, and bootstrap. I'm guessing it might be bad practice to mix all these dependencies, but the reason I am using react-bootstrap is because I want to use their modal functionality, which uses js, instead of vanilla bootstrap's jQuery. Here is my component:
        <Modal size="lg" show={show} onHide={handleClose}>
          <Modal.Header closeButton>
              <Modal.Title>Create Freelancer Account</Modal.Title>
            </Modal.Header>
            <form>
              <Modal.Body>

                  University
                  <input type="text" className="form-control" name="University" onChange={handleInputChange} required />

                  Student ID
                  <input type="text" className="form-control" name="StudentID" onChange={handleInputChange} required />

                  Major(s)
                  <input type="text" className="form-control" name="Major" onChange={handleInputChange} required />

                  Skills
                  <input type="text" className="form-control" name="Skills" onChange={handleInputChange} required />

              </Modal.Body>
              <Modal.Footer>
                <Button variant="secondary" onClick={handleClose}>
                  Close
                </Button>
                <Button type="submit" variant="primary" onClick={handleSubmit}>
                  Submit
                </Button>
              </Modal.Footer>
            </form>
        </Modal>

I have enclosed the entire section that includes the inputs and the button in a form tag, since from my research those need to be encapsulated together for the required to work. However, when I click the button, it still submits, even when the form is empty. What is wrong here?


text:
Q: magento sort attribute option collection by position? Greetings,
I am trying to sort an array of attribute option values by their "position" as entered in the manage attributes panel. I seem to have tried everything, does anyone know how this is possible?
I thought for sure this would work:
    $_collection = Mage::getResourceModel('eav/entity_attribute_option_collection')
        ->setStoreFilter(0)
        ->setAttributeFilter($_productAttribute->getId())
        ->addAttributeToSort('position')
        ->load();

But it didn't. Any help would be greatly appreciated!

A: I've alredy been experienced with addAttributeToSort in a previous project: maybe this function doesn't works until today try with setOrder('columname') or try to update your magento to last version

A: Working great. In Magento 1.6 + use setOrder('sort_order').

A: $attribute = Mage::getModel('eav/entity_attribute')->load( $code, 'attribute_code');
$option_col = Mage::getResourceModel( 'eav/entity_attribute_option_collection')
 ->setAttributeFilter( $attribute->getId() )
 ->setStoreFilter()
 ->setPositionOrder( 'ASC' );
$option_col->getSelect()->order('main_table.sort_order '.$orderby);

A: At the begining of app/design/frontend/default/default/template/manapro/filtercheckboxes/items.phtml add following code:
function cmp($a, $b){
  if ($a == $b)
    return 0;
  return ($a['position'] < $b['position']) ? -1 : 1;
}
$array = $this->getItems();
usort($array, "cmp");

And replace $this->getItems() with  $array in foreach loop.

A: As it eav collection it load load join query to collection and using load function. so if you add  order after
Mage::getResourceModel('eav/entity_attribute_option_collection')

just like:
$_collection = Mage::getResourceModel('eav/entity_attribute_option_collection')->getSelect()->order('main_table.sort_order '.$orderby);
        $_collection->setStoreFilter(0)
        ->setAttributeFilter($_productAttribute->getId())
        ->load();


text:
Q: Javafx: Incorrect usage of setPredicate method of a filtered list I have a TableView that contains an observable list of Person items. Each row displays a Person object and its name attribute is also displayed.
I want to pass this observable into a filtered list and set the predicate on the name attribute.
What I want to achieve is that:
If I double click any one row in the TableView that contains Person items, I would be able to extract the names attributes of the selected Person object and set the predicate of the filtered list to be the selected name.
So the filtered list will only contain Person items with the selected name.
The following code almost achieve everything I want. However, there is an edge case where it does not work as expected. This is when for example, I double click on the person with "name = John". The filtered list will filter all the person with name "John". Now, if I change one of the person's name within the filtered list to "Tim". This person is still retained in the filtered list. Ideally, I want it to be removed automatically. But I am not able to do so.
I believe that I am not using setPredicate correctly, as I feel like I am writing redundant codes and there should be more efficient way to do this and will automatically remove Person with a different name right after Edit.
Within my Person class,
private StringProperty Name;
private final BooleanProperty filteredName = new SimpleBooleanProperty() ;

public final boolean getFilteredName(){
    return filteredNameProperty().getValue();
}

public final BooleanProperty filteredNameProperty(){
    return this.filteredName;
}

public final void setFilteredName(String name){
    if(getName().equals(name)){
        this.filteredNameProperty().set(true);
    } else{
        this.filteredNameProperty().set(false);
    }
}

Within my Controller, I have:
        private ObservableList<Person> observableListOfPerson = FXCollections.observableArrayList(p->
        new Observable[]{
                p.nameProperty(),
                p.filteredNameProperty()
        }
    );
        private FilteredList<Person> filterListOfPerson= new FilteredList<>(observableListOfPerson, p-> p.filteredNameProperty().get());

public void initializeFilteredTable(){
        filteredTab.setText("Filtered History");
        filterTable.setItems(filterListOfPerson);

        filterListOfPerson.addListener(new ListChangeListener<Person>(){
              @Override
                public void onChanged(ListChangeListener.Change change) {
                  filterTable.setItems(filterListOfPerson);
              }
        });
        filterTable.setItems(filterListOfPerson);}

Within my AnimatedRow class, I have:
public class AnimatedRow<T> extends TableRow<T> {
    private TabPane fxTabPaneLower;

    /**
     * The data as an observable list of Person.
     */
    private ObservableList<Person> observableListOfPerson;
    private FilteredList<Person> filterListOfPerson;

    public AnimatedRow(Function<T, StringExpression> nameExtractor, ObservableList<Person> observableListOfPerson, FilteredList<Person> filterListOfPerson, TabPane fxTabPaneLower) {
                   setOnMouseClicked(event -> {
            if (event.getClickCount() == 2 && (!isEmpty()) ) {
                final StringExpression nameBE = nameExtractor.apply(getItem());
                for(Person t : observableListOfPerson){
                    t.setFilteredName(nameBE.get());

                }
                filterListOfPerson.setPredicate(p-> p.filteredNameProperty().get());

                fxTabPaneLower.getSelectionModel().select(1);
                ((TableView<Person>)fxTabPaneLower.getTabs().get(1).getContent()).setItems(filterListOfPerson);
          }
        });
    }
}

A: (This is essentially a duplicate of JavaFX FilteredList, filtering based on property of items in the list.)
It looks like you are trying to implement filtering in your Person class. The whole point of a FilteredList is that it implements the filter for you.
So I think you just get rid of the filteredName property entirely and then do
public AnimatedRow(Function<T, StringExpression> nameExtractor, ObservableList<Person> observableListOfPerson, FilteredList<Person> filterListOfPerson, TabPane fxTabPaneLower) {
    setOnMouseClicked(event -> {
        if (event.getClickCount() == 2 && (!isEmpty()) ) {
            final StringExpression nameBE = nameExtractor.apply(getItem());
            filterListOfPerson.setPredicate(p-> p.getName().equals(nameBE.get()));

            fxTabPaneLower.getSelectionModel().select(1);
            ((TableView<Person>)fxTabPaneLower.getTabs().get(1).getContent()).setItems(filterListOfPerson);
        }
    });
}

As long as you have the name property returned as part of the extractor for the underlying list, the filter will get re-evaluated when the name changes.


text:
Q: Azure Custom Controller - Doing Login I have had a MobileService running on Azure, and have decided to implement a login service.
Currently I have Authentication working, and can do migrations/update-database. I am following the TodoItem example. I now want to create my own Custom API, which easily worked on MobileService, but I cannot get it working on Azure Mobile App :/
I have created a new controller:
[HttpGet]
[ResponseType(typeof(Cliente))]
[Route("api/Clientes/{Username}/{Senha}")]

private Cliente DoCustomerLogin(string username, string senha)
{
    return db.Clientes.First(x => x.Username == username && x.Senha == senha);
}

But i am getting Http 404 error.
How I can solve it?


text:
Q: ClientModel::create($validations) does not receive value in code verification snippet I'm having a problem checking if a certain snippet in my code is being passed parameters. The snippet that has the IF is never called even when I do the validations on the form so that it is possible to enter this condition.
I used dd($validations); and dd($ClientModel::create($validations)); And they only return the information array when all form fields are validated, otherwise they always return to the form showing the fields to be correctly validated.

*

*Using dd($validations)

*Using dd($ClientModel::create($validations))

    public function store(ClientRequest $request)
    {
        try {
            $validations = $request->validated();
            dd($ClientModel::create($validations)); // Only work and return array datas when fields of form are correctly fillables
            if (!ClientModel::create($validations)){ // No working
                throw new Exception($this->logClient->logCreateClientError());
            }
            $this->loggingModel->create([
                'description' => $this->logClient->logCreateClient(),
                'method_operation' => 'store',
            ]);
            return redirect('client')->with('success-store','Client registered in system.');
        } catch (Exception $e) {
            $e->getMessage();
        }
    }

In logic the code seems to work when all the form fields are filled in correctly, otherwise the IF I made doesn't work.

A: When your data is invalid $request->validated() throws an ValidationException. And laravel handles this exception by default with an automatic redirect back to the previous action.
https://laravel.com/docs/9.x/validation#quick-writing-the-validation-logic

If validation fails during a traditional HTTP request, a redirect response to the previous URL will be generated. If the incoming request is an XHR request, a JSON response containing the validation error messages will be returned.

When you don't want this behaviour of an automatic redirect, you could catch the ValidationException like so:
try {
    $validated = $request->validated();
} catch (\Illuminate\Validation\ValidationException $e) {
    // Data is invalid, do something else...
}


text:
Q: I want to get sliding functionality in my app which is a fragment <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/services">
    <LinearLayout
        android:id="@+id/first"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btnBalance"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:layout_weight="1"
            android:background="@drawable/custom_button"
            android:text="@string/btnBalance" />

        <Button
            android:id="@+id/btnMeeting"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:layout_weight="1"
            android:background="@drawable/custom_button"
            android:text="@string/btnNextMeetingDateTime" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/second"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/first"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btnBalanceTransfer"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:layout_weight="1"
            android:background="@drawable/custom_button"
            android:text="@string/btnBalanceTransfer" />

        <Button
            android:id="@+id/btnMobileTopUp"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:layout_weight="1"
            android:background="@drawable/custom_button"
            android:text="@string/btnMobileTopUp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/second"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btnStatement"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:layout_weight="1"
            android:background="@drawable/custom_button"
            android:text="@string/btnStatement" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView"/>
    </LinearLayout>
</RelativeLayout>

This is my layout I want to replace this layout when button is click and replace with another fragment layout with sliding effect to right .. I could get the functionality but only the top linear layout is replaced while I want to replace whole layout. The code I wrote in onClick even is this
FragmentTransaction fragTransaction = getFragmentManager()
             .beginTransaction();
             fragTransaction.setCustomAnimations(R.anim.slide_left,
             R.anim.slide_right);
             Meeting fragMeeting = new Meeting();
             fragTransaction.replace(R.id.first, fragMeeting);
             fragTransaction.addToBackStack("test");
             fragTransaction.commit();

A: take one RelativeLayout inside your parent RelativeLayout
<RelativeLayout
    android:id="@+id/main"
    android:layout_width="fill_parent"
    android:layout_height="match_parent" >

    //your LinearLayout code

</RelativeLayout>

and give its id in fragTransaction.replace
fragTransaction.replace(R.id.main, fragMeeting);

A: you replaced R.id.first with your fragment
where as to replace whole view, you have to write
android.R.id.content
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.slide_left,R.anim.slide_right);
Fragment fragMeeting = new Meeting();
ft.replace(android.R.id.content, fragMeeting);
ft.addToBackStack(null);
ft.commit();

if my answer help, kindly make it +1

A:
This is the screen shot. The Back button and the text view is the fragment I want to replace current fragment with

A: I managed to overcome the problem of overlapping the fragment but changing the background color to white but new problem came up that is the fragment shown after clicking the button shows in every tab... any fixes or ideas I have missed to understand that I can read?


text:
Q: C# simple way to do file I/O with big multidimensional (non-jagged) array of bytes I am working with big multidimensional byte arrays (~500mb per array, like, an array with dimensions of [8,8192,8192]) and I'd like to read and write them into file for storage.
I tried using BinaryFormatter but is very slow (takes minutes to do).
I tried using BinaryWriter but it only takes in a single dimensional array. Now, in C, there was no problem passing multi-dimensional array as single-dimensional. In C#, from what I see, I have two options:

*

*Allocate another chunk of memory for single-dimensional array, copy data into it with for loops, then write this array into file using BinaryWriter

*Using for loops, write each individual byte into file using BinaryWriter

Obviously it would be much faster if i'd just use byte[] everywhere and instead of using myarray[i,j] use myarray[i+j*myarray_width] but that would require rewrite of whole class just for purpose of easier working of one set of I/O functions (Save/Load).
There's gotta be a better way.

A: When it comes to fast serialization, unsafe code might come in handy. There are two techniques that can help here:

*

*Do a memcpy from your byte[,] to a fresh byte[] that you can pass to FileStream.Write. This requires, of course, a temporary doubling of storage space and some copying. You could split this work into 64KB chunks, though.

*PInvoke to the unmanaged WriteFile and pass it the FileStream.SafeHandle value. WriteFile takes an arbitrary pointer so you can directly write out your byte[,] (converted into a void*).

Option 2 is maximally fast ("zero-copy").
Sidenote: Unsafe code comes in handy whenever you need to reinterpret bytes. This capability leads to some nice abstractions in C. Fortunately, C# has that capability, too.


text:
Q: How to update multiple rows? The table looks like this:
status1   status2   status3   element
  0         1         2       music1
 ...

My script extract hundreds of thousands of rows like this, do some processing with them and then write back the new status. The problem is, if i update these rows one by one like this:
UPDATE music_table
  SET status1 = '10',
      status2 = '20,
      status3 = 30
WHERE element = 'music1';

It would take an awful lot of time to finish all. (over 1.5 hours!!)
So the question is, how do I update multiple rows at the same time or is it even possible?

A: Having an index on the element columns make it faster to find the row, if you update one row at a time.
However, it is also possible to update multiple rows at a time, if you can do the computation of the new status in an SQL expression:
UPDATE music_table SET status1 = status1 + 1

(This changes the status of all rows; you can still use WHERE to restrict the update to some rows.)
If the computation is more complex, you can register a user-defined function:
from pysqlite2 import dbapi2 as sqlite3

def compute_status1(a, b, c):
    return a + b + len(c)

db = sqlite3.connect(...)
db.create_function("compute_status1", 3, compute_status1)
cur = db.cursor()
cur.execute('UPDATE music_table SET status1 = compute_status1(status2, status3, element)')
cur.close()


text:
Q: Invariant Sylow subgroups and solvability of finite groups This is a article which Antonio Beltran. I'm reading lemma 2.2.c). I see that:
"Lemma 2.2. Suppose that A is a finite group acting coprimely on a finite group G, and let $C = C_G(A)$. Then, for every prime p,
(b) $ν_p(C)$ divides $ν_p^A (G)$ and $ν_p^A (G)$ divides $ν_p(G)$.
(c) if N is an A-invariant normal subgroup of G, then $ν_p^A (N)$ and $ν_p^A (G/N)$ divide $ν_p^A (G)$. "
In the proof c) below, I don't understand "If P is an A-invariant Sylow p-subgroup of G, then $PN/N$ is an A-invariant Sylow subgroup of G/N "
https://www.researchgate.net/publication/291552840_Invariant_Sylow_subgroups_and_solvability_of_finite_groups
Thank you very much.

A: You asked in your comment why $$|CN/N:N_{CN/N}(PN/N)|=|CN/N:\color {red}{N_C(P)N/N}|.$$ Well, I think there is a typo here, it should read
$$|CN/N:N_{CN/N}(PN/N)|=|CN/N:\color {red}{N_{CN}(PN)/N}|.$$
Let me explain. In general, if you have a group $G$ with $N \unlhd G$, $H \leq G$, then $N_{\overline{G}}(\overline{H})=\overline{N_G(HN)}$, for a proof see Corollary 1 here. Now replace in this formula $"G"$ by $"CN"$ and $"H"$ by $"P"$, and you get
$$N_{CN/N}(PN/N)=N_{CN}(PN)N/N.$$
And $N_{CN}(PN)=CN \cap N_G(PN)$ obviously contains $N$, hence $N_{CN/N}(PN/N)=N_{CN}(PN)/N$. It follows that $n_p^A(G/N)=|CN:N_{CN}(PN)|$. Now observe that $N \subseteq N_G(PN) \cap CN = N_{CN}(PN) \subseteq CN$, hence $CN=C \cdot N_{CN}(PN)$. Also, $C \cap N_{CN}(PN)=C \cap CN \cap N_G(PN)=N_C(PN).$ This implies that $\color {blue}{n_p^A(G/N)}=|CN:N_{CN}(PN)|=\color {blue}{|C:N_C(PN)|}$ and since $N_C(P) \subseteq  N_C(PN)$, we see that $n_p^A(G/N)$ divides $n_p^A(G)=|C:N_C(P)|.$ As a corollary we get $n_p^A(G)=n_p^A(G/N)$ if and only if $N_C(P)=N_C(PN)$.


text:
Q: Javascript - outputting set string value from dropdown/select box with buttons I have three select dropdowns, each with a few options which have unique values. I want these values to be outputted comma separately, as shown in the jsfiddle. i've put them into an array, is there an easier/better way of doing this? also can it be outputted into a textfield? and finally I can't figure out how you can clear the array with another button.
Heres the jsfiddle:
http://jsfiddle.net/m6nRU/4/
  var content="Text Message:
";
   for(var i = 0; i < serial.length; i++) {
     content +=serial[i]+",";
  }

Thanks for your help in advance.

A: How about:
var selects = document.getElementsByTagName("select");
var arr = [];
for (var i = 0; i < selects.length; i++) {
    var value = selects[i].options[selects[i].selectedIndex].value;
    arr.push(value);
}

console.log(arr); //array of selected values

Edit: Just saw the jQuery tag:
var values = $("select").map(function() {
    return this.value;
}).get();


text:
Q: Jenkins | UNIX | ZIP zip -r social.zip Google/Facebook/Instagram/*

I'm using the above command in Jenkins script to create a ZIP. But I don't want the same directiory structure in ZIP. I need all the directories & files under Google/Facebook/Instagram/* directly in ZIP.

A: You can make Google/Facebook/Instagram your current directory by doing a cd or pushd then return to your original directory.
(cd Google/Facebook/Instagram ; zip -r ../../../social.zip *)
or
pushd Google/Facebook/Instagram ; zip -r ../../../social.zip * ; popd

A: Read the manual; zip -j -r ... or zip --junk-paths -r ...
It even says:

You may want to make a zip archive that contains the files in foo, without recording the directory name, foo. You can use the -j option to leave off the paths, as in:
    zip -j foo foo/*


text:
Q: How I can delete broken GitLab repository, if standard way shows me Error 500? After an unsuccessful upgrade, some of the repositories broke, when trying to delete the repository as standard way, it shows Error 500 ("500 Whoops, something went wrong on our end.
Try refreshing the page, or going back and attempting the action again. Please contact your GitLab administrator if this problem persists. Go back"). How I can delete the repository on the ubuntu server?
In production.log I found such entries about my attempt to delete the repository:
Started DELETE "/student100675/anagrams" for 217.MY.IP.HERE at 2021-11-09 11:30:30 +0200
Processing by ProjectsController#destroy as HTML
Parameters: {"authenticity_token"=>"[FILTERED]", "namespace_id"=>"student100675", "id"=>"anagrams"}
Completed 500 Internal Server Error in 60ms (ActiveRecord: 3.5ms | Elasticsearch: 0.0ms | Allocations: 9529)
OpenSSL::Cipher::CipherError ():
lib/gitlab/crypto_helper.rb:28:in aes256_gcm_decrypt' app/models/concerns/token_authenticatable_strategies/encryption_helper.rb:18:in decrypt_token'
app/models/concerns/token_authenticatable_strategies/encrypted.rb:45:in get_token' app/models/concerns/token_authenticatable_strategies/base.rb:32:in ensure_token'
app/models/concerns/token_authenticatable_strategies/encrypted.rb:32:in ensure_token' app/models/concerns/token_authenticatable.rb:43:in block in add_authentication_token_field'
app/services/projects/destroy_service.rb:10:in async_execute' app/controllers/projects_controller.rb:162:in destroy'
app/controllers/application_controller.rb:485:in set_current_admin' lib/gitlab/session.rb:11:in with_session'
app/controllers/application_controller.rb:476:in set_session_storage' lib/gitlab/i18n.rb:105:in with_locale'
lib/gitlab/i18n.rb:111:in with_user_locale' app/controllers/application_controller.rb:470:in set_locale'
app/controllers/application_controller.rb:464:in set_current_context' lib/gitlab/middleware/speedscope.rb:13:in call'
lib/gitlab/request_profiler/middleware.rb:17:in call' lib/gitlab/jira/middleware.rb:19:in call'
lib/gitlab/middleware/go.rb:20:in call' lib/gitlab/etag_caching/middleware.rb:21:in call'
lib/gitlab/middleware/multipart.rb:172:in call' lib/gitlab/middleware/read_only/controller.rb:50:in call'
lib/gitlab/middleware/read_only.rb:18:in call' lib/gitlab/middleware/same_site_cookies.rb:27:in call'
lib/gitlab/middleware/handle_malformed_strings.rb:21:in call' lib/gitlab/middleware/basic_health_check.rb:25:in call'
lib/gitlab/middleware/handle_ip_spoof_attack_error.rb:25:in call' lib/gitlab/middleware/request_context.rb:21:in call'
config/initializers/fix_local_cache_middleware.rb:11:in call' lib/gitlab/middleware/rack_multipart_tempfile_factory.rb:19:in call'
lib/gitlab/middleware/sidekiq_web_static.rb:20:in call' lib/gitlab/metrics/requests_rack_middleware.rb:74:in call'
lib/gitlab/middleware/release_env.rb:12:in `call'

A: I'm my case was fixed after restoring the /etc/gitlab/gitlab-secrets.json
More refs:
https://forum.gitlab.com/t/after-updating-from-version-gitlab-11-8-10-breaks-runners-ci/30037

A: It was the problem with hashed and legacy repositories, I solved it with this tip:
gitlab-rails console
projects = Project.where(repository_read_only: true)
projects.each do |p|
  p.update!(repository_read_only:nil)
end
gitlab-rake gitlab:storage:migrate_to_hashed
gitlab-ctl reconfigure

A: I tried all two versions of what's written here and they didn't help me
The only thing that helped me is a complete reinstallation of gitlab
before deleting everything I copied all the repositories to my local disk and all users
after installation created new repositories and push an existing Git repository

A: Another way if you have a "read-only" legacy repositories:

*

*Reset runner registration tokens
https://docs.gitlab.com/ee/raketasks/backup_restore.html#when-the-secrets-file-is-lost

*sudo gitlab-rails console

Project.all.find_each { |project| project.update!(repository_read_only: false) }


text:
Q: jQuery attribute selector based on value with periods in it Trying:
$("div.docs-right div.api-manager div[ng-model=page.api.examples]").length

This breaks with:

Uncaught Error: Syntax error, unrecognized expression: div.docs-right div.api-manager div[ng-model=page.api.examples]

How do I select by ng-model=page.api.examples?

A: Try this :
    $("div.docs-right div.api-manager div[ng-model=\"page.api.examples\"]").length


text:
Q: How to delete duplicates in streaming data? I am using spark-sql 2.4.1  structured streaming with kafka ,java8.
My dataset looks as below for example

I need to find out the duplicates based on ColA ColB ColC and take the latest one among it based on ColDate and delete the rest.
i.e.
from the above data result should be

How can it be done using spark streaming ?
I.e I will be getting data in streams like ... not sure when the duplicate comes if duplicates as specified earlier logic I need to delete records.
how can it be done generally in streaming scenario?

A: In general streaming scenario you could check for duplicates using a hash table, which you can empty every x-hours.
  hashed =table['ColA','ColB','ColC']
  hashed=hashed.withColumn("row_sha2", sha2(concat_ws("||", *hashed.columns), 256))

To remove duplicates in a later stage you can drop them with
import pyspark.sql.functions as f
df.groupBy("ColA","ColB","ColC").agg((f.count("*")>1).cast("int").alias("e")).show()

A: You could have used the exactly-once data delivery notion (here), had your duplicates were actually duplicates (i.e. same records, no intervening).
Even if you cache the 'latest' record that would result in storing N records in memory (worst case scenario). In addition, there is no guarantee to the consumer as to when they can consume the "right" record.
I think you should consider a batch job.


text:
Q: How do I place vertical GridLines in front of horizontal ones? By default horizontal GridLines are placed in front of vertical GridLines:
style = Directive[#, AbsoluteThickness[5]] &;
Graphics[Circle[], Frame -> True, ImagePadding -> 1, GridLines -> Automatic,
    GridLinesStyle -> style /@ #] & /@ {{LightGray, Black}, {Black, LightGray}} // GraphicsRow

How can I place the vertical lines in front so that they appear uninterrupted?
I do not wish to resort to manually drawing Line expressions.

A: This at least gets the result:
style = Directive[#, AbsoluteThickness[5]] &;
Overlay[
    {Graphics[Circle[], Frame -> True, ImagePadding -> 1,
      GridLines -> Automatic,
      GridLinesStyle -> style /@ {#1, #2}],
     Graphics[Circle[], Frame -> True, ImagePadding -> 1,
      GridLines -> Automatic,
      GridLinesStyle -> style /@ {#1, Opacity[0]}]}] & @@@
  {{LightGray, Black}, {Black, LightGray}} // GraphicsRow

A: More a workaround rather than a solution, but simple and maybe useful with some pre-planning of data and such:
Rotate[Graphics[Circle[], Frame -> True, ImagePadding -> 1,
  GridLines -> Automatic,
  GridLinesStyle -> style /@ {LightGray, Black}], 90 Degree]

A: This is a possible way by Inset, but I'm still not very sure why it's 2.1:
style = Directive[#, AbsoluteThickness[5]] &;

Graphics[{Opacity[0], Circle[]}, Frame -> True,
  FrameStyle -> Opacity[0], ImagePadding -> 1,
  GridLines -> {Automatic, Automatic},
  GridLinesStyle -> style /@ {Opacity[0], Black}];

Graphics[Circle[], Frame -> True, ImagePadding -> 1,
  GridLines -> {Automatic, Automatic},
  GridLinesStyle -> style /@ {LightGray, Opacity[0]}];

Show[%%, Epilog -> Inset[%, Center, {0, 0}, {2.1, Automatic}]]

According to the documentation of PlotRangePadding:

PlotRangePadding->Automatic adds a total of 4% for PlotRange settings All, Full, and Automatic.

It should be $2\times (1+4\%)=2.08$, but in fact 2.08 will be worse than 2.1 here. Don't know why...

A: I guess I'll put on paper a simple fix that works only with the gray/black lines as shown rather than being a general solution.  (Desiring a general solution was the reason I originally used the garish colored lines that Yves complained about.)
style = Directive[#, AbsoluteThickness[5]] &;

Graphics[Circle[], Frame -> True, ImagePadding -> 1, GridLines -> Automatic,
 GridLinesStyle -> style /@ {Black, Opacity[0.3]}]

Plainly this won't work with other combinations (warning: garish colors):
Graphics[Circle[], Frame -> True, ImagePadding -> 1, GridLines -> Automatic,
 GridLinesStyle -> style /@ {Yellow, {Green, Opacity[0.3]}}]


text:
Q: Getting the word "extend" when passing the key on a button click event within a for-in loop I have a json that looks like this:
contacts = [{"id":"0001","title":"Mr","name_first":"Bob","name_last":"Edwards","address1":"2 ford road","address2":null,"address3":null,"town":"Bedford","county":"Bedfordshire","postcode":"Mk16hd","telephone1":"01827485999","telephone2":null,"email":"bob@email.com"},
{"id":"8003","title":"Mr","name_first":"Joe","name_last":"Bloggs","address1":"186 Bath Road","address2":null,"address3":null,"town":null,"county":null,"postcode":null,"telephone1":"01827485648","telephone2":null,"email":"joe@email.com"},
{"id":"R005","title":"Mr","name_first":"Foo","name_last":"Bar","address1":null,"address2":null,"address3":null,"town":null,"county":null,"postcode":null,"telephone1":"01827485647","telephone2":null,"email":"foo@email.com"}];

I then loop through this like this, creating a button for each one:
for (var key in contacts) {
    if (contacts.hasOwnProperty(key)) {
        var contact = contacts[key];

        var button = document.createElement('button');
        button.innerHTML = 'Edit';
        button.onclick = function() { editContact(key); return false; };
    }
}

When clicking each button I get the word "extend" as the value of index in the editContact()function:
function editContact (index) {
    console.log(index);
    return false;
}

Q: What is this and how can I set this up so I get the key for each json item into the editContact() function?

A: It is because of closure
for (var key in contacts) {
    if (contacts.hasOwnProperty(key)) {
        var contact = contacts[key];

        var button = document.createElement('button');
        button.innerHTML = 'Edit';
        button.onclick = (function(key){
            return function() { editContact(key); return false; };
        })(key);
    }
}

Demo: Fiddle

A: contacts is an array. If you want to loop through the properties of one contact you have to specify it (e.g. with contact[0]). If you want to loop through the properties of each contact you have to loop through them:
for (var i=0;i<contacts.length;i++) {
    for(var key in contacts[i])

Second problem:
button.onclick = function() { editContact(key); return false; };

Every time you click the button editContact is called with the last value that was assigned to key. Assuming you want to preserve the value of key you can do the following:
(function() {
    var currentKey = key;
    button.onclick = function() { editContact(currentKey); return false; };
(());

Edit:
Since you only want to loop through the contacts you can do the following, if you don't have to support IE < 9 ( or can use a shim):
contacts.forEach(function(element, index) {
    var button = document.createElement('button');
    button.innerHTML = 'Edit';
    button.onclick = function() { editContact(index); return false; };
});

A: Every time you click the button, editContact is called with the last value that was assigned to key.
So it needs to preserve the index of json row and use that index for further stuff.
I did it in following way so you can get all the keys from your json.
  function addButtons() {

    for ( var key in contacts) {
        if (contacts.hasOwnProperty(key)) {
            var contact = contacts[key];
            var button = document.createElement('button');
            document.body.appendChild(button);
            button.setAttribute('id', key);
            button.innerHTML = 'Edit';
            button.onclick = function() {
                editContact(this.id);
                return false;
            };
        }
    }
}

function editContact(index) {
    for ( var key in contacts[index]) {
        console.log("Key :" + key+" Value:"+contacts[index][key]);
    }
    return false;
}

My html looks like


text:
Q: return to libc - problem I'm having problems with return-to-libc exploit. The problem is that nothing happens, but no segmentation fault (and yes I'm actually overflowing the stack).
This is my program:
int main(int argc, char **argv) {
  char array[512];
  gets(array);
}

I'm using gets instead of strcopy, because my addresses start with 0x00 and strcpy thinks it's the end of a string, so I can't use it.
Here are the addresses that I need:
$ gdb main core
(gdb) p system
$1 = {<text variable, no debug info>} 0x179680 <system>
(gdb) p exit
$2 = {<text variable, no debug info>} 0x16f6e0 <exit>
(gdb)  x/s 0xbffffe3f
0xbffffe3f:      "/bin/sh"

When inputing the right sequence, this happens:
eleanor@eleanor32:~/testing/root$ perl -e 'print "\x41"x516 . "\x80\x96\x17\x00" . "\xe0\xf6\x16\x00" . "\x3f\xfe\xff\xbf"' | ./main
eleanor@eleanor32:~/testing/root$

so nothing.
But if I enter 520 'A's (0x41), then the EIP is overflown with 'A's. If there's 516 'A', nothing happens but EIP contains the system address, following the exit address, following the /bin/sh pointer.
Why nothing happened?

A: Let's do some asm before:
Code
$ cat gets.c
int main(int argc, char **argv) {
  char array[512];
  gets(array);
}

Asm
$ gcc gets.c -o getsA.s -S -fverbose-asm
$ cat gets.s
    ....
.globl main
        .type   main, @function
main:
        leal    4(%esp), %ecx   #,
        andl    $-16, %esp      #,
        pushl   -4(%ecx)        #  (1)
        pushl   %ebp            #  2
        movl    %esp, %ebp      #,
        pushl   %ecx            #  3
        subl    $516, %esp      #,
        leal    -516(%ebp), %eax        #, tmp60
        movl    %eax, (%esp)    # tmp60,
        call    gets            #  << break here
        addl    $516, %esp      #,  << or here to see the stack picture
        popl    %ecx            #  (3')
        popl    %ebp            #  (2')
        leal    -4(%ecx), %esp  #  (1')
        ret
        .size   main, .-main

The prologue and epilogue (these are with alignment code) is described in detail here Understanding the purpose of some assembly statements
Stack layout:
(char)  array[0]
...
(char)  array[511]
(32bit) $ecx - pushed by 3 - it was the address on the stack of the eip which main will return to
(32bit) $ebp - pushed by 2
(32bit) $esp - pushed by 1 - change the $esp to the original value

So, if you want to change a return address of main, you should not to change address in stack which will be used by ret, but also to repeat the values saved in stack by (1),(2),(3) pushes. Or you can embed a new return address in the array itself and overwrite only (3) by the your new stack address+4. (use 516 byte string)
I suggest you use this source code to hack it:
$ cat getss.c
f()
{
  char array[512];
  gets(array);
}
int main(int argc, char **argv) {
    f();
}

because f have no problems with stack realignement
.globl f
        .type   f, @function
f:
        pushl   %ebp    #
        movl    %esp, %ebp      #,
        subl    $520, %esp      #,
        leal    -512(%ebp), %eax        #, tmp59
        movl    %eax, (%esp)    # tmp59,
        call    gets    #
        leave
        ret
        .size   f, .-f

Stack layout for f():
(char)  array[0]
...
(char)  array[511]
(32bit) old ebp
(32bit) return address

Breakpoint at ret instruction in f() with 520 bytes of "A"
(gdb) x/w $sp
0xXXXXXa3c:     0x41414141


text:
Q: Crystal Reports Leaving out parameter I have a crystal report that I am modifying the record selection formula. I have a parameter "Inventory_Class" that can have 3 values 0, 1 or 2. If set to 1 I want my DB field "NON_Controllable" that is binary field to select all False records, if the parameter is set to 2 then I want all True records but if the incoming parameter is set to 0 then I don't want to filter on the DB field "NON_Controllable" at all. I can get formula to work when parameter is set to 1 and 2 selecting Non_Controllable false and true records but when the parameter is set to 0 my report returns no records when it should be returning all records.
{Inventory_Catalog.PROP_NO} = {?PROPERTY} and
{Inventory_Cat_Header.INVEN_TYPE_CD} = {?TYPE} and
{Inventory_Cat_Header.OPER_BUS_SEG_CD} = {?OPER_BUS_SEG} and
{Inventory_Catalog.SURP} = {?SURP} and
{Inventory_Catalog.COND_CD} = {?CONDITION} and
{Inventory_Cat_Header.INVEN_ID} = {?INVEN_ID} and
{Inventory_Catalog.SER_NO} = {?SERIAL} and
{Inventory_Cat_Header.BUS_UNIT_CD} = {?BUS_UNIT_CD} and
IF ({?INVENTORY_CLASS} = 1) THEN
    {Inventory_Cat_Header.NON_CONTROLLABLE} = FALSE
ELSE IF ({?INVENTORY_CLASS} = 2) THEN
    {Inventory_Cat_Header.NON_CONTROLLABLE} = TRUE
ELSE IF ({?INVENTORY_CLASS} = 0) THEN
    NOT {Inventory_Cat_Header.NON_CONTROLLABLE}

How can I modify this formula to work?

A: you can try passing the parameters for each conditions instead.
IF
({?INVENTORY_CLASS} = 1) THEN
{Inventory_Cat_Header.NON_CONTROLLABLE} = FALSE and
{Inventory_Catalog.PROP_NO} = {?PROPERTY} and
{Inventory_Cat_Header.INVEN_TYPE_CD} = {?TYPE} and
{Inventory_Cat_Header.OPER_BUS_SEG_CD} = {?OPER_BUS_SEG} and
{Inventory_Catalog.SURP} = {?SURP} and
{Inventory_Catalog.COND_CD} = {?CONDITION} and
{Inventory_Cat_Header.INVEN_ID} = {?INVEN_ID} and
{Inventory_Catalog.SER_NO} = {?SERIAL} and
{Inventory_Cat_Header.BUS_UNIT_CD} = {?BUS_UNIT_CD}
ELSE IF
({?INVENTORY_CLASS} = 2) THEN
{Inventory_Cat_Header.NON_CONTROLLABLE} = TRUE and
{Inventory_Catalog.PROP_NO} = {?PROPERTY} and
{Inventory_Cat_Header.INVEN_TYPE_CD} = {?TYPE} and
{Inventory_Cat_Header.OPER_BUS_SEG_CD} = {?OPER_BUS_SEG} and
{Inventory_Catalog.SURP} = {?SURP} and
{Inventory_Catalog.COND_CD} = {?CONDITION} and
{Inventory_Cat_Header.INVEN_ID} = {?INVEN_ID} and
{Inventory_Catalog.SER_NO} = {?SERIAL} and
{Inventory_Cat_Header.BUS_UNIT_CD} = {?BUS_UNIT_CD}
else
{Inventory_Catalog.PROP_NO} = {?PROPERTY} and
{Inventory_Cat_Header.INVEN_TYPE_CD} = {?TYPE} and
{Inventory_Cat_Header.OPER_BUS_SEG_CD} = {?OPER_BUS_SEG} and
{Inventory_Catalog.SURP} = {?SURP} and
{Inventory_Catalog.COND_CD} = {?CONDITION} and
{Inventory_Cat_Header.INVEN_ID} = {?INVEN_ID} and
{Inventory_Catalog.SER_NO} = {?SERIAL} and
{Inventory_Cat_Header.BUS_UNIT_CD} = {?BUS_UNIT_CD}


text:
Q: How can a .bat file start bash and change directory? I was using
start bash
cd "/mnt/c/Users/James/Documents/_Github-Projects"

but this doesn't make any sense since start bash will open a new window, but the cd command is still ran on the other window.

A: I realized shortly after, the bash window opened automatically cd's into the directory the other cmd prompt was in. So I have this is my .bat file
cd "C:/Users/James/Documents/_Github-Projects"
start bash


text:
Q: How to group data by month in R with dplyr How can I group my data by month (y%,m%,d%), then create a table with a count of how many rows are in each month?
Date is in column "orderdate".
So what I'm looking for is 01= 35744, 02= 747362, etc
All in a new table
I have gotten data arranged by date, but not month specifically. So current grouped and filtered table is Example_Table

A: By using lubridate::date and simple dplyr
library(dplyr)

dummy <- data.frame(
  orderdate = seq(as.Date("2020-01-02"),as.Date("2021-07-13"), by = "days")
)

dummy %>%
  as_tibble %>%
  mutate(month = lubridate::month(orderdate)) %>%
  group_by(month) %>%
  summarise(n = n())

   month     n
   <dbl> <int>
 1     1    61
 2     2    57
 3     3    62
 4     4    60
 5     5    62
 6     6    60
 7     7    44
 8     8    31
 9     9    30
10    10    31
11    11    30
12    12    31

as table
dummy2 <- dummy %>%
  as_tibble %>%
  mutate(month = lubridate::month(orderdate)) %>%
  group_by(month) %>%
  summarise(n = n()) %>%
  select(n) %>%
  t %>%
  as.table
colnames(dummy2) <- seq(1:12)
dummy2

   1  2  3  4  5  6  7  8  9 10 11 12
n 61 57 62 60 62 60 44 31 30 31 30 31

A: If you have data for multiple years do you count each month separately ? Meaning June 2020 should be captured separately from June 2021.
If so, you can use
library(dplyr)

result <- Example_Table %>% count(month = format(orderdate, '%b-%Y'))

Or in base R -
result <- table(format(Example_Table$orderdate, '%b-%Y'))

If you want to consider June 2020 and June 2021 in the same group use only '%b' in format instead of '%b-%Y'.


text:
Q: Javascript: Subtracting a whole integer from a integer with a decimal alters the decimal value? The goal is to isolate the decimal value (with simply turning the integer into a string and splitting it).
To that affect I have:
var x = 1001.1;
var roundedDown = Math.floor(x); // Produces 1001
var decimal = x - roundedDown;

The expected value of decimal should be 0.1 (1001.1 - 1001). But instead I get 0.0999999 recurring.
I have tried with Math.trunc as well but get the same results.
Would anyone know why this is?