text:
Q: How to not reuse UITableViewCell and keep cells in memory after they disappear from the view? I have a "not so big" dynamic tableView with a number of rows that can vary between 10 and 20.
I used Storyboard and created 4 different cell prototypes which all have their own identifier. Most of these cells have UITextFields in them and the user will enter information such as e-mail adresses etc...
I use dequeueReusableCellWithIdentifier: in tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) to create my cells.

However whenever I scroll my tableView I can see that the appearing cells get the data from upper cells, because cells that disappear are enqueued for reuse.
Given the fact that I have a limited number of cells, I would like to get rid of the reusing feature and just have my set of cells with their own data inside. When I scroll down I see cells that correspond to the lower cells, and when I go back up I see again my upper cells.
How can I do that?
and how can I then create a cell that corresponds to a prototype from the storyboard without using dequeueReusableCellWithIdentifier: ?

I have already searched among similar question here in StackOverflow and tried to keep an array of my cells and just return the correct element if it already exists from tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) but nothing worked so far

A: You are overthinking this a bit. If you think about what dequeueReusableCellWithIdentifier: does, it just grabs a cell that it finds with that specific identifier. If you want every row to have it's own unique cell that is not used by any other row, just give each row it's own identifier. The simplest way would be to just to stringify the indexPath row, or both the row+section if you have multiple sections.
Something like this should do it:
let cellIdentifier = String(indexPath.section) + "-" + String(indexPath.row)

A: In these cases I will typically create what would be the content of the table view cell in its own view controller or custom view, something like "SignupFormViewController", and store that as a property on the view controller that is managing your table view.  In your case this could also be multiple view controllers of this type in several properties or an array.  Then dequeue your cells as normal but treat them as dumb containers to which the view controllers' views are added as subviews.  Then you'll just to have tie up all the loose ends—removing the view from the cell when the cell dequeued, not adding a view if the identical view is already a child of the cell, constraints to match cell size, etc.


text:
Q: How can I convert CSS BoxShadow to Flutter BoxShadow? I need to convert CSS BoxShadow to Flutter BoxShadow Here is the code:
box-shadow: 10px 10px 21px -8px #b6c6d4, -3px -4px 6px rgba(255, 255, 255, 0.5);

How does this should look on Flutter ?

A: Container(
          decoration: BoxDecoration(
            boxShadow: [
              BoxShadow(
                color: Color(0xFFB6C6D4);,
                spreadRadius: -8,
                blurRadius: 21.0,
                offset: Offset(10, 10),
              ),
              BoxShadow(
                color: Color.fromRGBO(255, 255, 255, 0.5),
                blurRadius: 6,
                offset: Offset(-3, -4),
              )
            ],
...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Vagrant Puppet cannot find my vagrant node I have configured my vm.hostname to "vagrant-development".
My puppet is supposed to look for a vagrant node name "vagrant-development".
I am new to puppet and vagrant. But have been through this doc http://docs.vagrantup.com/v2/provisioning/puppet_agent.html and have a configured Vagrantfile.
I don't understand why do I keep running into
debug: Executing '/usr/bin/perl /usr/local/abc/components/kvagrant/bin/enc.pl    /vagrant/.enc/vagrant-development vagrant-development'
debug: Empty response for vagrant-development from exec terminus
Could not run: Could not find node vagrant-development

How do I make puppet find the vagrant node?


text:
Q: Diagonals of a Hexagon The diagonals of a hexagon each bisect its area. Prove that the difference of the square of the lengths of alternating edges is zero.
I tried to use the shoelace theorem but it become a bit too messy???


text:
Q: Curl(curl(A)) with Einstein Summation Notation (subscript & superscript !) I am a rookie so I hope you know the answer!
Okay so from C. Möller and Landau & Lifshitz I have gathered that:
$$
\gamma_{ij}=g_{ij}-\frac{g_{0i}g_{0j}}{g_{00}} \quad \gamma^{ij}\gamma_{jk}=\delta^i_k\quad \gamma^{ij}=g^{ij}\quad\gamma = \textbf{det}(\gamma_{ab}) = \frac{1}{\textbf{det}(\gamma^{ab})}\\
\epsilon_{ijk} = \epsilon^{ijk}=\left\{\begin{array}{ll}
1 & \text{if } (i,j,k) \text{ is an even permutation of } (1,2,3) \\
-1 &\text{if } (i,j,k) \text{ is an odd permutation of } (1,2,3) \\
0 & \text{otherwise}
\end{array}\right.\\
\varepsilon_{ijk}=\sqrt{\gamma}\epsilon_{ijk}\quad \varepsilon^{ijk}=\frac{1}{\sqrt{\gamma}}\epsilon^{ijk}\\
[\textbf{curl}(\textbf{v})]^{i}=\varepsilon^{ijk} v_{k,j}=\frac{1}{2}\varepsilon^{ijk}(v_{k,j}-v_{j,k})\quad\textbf{div}(\textbf{v})=\frac{1}{\sqrt{\gamma}}[\sqrt{\gamma} v^i]_{,i}
$$
Can you similarly define
$$
[\mathbf{curl}(\mathbf{\tilde{v}})]_i =\varepsilon_{ijk}v^{k,j}
$$
And thereafter
$$
[\mathbf{curl}\circ\mathbf{curl}(\mathbf{\tilde{v}})]^a=\varepsilon^{abc} [\varepsilon_{cde}v^{e,d}]_{,b}\\
[\mathbf{curl}\circ\mathbf{curl}(\mathbf{v})]_a=\varepsilon_{abc} [\varepsilon^{cde}v_{e,d}]^{,b}
$$
And if so, what is the partial derivative of $\sqrt{\gamma}$ and $\frac{1}{\sqrt{\gamma}}$? Is it valid to reexpress the equations above as
$$
[\mathbf{curl}\circ\mathbf{curl}(\mathbf{\tilde{v}})]^a=\varepsilon^{abc} \varepsilon_{cde}v^{e,d}_{\quad,b}\\
[\mathbf{curl}\circ\mathbf{curl}(\mathbf{v})]_a=\varepsilon_{abc} \varepsilon^{cde}v_{e,d}^{\quad,b}
$$
or is that wrong? Realized a commaderivative upstairs is not defined. Would it be expressed with codifferential somehow?
(http://en.wikipedia.org/wiki/Ricci_calculus#Raised_and_lowered_indices for summation convention)

A: I would answer to your question by collecting some facts on the structures you introduce above.
- A typo
The relations
$$\epsilon_{ijk}=\sqrt{\gamma}\epsilon_{ijk}, $$
$$\epsilon^{ijk}=\frac{1}{\sqrt{\gamma}}\epsilon^{ijk}, $$
are not true, unless $\sqrt{\gamma}=1$.
- On curl on $v=v_ie_i$.
The curl operator on vectors $v=v_ie_i$ in $\mathbb R^3$ gives the vector
$$\left(\operatorname{curl}(v)\right)_i=\epsilon_{ijk}\partial_jv_k; $$
such $\operatorname{curl}(v)$ is equal to your $\boldsymbol{\operatorname{curl}}(v)$ as $\epsilon_{ijk}=\epsilon^{ijk}$. Then
$$\boldsymbol{\operatorname{curl}}\left(\boldsymbol{\operatorname{curl}}(v)\right)_i=\operatorname{curl}(\left(\operatorname{curl}(v)\right)_i=\epsilon_{ijk}\partial_j
(\epsilon_{krs}\partial_rv_s)=
\epsilon_{ijk}\epsilon_{krs}\partial_j
\partial_rv_s; $$
using the relations
$$\epsilon_{ijk}\epsilon_{krs}=\epsilon_{kij}\epsilon_{krs}=\delta_{ir}\delta_{js}-\delta_{is}\delta_{jr},$$
one arrives at
$$\operatorname{curl}(\left(\operatorname{curl}(v)\right)_i=
(\delta_{ir}\delta_{js}-\delta_{is}\delta_{jr})\partial_j
\partial_rv_s=\partial_s\partial_iv_s-\sum_r\partial^2_rv_i,  $$
or
$$\boldsymbol{\operatorname{curl}}(v)=\nabla(\operatorname{div}(v))-\nabla^2(v)$$
- On curl on $\tilde{v}=v^ie_i$.
The curl operator on vectors $v=v^ie_i$ in $\mathbb R^3$, where
$$v^i=g^{in}v_n, $$
is the vector
$$\left(\boldsymbol{\operatorname{curl}}(\tilde{v})\right)_i=\epsilon_{ijk}\partial_j(g^{kn}v_n); $$
then
$$\boldsymbol{\operatorname{curl}}\left(\boldsymbol{\operatorname{curl}}(\tilde{v})\right)_i=\epsilon_{ijk}\partial_j
(\epsilon_{krs}\partial_r(g^{rq}v_q))=
\epsilon_{ijk}\epsilon_{krs}\partial_j
(\partial_rg^{rq}v_q+g^{rq}\partial_rv_q). $$
Using once again the relations $$\epsilon_{ijk}\epsilon_{krs}=\delta_{ir}\delta_{js}-\delta_{is}\delta_{jr}$$ you can arrive at the result you are looking for.


text:
Q: How to write a SQL statement? I would like to know the SQL statement to cover the following problem.I have some problem in here.
SupplierID  ContractStart   ContractEnd

20          1/1/2010        1/3/2010
24          12/12/2008      12/1/2009
31          13/1/2008       13/2/2008
20          13/1/2008       13/2/2008
24          11/11/2007      11/12/2010
31          12/12/2008      1/1/2009

Please identify the Supplier ID that overlapping contract in this table.

A: If your table is t, this should do it:
select a.supplierid, b.supplierid
from t a, t b
where ((b.contractstart<a.contractend and b.contractend>a.contractend)
    or (a.contractstart<b.contractstart and a.contractend>b.contractstart))
    and a.supplierid<b.supplierid -- strict so you don't get doubles

Edit: This is assuming your duplicate ID's are typos.

A: SELECT a.sid
FROM contracts a, contracts b
WHERE a.sid == b.sid
AND a.start < b.start
AND a.end > b.start;

A: If you are looking to identify overlap by supplier id this should work:
FYI I used mm/dd/yyyy
declare @contract table ( SupplierID int, ContractStart datetime, ContractEnd datetime)

insert into @contract
select 20, '1/1/2010', '3/1/2010'
union all
select 24 , '12/12/2008', '1/12/2009'
union all
select 31, '1/13/2008 ', '2/13/2008'
union all
select 20, '1/13/2008', '2/13/2008'
union all
select 24, '11/11/2007 ', '12/11/2010'
union all
select 31, '12/12/2008 ', '1/1/2009'

SELECT a.supplierid,
       a.contractstart,
       a.contractend,
       b.contractstart,
       b.contractend
FROM   @Contract a
       INNER JOIN @Contract b
         ON b.supplierid = a.supplierid
WHERE  ( b.contractstart < a.contractend )
       AND ( b.contractend > a.contractstart )
       AND ( b.contractstart != a.contractstart --Ignore overlap with self
             AND b.contractend != a.contractend )
       AND b.contractstart > a.contractstart -- No Duplicates


text:
Q: Prove that series $ \sum^{+\infty}_{n=0}a_n(x-x_0)^n $ and $ \sum^{+\infty}_{n=0}(n+1)a_{n+1}(x-x_0)^n $ have the same radius of convergence. I want to prove that these two power series
$$
\sum^{+\infty}_{n=0}a_n(x-x_0)^n
$$
and
$$
\sum^{+\infty}_{n=0}(n+1)a_{n+1}(x-x_0)^n
$$
have the same radius of convergence.

What I've done so far is:

*

*I replace $(x-x_0)$ with $y$ to make calculations easier.

*In order to find the radius I use the Cauchy's criterion (Root test):
1:
$$
\lim_{n \to \infty}\sqrt[n]{a_ny^n} < 1\\
y\lim_{n \to \infty}\sqrt[n]{a_n} < 1\ \ \ (*)\\
$$
2:
$$
\lim_{n \to \infty}(\sqrt[n]{(n+1)a_{n+1}y^n}) < 1\\
y\lim_{n \to \infty}(\sqrt[n]{n+1})\lim_{n \to \infty}(\sqrt[n]{a_{n+1}}) < 1\\
y\lim_{n \to \infty}(\sqrt[n]{a_{n+1}}) < 1 \ \ \ (**)
$$

*I haven't found the radius, but if I take the limit of $(*)$ and $(**)$ as $n \to \infty$ then $(*)$ and $(**)$ should be equal.

Is my reasoning correct? Can we actually get a formula for the radius?

A: Yes, you can apply the formula of the radius of convergence. Your solution is essentially correct. Here is a more direct way to present it.
Given the series
$$
S_1(x)= \sum^{+\infty}_{n=0}a_n(x-x_0)^n
$$
its radius of convergence $\rho_1$ is
$$\frac{1}{\rho_1} = \limsup_{n \to \infty}  \sqrt[n]{\vert a_n  \vert}$$
Given the series
$$
S_2(x)= \sum^{+\infty}_{n=0}(n+1)a_{n+1}(x-x_0)^n
$$
then, its radius of convergence $\rho_2$ is
$$\frac{1}{\rho_2} = \limsup_{n \to \infty}  \sqrt[n]{(n+1)\vert a_{n+1}  \vert}$$
Now, since we know $\lim_{n \to \infty}\sqrt[n]{n+1}=1$, we have
$$\frac{1}{\rho_2} = \limsup_{n \to \infty}  \sqrt[n]{(n+1)\vert a_{n+1}  \vert}=(\lim_{n \to \infty}\sqrt[n]{n+1})\limsup_{n \to \infty}  \sqrt[n]{\vert a_{n+1}  \vert}=\limsup_{n \to \infty}  \sqrt[n]{\vert a_n  \vert}=\frac{1}{\rho_1}$$
So we have $\rho_1=\rho_2$.

A: Regarding the last question on whether or not one can get a formula, the Cauchy--Hadamard theorem says that the radius of convergence $R$ of $\sum_{n=0}^\infty a_n (x-x_0)^n$ satisfies $$\frac{1}{R} = \limsup_{n \to \infty} \lvert a_n \rvert^{1/n},$$
where the possibilities $0$ and $\infty$ are treated in the natural way.

A: Your solution seems to be reasonable, however I believe that there is an easier way to prove the statement.

Note that the second series is, actually, a derivative of the first.
Indeed, denote
$F(x) = \sum^{+\infty}_{n=0}a_n(x-x_0)^n$ and
$G(x) = \sum^{+\infty}_{n=0}(n+1) a_{n+1}(x-x_0)^n$.
Take derivative of $F$:
$$
F'(x) = \left(\sum^{+\infty}_{n=0}a_n(x-x_0)^n\right)' =
\left(a_0 + \sum^{+\infty}_{n=1}a_n(x-x_0)^n\right)' =
\sum^{+\infty}_{n=1}na_n (x-x_0)^{n-1}
$$
Let us shift summation index by $-1$ by making change of variables $m = n-1$.
Then we get
$$
F'(x) =  \sum^{+\infty}_{n=1}na_n (x-x_0)^{n-1}
= \sum^{+\infty}_{m=0}(m+1)a_{m+1} (x-x_0)^{m}
$$
Without Loss of generality, we can re-lable $m$ back to $n$, thus getting
$$
F'(x) = \sum^{+\infty}_{n=0}(n+1)a_{n+1} (x-x_0)^{n} = G(x)
$$
As we know, differentiation and integration does not change radius of convergence of power series.
Thus,  the radius of convergence of $F$ and $G$ is the same.
Q.E.D.


text: Q: qgis2web - layers are not shown I want to export my project with qgis2web. In the Export-Dialogue, the layers that should be visible are activated, but not shown in the preview screen, just the zoom-in and zoom-out sign. Also after exporting the map is shown, but has no content. Any hints?


text:
Q: Java Inheritance: Child class not executing I was practicing inheritance in Java, and faced the following issue:
Code for parent class:
public class FEB7 {
    String address,name;
    void get(String n, String a){
        name = n;
        address = a;
    }

    void show(){
        System.out.println("name is "+name);
        System.out.println("address is " + address);
    }

    public static void main(String args[]) {
        // compile time poly is method overloading, we will look at runtime poly
        FEB7 obj = new FEB7();
        obj.get("name1","address1");
        obj.show();
    }
}

Code for child class:
public class FEB8 extends FEB7 {
    String regno;

    void get(String r) {
        regno = r;
    }

    void showreg() {
        System.out.println("regno is " + regno);
    }

    public static void main(String args) {
        FEB8 obj1 = new FEB8();
        obj1.get("name2", "address2");
        obj1.get("regno1");
        obj1.show();
        obj1.showreg();
    }
}

Both are separate .java files. When I try to execute the parent class file, it works, but for some reason I cannot even run the child class. The following message is there:

The file FEB8.java is not executable. please select a main class you
want to run

How do I solve this issue?

A: The main method in FEB8 has String args as the argument instead of String args[]. Change it to args[] and try again.


text:
Q: Verb tense after stated expectation In the following sentence:

The newspaper expects its editors to check the facts.

What is the grammatical role of "to check"? Why can it not be replaced by "checking"? I thought they were both verbs. How does the verb "expects" modify what verb "check"?


text:
Q: jQuery ajaxSuccess and ajaxError behavior The global events ajaxSuccess and ajaxError are not working properly for me. I disconnected my Internet connection and ajaxSuccess handler executes with xhr.status=0, and ajaxError is not executing at all. I need you to confirm if this is bug or am I doing something wrong?
Thanks!

A: It is a bug, a 0 being "successful" was originally added because Opera returns a 304 as a 0, or at least used to, you can see it in a comment in the jQuery core code here.
However if you look at the main branch, you'll see this status == 0 exception has been removed for the jQuery 1.5 release, so it's already fixed and you'll see this fix in 1.5.


text:
Q: Dictionary from a String with particular structure I am using python 3 to read this file and convert it to a dictionary.
I have this string from a file and I would like to know how could be possible to create a dictionary from it.
[User]
Date=10/26/2003
Time=09:01:01 AM
User=teodor
UserText=Max Cor
UserTextUnicode=392039n9dj90j32

[System]
Type=Absolute
Dnumber=QS236
Software=1.1.1.2
BuildNr=0923875
Source=LAM
Column=OWKD

[Build]
StageX=12345
Spotter=2
ApertureX=0.0098743
ApertureY=0.2431899
ShiftXYZ=-4.234809e-002

[Text]
Text=Here is the Text files
DataBaseNumber=The database number is 918723

..... (There are more than 1000 lines per file) ...
On the text I have "Name=Something" and then I would like to convert it as follows:
{'Date':'10/26/2003',
'Time':'09:01:01 AM'
'User':'teodor'
'UserText':'Max Cor'
'UserTextUnicode':'392039n9dj90j32'.......}

The word between [ ] can be removed, like [User], [System], [Build], [Text], etc...
In some fields there is only the first part of the string:
[Colors]
Red=
Blue=
Yellow=
DarkBlue=

A: What you have is an ordinary properties file. You can use this example to read the values into map:
try (InputStream input = new FileInputStream("your_file_path")) {
    Properties prop = new Properties();
    prop.load(input);

    // prop.getProperty("User") == "teodor"

} catch (IOException ex) {
  ex.printStackTrace();
}

EDIT:
For Python solution, refer to the answerred question.
You can use configparser to read .ini, or .properties files (format you have).
import configparser

config = configparser.ConfigParser()
config.read('your_file_path')

# config['User'] == {'Date': '10/26/2003', 'Time': '09:01:01 AM'...}
# config['User']['User'] == 'teodor'
# config['System'] == {'Type': 'Abosulte', ...}

A: I would suggest to do some cleaning to get rid of the [] lines.
After that you can split those lines by the "=" separator and then convert it to a dictionary.

A: Can easily be done in python. Assuming your file is named test.txt.
This will also work for lines with nothing after the = as well as lines with multiple =.
d = {}
with open('test.txt', 'r') as f:
    for line in f:
        line = line.strip() # Remove any space or newline characters
        parts = line.split('=') # Split around the `=`
        if len(parts) > 1:
            d[parts[0]] = ''.join(parts[1:])
print(d)

Output:
{
  "Date": "10/26/2003",
  "Time": "09:01:01 AM",
  "User": "teodor",
  "UserText": "Max Cor",
  "UserTextUnicode": "392039n9dj90j32",
  "Type": "Absolute",
  "Dnumber": "QS236",
  "Software": "1.1.1.2",
  "BuildNr": "0923875",
  "Source": "LAM",
  "Column": "OWKD",
  "StageX": "12345",
  "Spotter": "2",
  "ApertureX": "0.0098743",
  "ApertureY": "0.2431899",
  "ShiftXYZ": "-4.234809e-002",
  "Text": "Here is the Text files",
  "DataBaseNumber": "The database number is 918723"
}


text:
Q: Averages for each row in my dataframe by a condition and put on a new dataframe I have the following data frame:
    I  UserID | Day_of_week | hour | min | sms
   #1    1           1          0     0      12
   #2    1           1          0     30     20
   #3    1           1          1     0      19
   #4    1           1          1     30     11
   #5    1           1          2     0      12
   #6    1           1          2     30     7
   ...   ...         ...       ...    ...   ....
   #10    1          2          0     0      142
   #11    1          2          0     30     201
   #12    1          2          1     0      129
   #13    1          2          1     30     111
   ...   ...         ...       ...    ...   ....

The column Day_of_week goes from 0 to 6 where

*

*(1 = Monday, 2 = Tuesday .... 5 = Friday)

*0, 6 are Saturday and Sunday respectively.

The column  hour ranges from 0 to 23.
I wanted to create the same date frame where I added days of the week (Monday through Friday) and weekends (Saturday and Sunday) with their respective averages for each hour and minute.
I want something like this: the average of all (Monday, Tuesday, ... Friday) at 0 hours and 0 min  was 12.1.
x- represent days of week
y- represent weekends
    I  UserID | Day_of_week | hour | min | sms
   #1    1           x          0     0      12.1
   #2    1           x          0     30     19.1
   #3    1           x          1     0      14
   #4    1           x          1     30     11
   ...   ...         ...       ...    ...   ....
   #10    1          y          0     0      1123
   #11    1          y          0     30     23
   #12    1          y          1     0      45
   #13    1          y          1     30     121
   ...   ...         ...       ...    ...   ....

A: Sample data:
# Read and expand the dataset with some weekend days
df = read.table(text='I  UserID  Day_of_week  hour  min  velocity
1    1           1          0     0      12
2    1           1          0     30     20
3    1           1          1     0      19
4    1           1          1     30     11
5    1           1          2     0      12
6    1           1          2     30     7
10    1          2          0     0      142
11    1          2          0     30     201
12    1          2          1     0      129
13    1          2          1     30     111',header=T)
df2 = df %>% mutate(Day_of_week=7)
df = rbind(df,df2)

You could use dplyr  and do the following:
library(dplyr)
df %>% mutate(daytype = ifelse(Day_of_week %in% seq(1,5),'weekday','weekend')) %>%
  group_by(UserID,daytype,hour,min) %>%
  summarize(velocity=mean(velocity))

Alternative with data.table:
library(data.table)
setDT(df)[,daytype := ifelse(Day_of_week %in% seq(1,5),'weekday','weekend')][,.(velocity=mean(velocity)),.(UserID,daytype,hour,min)]

or with base R:
df$daytype = ifelse(df$Day_of_week %in% seq(1,5),'weekday','weekend')
aggregate(velocity~UserID+daytype+hour+min,df,FUN='mean')

Output:
    UserID daytype hour min velocity
 1:      1 weekday    0   0     77.0
 2:      1 weekday    0  30    110.5
 3:      1 weekday    1   0     74.0
 4:      1 weekday    1  30     61.0
 5:      1 weekday    2   0     12.0
 6:      1 weekday    2  30      7.0
 7:      1 weekend    0   0     77.0
 8:      1 weekend    0  30    110.5
 9:      1 weekend    1   0     74.0
10:      1 weekend    1  30     61.0
11:      1 weekend    2   0     12.0
12:      1 weekend    2  30      7.0


text:
Q: Lucene Document Container with Null Fields I have a desktop application that
 implements the lucene 3.6.2 search engine
 for database search.
 The database contains columns
  with both date and char data types
. Some columns can also contain null fields.
  Datetools is also used to convert Date to
String for analysis by Lucene
 However looks like when lucene is not
able to add null fields from the
 date columns to the Document container
for analysis.
I present code snippets below:
 doc = new Document();

         if(rs.getDate("DATE_OF_LETTER")== null)
         { doc.add(new Field("date_of_letter","",Field.Store.YES,Field.Index.ANALYZED)); }
         else {
        doc.add(new Field("date_of_letter",DateTools.dateToString(rs.getDate("DATE_OF_LETTER"),
                DateTools.Resolution.DAY),Field.Store.YES,Field.Index.ANALYZED));
         }

        if(rs.getDate("DATE_RECEIVED")== null)
         { doc.add(new Field("date_received","",Field.Store.YES,Field.Index.ANALYZED)); }
        else {
          doc.add(new Field("date_received",DateTools.dateToString(rs.getDate("DATE_RECEIVED"),
                DateTools.Resolution.DAY),Field.Store.YES,Field.Index.ANALYZED));
        }

         if(rs.getString("REMARKS")== null)
         { doc.add(new Field("remarks","",Field.Store.YES,Field.Index.ANALYZED)); }
         else {
         doc.add(new Field("remarks",rs.getString("REMARKS"),Field.Store.YES,Field.Index.ANALYZED));  }

          if(rs.getDate("DATE_DISPATCHED")== null)
         { doc.add(new Field("date_dispatched","",Field.Store.YES,Field.Index.ANALYZED)); }
         else {
        doc.add(new Field("date_dispatched",DateTools.dateToString(rs.getDate("DATE_DISPATCHED"),
                DateTools.Resolution.MINUTE),Field.Store.YES,Field.Index.ANALYZED));

                }
           }
         iw.addDocument(doc);
         }

   }

any suggestion.

A: This line:
doc.add(new Field("date_received","",Field.Store.YES,Field.Index.ANALYZED));

Doesn't really do anything.  There is nothing to index.  It might store the field (I'm not sure, right off), but it certainly won't be indexed in any way, and so won't be searchable.  Lucene indexes tokens, and an empty string has no tokens, and so there is nothing to index, nothing to search with.
If you wish to be able to search for nulls, you should index a placeholder value for them, such as;
doc.add(new Field("date_received","null",Field.Store.YES,Field.Index.ANALYZED));


text:
Q: Creating a user-defined function with SQL::Statement::Functions in Perl creates a syntax error I am trying to work with UDFs, defined through SQL::Statement::Functions in Perl with a mySQL database in the backend. I am playing it by the book, as stated in http://metacpan.org/pod/SQL::Statement::Functions#User-Defined-Functions, however, before I even leave square one, an error in the CREATE FUNCTION statement is rearing its ugly head.
Here's the code first ($dbh is a given and works fine, it is just part of a bigger construct of the framework I am working with, so I don't want to spam my question with all of it; if I replace foo() in the SELECT by 22, or by "_PK FROM locations", all is good and I get a 22 or a value corresponding to the query in Data::Dumper, so, the connection is ok):
use Data::Dumper;
use SQL::Statement::Functions;

sub foo {
    return 999;
}

#$dbh is defined elsewhere
$dbh->do("CREATE FUNCTION foo") or die "error creating function foo(); " . $dbh->errstr;

my $sth = $dbh->prepare("SELECT foo(22)") or die "error preparing query: " . $dbh->errstr;
$sth->execute or die "error executing query: " . $sth->errstr;

my $row = $sth->fetchrow_arrayref();
print "ROW " . Dumper($row);

The error message reads as follows: error creating function foo(); You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1, refering to the $dbh->do("CREATE...") line.
I have tried to dumb the CREATE FUNCTION part down as much as possible, but I also tried it with ...foo EXTERNAL and ...foo EXTERNAL NAME foo as suggested by the manual. Heck, I even created a package for the function, to no avail.
Any ideas what I am doing wrong here?
I checked, and the user I am connected to the database with does have all privileges, including alter_routine_priv and create_routine_priv, if that is what SQL::Statement is using.

A: You are not using the module as it is intended. It's an extension to the SQL::Parser module that is used by DBDs to implement SQL syntax and functions. The documentation states:

This module contains the built-in functions for SQL::Parser and
  SQL::Statement. All of the functions are also available in any DBDs
  that subclass those modules (e.g. DBD::CSV, DBD::DBM, DBD::File,
  DBD::AnyData, DBD::Excel, etc.).

To me, that sounds like it has nothing to do with mysql. The DBD::mysql is used as a wrapper around a real mysql database. It just connects, forwards the queries, prepares them and so on. It does not parse them, however. That's what the database is doing, just like if you were to connect to an Oracle or MSSQL database. In those cases, the driver is like an API wrapper.
On the other hand, DBD::CSV and the others mentioned above are parsing the sql themselves. DBD::CSV opens a CSV file, understands the SQL and (very simply described) translates it into Perl code to look for stuff in the CSV data. The same goes for the others. They use SQL::Parser to make sense of the SQL. SQL::Statement::Functions seems to be the module that provides the equivalent Perl functions for the SQL.

When using SQL::Statement/SQL::Parser directly to parse SQL ...


text:
Q: Run command from iTerm window after another is finished Is there a way to run a command from a split window (2) in iTerm, when the command in window (1) finishes?
I often have use-cases where I want to run one command after another, and would love to have a straightforward way to ad-hoc do that (the scripts are oftentime very different, so not always the same)


text:
Q: SQL Server 2012 Merge Understanding what happens for distinct records with fields not included in ON I have been digging into this for a few hours now and not having much luck finding what should happen in a merge when using a group by to get a distinct set of values is not all inclusive of what is specified in ON.
pat table(Target):
ID (auto incremented and assigned PK)
PAT_Name
Birth_Date
Add_LINE_1
ADD_LINE_2
City
State
Zip
home_phone
mobile_phone
email

ord table (Source):
ID (PK, auto incremented)
PAT_Name
Birth_Date
Add_LINE_1
ADD_LINE_2
City
State
Zip
Pat_home_phone
mobile_phone
email
... additional fields I don't use in target table

Merge statement:
MERGE INTO pat AS TARGET
USING (SELECT PAT_NAME, BIRTH_DATE, ADD_LINE_1, ADD_LINE_2, CITY, STATE, ZIP, PAT_HOME_PHONE, MOBILE_PHONE, EMAIL from Ord GROUP BY PAT_NAME, BIRTH_DATE, ADD_LINE_1, ADD_LINE_2, CITY, STATE, ZIP, PAT_HOME_PHONE, MOBILE_PHONE, EMAIL) AS SOURCE ON TARGET.PAT_NAME = SOURCE.PAT_NAME AND TARGET.ADD_LINE_1 = SOURCE.ADD_LINE_1 AND TARGET.ADD_LINE_2 = SOURCE.ADD_LINE_2 AND TARGET.CITY = SOURCE.CITY AND TARGET.STATE = SOURCE.STATE AND TARGET.ZIP = SOURCE.ZIP
WHEN NOT MATCHED THEN
    INSERT(PAT_NAME, BIRTH_DATE, ADD_LINE_1, ADD_LINE_2, CITY, STATE, ZIP, HOME_PHONE, MOBILE_PHONE, EMAIL)
    VALUES (SOURCE.PAT_NAME, SOURCE.BIRTH_DATE, SOURCE.ADD_LINE_1, SOURCE.ADD_LINE_2, SOURCE.CITY, SOURCE.STATE, SOURCE.ZIP, SOURCE.PAT_HOME_PHONE, SOURCE.MOBILE_PHONE, SOURCE.EMAIL);

As you can see my ON only has name and address fields and not phones and emails.  So what is happening:
My select statement with the group by is producing records that:

*

*Are matched on the address fields but have a different phone in which case are not being inserted (As expected)

*Are not matched in the address field at the time of the query and produce two rows because the address matches but they have two separate phone numbers so both rows are being inserted.  I end up with two rows with the same address fields(The fields in my ON) but with different numbers.

So my question/clarification is does the merge always insert anything that, in this case since I am using when not matched, doesn't match at time of query?  Since my select returned two rows with a new address and differing phone numbers it inserts both.  But if I run the same query again with an existing address and differing phone numbers they won't be inserted.
Or another way to put it?  If the select statement above returned 50 records all with the same address fields in my ON, address not in target, but 50 different phone numbers, would it always insert those 50 records into my target? It would never insert one record with a new address and see those and not insert the rest correct?
I can try to clarify:
EDIT with values:
Source table
Pat_name Add_Line_1 Add_Line_2   CITY   STATE  ZIP   home_phone  mobile_phone   email
Bob S    333 west                Go      CA    99521 555-5503                    bob@gmail.com
Bob S    444 east                Stop    CA    99950 555-5552                    bob@GMAIL.COM
BOB S    444 east                Stop    CA    99950 555-5560                    bob@gmail.com

Target Table:
Pat_name Add_Line_1 Add_Line_2   CITY   STATE  ZIP   home_phone  mobile_phone   email
Bob S    333 west                Go      CA    99521 555-5511                      bob@gmail.com

In this case when run the select will return all 3 rows which.  The first row has a match on the address fields specified in the ON so that will not be inserted even though it has a different phone number.  However, the last two rows will be inserted because when the select statement was run those address fields were not in the target so it inserts all results from the select without a match on the address fields.  It will never stop after the first one is inserted in the target because those address fields are now present correct?

A: you will have to add the pat_home_number and mobile_number numbers to the matching criteria like below. if not like you described members with the same name and different phone number will not be inserted as desired.
MERGE INTO pat AS TARGET
USING (
    SELECT
        PAT_NAME, BIRTH_DATE, ADD_LINE_1, ADD_LINE_2, CITY
        , STATE, ZIP, PAT_HOME_PHONE, MOBILE_PHONE, EMAIL
    FROM Ord
    GROUP BY PAT_NAME, BIRTH_DATE, ADD_LINE_1, ADD_LINE_2,
    CITY, STATE, ZIP, PAT_HOME_PHONE, MOBILE_PHONE, EMAIL
) AS SOURCE

ON TARGET.PAT_NAME = SOURCE.PAT_NAME
AND TARGET.ADD_LINE_1 = SOURCE.ADD_LINE_1
AND TARGET.ADD_LINE_2 = SOURCE.ADD_LINE_2
--ADD these lines
AND TARGET.HOM = SOURCE.PAT_HOME_PHONE
AND TARGET.MOBILE_PHONE = SOURCE.MOBILE_PHONE
--
AND TARGET.CITY = SOURCE.CITY
AND TARGET.STATE = SOURCE.STATE
AND TARGET.ZIP = SOURCE.ZIP
WHEN NOT MATCHED THEN
    INSERT(PAT_NAME, BIRTH_DATE, ADD_LINE_1, ADD_LINE_2, CITY, STATE, ZIP, HOME_PHONE, MOBILE_PHONE, EMAIL)
    VALUES (SOURCE.PAT_NAME, SOURCE.BIRTH_DATE, SOURCE.ADD_LINE_1, SOURCE.ADD_LINE_2, SOURCE.CITY,
    SOURCE.STATE, SOURCE.ZIP, SOURCE.PAT_HOME_PHONE, SOURCE.MOBILE_PHONE, SOURCE.EMAIL);


text:
Q: Javascript Date constructor ignoring parameters Supposedly, I should be able to create an arbitrary date using the Date constructor as demonstrated here and referenced here
Where am I going wrong?  Please notice that on the last few lines of prettyDateToTimeStamp, I modify the month and day to verify that the Date constructor is doing something - but it is not noticing anything I pass in and just returns the current date.
Here is my code below:  and a jsfiddle
<!DOCTYPE html>

Click the button to display the full year of todays date.

todays date.

some other date.

<button onclick="showdates()">Try it</button>

A: omg, I have to say "new" Date ....   (I've been using Python too much lately)
corrected code now works.
   function prettyDateToTimeStamp(prettyDate) {
      var halves = prettyDate.split(' ');
      var calpart = halves[0];
      var clockpart = halves[1];
      var calbits = calpart.split('/');
      var timebits = clockpart.split(':');
      var year = parseInt(calbits[2],10);
      var month = parseInt(calbits[0],10);
      var day = parseInt(calbits[1],10);
      var hour = parseInt(timebits[0],10);
      var min = parseInt(timebits[1],10);
      var sec = parseInt(timebits[2],10);
      month += 3; // change month radically to demonstrate the problem
      day += 7; // change day too
      var ts = new Date(year,month,day,hour,min,sec,0); // you have to use NEW here!
      return ts;
   }


text:
Q: Import Question Newbie question.
If I want to import a new load of products and will it overwrite the existing ones or just add the new ones.
This is a real newbie question but I just want reassurance that I wont delete the 2000 products already on the site.
Thanks
Joe

A: The SKU is used as the identifier,

*

*So if the SKU exists already, it will update the existing product

*If the SKU doesn't exist, it will create a new product


text:
Q: Javascript function not working properly Ok, so i've got the following javascript on my website to countdown timer:

I add a span box like this:
<?php
$time_left = $from_database['time_left']; //timestamp;
?>

<input type="submit" id="unlock_this" <?php if ($time_left - Time() > 0) { echo 'disabled'; } ?> />

The problem is, that when I refresh this page (after $time_left), the 'Done' message is not being displayed and I get a javascript error (document.getElementById = null) which directs back to
else if (trigger_a == "enable" && trigger_b != "") { document.getElementById(trigger_b).disabled = false; }

It's probably just a little thing, but i can't figure out what i've done wrong, so please help.

A: It looks as though the problem is simply that you execute the timer function before the input with the unlock_this id has had a chance to load. I realise you've put a delay in with the setTimeout call of display but have you tried putting the script below the input element?
Or better still calling timer when the whole window has loaded? The easiest way to do the second of these options would be:
window.onload = function () {
    timer("test", "<?php echo $time_left; ?>", "long", "", "", "enable", "unlock_this", "Done");
};

But you are already using the onload property of the window, you will need to load it in a smarter way (either by using a library like JQuery, or by safeguarding existing functions with a wrapper function).

A: I think the problem is that with your html looking like

<input type="submit" id="unlock_this" disabled />

by the time timer(), which calls display(), is called, the input with id "unlock_this" has not yet been parsed and added to the browsers DOM.
You should delay the call to timer() until the browser has finished parsing the document, like so:

Not though that this method will overwrite any previously added window.onload handlers.


text:
Q: Disposing a WCF windows service client inside a WCF web service I have a WCF web service that accesses a WCF windows service on a different machine. The windows service does all the data accessing and passes the results to the web service. I have read several articles about disposing the service client for a WCF service correctly, but I'm not sure what the best way is to do this in a web service. (If this helps, the web service is PerCall not PerSession)
This is all I'm doing right now:
 Public Class Service1
  Implements IService1

  Private p_oWindowsService As DataService.Service1Client

  Public Sub New()
    p_oWindowsService = New DataService.Service1Client
  End Sub

  Public Function GetData(ByVal value As Integer) As String Implements IService1.GetData
    Return p_oWindowsService.GetData(value)
  End Function

  Public Function GetDataUsingDataContract(ByVal composite As CompositeType) As CompositeType Implements IService1.GetDataUsingDataContract
    If composite Is Nothing Then
      Throw New ArgumentNullException("composite")
    End If
    If composite.BoolValue Then
      composite.StringValue &= "Suffix"
    End If
    Return composite
  End Function

I'm not disposing the service client at all right now, from what I've read this is a major issue. The workaround I'm looking at is something like this inside the GetData function:
 Public Function GetData(ByVal value As Integer) As String Implements IService1.GetData
     Using oWindowsService As New DataService.Service1Client
        Return oWindowsService.GetData(value)
     End Using
  End Function

Based off What is the best workaround for the WCF client `using` block issue?, I know I shouldn't actually depend on the using block. But should I be creating and disposing a service client in every function? That's my real question.
Thank you.

A: Yes do not use dispose. Do it like this:
var client = new ...;
try {
   // Do work

   // Everything went well so close the client
   client.Close();
}
catch( Exception ex ) {
   // Something went wrong so call abort
   client.Abort();

   // Other logging code
}

if( client.State != System.ServiceModel.CommunicationState.Closed ) {
   client.Close();
}

Calling Close() on client notifies the service instance that it is no longer in use and may be collected by GC (subject to service instance management).
You may wonder why Abort in the catch block? The reason is:

Given the WCF binding use transport sessions, the client after a fault would not even be able to close it (if there was no transport layer session then the client could use or close the proxy, but this is not recommended as the configuration of sessions could change). So after a fault has happened the only safe operation is to abort a proxy.

See this for more on Abort vs Close.

EDIT
In your comments you asked:

Do you recommend creating and closing a service client like this within every function the web service calls the windows service?

No I don't think that is necessary. Let's see you are calling the WCF service from a web application (ASP MVC), then you would do something like this in the Dispose method of the controller since ClientBase<TChannel> implements ICommunicationObject:
protected override void Dispose(bool disposing) {
     base.Dispose( disposing );

     ServiceHelper.DisposeService( ( this._whateverServiceClient as ICommunicationObject ) );
 }

And here is the ServiceHelper class that you can use from anywhere:
public static class ServiceHelper {

  /// <summary>
  /// Disposes the given service.
  /// </summary>
  /// <param name="service">The service.</param>
  public static void DisposeService(ICommunicationObject service) {

     if( service != null ) {

        bool abort = true;

        try {
           if( service.State == CommunicationState.Opened || service.State == CommunicationState.Opening ) {
              service.Close();
              abort = false;
           }
        }
        finally {

           // Determine if we need to Abort the communication object.
           if( abort )
              service.Abort();
        }
     }
  }

}
The idea would be the same if you were calling it from another client.

A: You don't need to explicitly dispose the client, how ever if you truly must, this is one way of properly closing & disposing your client:
        // use client
        try
        {
            ((IClientChannel)client).Close();
        }
        catch
        {
            ((IClientChannel)client).Abort();
        }
        finally
        {
            ((IDisposable)client).Dispose();
        }


text:
Q: с - warning: negative integer implicitly converted to unsigned type Есть код, позаимствованный из общественного источника. Задача этой функции - дождаться нажатия любой клавиши в терминале Linux и продолжить выполнение. Функция работает замечательно, но при сборке gcc выдаёт предупреждение:
warning: negative integer implicitly converted to unsigned type [-Wsign-conversion]
  ttynew.c_lflag &= ~(ICANON | ECHO); /* disable canonical mode */

И даже clang выдаёт свой warning:
warning: implicit conversion changes signedness: 'int' to 'unsigned int' [-Wsign-conversion]
        ttynew.c_lflag &= ~(ICANON | ECHO);
                   ~~ ^~~~~~~~~~~~~~~~

Анализ источников проблемы не прояснил ситуации:
termbits.h:
struct termios {
    ...
    tcflag_t c_lflag;    /* local mode flags */
    ...
};

typedef unsigned int tcflag_t;

#define ICANON 0000002
#define ECHO 0000010

И на старых gcc, и на новых ситуация идентична. Это баг в стандартных библиотеках или ЧЯДНТ?
/**
 * @brief Wait for a while when any key will be pressed
 */
char press_any_key(void){

    // Return result
    char ch = 0;

    // save old terminal attributes
    struct termios ttyold,ttynew;
    /* get current terminal attirbutes; 0 is the file descriptor for stdin */
    if (tcgetattr(0, &ttynew) != 0)
    {
        fprintf(stderr, "Failed getting terminal attributes\n");
        exit(EXIT_FAILURE);
    }
    ttyold = ttynew;

    ttynew.c_lflag &= ~(ICANON | ECHO); /* disable line buffering and feedback */
     /* set immediately */
    tcsetattr(0, TCSANOW, &ttynew);

    // Press any key there
    if (scanf("%c",&ch) != 1) {
        fprintf(stderr, "scanf() error\n");
    }

    // Return old settings
    if (tcsetattr(0, TCSANOW, &ttyold) != 0)
    {
        fprintf(stderr, "Failed getting terminal attributes\n");
        exit(EXIT_FAILURE);
    }

    return(ch);
}

EDIT:
Правильный код после правок. Спасибо @AnT и @sanmai!
/**
 * @brief Wait for a while when any key will be pressed
 * @details When you read from stdin (with getchar(), or
 * any other way), it will return characters immediately,
 * without waiting for a Return/Enter. In addition, backspace
 * will no longer 'work' -- instead of erasing the last character,
 * you'll read an actual backspace character in the input.
 * Also, you'll want to make sure to restore canonical mode before your
 * program exits, or the non-canonical handling may cause odd effects
 * with your shell.
 *
 */
char press_any_key(void){

    // Return result
    char ch = 0;

    // save old terminal attributes
    struct termios ttyold,ttynew;
    /* get current terminal attirbutes; 0 is the file descriptor for stdin */
    if (tcgetattr(0, &ttynew) != 0)
    {
        fprintf(stderr, "Failed getting terminal attributes\n");
        exit(EXIT_FAILURE);
    }
    ttyold = ttynew;

    // Cast to tcflag_t because there is the error without it:
    // warning: negative integer implicitly converted to unsigned type [-Wsign-conversion]
    // .c_lflag &= ~(ICANON | ECHO); /* disable canonical mode */
    // warning: implicit conversion changes signedness: 'int' to 'unsigned int' [-Wsign-conversion]
    // .c_lflag &= ~(ICANON | ECHO);
    //      ~~ ^~~~~~~~~~~~~~~~
    ttynew.c_lflag &= ~((tcflag_t) ICANON | (tcflag_t) ECHO); /* disable line buffering and feedback */
     /* set immediately */
    tcsetattr(0, TCSANOW, &ttynew);

    // Press any key there
    if (scanf("%c",&ch) != 1) {
        fprintf(stderr, "scanf() error\n");
    }

    // Return old settings
    if (tcsetattr(0, TCSANOW, &ttyold) != 0)
    {
        fprintf(stderr, "Failed getting terminal attributes\n");
        exit(EXIT_FAILURE);
    }

    return(ch);
}

A: Компилятор не выдает сообщение об ошибке. Компилятор выдает предупреждение. В данном случае это то предупреждение, которое и на самом деле является просто предупреждением, а не "ошибкой, которую gcc решил не считать ошибкой". То есть код формально корректен с точки зрения языка С.
Константы ICANON и ECHO - восьмеричные константы типа int. Результат операции ICANON | ECHO имеет тип int и положительное значение. Результат применения ~ к ICANON | ECHO имеет тип int и отрицательное значение.
Затем это отрицательное значение участвует в операции &= с операндом типа unsigned int. В такой ситуации по правилам языка С "побеждает" беззнаковый тип, т.е. вышеупомянутое значение типа int будет неявно преобразовано к типу unsigned int. Таким образом у вас имеет место неявное преобразование отрицательного значения к типу unsigned int. Об этом вас и предупреждает компилятор, на всякий случай. Формальной ошибки в таком неявном преобразовании нет - оно разрешено и четко определено правилами языка.
В данном случае на платформе с дополнительным кодом ничего страшного не произойдет и все будет работать "как надо", ибо преобразование int -> unsigned int на такой платформе чисто концептуально и битового представления числа не меняет.
Но во избежание предупреждения не мешало бы избавиться от знаковых типов в битовых операциях и везде использовать беззнаковые типы
#define ICANON 0000002u
#define ECHO 0000010u

A: Это и баг, и фича.

*

*Фича - потому что язык C делает такую конверсию за вас. Потому такие предупреждения не показываются по умолчанию.

*Баг - потому что разработчики библиотеки не подумали явно указать что их константы - без знака. Значит, компилятору приходится приводить типы.
Короче, с этим предупреждением по-хорошему вы должны ничего делать кроме как отключить показ таких предупреждений вообще.
Но если вы хотите любой ценой его убрать, то это можно сделать явным приведением типа:
ttynew.c_lflag &= (unsigned int) ~(ICANON | ECHO);

Предупреждение при компиляции пропадёт.

A: Из опубликованных тут решений, оба решения имеют проблемы:

*

*В случае изменения библиотеки, вам придется поддерживать ее самому до скончания веков. В данном случае termbits.h:

*В случае, если просто "прикастить" нужный тип, то это убирает варнинг только для текущей реализации. В будущем тип может измениться и варнинг вернется (хотя на практике этого навернка не будет).


text:
Q: Opmap Based Linear regulator I am designing an opamp based linear regulator for educational purpose.Please find the attached image.

I know that due to negative feedback voltage at the both terminals of the opamp will be same and is equal to Vref .Here it is 1.25V and Vout=Vref(1+R2/R1) and I obtained the proper 2.5V at output.
Now I removed the refernce and Vin(5V) is directly connected to Opamps non inverting terminal.

At this time the output obtained is 5V only as per the equation it shoud be 10V.May I know why
I am not getting 10V at output.Please tell me where I went wrong in understanding the circuit.

A:
May I know why I am not getting 10V at output.

You are not getting anything higher than 5 volts at the output because although the op-amp is powered from a positive supply of 15 volts, its output is clamped by the now forward biased base-collector region of Q1. See below and the little diode symbol I've added in red; it will limit U1's output to about 5.7 volts and, of course, that becomes about 5 volts at the emitter because both PN junctions in Q1 are forward biased: -

If you disconnected the collector from the circuit you should then see 10 volts at the output but, it's not much of a power regulator like this of course. If the 5 volts at the input (Vin) were sourced from a bridge rectifier (as per many supplies) then the bridge rectifier would get reversed biased due to the action of the red diode and the op-amp output would be able to lift the collector voltage with the outcome being that emitter would become 10 volts and hit the regulation target.

A: If I understand correctly, \$V_{IN}\$ is 5V. \$V_{OUT}\$ will never be more than \$V_{IN}\$ in your circuit.

A: For the second circuit, change the input V4 to 6 V.  The output probably will go to 6 V.  this is not because the circuit is functioning at unity bain.  It is because the circuit output is saturated.
To see what is going on, delete U2 and replace it with a 1.2K resistor to GND. Leave R3 in place.  Now the opamp input is approx 1 V, and the output should go to 2 V.


text:
Q: Generalization of Killing form I am reading Knapp's book "Lie groups beyond introduction". On page 369, he has described the following. Let $\mathfrak g$ be a real semisimple Lie algebra. Suppose $\theta\colon\mathfrak g\to \mathfrak g$ is a Cartan involution. Let $B$ be a nondegenerate symmetric bilinear form on $\mathfrak g$ which is $\theta $-invariant and $B_\theta(X,Y):=-B(X,\theta Y)$ is positive definite. Let $\mathfrak g=\mathfrak k\oplus\mathfrak p$ be the Cartan decomposition of $\mathfrak g$ where $\mathfrak k$ and $\mathfrak p$ are eigenspaces of $\theta$ corresponding to eigenvalues $1$ and $-1$ respectively. Then clearly, $\mathfrak k\oplus i\mathfrak p$ is a compact real form of $\mathfrak g^{\mathbb C}$ (complexification of $\mathfrak g).$ Hence $B$ is negative definite on a maximal abelian subspace of $\mathfrak k\oplus i\mathfrak p$. I understood up to this point. Now Knapp argues that from above one can conclude that for any Cartan subalgebra of $\mathfrak g^{\mathbb C}$, $B$ is positive definite on the real subspace where all the roots are real valued. I do not understand how to get this. However, if $B$ is in particular the Cartan-Killing form then I can check by hand that this claim holds. Can someone please help me out?

A: According to theorem 2.15, all Cartan subalgebras of a complex semi-simple Lie algebras are conjugated. I.e. there exists $\alpha \in \mathrm{Inn}(\mathfrak{g})$ such that $\mathfrak{h}_1 = \alpha(\mathfrak{h}_2).$ Since any invariant form $B$ is also invariant with respect to the group of inner automorphisms (sorry, I don't know if or where Knapp proves this), it follows that any positivity property is preserved for corresponding real forms of all Cartan subalgebras.


text:
Q: Access VBA cascade methods How can I cascade methods for a custom class?
What I am working on is a custom class to work with dates.
I feed the class a date as a property. Then I would like to return the date based on the method associated. For example:
InputDate.AdjustToFirst

So if I input 5/15/2015 the above would return 5/1/2015.
Likewise could I do:
InputDate.AdjustToFirst.ReduceOneYear

so if input 5/15/2015 the return would be 5/1/2014.
Further
InputDate.ReduceOneYear

5/15/2015 would return 5/15/2014.
I know about DateSerial, I am just trying to learn how to do the above. The idea is similar to VBs variable.ToString method.

A: You can have the function simply return a new object (method chaining as mentioned by Fred Wilson already). Here a small example of a class I called MyDate:
Private m_date As Date

Public Sub Init(ByVal d As Date)
m_date = d
End Sub

Public Function ToString() As String
ToString = m_date
End Function

Public Function AddYear(y As Integer) As MyDate
Dim newDate As MyDate
Set newDate = New MyDate
newDate.Init (DateAdd("yyyy", y, m_date))
Set AddYear = newDate
End Function

Public Function AddMonth(m As Integer) As MyDate
Dim newDate As MyDate
Set newDate = New MyDate
newDate.Init (DateAdd("m", m, m_date))
Set AddMonth = newDate
End Function

Now you can use AddYear and AddMonth as a chain function:
Dim d As MyDate
Set d = New MyDate
d.Init (Now)
MsgBox d.AddYear(2).AddMonth(4).ToString()


text:
Q: How to change code from fragment to activity I am new to android and have faced some problem, I am making a StudentArraylist to view the student from my firebase database to show them in ListView. But I face some problem because the code I have now I meant for fragment but not activity and
Here is my error
This is the ViewStudentActivity
    StudentArrayList adapter = new StudentArrayList(getActivity(),studentList);
            studentlist.setAdapter(adapter);

*This is the StudentArrayList:
public StudentArrayList(Activity context, List<Student>studentList){
super(context, R.layout.student_list, studentList);
this.context = context;
this.studentList = studentList;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull
ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();

View listViewItem = inflater.inflate(R.layout.student_list, null, true);
s_sid = (TextView)listViewItem.findViewById(R.id.txtSid);
s_name = (TextView)listViewItem.findViewById(R.id.txtName);
s_email = (TextView)listViewItem.findViewById(R.id.txtEmail);
s_fyp = (TextView)listViewItem.findViewById(R.id.s_fyp);
btnUpdate = (Button) listViewItem.findViewById(R.id.btnUpdate);
firebaseDatabase = FirebaseDatabase.getInstance();
pdatabaseReference  = firebaseDatabase.getReference();
auth = FirebaseAuth.getInstance();

final Student student = studentList.get(position);

s_sid.setText("Student ID : " + student.gets_sid());
s_name.setText("Student Name : " +student.gets_name());
s_email.setText("Date : " +student.gets_email());
s_fyp.setText("Time Start : " +student.gets_fyp());

return listViewItem;

}


text:
Q: Nearby using Long/Lat SQL Server 2008 I have a table called Places, every record in this table have its longitude and latitude.
I want to search on this table to find the places near by specific long and lat (Assume the radius of the nearby circle is 25 KM)

A: As you have a given distance to limit your search, your question is a little different with question those ask to find nearest points (without limitation). I have invented two formula which simplifies the distance calculation to degrees difference. These formula is just fitting the earth shape not any other spherical shape:
The following one shows how many Kilometers is surrounded in 1 degree of Longitude around a given latitude:
LongDistanceFactor = − 0.0114 * (lat)^2 − 0.2396(lat) + 112.57

and the second one shows how many kilometers is surrounded in 1 degree of latitude around a given latitude:
LatDistanceFactor = 0.0139(lat) + 110.51

So for given 25Km around the (lat,lng) you just need to find points which their lat is between lat ± (25/LatDistanceFactor) and long between lng ± (25/LongDistanceFactor)
Edit: As I am using ± for both Lat and Lng, the target area would be a square with length of 50Km for each side. If you insist on a circular area, you may make a scond round calculation on first series of result with real formula of points distance and omit those are not in your circle.


text:
Q: Improve countdown.lua in OBS to change scenes when timer complete I figured out how to add and populate a dropdown of scenes in countdown.lua, and I see where to put the code that would switch scenes.  How do I changes scenes in OBS using lua?  The dropdown with the chosen destination scene is called next_scene.
function set_time_text()
    ...
    if cur_seconds < 1 then
        --# BJS goto scene stored in field "next_scene"
    end
...
function script_properties
...
    local t = obs.obs_properties_add_list(props, "next_scene", "Next Scene", obs.OBS_COMBO_TYPE_EDITABLE, obs.OBS_COMBO_FORMAT_STRING)
    local scenes = obs.obs_frontend_get_scene_names()
    if scenes ~= nil then
        for _, scene in ipairs(scenes) do
            obs.obs_property_list_add_string(t, scene, scene)
        end
    end

A: function set_time_text()
        ....
        if cur_seconds < 1 then
        if next_scene ~= "" and next_scene ~= "-----" then
            local source = obs.obs_get_source_by_name(next_scene)
            obs.obs_source_release(source)
            obs.obs_frontend_set_current_scene(source)
        else
            text = stop_text
        end
    end


text:
Q: Flot Series label undefined Im struggling to get my pie chart to show the correct label, rather than "undefined".
In my console log, the labels are there, and the amounts are being shown.
[ { label: "Opened", data: 5}, { label: "Qualified", data: 6}, { label: "Closed", data: 1}, { label: "Pending", data: 2},];

This is made from an $.each function that receives the data from an ajax query.
I have the below script creating the graph:
var dataOut = "[";
$.each(value, function(item2, val2){
    dataOut = dataOut + ' { label: "' + val2[0] + '", data: ' + val2[1] + '},';
});
dataOut = dataOut + "];";

var placeholder = $("#graph_myleads");

$.plot(placeholder, dataOut, {
    series: {
        pie: {
            show: true,
            radius: 3/4,
            label: {
                show: true,
                radius: 3/4,
                formatter: _labelFormatter,
                background: {
                    opacity: 0.5,
                    color: '#000'
                }
            }
        }
    },
    legend: {
        show: false
    }
});

and the below formatter for the label:
var _labelFormatter = function(label, series) {
    return "
" + series.label + "
" + Math.round(series.percent) + "%
";
};

The code is currently outputting this:

Any help on this one would be appreciated :)

A: Output label instead of series.label.
var _labelFormatter = function(label, series) {
    console.log(dataOut);
    return "
" + label + "
" + Math.round(series.percent) + "%
";
};

A: You have your data as array (which is what flot needs) but then you build a string from that and try to give that to flot. Just change the $.each loop to build an array.
var dataOut = [];
$.each(data, function (item2, val2) {
    dataOut.push( { label: val2[0], data: val2[1] });
});

$.plot(placeholder, dataOut, { ... });

See this fiddle for the working code.


text:
Q: How to capture output from Beanshell I've been using BeanShell to interpret simple files that just do some calculations and then output to the console. Thing is, I want to grab the output. Such that from System.out.println("test"); I can get "test" as a string to put somewhere else.
I've looked at Interpreter.getOut(), but I haven't managed to understand what it's actually for (the documentation isn't that useful). I tried grabbing the PrintStream using getOut() and then printing its contents, but it is empty. I also tried the following after messing around:
Interpreter i = new Interpreter();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
i.setOut(ps);
i.eval("System.out.println(\"test\");");
String out = baos.toString();

But that is also empty.

A: Interpreter i = new Interpreter();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);

System.setOut(ps);

try {
  //i.eval("System.out.println(\"test\");");
  i.source("c:\\htdocs\\test.bsh");
} catch (Exception e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

String out = "hello : "+baos.toString();
System.err.println(out);


text:
Q: Avoid window opening between two screens I am writing a Photoshop plugin for Windows and want to place the plugin dialog in the center of the main window.
This is my code:
void centre_window(HWND hwnd){
    RECT rs, rd;
    HWND hw = GetParent(hwnd); // GetDesktopWindow();
    if (GetWindowRect(hw, &rs) && GetWindowRect(hwnd, &rd))
        MoveWindow(hwnd,(rs.right + rs.left + rd.left - rd.right) / 2,
                  (rs.bottom + rs.top + rd.top - rd.bottom) / 3,
                  rd.right - rd.left, rd.bottom - rd.top, TRUE);
}

So far, it works. But there is one flaw: If the main window is spread across two screens, then my window is between both screens.
I looked at other Photoshop plugins and they handle it like this:

*

*Place the window at the main window center

*If it would be between two screens, choose one of these two and place it at the border of the screen

How can I do that?

A: With the helpful hint of @IInspectable , I wrote following code:
void _doMonitorAdjustments(LPRECT rcPlugin) {
    RECT rcMonitorWork;
    HMONITOR hMonitor;
    MONITORINFO grMonitorInfo = { sizeof(grMonitorInfo) };
    int nXAdjust = 0, nYAdjust = 0, nPluginWidth, nPluginHeight, nMonitorWorkWidth, nMonitorWorkHeight;

    hMonitor = MonitorFromRect(rcPlugin, MONITOR_DEFAULTTONEAREST);
    if (hMonitor == NULL) return;

    if (!GetMonitorInfoA(hMonitor, &grMonitorInfo)) return;
    rcMonitorWork = grMonitorInfo.rcWork;

    // Don't let the window exit the left/right borders of the monitor
    nPluginWidth = rcPlugin->right - rcPlugin->left;
    nMonitorWorkWidth = rcMonitorWork.right - rcMonitorWork.left;
    if (nPluginWidth > nMonitorWorkWidth) {
        // Window larger than screen width. Decrease the width!
        rcPlugin->left = rcMonitorWork.left;
        rcPlugin->right = rcMonitorWork.right;
    }
    else if (rcPlugin->left < rcMonitorWork.left) {
        nXAdjust = rcMonitorWork.left - rcPlugin->left;
    }
    else if (rcPlugin->right > rcMonitorWork.right) {
        nXAdjust = rcMonitorWork.right  - rcPlugin->right;
    }

    // Don't let the window exit the top/bottom borders of the monitor
    nPluginHeight = rcPlugin->bottom - rcPlugin->top;
    nMonitorWorkHeight = rcMonitorWork.bottom - rcMonitorWork.top;
    if (nPluginHeight > nMonitorWorkHeight) {
        // Window larger than screen height. Decrease the height!
        rcPlugin->top = rcMonitorWork.top;
        rcPlugin->bottom = rcMonitorWork.bottom;
    }
    else if (rcPlugin->top < rcMonitorWork.top) {
        nYAdjust = rcMonitorWork.top - rcPlugin->top;
    }
    else if (rcPlugin->bottom > rcMonitorWork.bottom) {
        nYAdjust = rcMonitorWork.bottom - rcPlugin->bottom;
    }

    OffsetRect(rcPlugin, nXAdjust, nYAdjust);
}

/*
* Centers a window to the center of its parent form but avoids
* being spread across two screens.
*/
void centre_window(HWND hwnd) {
    RECT rcParent, rcWindowOriginal, rcPlugin;
    HWND hParent;

    hParent = GetParent(hwnd);
    if (hParent == NULL) hParent = GetDesktopWindow();

    if (!GetWindowRect(hParent, &rcParent)) return;
    if (!GetWindowRect(hwnd, &rcWindowOriginal)) return;

    rcPlugin.left =
        rcParent.left
        + (rcParent.right - rcParent.left) / 2
        - (rcWindowOriginal.right - rcWindowOriginal.left) / 2;
    rcPlugin.top =
        rcParent.top
        + (rcParent.bottom - rcParent.top) / 2
        - (rcWindowOriginal.bottom - rcWindowOriginal.top) / 2;
    rcPlugin.right =
        rcPlugin.left + rcWindowOriginal.right - rcWindowOriginal.left;
    rcPlugin.bottom =
        rcPlugin.top + rcWindowOriginal.bottom - rcWindowOriginal.top;

    // Avoid that the window is spread across two screens
    _doMonitorAdjustments(&rcPlugin);

    MoveWindow(hwnd,
        rcPlugin.left,
        rcPlugin.top,
        /*width=*/rcPlugin.right - rcPlugin.left,
        /*height=*/rcPlugin.bottom - rcPlugin.top,
        TRUE);
}


text:
Q: Load animations easily I'm programming an app that has several UIImage animations in different views. Now i'm using this line of code to load all the images:
[UIImage    imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"10001.png" ofType:nil]],
[UIImage    imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"10002.png" ofType:nil]],
[UIImage    imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"10003.png" ofType:nil]],
[UIImage    imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"10004.png" ofType:nil]],
[UIImage    imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"10005.png" ofType:nil]],

and load all the 100 images like this.
And then, on the second view, I load it like these:
[UIImage    imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"20001.png" ofType:nil]],
[UIImage    imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"20002.png" ofType:nil]],
[UIImage    imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"20003.png" ofType:nil]],
[UIImage    imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"20004.png" ofType:nil]],
[UIImage    imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"20005.png" ofType:nil]],

and again load the 100 images.
Is there any way to load all the images but only putting the name of the image one time? What I would like is to, for example, put the first 2 numbers (10) and then load the rest of the images automatically. Is it possible in Xcode? Thanks!

A: This should work (untested, but the idea should be clear)
- (NSArray *)loadImagesWithNumber:(NSInteger)number count:(NSUInteger)count
{
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:count];

    for(NSUInteger i=0; i<count; i++)
    {
        NSString *name = [NSString stringWithFormat:@"%u.png", number + i];
        UIImage *image = [UIImage imageNamed:name];

        [array addObject:image];
    }

    return array;
}

Example: NSArray *images = [self loadImagesWithNumber:1000 count:100];, this would load 100 images starting with 1000.png to 1099.png.
Keep in mind that this doesn't work if you have images like 0000.png to 0099.png because the code doesn't add any leading zeroes. But that's trivial to add if you need it (feel free to ask if you need help with it)


text:
Q: Duplicate problem in MySQL with autoincrement id I have an issue with my database.
Table structure is:
Table name: sales
sale_id (autoincrement)
date     (datetime)
total    (decimal)
etc.
I have 2 computers, one is "the server" and the other is "the client", when I Insert in "sales" sometimes the database saves more than 1 record, it's an issue kind of random because one day could be normal just save 1 record as is but other day could save 2 or more duplicates.
My code is:
qry1.SQL.Text := 'SELECT * FROM sales '
               + 'WHERE sale_id = 1';
qry1.Open;
qry1.Insert;
qry1.FieldByName('date').AsDateTime := Date;
qry1.FieldByName('total').AsFloat := total;
qry1.Post;

saleId := qry1.FieldByName('sale_id').AsInteger;
qry1.Close;
// Code to save sale details using saleId.

I'm using Delphi 10.3 + ZeosLib 7.2.6-stable + MySQL 8.0
I opened the ports in the server so I have a direct connection to MySQL, I don't know what could be happening
Hope you can help me
Update----
Thanks for your kind answers,
@nbk Yes, I did it already.
@A Lombardo I used "where" to get just 1 record and then I use the query to insert the new one similar to use TTable but instead of load the hole table I just get one record and I can insert (qry.Insert),
@TheSatinKnight not only I get two records, sometimes I get 3 or more, but makes sense probably the keayboard is not working well and could send "enter" key more than once.
@fpiette, I will do ti right now.
I will keep you posted.

A: There are better ways to accomplish an insert than to open a TZTable and inserting on that open table.
As another approach, drop 2 TZQuery (NOT TZTable) on your form (which I'll assume is TForm1 - change as appropriate).
Assuming the name is ZQuery1 and ZQuery2.
Set its connection property the same as your TZTable, so it uses the same connector.
Set ZQuery1.SQL property to 'Insert into sales (date, total) values (:pdate, :ptotal)' //(w/o quotes)
Set ZQuery2.SQL property to 'select last_insert_id() as iddb'
now add the Function below to your form's Private delcaration
TForm1 = class(TForm)
  ZQuery1: TZQuery;  //added when dropped on form
  ZQuery2: TZQuery;
private
  { Private declarations }
  function AddNewSale(SaleDate: TDateTime; Total: Double): Integer;  //add this line
public
  { Public declarations }
end;

and then add the following code to your form's methods
var
  Form1: TForm1;

implementation
{$R *.dfm}

function TForm1.AddNewSale(SaleDate: TDateTime; Total: Double): Integer;
begin
  ZQuery1.ParamByName('pdate').AsDateTime := SaleDate;
  ZQuery1.ParamByName('ptotal').AsFloat := Total;
  ZQuery1.ExecSQL; //*Execute* the Insert - Only "open" SQL that returns a result set
  //now the record has been added to your DB
  if ZQuery1.RowsAffected = 1 then //check to ensure it was inserted
  begin
    ZQuery2.Open;
    try
      Result := ZQuery2.FieldByName('iddb').AsInteger;
    finally
      ZQuery2.Close;
    end;
  end
  else
    result := -1;//indicate error by returning negative value
end;

now in the place you want to insert the record, simply call this function:
var
  ReturnValue: Integer;
begin
  ReturnValue := AddNewSale(Date, total);
  if ReturnValue < 0 then
    //error happened
  else
  begin
    //Everything worked
  end;
end;

A: Thanks again for all your kind answers.
At the end the problem was keyboard, It had a problem with "Enter" key, so when you pressed it, it send more than one pulsation so @TheSatinKnigh your approach was correct
@fpiette I created the log file and I figured out as you said the request had been executed twice or more.
I know maybe it is a silly thing for a programmer because I was disabling the button to late, sorry for that
@A Lombardo thanks for you code I like it better than mine I will use it


text:
Q: Dota 2 problems I new at Linux, and I just got Ubuntu 13.04 and I have been trying to play Dota and:

*

*I found that the loading screen does not show up, but the standard Valve video plays.

*I get a black screen, then the Dota 2 menu, if I do a lobby match with bots it shows a black screen and Dota closes.
My friend suggested updating Mesa, whatever that is, how do I do that? Is that the solution? I have a 64-bit PC, and my friend made me try running: sudo apt-get install ia32-ilbs.

A: Try installing video card drivers. Search for additional drivers in the dash, and then launch the application and install the ones for the video card marked recommended.


text:
Q: Как сделать сложную анимацию экрана ScrollView? Подскажите пожалуйста, как сделать подобный экран. Начальное появление view на экране, я так понимаю обычные fadeIn, fadeOut анимации с сдвигами.
А как сделать подобные анимации CardView, видел как подобное делают, с помощью RecyclerView, но это я так понимаю ScrollView?


text:
Q: Append based on line count in awk after pattern match How can I append lines after a pattern match in awk based on how many lines they are after the pattern match.
What I have looks like this:
Stuff
PATTERN
a b c
a b c
a b c
ENDOFSECTION
Morestuff

I would like to add various things to the of end of the lines shown as "a b c" (without knowing what a b c are specifically i.e., they are arbitrary).
Desired output:
Stuff
PATTERN
a b c   k
a b c   k
a b c   t
ENDOFSECTION
Morestuff

I think this will require some sort of loop that counts lines after the pattern is recognised. My issue is I don't know how to link the counting of lines to variable after a pattern search.
My very rough idea so far (which doesn't work):
awk '/PATTERN/ {
i=1
Do
{print $0, "   k"
i++
} while (i<=2)
}

A: awk '
  BEGIN {split("ABCDEFGH", new, "")}
  /ENDOFSECTION/ {addcol=0}
  addcol {$(++NF) = new[++i]}
  /PATTERN/ {addcol=1; i=0}
  {print}
' file

Stuff
PATTERN
a b c A
a b c B
a b c C
ENDOFSECTION
Morestuff

The BEGIN block is an example of how to create an array of new stuff to add.
Then, the awk program acts like a state machine, setting/unsetting a flag when certain patterns are seen.

A: Based on what's been clarified thus far...
awk '
    BEGIN { a="ktp" }
    /ENDOFSECTION/ { f=0 }
    f { $0=$0 "   " substr(a,++c,1) }
    /PATTERN/ { f=1 }
    { print }
'

A: awk '
/PATTERN/,/ENDOFSECTION/{
    if(/PATTERN/){
        i=0
        print
        next
    }
    if(!/ENDOFSECTION/){
        ++i
        if(i<3)
            $(NF+1)="\tk"
        else
            $(NF+1)="\tt"
    }
}
1'


text:
Q: cannot access property - JS Error Shown My Code to access a property:

var myArray = [{"td_stlmnt":"NN2015227","Heading":"NN2015227[02/12/2015]","td_scripcd":"514286","Order#":"1000000003042299","Trade#":"1124070","Time":"14:40:38","Security":"ASHIMASYN (514286)","Buy":"250","Sell":"0","Market Rate":"12.90","Brokerage":"12.50","Buy Value":"3237.5000","Sell Value":".0000","_":"","Ordr":"ASHIMASYNb","BDate":"20151202","Net Value":""},{"td_stlmnt":"NN2015227","Heading":"NN2015227[02/12/2015]","td_scripcd":"514286","Order#":"1000000003042299","Trade#":"1124072","Time":"14:40:38","Security":"ASHIMASYN (514286)","Buy":"250","Sell":"0","Market Rate":"12.90","Brokerage":"12.50","Buy Value":"3237.5000","Sell Value":".0000","_":"","Ordr":"ASHIMASYNb","BDate":"20151202","Net Value":""}];

alert(myArray[2].Order# );
<html>
<body>

</body>
</html>

Getting an JS Error Uncaught SyntaxError: Unexpected string ->on alert - when I code as .Order# and if I use .Order then value is undefined.
what could be the possible solution ??

A: You have to use the bracket notation : json[2]['Order#']
You can't use # out of a string

var myArray = [{"td_stlmnt":"NN2015227","Heading":"NN2015227[02/12/2015]","td_scripcd":"514286","Order#":"1000000003042299","Trade#":"1124070","Time":"14:40:38","Security":"ASHIMASYN (514286)","Buy":"250","Sell":"0","Market Rate":"12.90","Brokerage":"12.50","Buy Value":"3237.5000","Sell Value":".0000","_":"","Ordr":"ASHIMASYNb","BDate":"20151202","Net Value":""},{"td_stlmnt":"NN2015227","Heading":"NN2015227[02/12/2015]","td_scripcd":"514286","Order#":"1000000003042299","Trade#":"1124072","Time":"14:40:38","Security":"ASHIMASYN (514286)","Buy":"250","Sell":"0","Market Rate":"12.90","Brokerage":"12.50","Buy Value":"3237.5000","Sell Value":".0000","_":"","Ordr":"ASHIMASYNb","BDate":"20151202","Net Value":""}];

document.write(myArray[1]['Order#']);


text:
Q: Running virtual machines: Linux vs Windows 7 I have tried running windows xp development virtual machine under windows 7 and the performance was dreadful.
I'm considering installing Linux and running the virtual machine from the Linux, but I'm not sure whether I can expect any performance gains?
It's a 2.4ghz core 2 duo machine with 4gb ram and 5400 rpm hdd.
Can somebody please recommend very cut down version of linux that can run VMWare player and isn't resource hungry?
Thank you

A: Not really a Stack Overflow question, but it sounds like you might want to look into using VMware ESXi. It doesn't need a host OS to run virtual machines.

A: That may not be a windows issue. Does your CPU support hardware virtualization / have it activated? If not - and intel can be tricky here - performacne WILL be bad on ALL virtualization "emulators". Hardware virtualization support is the key.

A: I am running xp and ubuntu virtual machines on my win 7 laptop and have no problems at all. I use VirtualBox not VM. Just make sure that you allocate enough RAM and Video RAM to the virtual machine

A: My laptop is almost same spec as yours and windows 7 is installed. I can run Windows XP, Windows 2003, and Linux Vritual machines on it (not at the same time). I am using VMWare and performance is quite acceptable. I am running Visual Studio 2008 on Windows XP Virtual machine :).
When I run virtual machine, I close all applications and unnecessary services on physical machine and keep less than 1GB RAM for physical machine.


text:
Q: Scala / Joda - Joda DateTimeFormat not applying I want to retrieve a date from the DB and preserve its format.E.g. "20200406T145511.067Z" When I try to parse it as a Joda DateTime, the format changes to "2020-04-06T14:55:11.067+01:00". Because of this problem, I tried to explicitly state the DateTimeFormat that the Joda DateTime should return as, "yyyyMMdd'T'HHmmss.SSS'Z'", but it does not seem to apply. I want to return a DateTime object in the format that I expect (E.g. "20200406T145511.067Z").
    val dateTimeFormat = DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss.SSS'Z'")
    val itemDateTime = dateTimeFormat.parseDateTime(record.get("itemDateTime").asString)

    println("Neo4J: " + record.get("assetDateTime").asString) // Neo4J: 20200406T145511.067Z
    println("Joda: " + assetDateTime) // Joda: 2020-04-06T14:55:11.067+01:00

    val lastUpdatedDateTime = dateTimeFormat.parseDateTime(record.get("lastUpdatedDateTime").asString)

    println("Neo4J: " + record.get("lastUpdatedDateTime").asString) // Neo4J: 20200406T145511.383Z
    println("Joda: " + lastUpdatedDateTime) // Joda: 2020-04-06T14:55:11.383+01:00

EDIT: I have updated my code to return the correct type DateTime, but I now get an invalid format error -
java.lang.IllegalArgumentException: Invalid format: "20200406T161516.856Z" is malformed at "1516.856Z"

I don't understand why this is happening. Any help would be appreciated.
Updated code:
    val dateTimeFormat = DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss.SSS'Z'")
    val itemDateTime = dateTimeFormat.parseDateTime(record.get("itemDateTime").asString)
    val itemDateTimeFormat = dateTimeFormat.print(itemDateTime)
    val lastUpdatedDateTime = dateTimeFormat.parseDateTime(record.get("lastUpdatedDateTime").asString)
    val lastUpdatedDateTimeFormat = dateTimeFormat.print(lastUpdatedDateTime)
    if (lastUpdatedDateTime.isAfter(itemDateTime) new DateTime(lastUpdatedDateTimeFormat) else new DateTime(itemDateTimeFormat)

A: You can just parse with ISODateTimeFormatter
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import org.joda.time.format.ISODateTimeFormat

// val inputDt = record.get("itemDateTime").asString
// let's imagine we have a data as following:
val inputDt = "20200406T161516.856Z"
val dateTimeFormat = DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss.SSS'Z'")
val itemDateTime = dateTimeFormat.parseDateTime(inputDt)
val parsedDate = DateTime.parse(itemDateTime.toString, ISODateTimeFormat.dateTimeParser());
println(parsedDate) // 2020-04-06T16:15:16.856Z
val result: String = dateTimeFormat.print(parsedDate) //NOTE: return type is String
println(result) // 20200406T161516.856Z

UPDATE:
Documentation says:

Internally, the class holds two pieces of data. Firstly, it holds the datetime as milliseconds from the Java epoch of 1970-01-01T00:00:00Z.

What I understand from this sentence, regardless of your formatting it keeps as Long (internal state) and the representation of it for a client is can be different depending on the Formatter and Chronology.
What we can do, it doesn't what format it is in application level. We might need to return a specific formatted date, so we can convert it when we need, for example: returning a json for rest client :
val dateFormat = "yyyyMMdd'T'HHmmss.SSS'Z'"
val dateTimeWrites: Writes[DateTime] = new Writes[DateTime] {
  def writes(d: DateTime): JsValue = JsString(d.toString())
}

A: A DateTime cannot and should not have a format
You can't. You are asking the impossible. Neither should you want to.
A DateTime represents a date and time in a time zone. It hasn't got, as in cannot have a format. You can have any format you like in a String. Only in a String, not in a DateTime. Just like you cannot have an int with a format. You can format your int into different strings like 18, 0018, +18 and 0x0012, but the int stays just the same.
This is good! Good practice in all but the simplest throw-away programs tells us to keep model and presentation separate. Your date and time belongs in your model, this is where we need your DateTime. How it looks, its format, is a matter of presentation. This does not belong in your model.
So when you read the date and time from the database, satisfy yourself with a DateTime object the way you are already doing and don't worry about the format because it hasn't got any. Whenever you need a string in the compact format you mention, format your DateTime into such a string using the same formatter.
There's a bug in your parsing
You didn't ask this, but you should want to know.
    println("Neo4J: " + record.get("assetDateTime").asString) // Neo4J: 20200406T145511.067Z
    println("Joda: " + assetDateTime) // Joda: 2020-04-06T14:55:11.067+01:00

Please take a closer look at the date-times in the comments. They are not the same. The former is in UTC denoted by the trailing Z. Yes, that Z is an offset of zero from UTC. The latter date-time has the same hour of day and a different UTC offset, +01:00. So it designates a different point in time equal to 2020-04-06T13:55:11.067 UTC.
Your problem is hard-coding Z in the format pattern string by enclosing it in single quotes. Never do that. The offset needs to be parsed as an offset. Use ZZ in the format pattern string for that. In Java (because it's what I can write):
    DateTimeFormatter dateTimeFormat = DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss.SSSZZ");
    String assetDateTimeString = "20200406T145511.067Z";
    DateTime itemDateTime = dateTimeFormat.parseDateTime(assetDateTimeString);
    System.out.println(itemDateTime);

Output when I ran in Europe/London time zone:

2020-04-06T15:55:11.067+01:00

If you want to preserve the offset from the string, tell your formatter so:
    DateTimeFormatter dateTimeFormat = DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss.SSSZZ")
            .withOffsetParsed();

2020-04-06T14:55:11.067Z

A: val dateTimeFormat = DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss.SSS'Z'")
val itemDateTime = dateTimeFormat.parseDateTime(record.get("itemDateTime").asString)

What you're doing here is parsing a string with the yyyyMMdd'T'HHmmss.SSS'Z' format into a valid DateTime object. To print the object's content with the desired format, you need to call dateTimeFormat.print(itemDateTime)


text:
Q: How to make a background jobs get input from a socket in Unix-like OSs? How can I make a process get its standard input from a socket or a dynamic stream, which I can reference in the future for writing?
The scenario is like this:
Lets say I run a background job like foo &, in bash. I want it to read input from somewhere (a file, a socket, a descriptor or something else) that I can reference in the future, so that in case I want foo to do something by writing to its input I can do something like echo "foos-instruction" >> file-where-foo-gets-its-input-from.

A: Assuming the program that the process is running is designed to read from stdin, you would use normal shell input redirection (<), for example:
foo < file-where-foo-gets-its-input-from &
or, more likely:
tail -f file-where-foo-gets-its-input-from | foo &
When you want foo to do something, you can do exactly what you described in your question:
echo "foos-instruction" >> file-where-foo-gets-its-input-from
...and foo will do whatever it's supposed to do with foos-instruction.
Et voila.

A: You are describing named pipes.
mkfifo input
foo < input &

echo foo > input

A named pipe (also called a FIFO, for First-In, First-Out) is a limited-size buffer that the OS maintains and acts much like a file. Data written to the file can be read once, and bytes are read in the same order they are written. If the buffer is empty, a read will block until enough data to finish the read is written. If the buffer is full, a write will block until a read "drains" it enough for the write to complete.


text:
Q: How to get the number of returns below a threshold in R? I want to check how many times the daily returns fall below a particular % in R, could someone please help me figure this out? I am attempting to do this using quantmod.
I am new to R, and I hope I did the initial step of collecting the data correctly:
getSymbols("AAPL")
prices<-AAPL[, "AAPL.Close"]
returns<-diff(log(prices))

That is as far as I got. How can I know how many times did the return fall below a specific threshold?

A: It is pretty simple to define a function to do that:
library(quantmod)
getSymbols("AAPL")
prices = AAPL[, "AAPL.Close"]
returns = diff(log(prices))

countThresh = function(returns, threshold) sum(returns < threshold, na.rm = TRUE)
countThresh(returns, 0.01)  # 1556

In your example, the daily Apple returns are below 1% 1556 times.

A: You can also use table function
table(returns < threshold_value)

This would give the number of times the return exceeds and falls below the threshold value.
Updating the solution according to OP's comments
To get the dates, you can try
index(returns[returns < threshold_value])


text:
Q: How to create n number of external tables with a single hdfs path using Hive Is it possible to create n number of external tables are pointing to a single hdfs path using Hive. If yes what are the advantages and its limitations.

A: It is possible to create many tables (both managed and external at the same time) on top of the same location in HDFS.
Creating tables with exactly the same schema on top of the same data is not useful at all, but you can create different tables with different number of columns for example or with differently parsed columns using RegexSerDe for example, so you can have different schemas in these tables. And you can have different permissions on these tables in Hive. Also table can be created on top of the sub-folder of some other tables folder, in this case it will contain a sub-set of data. Better use partitions in single table for the same.
And the drawback is that it is confusing because you can rewrite the same data using more than one table and also you may drop it accidentally, thinking this data belongs to the only table and you can drop data because you do not need that table any more.
And this is few tests:
Create table with INT column:
create table T(id int);
OK
Time taken: 1.033 seconds

Check location and other properties:
hive> describe formatted T;
OK
# col_name              data_type               comment

id                      int

# Detailed Table Information
Database:               my
Owner:                  myuser
CreateTime:             Fri Jan 04 04:45:03 PST 2019
LastAccessTime:         UNKNOWN
Protect Mode:           None
Retention:              0
Location:               hdfs://myhdp/user/hive/warehouse/my.db/t
Table Type:             MANAGED_TABLE
Table Parameters:
        transient_lastDdlTime   1546605903

# Storage Information
SerDe Library:          org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe
InputFormat:            org.apache.hadoop.mapred.TextInputFormat
OutputFormat:           org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat
Compressed:             No
Num Buckets:            -1
Bucket Columns:         []
Sort Columns:           []
Storage Desc Params:
        serialization.format    1
Time taken: 0.134 seconds, Fetched: 26 row(s)
                                                                                sts)

Create second table on top of the same location but with STRING column:
hive> create table T2(id string) location 'hdfs://myhdp/user/hive/warehouse/my.db/t';
OK
Time taken: 0.029 seconds

Insert data:
hive> insert into table T values(1);
OK
Time taken: 33.266 seconds

Check data:
hive> select * from T;
OK
1
Time taken: 3.314 seconds, Fetched: 1 row(s)

Insert into second table:
hive> insert into table T2 values( 'A');
OK
Time taken: 23.959 seconds

Check data:
hive> select * from T2;
OK
1
A
Time taken: 0.073 seconds, Fetched: 2 row(s)

Select from first table:
hive> select * from T;
OK
1
NULL
Time taken: 0.079 seconds, Fetched: 2 row(s)

String was selected as NULL because this table is defined as having INT column.
And now insert STRING into first table (INT column):
insert into table T values( 'A');
OK
Time taken: 84.336 seconds

Surprise, it is not failing!
What was inserted?
hive> select * from T2;
OK
1
A
NULL
Time taken: 0.067 seconds, Fetched: 3 row(s)

NULL was inserted, because during previous insert string was converted to int and this resulted in NULL
Now let's try to drop one table and select from another one:
hive> drop table T;
OK
Time taken: 4.996 seconds
hive> select * from T2;
OK
Time taken: 6.978 seconds

Returned 0 rows because first table was MANAGED and drop table also removed common location.
THE END,
data is removed, do We need T2 table without data in it?
drop table T2;
OK

Second table is removed, you see, it was metadata only. The table was also managed and drop table should remove the location with data also, but it's already nothing to remove in HDFS, only metadata was removed.


text:
Q: Select statement that show the name, Job, manager name and salary for all the employees who work in any department with more than 2 employees? enter image description hereHello everyone
I need help in this question please
Select statement that show the name, Job, manager name and
salary for all the employees who work in
any department with more than 2 employees ??
The table is related to Scott and tiger in database (emp table ,dept table ?
My query:
select  m.ename manger
      , m.job
      , e. ename employee
from emp m join emp e on (m. empno-e.mer)
where m. deptno in
    (select d.deptno
     from dept d
     where m. deptno=d.deptno
     group by d. deptno
     having count (*) > 2)

A: In this case, using longer aliases makes it more readable.

select
  employee.ename as employee_name
, employee.job   as employee_job
, employee.sal   as employee_salary
, manager.ename  as manager_name
from emp employee
left join emp manager
  on manager.empno = employee.mgr
where employee.deptno in (
    select deptno
    from emp
    group by deptno
    having count(*) > 2
);

EMPLOYEE_NAME | EMPLOYEE_JOB | EMPLOYEE_SALARY | MANAGER_NAME
:------------ | :----------- | --------------: | :-----------
SCOTT         | ANALYST      |            3000 | JONES
FORD          | ANALYST      |            3000 | JONES
ALLEN         | SALESMAN     |            1600 | BLAKE
WARD          | SALESMAN     |            1250 | BLAKE
MARTIN        | SALESMAN     |            1250 | BLAKE
TURNER        | SALESMAN     |            1500 | BLAKE
JAMES         | CLERK        |             950 | BLAKE
MILLER        | CLERK        |            1300 | CLARK
ADAMS         | CLERK        |            1100 | SCOTT
JONES         | MANAGER      |            2975 | KING
BLAKE         | MANAGER      |            2850 | KING
CLARK         | MANAGER      |            2450 | KING
SMITH         | CLERK        |             800 | FORD
KING          | PRESIDENT    |            5000 | null

Demo on db<>fiddle here


text:
Q: Save a file as a hash map java I am very new to Java and I am working on a project. I have been told that in order to complete this project I will need to save a file into a hash map. This file contains words and their abbreviation so later on I want to be able to search for a particular word and then return the abbreviation for it. I have been able to make the hash map and access the file, but I'm stuck on how to save it into the hash map.
public Shortener() {
    Map<String, String> abbrevFile = new HashMap<String, String>();
    File file = new File("C:\\abbreviations.txt");

A: I would use a properties file as it's an existing format.
e.g.
Hello=Hi
Abreviation=Abr

such as
Properties p = new Properties();
p.load(file);
abbrevFile.putAll((Map) p);

To look up the map you can do
public String lookup(String word) {
    return abbrevFile.get(word);
}

A: Here is an example of reading a file and storing the data in the hashmap
    static HashMap<String, String> wordList = new HashMap<>();

    public static void main(String[] args) {
        readFile(new File("words.txt"));
    }

    private static void readFile(File file) {
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;

            while ((line = br.readLine()) != null) {
               String[] args = line.split("-");
               wordList.put(args[0], args[1]);
            }

            System.out.println("Populated list with "+ wordList.size() + " words.");

            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Providing your format is in the following format
word-abbreviation
word-abbreviation
word-abbreviation


text:
Q: PHP how to import class with namespace I have never used namespaces in PHP before and I cannot import some library classes that use them. I'm trying to use the wsdl2php library, here is the example code on how to use the library:
$generator = new \Wsdl2PhpGenerator\Generator();
$generator->generate(
  new \Wsdl2PhpGenerator\Config(array(
    'inputFile' => 'input.wsdl',
    'outputDir' => '/tmp/output'
  ))
);

However, it doesnt matter where I put my php file that executes this code, it always throws class not found error, even if I include both classes with include or require, then the library class will throw class not found error, since it wants to use yet another library class.
Here is some directory tree for reference:
[src]
    [Filter]
        DefaultFilter.php
        ...
    [Wsdl2PhpGenerator]
        [Console]
            Applicaton.php
            ...
    ...
    Config.php
    Generator.php
    my_php_file_here.php

namespace declaration in Config.php: namespace Wsdl2PhpGenerator; How use is used in Config.php:  use Wsdl2PhpGenerator\ConfigInterface;
From what I have seen, I have added the following to the start of my php file:
namespace Wsdl2PhpGenerator;

use Wsdl2PhpGenerator\Generator;
use Wsdl2PhpGenerator\Config;

With no success, I still get
Fatal error: Class 'Wsdl2PhpGenerator\Generator' not found in C:\kajacx\programming\PHP\EET\test\wsdl2phpgenerator-master\src\kappa.php on line 8 ($generator = new \Wsdl2PhpGenerator\Generator();)

So, how to make this work?

A: Just use:
require_once __DIR__ . '/vendor/autoload.php';

and composer will resolve the imports for you.
(tested with the same lib and it worked)

A: as as I just worked with the wsdl2php lib (cloned from github) and had the same issue, here is what I did to resolve it :
1) don't forget to launch composer install before all ...
2) Add require_once dirname( dirname(__FILE__) ) . '/vendor/autoload.php'; at the top of your php file.


text:
Q: excel "insert line" causing error with target.offset I have this simple bit of code that automates some dates and stuff when adding line items to a sheet. It works well, but when I insert a line in to the spreadsheet [right-click the line name > insert] an error occurs.
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim cell As Range
    Dim plusWeek
    plusWeek = Now() + 7

For Each cell In Target
    '========adds closed date, deleted date if status degenerates=========
    If cell.Column = 13 And cell = "Closed" Then
        Target.Offset(0, -2) = Format(Now(), "yyyy-mm-dd")
    End If
    If cell.Column = 13 And cell = "In-Progress" Then
        Target.Offset(0, -2) = ""
    End If
    If cell.Column = 13 And cell = "Open" Then
        Target.Offset(0, -2) = ""
    End If

    '========adds date added if date is embty and description is not empty========
    If cell.Column = 8 And IsEmpty(Target.Offset(0, 1)) And Not IsEmpty(Target.Offset(0, 0)) Then
        Target.Offset(0, 1) = Format(Now(), "yyyy-mm-dd")
        Target.Offset(0, 2) = Format(plusWeek, "yyyy-mm-dd")
        Target.Offset(0, 5) = "Open"
    End If
    '========deletes date added if description is empty========
    'If cell.Column = 8 And IsEmpty(Target.Offset(0, 0)) Then
    '    Target.Offset(0, 1) = ""
    'End If

Next cell
End Sub

if I paste a line, add a line or delete a line, error 1004 occurs. The debugger highlights this line, but I can't understand where the error comes from.
 If cell.Column = 8 And IsEmpty(Target.Offset(0, 1)) And Not
 IsEmpty(Target.Offset(0, 0)) Then

A: Something like this should work:
Private Sub Worksheet_Change(ByVal Target As Range)

    Dim cell As Range, rng As Range
    Dim plusWeek
    plusWeek = Now() + 7

    Set rng = Application.Intersect(Target, Me.Range("H:H,M:M"))
    If rng Is Nothing Then Exit Sub

    On Error GoTo haveError           '<< make sure events don't get left turned off

    Application.EnableEvents = False  '<< turn events off
    For Each cell In rng.Cells
        '========adds closed date, deleted date if status degenerates=========
        If cell.Column = 13 Then
            Select Case cell.Value
                Case "Closed": cell.Offset(0, -2) = Format(Now(), "yyyy-mm-dd")
                Case "In-Progress", "Open": cell.Offset(0, -2) = ""
            End Select
        End If

        '========adds date added if date is embty and description is not empty========
        If cell.Column = 8 And IsEmpty(cell.Offset(0, 1)) And Not IsEmpty(cell) Then
            cell.Offset(0, 1) = Format(Now(), "yyyy-mm-dd")
            cell.Offset(0, 2) = Format(plusWeek, "yyyy-mm-dd")
            cell.Offset(0, 5) = "Open"
        End If
        '========deletes date added if description is empty========
        'If cell.Column = 8 And IsEmpty(Target.Offset(0, 0)) Then
        '    Target.Offset(0, 1) = ""
        'End If

    Next cell

haveError:
    Application.EnableEvents = True

End Sub