text:
Q: Iterator in Thread On CopyOnWriteArrayList not working I am doing some exercises for the OCP exam. At the moment I tried to print out the contents of a CopyOnWriteArrayList when using several threads. According to the documentation the iterator of a CopyOnWriteArrayList will

print the numbers in the list which are present at the moment the iterator is created

So when starting one thread writing on the CopyOnWriteArrayList and another one reading from the CopyOnWriteArrayList I expect (sometimes) some items printed out. When traversing the CopyOnWriteArrayList after the writing thread finished I expect a new iterator printing out all of the items.
Unfortunately this does not work when using anonymous implementations of Runnable interface. But it works when using custom thread classes, in which I pass a reference to CopyOnWriteArrayList.
Right now, I cannot see why this happens. I am not sure if final CopyOnWriteArrayList<Integer> intList = new CopyOnWriteArrayList<>(); causes this effect - and if it is so - I have no clue why at all?
Any input on this topic would be appreciated!
Using anonymous implementations of Runnable - does not work as expected
static void copyOnWriteCollections() {
    System.out.println("copyOnWriteCollections".toUpperCase());

    final CopyOnWriteArrayList<Integer> intList = new CopyOnWriteArrayList<>();

    Thread tADD = new Thread(new Runnable() {
        public void run() {
            for (int i = 0; i < 10000; i++) {
                intList.add(i);
            }
        }
    });
    tADD.start();

    /// will print the numbers in the list which are present
    /// at the moment the iterator is created
    Thread tREAD = new Thread(new Runnable() {
        public void run() {
            for (Integer i : intList) {
                System.out.print(i);
                System.out.print(" ");
            }
        }
    });
    tREAD.start();

    try {
        tADD.join();
        tREAD.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    // will print out all numbers - as iterator is created when all
    // modifications
    // to intList have finished
    System.out.println();
    new Thread(new Runnable() {
        public void run() {
            System.out.println("new");
            System.out.println("\tsize of intList: " + intList.size());

            Iterator<Integer> it = intList.iterator();

            while (it.hasNext()) {
                int i = it.next();
                System.out.print(i);
                System.out.print(" ");
            }

            System.out.println("end");
        }
    }).start();
}

output (sometimes - as there are threads)

use of custom thread class - works as expected
class CopyOnWriteThread extends Thread {

    Iterator<Integer> it = null;
    boolean read = false;
    CopyOnWriteArrayList<Integer> intList = null;

    public CopyOnWriteThread(CopyOnWriteArrayList<Integer> intList, boolean read) {
        this.intList = intList;
        this.read = read;
    }

    public void run() {
        if (read) {
            it = intList.iterator();

            System.out.println("START read (" + Thread.currentThread().getName() + ")");
            System.out.print("\t");
            while (it.hasNext()) {
                System.out.print(it.next());
                System.out.print(" ");
            }
            System.out.println();
            System.out.println("END read (" + Thread.currentThread().getName() + ")");
        } else {
            System.out.println("START write (" + Thread.currentThread().getName() + ")");
            for (int i = 0; i < 10000; i++) {
                intList.add(i);
            }
            System.out.println("END write (" + Thread.currentThread().getName() + ")");
        }
    }
}

static void copyOnWriteCollections_CustomThread() {
    CopyOnWriteArrayList<Integer> intList = new CopyOnWriteArrayList<>();

    CopyOnWriteThread tWRITE = new CopyOnWriteThread(intList, false);
    CopyOnWriteThread tREAD = new CopyOnWriteThread(intList, true);
    tWRITE.start();
    tREAD.start();

    try {
        tWRITE.join();
        tREAD.join();
    } catch (InterruptedException e) {
    }

    CopyOnWriteThread tREAD2 = new CopyOnWriteThread(intList, true);
    tREAD2.start();
}

output - works as expected

Currently I am working on a Win10 machine, with JDK 1.7.0_25 and Eclipse Mars Release 4.5.0

A: As @user2357112 posted there is nothing wrong with the code. The problem seems to be Eclipse related!
When running the question code in Eclipse Mars / JRE 1.7.0_25 it won't print out numbers from 0 to 9999. Instead it will exit right away as if there was no new iterator.
I compiled the code from command line and started it by using java.exe and javaw.exe. Both showed correct output.
java command
java -classpath "c:\Chapter14\ConcurrentCollections\bin" concurrentCollections.TestClass
result

javaw command
javaw -classpath "c:\Chapter14\ConcurrentCollections\bin" concurrentCollections.TestClass > "c:\test.txt"
result

Right now I can say (for sure) there is nothing wrong with my code, nor with the JVM!
EDIT
I redirected the output to a file by modifying Run Configurations. Restarted the application in eclipse. Output.txt contains all numbers - but in my console window within Eclipse (allocate console) the numbers won't appear...


text:
Q: Добавление слушателя ActionListener в цикле Java Добрый день.
Вопрос такой: после запуска ввожу в jtf текст, получаю исключение

.ArrayIndexOutOfBoundsException: 10

Почему не работает? И как исправить?
void iter() {
    jtfAnswer = new JTextField[10];
    for(  j=0; j < jtfAnswer.length; j++) {
        jtfAnswer[j] = new JTextField(15);

        jtfAnswer[j].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                if(jtfAnswer[j].getText().equals(jlab1.getText()))
                    jlab2.setText("try");
                else
                    jlab2.setText("false");
            }
        });
    }
}

A: После того как ваш цикл исполняется, значение j равно 10.
Вы вводите значение в текстовое поле и попадаете в обработчик события, в котором обращаетесь к элементу массива. С каким индексом? 10.
Обращайтесь к объекту инициировавшему событие через ae.getSource().

redpajama_set_name: RedPajamaStackExchange


text:
Q: KeyError: "Not all names specified in 'columns' are found" I have a dataframe like as shown below
Date,cust,region,Abr,Number,,,dept
12/01/2010,Company_Name,Somecity,Chi,36,136,NaN,sales
12/02/2010,Company_Name,Someothercity,Nyc,156,NaN,41,mfg

tf = pd.read_clipboard(sep=',')

I am trying to do some manipulation to the excel file
writer = pd.ExcelWriter('duck_data.xlsx',engine='xlsxwriter')
for (cust,reg), v in df.groupby(['cust','region']):
    v.to_excel(writer, sheet_name=f"DATA_{cust}_{reg}",index=False, columns = modified_col_list)
writer.save()

but the problem is when the file is written, it uses unnamed:5, unnamed:6 to represent empty column names. So, I created a modified_col_list as shown below and passed it as input to to_excel function
ordiginal_col_list = ['Date','cust','region','Abr','Number',nan,nan,'dept']

modified_col_list = ['Date','cust','region','Abr','Number',' ',' ','dept']

But my objective is to have empty column names as is during excel write itself. But this resulted in below error

KeyError: "Not all names specified in 'columns' are found"

I expect my output to be like as shown below (you can see the column names are empty)

A: You can use:
writer = pd.ExcelWriter('duck_data.xlsx',engine='xlsxwriter')
for (cust,reg), v in df.groupby(['cust','region']):
    #if columns name has `Unnamed` replace by empty string
    #v.columns = ['' if 'Unnamed' in x else x for x in v.columns]
    #if columnshas missing values replace them to empty string
    v.columns = v.columns.to_series().fillna('')
    #removed columns parameter
    v.to_excel(writer, sheet_name=f"DATA_{cust}_{reg}",index=False)
writer.save()

Another idea is change columns names before groupby:
#if columns name has `Unnamed` replace by empty string
#df.columns = ['' if 'Unnamed' in x else x for x in df.columns]
#if columnshas missing values replace them to empty string
df.columns = df.columns.to_series().fillna('')

writer = pd.ExcelWriter('duck_data.xlsx',engine='xlsxwriter')
for (cust,reg), v in df.groupby(['cust','region']):
    #removed columns parameter
    v.to_excel(writer, sheet_name=f"DATA_{cust}_{reg}",index=False)
writer.save()


text:
Q: Using TikZ to draw a water channel profile I want to draw a relatively simple sketch using TikZ but I can't do it.
What I want is a representation of an open water channel with 4 pools, a dam upstream, and a waste reservoir downstream, as depicted in the picture below:

I would like to label the pools, dam and waste as I did in the drawing. In addition, I also would like to label the interface locations (numbered from 4 to 8, in this example).
Those inclined lines are supposed to represent the ground. The water representation itself, in blue, is not mandatory, I included it in the drawing just for better understanding. I may not include it in the final sketch.
I like to use LaTeX and TikZ and I like to do these things in a flexible way that let me easily adjust sizes or reuse parts of the code in other pictures.

A: And here's a slightly different approach using Metapost.

prologues := 3;
outputtemplate := "%j%c.eps";

% routine to make a ragged version of a path
vardef ragged(expr n, r, p) =
   save s; s = arclength(p)/n;
   point 0 of p
     for t=s step s until arclength(p)-s:
       -- point arctime t of p of p shifted (r*normaldeviate, r*normaldeviate)
   endfor -- point infinity of p
   enddef;

beginfig(1);

% define a line of regular steps with varying widths, that finishes on the y-axis
path ground_level;
step_height = 20; x = 0; y = 6*step_height;
ground_level = for dx=70,90,50,70,80,80:
                 (x,y) -- hide(x:=x+dx)
                 (x,y) -- hide(y:=y-step_height) endfor (x,0);

% water reaches this far up each step
water_depth = step_height/4;

color earth; earth = (213/255,197/255,165/255);
color water; water = (192/255,212/255,230/255);

% overlay three solid fills to create the desired areas of colour
fill origin -- ground_level shifted (0,water_depth) -- cycle withcolor water;
fill origin -- ground_level                         -- cycle withcolor earth;
fill origin -- ragged(500,1/5,ground_level) shifted (-4,-4) -- cycle withcolor background;

% draw the barriers and the call outs
for i=1 step 2 until 10:
  draw ((0,0) -- (0,1.2water_depth)) shifted point i of ground_level;
  draw ((0,0) -- (0,-20)) shifted point i+1 of ground_level dashed evenly scaled .4;
  endfor

% draw in the ground level with a thicker pen
draw ground_level withpen pencircle scaled 1;

% add the labels in the right places
label.top(btex Dam    etex, point 0.5 of ground_level shifted (0,water_depth));
label.top(btex Pool 1 etex, point 2.5 of ground_level shifted (0,water_depth));
label.top(btex Pool 2 etex, point 4.5 of ground_level shifted (0,water_depth));
label.top(btex Pool 3 etex, point 6.5 of ground_level shifted (0,water_depth));
label.top(btex Pool 4 etex, point 8.5 of ground_level shifted (0,water_depth));
label.top(btex Waste  etex, point 10.4 of ground_level shifted (0,water_depth));

label.bot(btex $L_4$ etex, point  2 of ground_level shifted 20 down);
label.bot(btex $L_5$ etex, point  4 of ground_level shifted 20 down);
label.bot(btex $L_6$ etex, point  6 of ground_level shifted 20 down);
label.bot(btex $L_7$ etex, point  8 of ground_level shifted 20 down);
label.bot(btex $L_8$ etex, point 10 of ground_level shifted 20 down);

% trim the rough edges left and right
setbounds currentpicture to bbox currentpicture shifted (10,0) xscaled 0.95;

endfig;
end.

A: A TikZ solution where an L shape pool is drawn by a macro called mypool that takes 6 arguments, displayed below.
#1=starting point, #2=vertically down  length, #3=for Label L4-L8,
#4=horizontal length of the pool #5=end point #6=Pool label 1-5.

Update: The OP wants the labels to be somewhere above the water border and center. Well, here just modify the macro to what is shown below.
\newcommand\mypool[6]{
% draw L shape line
\draw[line width=1pt] ([yshift=1cm]#1) -- +(0,#2)coordinate[](a){}node[below=0.5cm](){#3} --node[above=0.2cm, pos=0.5]{#6} +(#4,#2)coordinate[](#5){}; <---- see #6 there
% fill water and patterns
\path[fill=blue!30](a) -- ([yshift=0.3cm]a)-- ([yshift=0.3cm]#5) -- (#5)--cycle;
\path[pattern=north east lines](a) -- ([yshift=-0.3cm]a)-- ([yshift=-0.3cm]#5) -- (#5)--cycle;
\draw[line width=1pt]([yshift=1cm]#1) |-(#5);
}

and yields

Code
\documentclass[border=10pt]{standalone}%[11pt]{article}

\usepackage{tikz}
\usetikzlibrary{positioning,patterns}
\newcommand\mypool[6]{
% draw L shape line
\draw[line width=1pt] ([yshift=1cm]#1)node[right=0.5cm]{#6} -- +(0,#2)coordinate[](a){}  node[below=0.5cm](){#3} -- +(#4,#2)coordinate[](#5){};
% fill water and patterns
\path[fill=blue!30](a) -- ([yshift=0.3cm]a)-- ([yshift=0.3cm]#5) -- (#5)--cycle;
\path[pattern=north east lines](a) -- ([yshift=-0.3cm]a)-- ([yshift=-0.3cm]#5) -- (#5)--cycle;
\draw[line width=1pt]([yshift=1cm]#1) |-(#5);
}
\begin{document}
%#1=starting point, #2=vertically down  length, #3=L4-L8, #4=length of the pool #5=end point #6=pool1-5.
\begin{tikzpicture}
\node[inner sep=0pt, outer sep=0pt] at (0,0) (O){};
\mypool{O}{-1}{}{2}{A}{Dam}
\mypool{A}{-2}{L4}{1}{B}{POOL1}
\mypool{B}{-2}{L5}{2}{C}{POOL2}
\mypool{C}{-2}{L6}{3}{D}{POOL3}
\mypool{D}{-2}{L7}{4}{E}{POOL4}
\mypool{E}{-2}{L8}{3}{F}{Waste}
\end{tikzpicture}
\end{document}

A: Again with tikz but using pic:
\documentclass[border=3mm]{standalone}

\usepackage{tikz}
\usetikzlibrary{patterns,calc}

\tikzset{%
pics/.cd,
dam/.style args={#1#2#3#4#5}{
  code={
    \begin{scope}[shift={(#1)}]
    \coordinate (a) at (0,0);     %% starting point
    \coordinate (b) at +(0,#2);   % height of right side
    \coordinate (c) at ([shift={(-#3,0.5)}]$(a)!0.5!(b)$); %top left point of water
    \coordinate (d) at ([shift={(-#3,-0.25)}]$(a)!0.5!(b)$); %bottom left point of hatch
    \fill [cyan!50] ($(a)!0.5!(b)$) rectangle ([xshift=\pgflinewidth]c)node[black,midway,above=2ex]{#4};
    \draw[thick] ($(a)!0.5!(b)$) -- ([yshift=-0.5cm]c);
    \fill [pattern = north east lines] ($(a)!0.5!(b)$) rectangle ([xshift=\pgflinewidth]d);
    \draw[thick] (a) -- (b);
    \path (a) -- +(0,-0.5)node[pos=1.2] {#5};
    \end{scope}
  }
},
}

\begin{document}
  \begin{tikzpicture}
    %dam={starting point}{height of right side}{width}{pool label Pool1..}{location label L1...}
    \pic {dam={0,0}{2}{3}{Dam}{L4}};
    \pic {dam={2,-1}{2}{2}{Pool1}{L5}};
    \pic {dam={5,-2.5}{3}{3}{Pool2}{L6}};
    \pic {dam={9,-4.5}{4}{4}{Pool3}{L7}};
    \pic {dam={10,-5.2}{1.4}{1}{Pool4}{L8}};
    \pic {dam={13,-5.2}{0}{3}{Waste}{}};
  \end{tikzpicture}

\end{document}

A: A PSTricks solution:
\documentclass{article}

\usepackage[pdf]{pstricks}

\newpsobject{water}{psframe}{
  dimen = m,
  linestyle = none,
  fillstyle = solid,
  fillcolor = blue!30
}
\newpsobject{basin}{psframe}{
  dimen = m,
  linestyle = none,
  fillstyle = hlines,
  hatchsep = 2pt
}

\def\pool(#1,#2)[#3,#4]#5#6{
  \water(#1,#2)(!#1 #4 add #2 0.5 add)
  \basin(!#1 #2 0.3 sub)(!#1 #4 add #2)
  \psline(!#1 #2 #3 add)(#1,#2)(!#1 #4 add #2)
  \rput(!#1 #4 2 div add #2 1 add){\small #5}
  \psline[linestyle = dashed, dash = 3pt 3pt](#1,#2)(!#1 #2 1 sub)
  \rput(!#1 #2 1.5 sub){\small $L_{#6}$}
%  \rput(!#1 #2 1.5 sub){\small L#6}
}
% syntax for \pool:
% \pool(<start position of basin; (x,y)>)
%      [<height of left side of basin>,
%       <width of basin>]
%      {<first label>}
%      {<second label>}

\begin{document}

\psset{unit = 0.64} % to avoid `overfull \hbox'
\begin{pspicture}(18,8.9)
  % dam
  \water(0,7.7)(3,8.2)
  \basin(0,7.4)(3,7.7)
  \psline(0,7.7)(3,7.7)
  \rput(1.5,8.7){\small Dam}
  % pools
  \pool(3,5.7)[3,4]{Pool~1}{4}
  \pool(7,4.7)[2,2]{Pool~2}{5}
  \pool(9,3.7)[2,3]{Pool~3}{6}
  \pool(12,2.7)[2,3.5]{Pool~4}{7}
  % waste
  \pool(15.5,1.7)[2,2.5]{Waste}{8}
\end{pspicture}

\end{document}

Update
In case you want a uniform vertical distance between the different pools, you can simplify the code a bit:
\documentclass{article}

\usepackage[pdf]{pstricks}

\newpsobject{water}{psframe}{
  dimen = m,
  linestyle = none,
  fillstyle = solid,
  fillcolor = blue!30
}
\newpsobject{basin}{psframe}{
  dimen = m,
  linestyle = none,
  fillstyle = hlines,
  hatchsep = 2pt
}

\def\pool(#1,#2)[#3]#4#5{
  \water(#1,#2)(!#1 #3 add #2 0.5 add)
  \basin(!#1 #2 0.3 sub)(!#1 #3 add #2)
  \psline(!#1 #2 2 add)(#1,#2)(!#1 #3 add #2)
  \rput(!#1 #3 2 div add #2 1 add){\small #4}
  \psline[linestyle = dashed, dash = 3pt 3pt](#1,#2)(!#1 #2 1 sub)
  \rput(!#1 #2 1.5 sub){\small $L_{#5}$}
%  \rput(!#1 #2 1.5 sub){\small L#5}
}
% syntax for \pool:
% \pool(<start position of basin; (x,y)>)
%      [<width of basin>]
%      {<first label>}
%      {<second label>}

\begin{document}

\psset{unit = 0.64} % to avoid `overfull \hbox'
\begin{pspicture}(18,7.9)
  % dam
  \water(0,6.7)(3,7.2)
  \basin(0,6.4)(3,6.7)
  \psline(0,6.7)(3,6.7)
  \rput(1.5,7.7){\small Dam}
  % pools
  \pool(3,5.7)[4]{Pool~1}{4}
  \pool(7,4.7)[2]{Pool~2}{5}
  \pool(9,3.7)[3]{Pool~3}{6}
  \pool(12,2.7)[3.5]{Pool~4}{7}
  % waste
  \pool(15.5,1.7)[2.5]{Waste}{8}
\end{pspicture}

\end{document}


text:
Q: Auth and get running instance count for azure in ruby How can I get the running instance count for Azure in ruby, I'm looking something equivalent to How to enumerate running ec2 instances and load them into a database using ruby? in AWS.
Thanks
Here is what I did:
subscription_id= 'xyz'
provider = MsRestAzure::ApplicationTokenProvider.new(tenant_id, client_id, secret)
  credentials = MsRest::TokenCredentials.new(provider)
  client = Azure::ARM::Resources::ResourceManagementClient.new(credentials)
  client.subscription_id = subscription_id
  resource_group_params = Azure::ARM::Resources::Models::ResourceGroup.new()
  resource_group_params.location = 'westus'
  promise = client.resource_groups.create_or_update('new_test_resource_group',resource_group_params)
  result = promise.value!
  resource_group_params = result.body
  p resource_group_params.name
  p resource_group_params.id

Response:
azureAuth.rb:35:in <main>': undefined methodvalue!' for # (NoMethodError)

A: From the description, it is hard to know this "running instance". Do you mean Azure web app or Azure cloud service instance? Based on your code snippet, you seem want to create Azure resource group and get some related info. For this scenario, I suggest you follow the sample code in Azure official site: Manage Azure resources and resource groups with Ruby. Hope it could give you some tips.
[Update]
I am sorry for that I did not test the sample code and give solution to you.

still it is throwing error "nil:NilClass (NoMethodError)

Based on my test, I think you did not create azure resource group, so the promise object is nil. Please try list resource group operation client.resource_groups.list.each{ |group| print_item(group) } I think you will get nil issue too. When I dig into the ms_rest_azure I could not even able to get token. When I change below code (application_token_provider.rb)  I could able to get the token
1) request_body['{resource_uri}'] = "https%3A%2F%2Fmanagement.azure.com%2F" #ERB::Util.url_encode(@settings.token_audience). Use management.azure.com instead of management.core.windows.net
2) response = connection.post do |request| get method change to post method.
3) :ssl => MsRest.ssl_options change to :ssl => {:verify => false}
I would suggest you use rest API to achieve the same purpose. Below is my Ruby code based on rest API. Hope it helps.
  connection = Faraday.new(:url => 'https://login.windows.net/<telnet id>/oauth2/token',:ssl => {:verify => false}) do |builder|
    builder.adapter Faraday.default_adapter
 end
 response = connection.post do |request|
    request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    request.body = 'resource=https%3A%2F%2Fmanagement.azure.com%2F&client_id=<your client id>&client_secret=<your client secret>&grant_type=client_credentials'
 end
  response_body = JSON.load(response.body)
  @token = response_body['access_token']
  getResrouceCon = Faraday.new(:url => 'https://management.azure.com/subscriptions/<subscriotion id>/resourcegroups?api-version=2015-01-01',:ssl => {:verify => false}) do |builder|
    builder.adapter Faraday.default_adapter
 end
 response_resource = getResrouceCon.get do |req|
     req.headers["Authorization"] = "bearer #{@token}"
 end
 puts "response #{response_resource.body}"

Note: I use the latest version azure_mgmt_resource
[Update]
We could find Azure classic cloud service from Azure resource portal. we can get a lot of useful info of Azure cloud service from configuration. here is the screenshot:

If you want to get roles and role instance. We can use this rest API in Azure resource portal https://management.azure.com/subscriptions/<subscription id>/resourceGroups/<group name>/providers/Microsoft.ClassicCompute/domainNames/<cloud service name>/slots/Production?api-version=2016-04-01
We only need to modify a little from my previous answer. Here is the code that could get cloud service configuration:
 getResrouceCon = Faraday.new(:url => 'https://management.azure.com/subscriptions/<subscription id>/resourceGroups/<group name>/providers/Microsoft.ClassicCompute/domainNames/<cloud service name>/slots/Production?api-version=2016-04-01',:ssl => {:verify => false}) do |builder|
    builder.adapter Faraday.default_adapter
 end
 response_resource = getResrouceCon.get do |req|
     req.headers["Authorization"] = "bearer #{@token}"
 end
 puts "response #{response_resource.body}"


text:
Q: Exposing a method with a return type of list in my C++/CLI assembly to my C# project I have a C++/CLI project that wraps a native C++ application, which I use in my C# project.  I added a few void methods in my C++/CLI class which expose correctly to my C# project.  The intellisense shows fine in C# and I can interact with the methods.  However, when I put a return type of a struct in C++/CLI, the method doesn't show as availible in C#.  Any ideas?
C++/CLI
IPFILTERINFOLIST GetBlockList()
{
   return _packetFilter->GetBlockList();
}

...which calls...
C++ Native
IPFILTERINFOLIST  PacketFilter::GetBlockList()
{
   return m_lstFilters;
}

A: You  should create a "managed version" of the IPFILERTINFO struct and copy your unmanaged data into it. Then you create a normal .NET List<> and add all those managed objects to it.


text:
Q: Pandas DateTime Interpretation Issues & Plotting with axvline Recently I've used pd.to_datetime to assist with formatting date-time series data into the respective format I need for a matplotlib plot. I haven't had any issues until now where for an unknown reason, when I use a axvline (Matplotlib), a date-time error is thrown. However, this is only thrown when my code is executed in a function and not run in the console. After trying for the past two days, I've opted to ask this on SO for some guidance.
The expected output is:

Where the dotted red-line indicates a singular failure date.
My function follows the logic below:
for i in result:

Asset_Num = i.strip(".csv")
dataframe = pd.read_csv(i)
df2 = dataframe[(dataframe['Asset_Number']==Asset_Num)]
#Convert the Date/Time object into a list of Time Stamp Values
fdl = pd.to_datetime(df2['Date/Time'], format="%Y-%m-%d %H:%M:%S").to_list()
ax = dataframe.plot(linewidth=2)
ax.axvline(fdl, color='r', linestyle="--")

The error that is then thrown as I run this function is:

But I am confused as both the X-axis and fdl variable, both are in the same date-time format and I have checked this numerous times.
What am I doing wrong?
I've attached some sample data as per our minimum criteria guidelines if you'd like to try recreate this. (http://www.sharecsv.com/s/292b419dc674302ac5b6a96a2da0e06e/SampleData.csv)
Thank you.


text:
Q: Return variable from its name in MATLAB Say I have a variable var=1 and a string str='var'.
How can I obtain the value of var from str?. I tried using str2num(str), but it didn't work.
Also, if I had 2 strings str1='some letters' and str2='str1', can I obtaing the phase 'some letters' from str2?
I want to do this because I have many matrices (quite big) and I want to separate them in some groups, so I thought about making cells with the names of each of the matrices that belong to a group (a matrix can belong to more than one group, so making cells with the matrices is not very good).

A: You can use eval:
x = eval( str ) ;

But it's not recommended.

A: Though it can easily be achieved with an eval as @Shai mentioned, you probably don't really want to do this. Using eval hinders your debugging and depending on the name of variables seriously limits the flexibility of your code. If you want to name something, you may be better off using a struct with a data field and a name field instead.
Judging from your description, I wonder about the following:
1. Why do you have many matrices?
For each variable that you have, you depend on a name. Depending on a lot of names is typically undesirable. Hence my suggestion:

Use a (cell) array containing these matrices

2. What way do you exactly want them to be in a group
It is not clear to me how you want the grouping to work, but think of this:

If you want to use names, create a struct or array of structs with a nameField, but
  otherwise just use a cell array and have each matrix get a number.

You can now handle the matrices more easily and things like 'selecting 10 random matrices' or 'selecting all matrices whose nameField contains 'abc'' can be done easily and efficiently.
You can now also have a field with your data specifying in which groups it is, or you can define groups as simple lists of numbers.


text:
Q: Why is the answer of laplace of $1 * t^2$ not equal to that you would get from convolution theorem? So I know that
$$L(t^2) = \frac{2}{s^3}$$
but why is is that, if we use the convolution theorem for $1 \ast t^2$, we get
$$L(1*t^2) = \frac{1}{s}*\frac{2}{s^3}$$
Isn't $1 \ast t^2$ equal to $t^2$? Or am I missing something in the definition?
Sorry if it's a dumb question but I just really can't seem to understand.
(edit: corrected the fraction)
(edit: sorry about that, I just realized I definitely didn't have a good grasp on the definition!)

A: $$\mathcal {L}(1*t^2) = \mathcal {L} (1) \mathcal {L}(t^2)=\frac{1}{s}\times \dfrac {2!}{s^3}=\dfrac 2 {s^4}$$
Note that the convolution theorem gives us :
$$f(t)=1 *t^2 =\int^t_0 1 \times \tau ^2 d\tau$$
$$f(t)=\dfrac {\tau ^3}3 \bigg |_0^t=\dfrac {t^3}3$$
$$\mathcal {L}(f(t))=\dfrac 13 \dfrac {3!}{s^4}=\dfrac 2 {s^4}$$


text:
Q: OpenFire: Hide all users in the same group from each other? We would like to restrict access to users within a group (Staff) so that they can only see/chat with users from another group (Support) and not each other. We would also like to ensure that users from the Support group can see all those in the Staff group.
Can this be achieved and if so, how?

A: You can do this using the Packet Filter Plugin, which is available by default in the Plugins section of the OpenFire admin. Using this plugin you can block messages between users of the Staff group from chatting with or seeing each other.
I'd post a screen shot and detailed instructions, but it seems like Ignite Realtime's site is down at the moment. I'll post back when they fix it.
EDIT: This works, I just tested it. Here's what you'll do:

*

*Install the Packet Filter Plugin from the "Plugins" tab of the OpenFire admin:

*Make sure you have your "Staff" and "Support" groups set up.

*Go to the "Packet Filter Rules" under "Server", "Server Settings"

*Create a new rule to Pass Any messages from Group Staff to Group Support:

*Then create a new rule to Drop Any messages from Group Staff to Group Staff. You should then have the following two rules:

You can optionally enable logging if you wish.
Now, any time a user from the Staff group tries to get the presence of or send a message to any other user from the Staff group, these messages will be dropped and the two will be unable to unable to see or chat with each other. However, messages from the Staff group to the Support group will be passed along.
You could chose in the second rule to Drop all messages from the Staff group if you choose. This will prevent them from communicating with anyone not in the Support group.
I hope this helps!

A: How about using a single account for the staff? You can set Openfire to allow accounts to be used from multiple locations. Then, when an user of the Support group will want to reach someone of the staff, the message will be displayed on all clients with the staff account enabled. So nobody of the staff will miss a request and they won't be able to talk each other with this single account.


text:
Q: PHP Script to re-run itself until process completed.and then restart every week I've made a script that retrieves XML content from a web service. The process needs to be run once a week, but the script itself needs to be re-run about 180 times to complete the process. Each run of the script takes about 3-8 minutes. I would like it to re-run about 5 seconds after each completion.
My current solution for this is:

*

*Task scheduler for windows opens the php page once a week.

*When script is run and completed, javascript makes the page restart 5 seconds after completion.

*When the last time of the script runs it removes the reload of the page so that it stops.

The problem with this solution is that it opens a new browser window every week. Is there any good alternative ways of doing this without having to manually close down the browser?
The reason of re-run of the script is due to script timeout settings of the php server max limit, and the possibility to after each run to see status whether any error occurred.
I'm not using cron since it would require to do extremely many polls in order to get the process to start within 5 seconds of last time run. For the weekly start up of the script I assume it wouldn't work as long as the script uses javascript to rerun itself?

A: With PHP:
<?php

// increase the maximum execution time to 43200 seconds (12 hours)
set_time_limit(43200);

function runTask() {
    static $cycles = 0;

    // do whatever you need to do

    // Increments cycle count then compares against limit
    if ($cycles++ < 180)  {
        sleep(5);  // wait five seconds
        runTask(); // run it again
    }
}

runTask(); // fire up the loop

Or, if you're a fan of Javascript...
With node.js:
var cycles = 0;

function runTask() {
  // do whatever you need to do

  // Increments cycle count then compares against limit
  if (cycles++ < 180) {
    setTimeout(runTask, 5000); // run again in 5000 milliseconds
  }
}

runTask(); // fire up the loop

Both solutions will not run the function again until 5 seconds after each iteration has completed.
Just have your task runner execute either script directly; no need for browsers.


text:
Q: Android Studio 2.2's incremental compiler can't see generated protobufs I upgraded my stable version of Android Studio to 2.2 and now the IDE's "incremental compiler" can't find any of the symbols for generated protobuf classes.  I open the project and it can build and deploy the app to a device just fine.  But when I open a Java class file that contains generated protobuf references, Android Studio marks them as errors soon after the file opens.  Every Java import of a generated proto class is marked with "Cannot resolve symbol".
I first noticed this a month ago on the canary channel but didn't think anything of it because I was floundering with other protobuf issues (upgrading to 3.0.0 with its javalite split).  I forgot about it until today.  It's still possible to work on the project, it's just that the IDE is near useless since it thinks there are errors (even though real compiles are fine with it).
For reference.
gradle-2.14.1
com.android.tools.build:gradle:2.2.0
com.google.protobuf:protobuf-gradle-plugin:0.8.0
com.google.protobuf:protobuf-lite:3.0.0
com.google.protobuf:protoc:3.0.0
com.google.protobuf:protoc-gen-javalite:3.0.0

And in the modules that contain .proto files:
protobuf {
    protoc {
        artifact = google_protoc_artifact
    }
    plugins {
        javalite {
            artifact = google_protoc_javalite_artifact
        }
    }
    generateProtoTasks {
        all().each { task ->
            task.builtins {
                remove java
            }
            task.plugins {
                javalite { }
            }
        }
    }
}

A: We had the same issue and found out the following:
1) In order for idea (studio) to see your source, you need to help it by adding the idea plugin to your module:
apply plugin: 'idea'
idea {
    module {
        // Use "${protobuf.generatedFilesBaseDir}/main/javalite" for LITE_RUNTIME protos
        sourceDirs += file("${protobuf.generatedFilesBaseDir}/main/java");
    }
}

2) Another bug, Android Studio seems to ignore any source directory under build/. You have to move your generated directory outside of build:
protobuf {
    generatedFilesBaseDir = "$projectDir/src/generated"
}

These two changes fixed the problem introduced by Android Studio 2.2 for us.

A: In my case, I was using the kotlin protobuf plugin and to fix the error of the IDE not being able to resolve it. I tweaked the other answer above to point to the main folder.
// build.gradle.kts
plugins {
    idea
}

idea {
    module {
        // explicitly tell intellij where to resolve generated proto files
        sourceDirs.plusAssign(file("build/generated/source/proto/main/"))
    }
}


text:
Q: How can i make a discord bot say something a user says without prefix Im trying to figure out how to make a discord bot say something a specific user says. For example, if i say something in general the bot says what i said in the text channel. I want it to be user specific but i dont know how to make this in the bot. Thanks to whoever answers this.

A: You use the on_message(ctx) event. For example:
@client.event
async def on_message(ctx):
    message = ctx.content.lower()
    if 'hello' in message and ctx.author.id == MY_ID:
        await ctx.channel.send('Hey there!')

    await client.process_commands(ctx)

Note: await client.process_commands(ctx) is very important, without it, all your commands won't work.
MY_ID is your your Discord ID (an integer value), so the bot will only respond if the author's ID equals your ID.


text:
Q: Google Map API cannot be inserted into url including in Google Map Json I have a this url shown below.
https://maps.googleapis.com/maps/api/geocode/json?key=MY-KEY-API&latlng=40.9927242,29.0231916

I want to get json result from url by Retrofit part shown below.
public static final String URL = "https://maps.googleapis.com";

@GET("/maps/api/geocode/json")
    Call<Location> getInformation(@Query("latlng") String lat);

Call<Location> req = Manager.getInstance().getCity("40.9927242,29.0231916");

The response is shown below.
response : Response{protocol=h2, code=200, message=, url=https://maps.googleapis.com/maps/api/geocode/json?latlng=40.9927242%2C29.0231916}

API key cannot be inserted into the url part even through it defines in AndroidManifest.xml
<meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

google_maps_key.xml
<string name="google_maps_key"
        templateMergeStrategy="preserve" translatable="false">
        MY-KEY-API
</string>

When I click url, the error is defined in json format because of not adding API into the url.
{
"error_message": "You must use an API key to authenticate each request to Google Maps Platform APIs. For additional information, please refer to http://g.co/dev/maps-no-account",
"results": [],
"status": "REQUEST_DENIED"
}

How can I fix it?

A: You need to explicitly add an API key to your Geocoding API request (i.e. https://maps.googleapis.com/maps/api/geocode/json?key=AIza...).
The key you inserted into your Android Manifest is used by the Maps SDK for Android to load a map on your Android app.
The Geocoding API on the other hand does not use nor recognize that Android key. It needs its own key. Right now your call to this API is keyless which is why you are getting that REQUEST_DENIED error.
Side-note: It's recommended that you use another API key for web services because the key in your xml file should be Android restricted.
As for how to restrict your Geocoding key, take a look  at the techniques mentioned in Google's documentation, "On mobile apps that use Maps Web Service APIs" section.
Hope this helps you.


text:
Q: Push to GitHub from Team City build step I have a build step in Team City which generates documentation which I want to commit with git and then push to GitHub.
I am using ssh to connect to GitHub and doing the following:
git add .
git commit -m "Update docs"
git push origin refs/heads/localbranch:refs/heads/remotebranch

I am getting:
Host key verification failed.
fatal: Could not read from remote repository.

Should this approach work or do I need to try something else?

A: It seems that you are missing the host key or the host key has changed.
See:SSH connection problem with "Host key verification failed…" error


text:
Q: gdb doesn't show the name of the function call gdb in msys, doesn't show the name of the function call. Next to the address of the function call I have normaly the name of the function like . Why it's not the case with this exe and how can I fix it? gdb console

A:
Why it's not the case with this exe

Because GDB doesn't know what function address 0x4023d0 corresponds to.

how can I fix it?

Depending on what code resides at address 0x4023d0, and why GDB doesn't have a name associated with it, this may or may not be fixable. But there is not enough info for me to even begin guessing what code might be there.


text:
Q: What does "outstanding" mean in specific economic term? When I read a webpage, I saw the word "outstanding"
I am wondering what does "Outstanding" actually mean in these case on that webpage
Days of inventory outstanding
Days sales outstanding
Days payables outstanding


text:
Q: Display a ListFragment inside an AlertDialog I'm trying to show a ListFragment in an AlertDialog. The ListFragment appears as expected when called from an activity, but it does not appear in the dialog.
Hers is the Alert:
public class ProfileSelectFragment extends DialogFragment {
    private static final String DEBUG_TAG = "ProfileSelectFragment";
    protected int layout = R.layout.profileselect_dialog;
    final Fragment fragment0 = new LoadedProfilesFragment();
    private Button loginButton;
    private Button createProfileButton;
    private Button anonymousButton;

    static ProfileSelectFragment newInstance() {
        ProfileSelectFragment f = new ProfileSelectFragment();
        return f;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        LayoutInflater inflater = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE));
        View customView = inflater.inflate(layout, null, false);

        ...

        Dialog myDialog = new AlertDialog.Builder(getActivity()).setView(customView)
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.d(DEBUG_TAG, "cancel");
                    }
                }).create();
        final android.support.v4.app.FragmentManager fm = getActivity().getSupportFragmentManager();
        final android.support.v4.app.FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(R.id.fragment, fragment0);
        transaction.commit();
        return myDialog;
    }
}

Here is the AlertDialog layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <FrameLayout
        android:id="@+id/fragment"
        android:layout_width="fill_parent"
        android:layout_height="80dip"
        android:background="#33CC33">
    </FrameLayout>
    <Button
        android:id="@+id/button1"
        style="@android:style/Holo.ButtonBar.AlertDialog"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/showlogin" />
    <Button
        android:id="@+id/button2"
        style="@android:style/Holo.ButtonBar.AlertDialog"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/createprofile" />
    <Button
        android:id="@+id/button3"
        style="@android:style/Holo.ButtonBar.AlertDialog"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/anonymous" />
</LinearLayout>

And here is the ListFragment:
public class LoadedProfilesFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
    private static final String DEBUG_TAG = "LoadedProfilesFragment";
    private static final int LIST_LOADER = R.loader.loadedprofilesfragloader;
    protected int layout = R.layout.log_fragment;
    protected int entryLayout = R.layout.list_item;
    protected final Uri table = ProfileProvider.URI_LOADEDPROFILEVIEW;
    protected SimpleCursorAdapter listAdapter;
    protected String[] uiBindFrom = { ProfilesColumns.USERNAME, ProfilesColumns.CREATIONDATE };
    protected int[] uiBindTo = { R.id.title, R.id.creationdate };
    protected String[] createProjection = { CommonDatabaseHelper._ID, ProfilesColumns.USERNAME,
            ProfilesColumns.CREATIONDATE };

    public LoadedProfilesFragment() {
        super();
    }

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLoaderManager().initLoader(LIST_LOADER, null, this);
        listAdapter = new SimpleCursorAdapter(getActivity().getApplicationContext(), entryLayout, null, uiBindFrom,
                uiBindTo, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        setListAdapter(listAdapter);
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
        final View view = inflater.inflate(layout, container, false);
        return view;
    }

    ...

}

Not sure if I need to call the ListFragment in a different way since it is an AlertDialog as opposed to an Activity. My plan is to apply styles to make the list fragment and buttons in the alert dialog appear as a continuous list. Thanks in advance.

A: Use a fragment dialog to display list items.
How to display an existing ListFragment in a DialogFragment. This link should help you.


text:
Q: Session values aren't kept I'm using a JRuby(latest, 1.7 RC2)/Sinatra mix on the Trinidad server, for background info.
get "/" do
    @user = session[:user] || [3,2]
    puts session[:user]
    haml :home
end

get "/signed_in" do
    "#{session[:loggedin]}"
end

post "/signup" do
    user = User.create(:username => params[:username], :password => Digest::SHA1.hexdigest(params[:password]))
    session[:user] = user
    session[:loggedin] = true
    puts session[:user]
end'

What I expect as output is (with comments):
# blank line
#<User:0x4049839a>
#<User:0x4049839a>

But what I really get is:
# blank line
#<User:0x4049839a>
# blank line

And after the post, /signed_in will still have no value to output, when it really should be true.
Why aren't these values being kept? No, I'm not using shotgun, I do have sessions enabled, and I do have a session secret set up.

A: You cannot keep DataMapper resources in session variables. Instead put the key to your user object in your session variable and use a before helper to set @user = User.first(session[:user]) and use the @user instance variable throughout your application
Also, you do not need the session[:loggedin] entry, just use @user.nil?


text:
Q: Prevent resource data to trigger $watch (Angular.js) I have a list of item with a quantity, some of them already have an quantity that is retrieve from a resource when the page loads. Then I watch that same field for any changes made by the user to be able to auto-save theses changes. The autosaving process works pretty well, but the thing is that watch is triggered when the quantity gets filed by the ressource and I would prefer not because it's just silly to put that information back to the server.
How would you do that? :)
app.controller('InventoryLineController', function($scope, inventoryService){
  // Populate les champs de lignes déjà enregistrés sur le serveur.
  inventoryService.getLine($scope.inventory, $scope.product).$promise.then(function(inventoryLine){
    $scope.quantity = inventoryLine.quantity;
  });

  // Sauvegarde automatique lors du changement de quantité.
  $scope.$watch('quantity', function(newVal, oldVal){
      console.log(newVal); // VALIDATIONS + CALL TO SAVE METHOD
  });
});

Here's the html:
<tr ng-repeat="product in productList" ng-controller='InventoryLineController'>
  <input type="number" class="form-control" name="quantity" value="{{quantity}}" min="0" smartFloat ng-model-options="{ updateOn: 'blur' }" ng-model="quantity">
</tr>

Thank's!

A: you can ignore newval if its equal to old val
   $scope.$watch('quantity', function(newVal, oldVal){
     if(newVal !== oldVal) {
        console.log(newVal); // VALIDATIONS + CALL TO SAVE METHOD
     }
  });

A: You might have to store a response from the resource separately, and use it to compare against a newVal if it is changed or not. For example:
app.controller('InventoryLineController', function($scope, inventoryService){
  var savedObj = {};

  // Populate les champs de lignes déjà enregistrés sur le serveur.
  inventoryService.getLine($scope.inventory, $scope.product).$promise.then(function(inventoryLine){
    savedObj = inventoryLine;
    $scope.quantity = inventoryLine.quantity;
  });

  // Sauvegarde automatique lors du changement de quantité.
  $scope.$watch('quantity', function(newVal, oldVal) {
    if (angular.equals(newVal, savedObj.quantity)) {
      return;
    }

    savedObj.quantity = newVal;
    console.log(newVal); // VALIDATIONS + CALL TO SAVE METHOD
  });
});

Hope this helps.


text:
Q: MSSQL - Dynamic selection of percentage in select statement I have a process that takes a group of rows, and updates a column based on whether it's in the top 50% of rows, the middle 20% of rows, or the bottom 30% of rows.
I've done this by using the percent select as below
update sourcetable
set targetcolumn = a.outputdata
    from (
select top 50 percent uniqueid, outputdata
    from sourcetable a
    join Lookupstable b on a.grouptype = b.grouptype and and datacontent =
'topbracket'
where targetcolumn is null
order by ranking desc
) a
join sourcetable b on a.uniqueid = b.uniqueid

I then duplicate accordingly for the middle and bottom selections. However, I have been told that these brackets may change in the future, so it would be nice to have the percentages in my lookups table and only ever need to touch that table when I'm changing the output column details or the brackets.
I have tried to declare a variable to simulate referencing of the bracket amount as below
declare @top int
set @top = 50 --this would be a query to look for the relevant bracket figure

select top @top percent *
    from Sourcetable

This does not work. Does anyone know an alternative way to dynamically select my percentage of rows from a lookup in another table?

A: I think you have to use qynamic SQL Query using EXEC
declare @top  varchar(100)-- int
set @top = '50' --this would be a query to look for the relevant bracket figure
DECLARE @sql nvarchar(4000)

set @sql = 'select top ' + @top + ' PERCENT * from Sourcetable '

exec (@sql)

A: You have to use bracket in variable.
declare @top int
set @top = 50 --this would be a query to look for the relevant bracket figure
select top (@top) percent *
    from Sourcetable
update sourcetable
set targetcolumn = a.outputdata
    from (
select top (@top) percent uniqueid, outputdata
    from sourcetable a
    join Lookupstable b on a.grouptype = b.grouptype and and datacontent =
'topbracket'
where targetcolumn is null
order by ranking desc
) a
join sourcetable b on a.uniqueid = b.uniqueid


text:
Q: Display Friendly Name in CheckedListBox I'm adding items from a List to a CheckedListBox. I want that box to display the friendly name of the item to the user but have a "secret" actual value to use when the user selects it.
foreach (string s in x)
{
    checkedlistBox1.Items.Add(friendlyValue);
    //Now how do I get this to have the real value?
}

With drop down menus I can set the DisplayName and ValueName to something and use something like:
combobox1.Items.Add(new ComboBoxItem { friendlyValue = x, realValue = y });

I can't seem to do this with a CheckedListBox.

A: Set the DisplayMember and ValueMember properties on the CheckedListBox.
Those are functionally equivalent to the DisplayName and ValueName properties of the ComboBox.
public class MyClass
{
    public string FriendlyValue { get; set; }
    public string RealValue { get; set; }
}

public class YourForm : Form
{
    public YourForm()
    {
        var friendlyList
            = new List<string>();  // imagine it's populated with friendly values

        foreach (var fv in friendlyList)
        {
            checkedListBox1.Items.Add(
                new MyClass { FriendlyValue = fv, RealValue = ??? });
        }

        checkedListBox1.DisplayMember = "FriendlyValue";
        checkedListBox1.ValueMember = "RealValue";
    }
}


text:
Q: Elasticsearch match query with partial text match Newbie question on elasticsearch. I have set up the elasticsearch lucene index and use searching for names that contain some term, such as
search_response = es.search(index = 'sample', body = {'query':{'match':{'first_name':"JUST"}}})

This does not return me the name "JUSTIN" but the following query does
search_response = es.search(index = 'sample', body = {'query':{'match':{'first_name':"JUSTIN"}}})

What am I doing wrong? Shouldn't "match" query return me the records that contain the term?
Thanks.

A: The best way to handle that need is by creating a custom analyzer which uses the edgeNGram token filter. Forget about wildcards and using * in query strings, those all underperform the edgeNGram approach.
So you'd have to create your index like this first and then reindex your data into it.
curl -XPUT http://localhost:9200/sample -d '{
    "settings": {
        "analysis": {
            "filter": {
                "prefixes": {
                    "type": "edgeNGram",
                    "min_gram": 1,
                    "max_gram": 15
                }
            },
            "analyzer": {
                "my_analyzer": {
                    "type": "custom",
                    "tokenizer": "standard",
                    "filter": ["lowercase", "prefixes"]
                }
            }
        }
    },
    "mappings": {
        "your_type": {
            "properties": {
                "first_name": {
                    "type": "string",
                    "analyzer": "my_analyzer",
                    "search_analyzer": "standard"
                }
            }
        }
    }
}'

Then when indexing first_name: JUSTIN, you'll get the following indexed tokens: j, ju, jus, just, justi, justin, basically all prefixes of JUSTIN.
You'll then be able to search with your second query and actually find what you expect.
search_response = es.search(index = 'sample', body = {'query':{'match':{'first_name':'JUST'}}})


text:
Q: PyQt5: QWebEngineView Distortion on Resize I have a python application that simply displays given html, with the following code:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout
from PyQt5.QtWebEngineWidgets import QWebEngineView

class IFace(QWidget):

    def __init__(self):
        super().__init__()
        self.setGeometry(300, 300, 1000, 500)
        self.view = WebView(self)
        self.setLayout(QGridLayout(self))
        self.layout().addWidget(self.view, 0, 0)
        self.layout().setContentsMargins(0, 0, 0, 0)

class WebView(QWebEngineView):

    def __init__(self, parent):
        super().__init__(parent)
        self.setHtml("""

Hi!

Hi!

Hi!

""")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = IFace()
    w.show()
    sys.exit(app.exec_())

The html is displayed correctly at first, but resizing the window vertically will cause the displayed webpage to 'stretch' downwards, distorting the text:
Before resizing:

After resizing:

Note how the the text is taller, but not wider.  The text also moves downwards as the window is shrunk vertically.
When I place another widget to the left of the QWebEngineView, such as a QLabel, the distortion affects the QLabel as well.  If I do not include the QWebEngineView, the QLabel is not distorted.
Why does this happen, and how can I fix it?
Thanks.
UPDATE:
It appears to have something to do with the instantiation of a QWebEngineView that has the window as a parent, as the effect persists when the QWebEngineView is only created not placed, and the effect does not remain when the QWebEngineView is instantiated by QWebEngineView() without the widget as a parent.

A: This problem occurred due to outdated drivers.  I found the solution (also on stackoverflow) here, though it was to a slightly different problem (widgets being hidden beneath the title bar, not distortion of the QWebEngineView).
I updated my Intel(R) HD Graphics driver (forwards, unlike the listed answer in the link) and the issue went away.


text:
Q: How to find the length of a state in a react component There is a function as follows:
async function validate(value) {
    try {
      const result = await schema.validate(value, { abortEarly: false });
      console.log(result);
      return result;
    } catch (error) {
      console.log(error.errors);
      setError({errors:error.errors});
      console.log(setError.length);
    }
  }

In line number 8, the errors are updated in the state without any problem, but when I want to find the length of the state setError array, it returns the value of 1, even though the value of the created array is greater than 1.
Is there a solution to find the state length in functional components in react?

A: Your code has 2 problems:

*

*set state functions in React are async. It means that your values are not updated immediately. So you should declare a new variable and then log the new variable or write your console.log in useEffect.

*You should log the length of the error state not the set state function.
So this would help you.
Let's assume you have this state:
const [error, setError] = useState({errors: []});

Using another variable:
async function validate(value) {
  try {
    const result = await schema.validate(value, { abortEarly: false });
    console.log(result);
    return result;
  } catch (error) {
    console.log(error.errors);
    const newError = {errors: error.errors};
    setError(newError);
    console.log(newError.errors.length);
  }
}

With useEffect:
async function validate(value) {
  try {
    const result = await schema.validate(value, { abortEarly: false });
    console.log(result);
    return result;
  } catch (error) {
    console.log(error.errors);
    setError({errors: error.errors});
  }

  useEffect(() => {
    console.log(error.errors.length);
  }, [error]);
}

A: If you want to use the length states, you must pass the array to the secondary state, then find the length from the primary state.
My problem is solved
In fact, I should write as follows
async function validate(value) {
try {
const result = await schema.validate(value, { abortEarly: false });
setError([]);
return result;
} catch (error) {
setError(error.errors);
}
  }

The main problem of my code was that I had not transferred the answer of the function to the result correctly
The problem was in the following line
const result = await validate(account);

I was then able to use result

A: you doing wrong man, you are assigning {} to error state and then you are checking the length of setError method, I don't know why are you doing this
try like this
const Component =()=>{
const [errors, setError]=useState([]);

    async function validate(value) {
    try {
      const result = await schema.validate(value, { abortEarly: false });
      console.log(result);
      return result;
    } catch (error) {
      console.log(errors.errors);
      setError([...errors,{errors:error.errors}]);
      console.log(errors.length); // here you will get previous length of errors array
    }
 }
// console here
console.log("ERROR LENGTH",errors.length);

return(
//UI stuff
)
}


text:
Q: Using enums in Swift I am new to swift, after programming years with Objective-C.
I declare this on a file
  public enum Identifier {
    case car, boat, toy, water
  }

From another class I do:
var type : Identifier = Identifier.car

ERROR: Use of undeclared Identifier

I also tried
class MyTypes {
  enum Identifier {
    case car, boat, toy, water
  }
}

and then
var type : MyTypes = MyTypes.Identifier.car

How do I use that?

A: Possible sources of the problem include that the file hasn't been saved yet or that the file hasn't been included in your Xcode project's target. It would appear that the latter issue is the problem here.

By the way, your second example, defined within MyTypes, should be declared as follows:
var type: MyTypes.Identifier = .car

Or as:
var type = MyTypes.Identifier.car


text:
Q: Диалог пропускает вопрос Python (Отлично, напомни, когда у тебя день рождения? (день(буквами) месяц)) hello = input("Привет ")
if hello == "привет":
hello = input("Я ищу xx, знаешь такого? ")
else:
print("Почему бы просто не поздороваться? ")
if hello == "да":
hello = input("Отлично, это ты? ")
else:
print("Тогда вызовешь меня, когда он придёт! ")
if hello == "да":
print('Отлично, напомни, когда у тебя день рождения? (день(буквами) месяц) ')
elif "нет":
print("Тогда вызовешь меня, когда он придёт!")
if hello == "xx":
print(
    "Поздравляю тебя с днём рождения, братик! Желаю тебе в этот День Рождения здоровья,
которого хватило бы"
    " на долгие годы, мощной энергии и нескончаемой силы. В душе будь всегда молодым, никогда
не опускай руки, "
    "будь весёлым, позитивным и радуйся веселым моментам жизни. Я Люблю Тебя! "
    "P.S Звони по чаще маме и про меня не забывай :)")
else:
print("Ты не знаешь день своего рождения!? Ты шутишь?")
if hello == "Да":
print(
    "Поздравляю тебя с днём рождения, братик! Желаю тебе в этот День Рождения здоровья,
которого хватило бы"
    " на долгие годы, мощной энергии и нескончаемой силы. В душе будь всегда молодым, никогда
не опускай руки, "
    "будь весёлым, позитивным и радуйся веселым моментам жизни. Я Люблю Тебя! "
    "P.S Звони по чаще маме и про меня не забывай :)")
elif "нет":
print("Ну ладно..."
      "Сегодня же ТВОЙ день рождения!!!"
      "Поздравляю тебя с днём рождения, братик! Желаю тебе в этот День Рождения здоровья,
которого хватило бы"
      " на долгие годы, мощной энергии и нескончаемой силы. В душе будь всегда молодым,
никогда не опускай руки, "
      "будь весёлым, позитивным и радуйся веселым моментам жизни. Я Люблю Тебя! "
      "P.S Звони по чаще маме и про меня не забывай :)")

A: Еще дело в отступах там где if , они должны быть так как вылетает ошибка не забывай про отступы и так же там где else: если на нем есть условие то тогда else hello == (что-то):


text:
Q: Creating boxplots in R using lattice for already processed data I am trying to create a a boxplot in R of an extremely large data set. The file containing the data is 2.5G and crashes R if I try to import it. Fortunately some other piece of (python) software can generate the mean and variance without a problem, which is all I really want to plot(for now).
Every tutorial I've found so far requires you to input the full data set, then R computes the statistics itself, but I was wondering how to pass the mean, median, min, max, etc... to bwplot just for plotting. The reason I prefer R and lattice is because it integrates well with the software suite the code might end up in. If I used matlab or some other software that would be a problem because it would be yet another requirement from our current users.

A: Boxplots do not plot mean or variance. You actually need the full ranked data to plot a proper boxplot, because the quantities are median, quartiles and the actual value of the closes data point within 1.5 times IRQ plus all data points that are outside that range (outliers). This is typically not a good idea for a large data set (because by definition you have millions of outliers).
That said, you can generate the essential summaries any way you want and use bxp to plot them - see ?bxp in R. Just make sure you clarify what quantities you are plotting if they are not the above.


text:
Q: Custom Navigation Bar not rectangular Is it possible to customize the Navigation Bar to look like the picture below? Obviously that has a transparent background not a grey one.

I've tried:
UINavigationBar.appearance().setBackgroundImage(UIImage(named:"pattern.png"),
                                                            for: .default)

That seems to capture the colour but not the format of the navigation bar.

I am trying to avoid creating a custom nav bar with a UIView or anything like that because that would mean a lot of extra work for such a small change.My app has a lot of views using a Navigation Controller.
Thanks in advance.

A: Use this to add the zigzag pattern to your navigationBar (version2), or you can create a custom UIImage with your desired pattern  (version1 (favorite))
Version 1 using UIImage and using self.navigationController?.navigationBar.setBackgroundImage method
Getting the image
import UIKit

extension UIImage {

    static func pathZigZagForCGRect(rect: CGRect) ->UIBezierPath
    {
        let width = rect.size.width
        let height = rect.size.height

        let zigZagWidth = CGFloat(7)
        let zigZagHeight = CGFloat(5)
        var yInitial = height-zigZagHeight

        var zigZagPath = UIBezierPath()
        zigZagPath.move(to: CGPoint(x:0, y:0))
        zigZagPath.addLine(to: CGPoint(x:0, y:yInitial))

        var slope = -1
        var x = CGFloat(0)
        var i = 0
        while x < width {
            x = zigZagWidth * CGFloat(i)
            let p = zigZagHeight * CGFloat(slope) - 5
            let y = yInitial + p
            let point = CGPoint(x: x, y: y)
            zigZagPath.addLine(to: point)
            slope = slope*(-1)
            i += 1
        }

        zigZagPath.addLine(to: CGPoint(x:width,y: 0))
        zigZagPath.addLine(to: CGPoint(x:0,y: 0))
        zigZagPath.close()
        return zigZagPath
    }

    static func zigZagImage(rect: CGRect,color:UIColor)->UIImage {

        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
        var ctx = UIGraphicsGetCurrentContext()!
        ctx.clear(CGRect(x: 0, y: 0, width: rect.size.width, height: rect.size.height))

        ctx.setFillColor(color.cgColor)
        let path = UIImage.pathZigZagForCGRect(rect: rect)
        ctx.addPath(path.cgPath)
        ctx.fillPath()
        //draw triangle

        let img = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        return img
    }

}

Using it
override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.navigationController?.navigationBar.setBackgroundImage( UIImage.zigZagImage(rect: CGRect(x: 0, y: 0, width: (self.navigationController?.navigationBar.frame.size.width)!, height: (self.navigationController?.navigationBar.frame.height)! + 20),color:UIColor.red).resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .stretch), for: .default)
    }

Result

Version 2 using layerMask
func pathZigZagForView(givenView: UIView) ->UIBezierPath
    {
        let width = givenView.frame.size.width
        let height = givenView.frame.size.height

        let zigZagWidth = CGFloat(7)
        let zigZagHeight = CGFloat(5)
        var yInitial = height-zigZagHeight

        var zigZagPath = UIBezierPath()
        zigZagPath.move(to: CGPoint(x:0, y:0))
        zigZagPath.addLine(to: CGPoint(x:0, y:yInitial))

        var slope = -1
        var x = CGFloat(0)
        var i = 0
        while x < width {
            x = zigZagWidth * CGFloat(i)
            let p = zigZagHeight * CGFloat(slope) - 5
            let y = yInitial + p
            let point = CGPoint(x: x, y: y)
            zigZagPath.addLine(to: point)
            slope = slope*(-1)
            i += 1
        }

        zigZagPath.addLine(to: CGPoint(x:width,y: 0))
        zigZagPath.addLine(to: CGPoint(x:0,y: 0))
        zigZagPath.close()
        return zigZagPath
   }

func applyZigZagEffect(givenView: UIView) {
    let shapeLayer = CAShapeLayer(layer: givenView.layer)
    shapeLayer.path = self.pathZigZagForView(givenView: givenView).cgPath
    shapeLayer.frame = givenView.bounds
    shapeLayer.masksToBounds = true
    givenView.layer.mask = shapeLayer
}

Using it
override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.navigationController?.navigationBar.backgroundColor = UIColor.red
        self.applyZigZagEffect(givenView: (self.navigationController?.navigationBar)!)
    }

Hope this helps you

A:
I am trying to avoid creating a custom nav bar with a UIView or
  anything like that because that would mean a lot of extra work for
  such a small change.My app has a lot of views using a Navigation
  Controller.

Subclass UINavigationController and implement the custom view on the UINavigationBar contained within.
Then anywhere you have a navigation controller in the app, replace its class with the custom subclass.
For example:
class MyCustomNavigationController: UINavigationController {

    override func viewDidLoad() {
        // ... code to implement custom view
        // you may not necessarily want to put it in viewDidLoad...
    }

}

That way you only have to write the custom view code once. A custom view as your navigation bar is most likely the only way to achieve what you desire.


text:
Q: Validating JSON schema always return true I've written a code that should validate my JSON schema by comparing the schema with the JSON string. It always returns True, even when instead of a given type in schema, I return a string or an int. I bet there is something that I missed in the logic of my schema to compare to.
Here is a code:
import json
import jsonschema
from jsonschema import validate

Emp_Schema = {
    "type": "object",
    "outputs": {
        "boundaries": {"type": "List[List[coords]]"},
        "connecter": {"type": "List[bool]"},
        "compare": {"type": "List[float]"},
        "center": {"type": "List[List[coords]]"},
        "classes": {"List[int]"},
    },
}

def validate_json(jsonData):
    try:
        validate(instance=jsonData, schema=Emp_Schema)
    except jsonschema.exceptions.ValidationError as error:
        return False
    return True

jsonStr = json.loads('''{
    "boundaries": [
        [
            150.05322,
            11.53223,
            300.532,
            123.1437
        ],
        [
            53.877,
            332.663879,
            49.9110756,
            441.316406
        ],
        [
            388.617188,
            298.171814,
            401.498016,
            308.061432
        ],
        [
            373.388794,
            269.419434,
            393.059235,
            284.425232
        ],
        [
            388.449,
            276.744293,
            401.1651,
            287.800415
        ],
        [
            371.061462,
            69.9721527,
            382.472076,
            81.5727
        ],
        [
            354.491974,
            147.660431,
            370.116882,
            160.380508
        ]
    ],
    "connected": [
        true,
        false,
        true,
        true,
        true,
        true,
        true
    ],
    "compare": [
        0.990648627,
        0.989233553,
        0.984282315,
        0.949795425,
        0.913895547,
        0.539879441,
        0.4897542
    ],
    "center": [
        [
            369.494934,
            116.291542
        ],
        [
            40.8455315,
            332.990143
        ],
        [
            395.057587,
            303.116638
        ],
        [
            383.224,
            276.922333
        ],
        [
            394.807068,
            282.272369
        ],
        [
            376.766785,
            75.7724228
        ],
        [
            362.304443,
            154.020477
        ]
    ],
    "classes": [
        0,
        0,
        0,
        0,
        0,
        0,
        0
    ]
}''')

# calling above define function
is_valid = validate_json(jsonStr)
if is_valid :
    print('Given JSON data:\n ', jsonStr)
    print("The JSON data is valid")
else:
    print(jsonStr)
    print("The JSON data is Invalid")

I am new to json format, so I bet i specified my Emp_Schema variable wrong. I would be grateful for any recommendations how to make it so, only the jsonStr would pass the test. Because the json string here is the string that should be valid, and any other should return as invalid.


text:
Q: Azure load balancer - balance on-premises servers I have at home 3 servers that host 3 websites (on-premises).
Is it possible for Azure load balancer to load balance between my sites and enable http2.0?
I cannot find info on http 2.0

A: It's not possible. The Azure load balancer is used to balance traffic between Azure VMs only and more specifically Azure VMs in the same availability set and Scale sets. Also, the Azure VMs are within the same Azure region. You can see the response from Azure networking team about the feedback of Load Balancer support for on-premise VMs.
You may consider that Azure traffic manager is the solution you can have endpoints which include on-premise services. But Traffic Manager endpoint should be any internet facing service hosted inside or outside of Azure.  Refer to this.

If you have endpoints that are inside a private network, Traffic
  manager cannot be used for that traffic.

Another option would be Azure Application gateway which is a layer 7 solution that can front services regardless of the region/on-premises. Refer to this.

Application Gateway can talk to instances outside of the virtual
  network that it is in as long as there is IP connectivity. If you plan
  to use internal IPs as backend pool members, then it requires VNET
  Peering or VPN Gateway.

Update
Add the http2.0 info per this doc.

HTTP/2 protocol support is available to clients connecting to
  Application Gateway listeners only. The communication to backend
  server pools is over HTTP/1.1.
By default, HTTP/2 support is disabled. The following Azure PowerShell
  code snippet example shows how you can enable it:
 $gw = Get-AzureRmApplicationGateway -Name test -ResourceGroupName hm
 $gw.EnableHttp2 = $true
 Set-AzureRmApplicationGateway -ApplicationGateway $gw


text:
Q: How would I find values in a file, but only on lines that don't start with #? I've got a document that looks something like this:
# Document ID 8934
# Last updated 2018-05-06
52 84 12 70 23 2 7 20 1 5
4 2 7 81 32 98 2 0 77 6
(..and so on..)

In other words, it starts off with a few comment lines, then the rest of the document is just a bunch of numbers separated by spaces.
I'm trying to write a regex that gets all digits on all lines that don't start with #, but I can't seem to get it.
I've read over answers such as

*

*Regular Expressions: Is there an AND operator?

*Regex: Find a character anywhere in a document but only on lines that begin with a specific word
and pawed through sites such as http://regular-expressions.info, but I still can't get an expression that works (the best I can get is a lengthy version of ^[^#].*
So how can I match digits (or text, or whatever) in a string, but only on lines that don't start with a certain character?

A: Your regex ^[^#].* uses a negated character class which matches  not a # from the start of the string ^ and after that matches any character zero or more times.
This would for example also match t test
What you might do is use an alternation to match a whole line ^#.*$ that starts with a # or capture in a group one or more digits (\d+)
Your digits are captured group 1. You could change the (\d+) to for example a character class ([\w+.]+) to match more than only digits.
(?:^#.*$|(\d+))
Details

*

*(?: Non capturing group

*

*^#.*$ Match from the start of the line ^ a # followed by any character zero or more times .* until the end of the string $

*| Or

*(\d+) capture one or more digits in a group

*) Close non capturing group

A: I think a way simpler method would be to replace the lines with "" first with this regex:
^#.*

And then you can just match all the numbers with this:
-?\d+ (-? is for negative)


text:
Q: How combine two SASS files in one CSS file via laravel mix? How to correct combine multiple scss files in one css file?
My current configuration webpack.mix.js
mix.sass(
[
    'resources/assets/sass/one.scss',
    'resources/assets/sass/two.scss',
], 'public/css/style.css');

But it does not work.
I try first first mix.combined scss files, then mix.sass ...
But after 'npm run watch' i got looped crazy CLI.

A: Instead of combining them through mix, import the stylesheets you need together in SCSS: https://sass-lang.com/guide#topic-5
If you want to keep them separate, make a new stylesheet that just imports the needed styles.


text:
Q: log in into two different applications which are merge in one with one log in details I am using Yii framework, and have one Data Base for my web application,
and i have one data base for Mibew messenger (webim chat), so I have two different databases.
I have one log in page for administrator page, and chat messenger have it's own log in page,
what I want to do is when i log in with my administrator details (which are in Yii web app database) to be automatically log in Mibew messenger.
I use this messenger inside my application.
Any suggestion how can I fix this problem,
Sorry if my question confused you, I don't know how to ask it correctly :)
Thank you very much,
Cheers.

A: Only have one database containing the login details, and connect to that database with the other application just for the login details. Or build a login API for one of the applications to use.


text:
Q: Nested lightning aura iteration I have a nested aura:iteration like this:
<aura:iteration items="{!v.results}" var="res">

        <aura:iteration items="{!v.ColumnsNameArr}" var="colName">

                    {!res[colName]}}

        </aura:iteration>

</aura:iteration>

How can I write correct {!res[colName]}? It is possible to do something like this in lightning?

A: It looks like you want to iterate the res property, what looks like to me of type Map. In Lightning Aura it's not possible to iterate over a Map (Apex) / Object (Javascript).
What you can do as solution would be to transform the res Map to a type of Array (Javascript) or in Apex to type of a List.
In Lightning Aura it is possible to iterate Array's.
So how would that look like:

{
  process: function() {
    var res = { a: 1, b: 2};
    var resArray = [];

    for (var key in res) {
      resArray.push({
        key: key,
        value: res[key]
      });
    }

    // now, from here on you can use the 'resArray' to iterate in your Aura component

  }
}

A: It is possible. Use the iteration variable at the next level down.
I think this will work...
<aura:iteration items="{!v.results}" var="res">

    <aura:iteration items="{!res.ColumnsNameArr}" var="colName">

                {!colName}}

    </aura:iteration>


text:
Q: A nim-game variant Suppose a bucket contains n balls. In each turn one removes some balls k from the basket. If first player removes even-number balls then second player must removes odd-number of balls and vice-versa. The winner is who plays the last turn and makes the bucket empty. The game is tie when it is impossible to make the bucket empty.
Assume both players play optimally. Here optimally means a player plays in a way so that the opponent player does not win.
0

A: Hint:  think first about what happens when $n$ is odd.  The strategy is rather simple then.  There is no reason that $n$ is limited to small numbers.  You can compute the winner in one line.


text:
Q: HTTP-GET request of Angular API call not working I'm using Angular Web-UI to control a backend application (serving on a localhost in my case) to perform some specific tasks, but it seems like the GET requests are being cached.
When i send the request independently using a browser window (or Postman), it will request the server (every time).
However, when the query is fired from Angular, it shows a 200 response status (browser > networks) but the server only sometimes recieves it.
Original Code :
this.http.get(`request_path`).subscribe((data: any) => {
    callback()
})

For imformation, the server will always run on same PC as the browser. Hostname will always be localhost in this case.
Thanks


text:
Q: SQLite database not updating I have a SpatiaLite database that I need to update from a shapefile.
I have successfully created a dictionary querying the shapefile and I've printed on my console statements like:
UPDATE POLE SET MSLHEIGHT2=69.496 WHERE CAB="PC1H64";

UPDATE POLE SET MSLHEIGHT2=68.138 WHERE CAB="Q19EB8";

UPDATE POLE SET MSLHEIGHT2=68.069 WHERE CAB="Q26V98";

If I execute these statements on spatialite_gui (one by one) they update correctly the SQLite database, but my Python script, run from ArcMap Python window (load script), is not updating the height fields as they remain null.
import sqlite3
import arcpy
import os

dicCAB_Height = {}
with arcpy.da.SearchCursor(SelectedLayer, ("CAB","MSLHEIGHT")) as rows:
    for row in rows:
        CAB = row[0].upper()
        Height = row[1]
        dicCAB_Height[CAB] = Height
arcpy.AddMessage("Dictionary created for " + str(len(dicCAB_Height)) + " CABs")

con = sqlite3.connect(sqlitePath)
cur = con.cursor()

#pragmaOff_SQL = "PRAGMA foreign_keys = OFF"
#cur.execute(pragmaOff_SQL)

for keys, value in dicCAB_Height.items():
    updateSQL = 'UPDATE POLE SET MSLHEIGHT2=' + str(dicCAB_Height[keys]) + ' WHERE CAB="' + str(keys) + '";'
    cur.execute(updateSQL)
    con.commit()
con.commit()

#pragmaOn_SQL = "PRAGMA foreign_keys = ON"
#cur.execute(pragmaOn_SQL)

I am using ArcGIS Desktop 10.6.1, Python 2.7.14, SpatiaLite 4.1.1 SQLite 3.7.17.
I have seen another similar question but in that case it was the absence of commit
The error I am getting is the following:
Traceback (most recent call last):
  File "<string>", line 142, in <module>
OperationalError: no such function: GeometryConstraints

The line 142 is the line with 'cur.execute(updateSQL)'
NOTE: I have tried with and without the ;


text:
Q: Rules for equation involving addition and subtraction of logarithms Given these two examples from my math course:
Example A:
$$\log(50) + \log(x/2) = 2 \implies \log 25x = 2 \implies 25x = 10^2 \implies x = 4.$$
Example B:
$$\log(72) - \log(2x/3) = 0 \!\implies\! \log(72) = \log(2x/3) \!\implies\! 72 = 2x/3 \!\implies\! 216 = 2x \!\implies \!108 = x$$
My question: Why in Example B, we move $-\log(2x/3)$ over to the other side instead of using the Quotient Property? On the other hand, in Example A we didn't move $\log(x/2)$ to the other side but used the product property instead.
Attempt:
In Example A, if we move $\log(x/2)$ to the other side, we have
$$\log(50) + \log(x/2) = 2 \implies \log(50) = -\log(x/2) +2.$$
Now we could raise everything to a common base of $10$ to cancel out the logarithms. So we are left with the following
$$50 = -(x/2) + 100.$$
Now we subtract 100 from each side to get
$$-50 = -(x/2) \implies -50 = -(x/2) \implies 100 = 4$$
But as shown in the example $x = 4$.
Why this didn't work?

A: When you raise the RHS $-\log x/2 + 2$ as the exponent using base 10, you get $10^{-\log x/2 + 2}=10^{-\log x/2}×10^2$ which is $100×(10^{\log x})^{-1/2}=100×(x)^{-1/2}$ The LHS is 50 so $(x)^{-1/2}=1/2$. There is easier way but following your approach. The mistake was when exponentiating, the addition of 2 needed to turn into multiplication by 100.

A: \begin{eqnarray}
\log(50)&=& -\log(x/2) +2\\
\log(50)&=&\log(2/x)+2\\
50&=&\frac{2}{x}\cdot10^2
\end{eqnarray}
So $x=\frac{200}{50}=4$

A: What you did in the  first example was simply not correct. I think I can understand what you meant though, so let's go through the problem using your way.
$$\log (50)+\log \big(\frac{x}{2}\big) = 2$$
$$\log (50) = 2-\log \big(\frac{x}{2}\big)$$
We can rewrite $2$ as a logarithm using base $10$. Use the definition of logs.
$$a^x = y \longleftrightarrow \log_a y = x$$
$$10^2 = 100 \longleftrightarrow \log_{10} 100 = 2$$
So, we can use $\log (100)$ instead of $2$.
$$\log (50) = \log (100)-\log \big(\frac{x}{2}\big)$$
Use the Quotient Rule.
$$\log (50) = \log \biggr(\frac{100}{\frac{x}{2}}\biggr)$$
$$\log (50) = \log \big(\frac{100(2)}{x}\big) \implies \log (50) = \log \big(\frac{200}{x}\big)$$
$$50 = \frac{200}{x} \implies x = \frac{200}{50}$$
$$\boxed{x = 4}$$
In the second example, you could have used the Quotient Rule.
$$\log (72)-\log \big(\frac{2x}{3}\big) = 0$$
$$\log \biggr(\frac{72}{\frac{2x}{3}}\biggr) = 0 \implies \log \big(\frac{72(3)}{2x}\big) = 0 \implies \log \big(\frac{108}{x}\big) = 0$$
Now, use the definition of logarithms.
$$\log_b x = y\longleftrightarrow b^y = x$$
$$\log \big(\frac{108}{x}\big) = 0 \longleftrightarrow 10^0 = \frac{108}{x}$$
$$1 = \frac{108}{x}$$
$$\boxed {x = \frac{108}{1} = 108}$$
As you can see, in both cases, we get the right answer, but they take longer. You have to get used to understanding which ways are "better" than others depending on the type of question.


text:
Q: Attach deposit in near cli I want to call transfer function using near cli.
But this command does not work:
near call $ID transfer '{"new_owner_id":"amiyarust.testnet", "amount":50}' --accountId amiyatulu.testnet

"transfer" is a payable method requires an attached deposit.
  #[payable]
    pub fn transfer(&mut self, new_owner_id: AccountId, amount: U128) {
        // NOTE: New owner's Account ID checked in transfer_from.
        // Storage fees are also refunded in transfer_from.
        self.transfer_from(env::predecessor_account_id(), new_owner_id, amount);
    }

The near call command gives following error:
panic_msg: "panicked at 'The required attached deposit is 38600000000000000000000, but the given attached deposit is is 0', src/avrit.rs:1026:13"

I already questioned a similar problem here, but unable to find a working solution or code.

A: If you want to attach deposit to a call, it should be done as a command-line argument, i.e, the call should look like
near call $ID transfer '{"new_owner_id":"amiyarust.testnet", "amount":50}' --accountId amiyatulu.testnet --amount 50

The amount argument you have in your contract method does not bear any significance in regards to attached tokens.


text:
Q: How should one deal with "The following package disappeared from your system..."? On dpkg-/apt-based systems, it is possible to encounter a message such as the following:
The following package disappeared from your system as
all files have been overwritten by other packages:
  qfdevelopment_metapkg
Note: This is done automatically and on purpose by dpkg.

What does this even mean?  How should we deal with it?
In this case, qfdevelopment_metapkg is an apt package that contains only dependencies in order to install the necessary packages prior to performing development for the qf project.  I had installed the package (originally) using:
sudo dpkg -i qfdevelopment_metapkg-0.3.8-Linux.deb
sudo apt install -f

I am eager to know how others deal with this, since I don't understand the workaround that I fumbled through (which I'll list if it does not come up in answers).

A: Why we should care: this issue manifests when a sudo apt-get upgrade helpfully offers that autoremove will remove all of the just added packages - because the package that depends on them was removed.
Workaround
It seems that this results from the package not installing anything.  I solved the problem by adding a trivial script that I install into the bin directory:
INSTALL(PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR}/list_qf_dev_info DESTINATION bin)

The contents of this list_qf_dev_info script are just:
#! /bin/sh

apt-cache show qfdevelopment_metapkg

Now, after installing, the presence of this script causes the apt/deb system to keep the package instead of automatically causing it to disappear.
Alternate workaround - without editing deb
A different workaround - that does not require modifying the deb - is to just install again at the end to get things squared away:
sudo dpkg -i qfdevelopment_metapkg-0.3.8-Linux.deb
sudo apt install -f
sudo dpkg -i qfdevelopment_metapkg-0.3.8-Linux.deb

PS
I had forgotten about this issue as I had worked unrelated items.  Today I was running into the issue again and was briefly excited to see somebody had asked before realizing it's my question and that there were no answers, so I had to fumble through it myself.


text:
Q: if $a \in \mathbb{Q}(2^{1/2},2^{1/4},2^{1/8},...)$ if $a \in \mathbb{Q}(2^{1/2},2^{1/4},2^{1/8},...)$ then why does it mean that $a$ can be expressed as a finite many different roots of $2$?

A: The key is to think about how you define something like $\mathbb{Q}(2^{1/2},2^{1/4},\ldots)$.
Defining that is sort of like defining $K[x_1,x_2,x_3,\ldots]$. Even though you've adjoined infinitely many variables, what does an element of $K[x_1,x_2,x_3,\ldots]$ look like? Well, it's a polynomial ring, so every element is a polynomial in arbitrarily many (but finitely so) variables (and with only finitely many terms!)
After all, $x_1 + x_2 + x_3 + x_4 + \cdots$ is not a polynomial.
The same is true for adjoining algebraic elements to a field, since after all the way you define a field extension of $K$ is by taking $K[x]/f(x)$, where $f(x)$ is an irreducible. Thus, your field is (by definition):
$$\mathbb{Q}[x_1,x_2,x_3,x_4,\ldots]/(x_1^2-2,x_2^4-2,x_3^8-2,x_4^{16}-2,\ldots)$$
Where modding out by the ideal $(x_1^2-2,x_2^4-2,x_3^8-2,x_4^{16}-2,\ldots)$ means that you should treat each $x_i$ as $\sqrt[2^i]{2}$.

A: Your field can be represented as a sequence of successive quadratic extensions $$\mathbb Q\subset\mathbb Q(\sqrt2)\subset\mathbb Q(\sqrt[4]2)\subset\mathbb Q(\sqrt[8]2)\subset\cdots\subset\mathbb Q(\sqrt[2^i]2)\cdots$$ from which you can see that $a$ given, necessarily there is a suitable $2^i$ so the element $a$ belongs to the subfield $\mathbb Q(\sqrt[2^i]2$) of finite degree.
Which is interesting to mention is that  this field is the only one where all construction with ruler and compass  is feasible. For instance the classic impossible problem of the trisection of the angle gives place to a cubic field (because of  the formula for third of the angle) which is not a subfield of your field.
Edit: I understand the downvote: I referred to the kind of field and number 2 obviously does not interfere in what I meant. It  was a distraction for me, it's true.


text:
Q: Executing a simple window.open script from the server I have a dynamically created menu which I have a menuItemClick event tied in.  In this event I want to execute a simple window.open script that uses the clicked items' url.  The reason I need to do this is I need to set the parameters of the window opening (i.e.  no scroll bars, no toolbars, etc...).
My question is, is there a way simply create a string of the script to be executed and then actually execute it?
So far I have:
string script = "window.open('" + e.Item.NavigateUrl + "' ,'_MAIN_WINDOW','width='+ screen.width + '-60,height=' + screen.height + '-500,left=' + screen.left + '-30,top=' + screen.top + '-30,screenx=0,screeny=0,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,copyhistory=no, resizable=yes')";

But I have no idea how to then execute this script.

A: You can put the window.open (...) code inside a javascript function called onButtonClick (item) and emit it with RegisterStartupScript () just as bdukes suggested, then in the aspx code for the page you can add an eventHandler like
Dummy item

Then when you click on the item, onButtonClick will be called with the clicked item as parameter.

A: You'll want to use Page.ClientScript.RegisterStartupScript (or ScriptManager.RegisterStartupScript if you need it to run after a partial postback).

A: Override the OnPreRender event of the page.
Inside there you make:
protected override void OnPreRender(EventArgs e)
{
  base.OnPreRender(e);

  foreach (MenuItem item in m1.Items)  // m1 is the menu in my case :)
  {
    item.Target = string.Format("window.open('{0}');", item.NavigateUrl);
  }
}


text:
Q: Android link .so for command line executable? I am developing a cross-platform library, and am trying to test on Android. I have compiled my library with ndk-build, and am trying to compile and run a command-line test fixture we have for the library.
I use adb push to put the test fixture and .so in /data/local/tmp and chmod both to 777.
Then I use adb shell to run the test, but get the following error
shell@android:/data/local/tmp $ ./mytest
./mytest
link_image[1936]:  7289 could not load needed library 'libtconfig.so' for './mytest' (load_library[1091]: Library 'libtconfig.so' not found)CANNOT LINK EXECUTABLE

Both mytest executable and libtconfig.so are in the same directory. I would have assumed it looks in "." directory first?

A: I found I can add the path /data/local/tmp to LD_LIBRARY_PATH and it will work, however when using adb shell commands in a script, each "adb shell" is a new instance, so LD_LIBRARY_PATH is reset


text:
Q: How to select a dropdown element on page load in AngularJs I have a page with a dropdown. When I call this page passing a parameter in query string, I want to load all the options using an API call, and then select the option related to the query string parameter (like ?country=5). This is the template:
<div ng-controller="MyCtrl" ng-init="loadPage()">
  <select
    id="country"
    ng-model="country"
    ng-change="changeCountry(country)"
    ng-options="option.name for option in countryOptions track by option.id">
  </select>
</div>

and this is the controller
$scope. loadPage = () => {
  const params = new URL(location.href).searchParams;
  const country = params.get('country'); // country is an int

  Countries.query({},
    function (res) {
      $scope.countryOptions = res; // THIS WORKS, The dropdown is populated with all options
      $scope.country = $scope.countryOptions.filter(c => [parseInt(country)].indexOf(c.id) > -1);// <- THIS DOES NOT WORK
    },
    function (err) {
      console.log('err');
      console.log(err);
  });

The select is populated correctly but I can't get the option I want selected. Any idea what is going on?
I alreay tried
$scope.object = {country: $scope.country};

with no luck.


text:
Q: SettingWitchCopyWarning Pandas using .ix I am looping through my dataframe using all samples but one in order to make a prediction for the one left out, which I want to do for all samples (I have a small dataset.
The loop I am currently using is the following.
   for i in range(0, length_df):
         np.delete(indices, i)
         baseline.fit(df.ix[indices, feature_labels], df.ix[indices, label_to_predict])
         df.ix[i,'prediction'] = baseline.predict(df.ix[left_out_index, feature_labels])
         np.add(indices,i)

I am getting the following two warnings from Pandas:
DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17
and willraise ValueError in 0.19.
Reshape your data either using X.reshape(-1, 1) if your data has a
single feature or X.reshape(1, -1) if it contains a single sample.
DeprecationWarning)

SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

I thought using .ix() made sure one doesn't make incorrect copies. Should I ignore these warnings? And a related question, is there perhaps a more efficient way to do this in Pandas?
Note: As of Pandas v0.20, .ix indexer is deprecated in favour of .iloc / .loc.


text:
Q: Extending FormControlDirective in Angular 2+ I'm looking at this question, trying to figure out how to extend FormControlDirective: Attempting to extend FormControlDirective to implement my own FormControl directive results in faulty binding.
There is an answer, but I'm not sure what is meant by:

The formControl \ formControlName selectors appear in one more
  place - the value
  accessor.
  In order your directive to work you should implement all default value
  accessors for the hybridFormControl directive ( following the
  pattern for the built-in directives).

Here is my code:
export const formControlBinding: any = {
  provide: NgControl,
  useExisting: forwardRef(() => ControlDirective)
};

@Directive({
  selector: '[appControl]',
  providers: [formControlBinding],
  exportAs: 'ngForm'
})
export class ControlDirective extends FormControlDirective implements OnInit {

  constructor(
    @Optional() @Self() @Inject(NG_VALIDATORS) validators: Array<Validator|ValidatorFn>,
    @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: Array<AsyncValidator|AsyncValidatorFn>,
    @Optional() @Self() @Inject(NG_VALUE_ACCESSOR) valueAccessors: ControlValueAccessor[],
    public renderer: Renderer2,
    public hostElement: ElementRef,
  ) {
    super(validators, asyncValidators, valueAccessors);
  }

  @Input() set appControl(form: FormControl) {
    console.log(form);
    this.form = form;
  }
}

It is very similar to @ronif's Plunker from his question. set appControl does run, even though I'm passing a value like <input type="text" class="form-control" appControl="firstName">, and FormControlDirective._rawValidators seems to always be an empty array, even though the FormGroup works with the standard FormControlDirective.
How would I go about 'implementing all default value accessors'?

A: In case anyone else runs into something like this, here is the solution I came up with. I wanted to dynamically create a form control model from the child form control element. This is so I didn't have to write an initial model with tons of form control fields while still getting the benefit of the reactive forms model. This is how to extend the FormControlName class:
@Directive({
  selector: '[hybridFormControl]'
})
class HybridFormControl Directive extends FormControlName implements ControlValueAccessor, OnChanges {
  @Input('hybridFormControl') name: string;

  onChange;
  onTouched;

  constructor(
      @Optional() protected formGroupDirective: FormGroupDirective,
      @Optional() @Self() @Inject(NG_VALUE_ACCESSOR) valueAccessors: ControlValueAccessor[],
      private fb: FormBuilder,
      private renderer: Renderer2,
      private element: ElementRef
  ) {
    super(formGroupDirective, [], [], valueAccessors, null);
    this.valueAccessor = this;
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (!this._registered) {
      // dynamically create the form control model on the form group model.
      this.formGroup = this.formGroupDirective.form;
      this.formGroup.registerControl(name, this.fb.control(''));
      this._registered = true;
    }

    // IMPORTANT - this ties your extended form control to the form control
    // model on the form group model that we just created above. Take a look
    // at Angular github source code.
    super.ngOnChanges(changes);
  }

  @HostListener('input', ['$event.target.value'])
  @HostListener('change', ['$event.target.value'])
  onInput(value): void {
    this.onChange(modelValue);
  }

  writeValue(value): void {
    const element = this.element.nativeElement;
    this.renderer.setProperty(element, 'value', value);
  }

  registerOnChange(fn): void {
    this.onChange = fn;
  }

  registerOnTouched(fn): void {
    this.onTouched = fn;
  }
}

And you would use this new hybrid directive like:
@Component({
  selector: 'app',
  template: `
    <form formGroup=[formGroup]>
      <input type="text" hybridFormControl="myName">
    </form>
  `
class AppComponent {
  formGroup: FormGroup

  constructor(fb: FormBuilder) {
    this.form = this.fb.group({});
  }
}

You will need to modify this.formGroup.registerControl(name, this.fb.control('')); line of code if you want to pass validators. I haven't verified this, but hopefully this helps someone else who runs across this question.
Sources: https://github.com/angular/angular/blob/master/packages/forms/src/directives/reactive_directives/form_control_name.ts#L212


text:
Q: plpgsql - syntax error at or near "if" I'm struggling to get the syntax correct for a plpgsql if statement.
I'd like to use a different where clause depending on the value of the m2 argument to the function.
But I get ERROR:  syntax error at or near "if"
create or replace function some_func(m1 int, m2 int)
returns table(match_id int) as
$$
begin
  return query
  select m.match_id from match as m
  if m2 < 1 then  -- ERROR:  syntax error at or near "if"
    where m.match_id > m1;
  else
    where m.match_id > m1 and m.match_id < m2;
  end if;
end;
$$ language 'plpgsql';

The documentation says I should do
39.6.2.2. IF-THEN-ELSE

IF boolean-expression THEN
    statements
ELSE
    statements
END IF;

But it seems I've done that, so I must be misunderstanding some other aspect of how plpgsql works.

A: You need a case statement there, rather than an if statement. For reference only, since it's a terrible query, it should look more like this:
return query
select m.match_id from match as m
 where case
       when m2 < 1 then m.match_id > m1
       else             m.match_id > m1 and m.match_id < m2
       end;

In your case just rewrite the query without the case:
return query
select m.match_id from match as m
 where m.match_id > m1
   and (m2 < 1 or m.match_id < m2);