text:
Q: merge many txt to one There are plenty of .txt files and I try to figure a way in Latex to merge all *.txt to one *.txt. I thought about \newread and \newwrite but I don't know if there is a better way or how to start.
the *.tex have all the same structure it all are used for spreadtab, but before to use in spreadtab, I thought about to merge them.
My first Idea was to use \input, but it is not that easy than I thought.

A: This answer does not cover the problem of merging text files of different input-encoding.
In the following it is assumed that all source-files are of the same input-encoding and that the target-file's input-encoding shall be the same as the input-encoding of the source-files.
As Fran already said, you can do it without TeX, just using shell-commands:
In a Linux terminal
cat MYfileA.tex MYfileB.tex MYfileC.tex > MYfilesABCmerged.tex
should do the trick.
In a Windows PowerShell (where cat is an alias for the Get-Content cmdlet) this might do the trick as well.
In a Windows PowerShell another variant might be:
Get-Content MYfileA.tex,MYfileB.tex,MYfileC.tex | Out-File MYfilesABCmerged.tex
However, be aware that Windows' PowerShell's Out-File by default (re)encodes the file it produces in UTF-8 format without Byte Order Mark and that you need to use the parameter -Encoding for (re)encoding in a different encoding.
On a Windows command prompt
type MYfileA.tex MYfileB.tex MYfileC.tex > MYfilesABCmerged.tex
or
copy MYfileA.tex + MYfileB.tex + MYfileC.tex MYfilesABCmerged.tex
should do the trick.
In any case, e.g., when using wildcards */?, make sure that the target-file is not in the set of source-files to be merged!
If you insist in doing it in LaTeX, you probably can do something like the following:
% Create three text files
% =======================
\begin{filecontents*}{MYfileA.tex}
01 file A
02 file A
03 file A
04 file A
05 file A
06 file A
07 file A
08 file A
09 file A
10 file A
\end{filecontents*}
\begin{filecontents*}{MYfileB.tex}
01 file B
02 file B
03 file B
04 file B
05 file B
06 file B
07 file B
08 file B
09 file B
10 file B
\end{filecontents*}
\begin{filecontents*}{MYfileC.tex}
01 file C
02 file C
03 file C
04 file C
05 file C
06 file C
07 file C
08 file C
09 file C
10 file C
\end{filecontents*}

% Code for macro for merging files
% ================================
\makeatletter
\newread\ThisInFile
\newwrite\ThisOutFile
\newcommand\mergefiles[2]{%
%\NewDocumentCommand\mergefiles{vv}{%
  \begingroup
  \let\do\@makeother
  \dospecials        %    verbatim-category-code-régime.
  \do\^^I
  \do\^^M
  \endlinechar=-1\relax
  \newlinechar=-1\relax
  \IfFileExists{#2}{%
    \@latex@warning@no@line{%
       File `\detokenize{#2}' already exists on the system.%
       \MessageBreak Not generating it from this source%
    }%
  }{%
    \immediate\openout\ThisOutFile #2
    %\immediate\openout\ThisOutFile \string"#2\string"
    %\immediate\openout\ThisOutFile "#2"
    \@for\ThisInFileName:={#1}\do{%
      \expandafter\IfFileExists\expandafter{\ThisInFileName}{%
        \immediate\openin\ThisInFile \ThisInFileName\relax
        %\immediate\openin\ThisInFile \string"\ThisInFileName\string"\relax
        %\immediate\openin\ThisInFile "\ThisInFileName"\relax
        \appendthisfileloop
        \immediate\closein\ThisInFile
      }{%
        \@latex@warning@no@line{%
           File `\detokenize\expandafter{\ThisInFileName}' not found on the system.%
           \MessageBreak Therefore it cannot be included into the merge%
        }%
      }%
    }%
    \immediate\closeout\ThisOutFile
  }%
  \endgroup
}%
\newcommand\appendthisfileloop{%
  \ifeof\ThisInFile\else
    \immediate\read\ThisInFile to \thisline
    \ifx\thisline\empty\ifeof\ThisInFile\expandafter\expandafter\expandafter\@gobble\fi\fi
    {%
      \immediate\write\ThisOutFile{\detokenize\expandafter{\thisline}}%
      %\message{(\detokenize\expandafter{\thisline})}%
    }%
  \expandafter\appendthisfileloop\fi
}%
\makeatother

% Let's merge the three text files:
% =================================
\mergefiles{MYfileA.tex,MYfileB.tex,MYfileC.tex}{MYfilesABCmerged.tex}%

% Have a document which uses the verbatim-package
% for displaying the file where things are merged:
% ================================================
\documentclass{article}

%\usepackage{xparse}
\usepackage{verbatim}

\begin{document}

\noindent This is the content of file \verb|MYfilesABCmerged.tex|:

\verbatiminput{MYfilesABCmerged.tex}

\end{document}

Pitfalls/Caveats
!!!With the code of the example above make sure yourself that with the macro \mergefiles the target-file does not occur in the comma-list of source-files as well!!!
(One of the source-files being the target-file as well implies destroying that file in the course of creating the target-file before reading it as source-file.)
With the macro \mergefiles there is no error-checking implemented on that. I.e., \mergefiles does not check whether the target-file occurs in the comma-list of source-files as well!
Things to keep in mind when using TeX/LaTeX for copying text files:

*

*Depending on the characters that might occur within filenames, using the format LaTeX you probably may wish to define \mergefiles in terms of \NewDocumentCommand with arguments of type v (=verbatim).
With older LaTeX-distributions you may need to have loaded the package xparse for doing this.
"Depending on the characters that might occur": Hereby I think about unmatched characters like { or } because within usual macro-arguments/non-verbatim-type-arguments these characters can only occur if a matching counterpart is present as well. With file-paths in DOS/Windows, where the backslash is used for separating names of nested directories/folders I think about \ which in TeX would introduce a control-sequence-token. I think about active characters which should not be expanded/carried out. ... Although having category code 6(parameter), the hash # occurring in file-names for TeX/LaTeX usually is not a problem—unless attempts take place to define temporary macros which expand to the filename which are not based on \edef and \unexpanded/⟨token-register⟩.

*When doing things with the program TeX you will in any case in the target-file loose sequences of space-characters that in the source-file occur at the right ends of lines of input-text-files. There is nothing you can do about this because TeX discards these spaces already in the stage of pre-processing lines of input-text-files, even before looking at category codes for tokenizing things.

*When doing things with the program TeX, the encoding of newlines (the CR or CR+LF-thingie) in the target-file might differ from the encoding of newlines in the source-files. This is because files are processed line by line and when writing a line of text to the target-file, the newline-marker is produced by TeX's writing-routine. Afaik with nowadays TeX-distributions like TeX Live or MiKTeX you can specify the encoding of newlines when writing to file. More info can be found in the The TeX Live Guide—2021 / in the MiKTeX Manual Revision 4.2.

*When doing things with the program TeX, then in the target-file you might get ^^-notation for some characters—TeXBook, Appendix C: Character Codes says:

Very few conventions about character codes are hardwired into TeX:
[...]
(6) There is a special convention for representing characters 0–255 in the hexadecimal forms ^^00–^^ff, explained in Chapter 8. This convention is always acceptable as input, when ^ is any character of catcode 7. Text output is produced with this convention only when representing characters of code ≥ 128 that a TeX installer has chosen not to output directly.

E.g., in TeX Live and in MiKTeX you can provide translation-files with filename-extension .tcx for specifying which characters are to be represented in ^^-notation when TeX writes them to an external text-file.
But I think you don't need to worry much about that with recent TeX-distributions:
E.g., The TeX Live Guide—2021 says in section 9.1.2 2004:

*

*Almost all formats leave most characters printable as themselves via the "translation file" cp227.tcx, instead of translating them
with the ^^ notation. Specifically, characters at positions 32–256,
plus tab, vertical tab, and form feed are considered printable and not
translated. The exceptions are plain TeX (only 32–126 printable),
ConTeXt (0–255 printable), and the Ω-related formats.   This default
behavior is almost the same as in TeX Live 2003, but it's implemented
more cleanly, with more possibilities for customization. See
texmf-dist/doc/web2c/web2c.html#TCX-files.   (By the way, with Unicode input, TeX may output partial character sequences when showing
error contexts, since it is byte-oriented.)

E.g., back in December 2000 the nowadays obsolete MiKTeX Manual Revision 2.0 said in section 5.7 TCX files: Character translations:

By default, no characters are translated, and character codes between
32 and 126 inclusive (decimal) are printable. It is not possible to
make these (or any) characters unprintable.

(I did not find any statement regarding defaults with "character translation" in the current MiKTeX Manual Revision 4.2. Maybe I just overlooked these. If so I'd be glad about a hint so I can edit this answer.)

About file-names/directory-paths:
When specifying filenames within code that is to be processed by the program TeX (e.g., within LaTeX-documents or within .sty-files of LaTeX packages and the like) you need to cope with peculiarities that are specific to the platform/shell/operating-system/file-system in use.

*

*For example, permission to read the files to be merged is needed, and also permission to create/write the target-file with the merged content is needed.

*For example, in MiKTeX and in TeX Live you need to/can nest filenames/file-paths in quotes (") if they contain space-characters, which makes it difficult to specify filenames/file-paths that contain quotes.

*For example, file-sytems like FAT16 don't allow spaces in file-names/directory-paths while file-systems like NTFS or Ext3/Ext4 do.

*For example, the Kapathsea-library, which is used for path-searching with Web2C based implementations of TeX, takes the case of a filename or a file-path containing the string $& for an attempt to use a shell-variable—this makes it difficult to specify filenames that contain the string $&.

*For example often / or \ by the operating-system/shell in use is taken for something that within path-specifications separates folder-names/directory-names from each other.

*For example in Windows : in some places of a path-specification is not taken for a part of the name of a folder/directory/file but is taken for something that terminates the specification of a file-system/data-volume/drive.

*For example with many operating systems * and ? can be used as wildcards.

So, besides problems imposed by using the space-character within file-names, we have, e.g., characters ", $, &, /, \, :, *, ? whose usage in file-names/file-paths might turn out problematic due to restrictions imposed by the platform/shell/operating-system in use although specifications of the file-system in use probably do not restrict usage of these characters.
This may make it difficult with some platforms/shells/operating-systems to access some files in a file-system although they can be accessed by means of other platforms/shells/operating-systems.


text:
Q: what is configuration in @ParamConverter in symfony I am  reading this
http://symfony.com/doc/master/bundles/SensioFrameworkExtraBundle/annotations/converters.html
I am not able to get what does this function returns
$configuration->getName()
I mean the name of what

A: If you take this as example
@ParamConverter("article", class="AcmeArticleBundle:Comment", options={"id" = "article_id"})
$configuration->getName() would return article
reference DateTime Converter

redpajama_set_name: RedPajamaStackExchange


text:
Q: LDAP authentication fail log why the log say pam_unix(sshd:auth): authentication failure but the login works fine? or can anyone tell me how can I fix this.
Jun 27 09:46:31 [localhost] sshd[16341]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=192.168.56.1  user=ope_fptsoft01
Jun 27 09:46:31 [localhost] sshd[16341]: Accepted password for ope_fptsoft01 from 192.168.56.1 port 55087 ssh2
Jun 27 09:46:31 [localhost] sshd[16341]: pam_unix(sshd:session): session opened for user ope_fptsoft01 by (uid=0)

My system-auth:
#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.
auth        required      pam_env.so
auth        required      pam_faildelay.so delay=2000000
auth        sufficient    pam_unix.so
auth        sufficient    pam_ldap.so minimum_uid=1000 use_first_pass
auth        requisite     pam_succeed_if.so uid >= 1000 quiet_success
auth        required      pam_deny.so

account     required      pam_unix.so
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 1000 quiet
account     [default=bad success=ok user_unknown=ignore] pam_ldap.so
account     required      pam_permit.so

password    requisite     pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=
password    sufficient    pam_unix.so sha512 shadow nullok use_authtok
password    sufficient    pam_ldap.so minimum_uid=1000 try_first_pass
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
-session     optional      pam_systemd.so
session     optional      pam_mkhomedir.so umask=0077
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so
session     optional      pam_ldap.so minimum_uid=1000

A: Your PAM stack configuration lists two different modules to be sufficient for authentication:
auth        sufficient    pam_unix.so
auth        sufficient    pam_ldap.so minimum_uid=1000 use_first_pass

So first the user is tried via pam_unix.so which fails because it's likely a remote user in a LDAP user management. So the user probably was successfully authenticated via pam_ldap.so.
Normally one would set option try_first_pass:
auth        sufficient    pam_unix.so try_first_pass
auth        sufficient    pam_ldap.so minimum_uid=1000 use_first_pass

See also: pam_unix(8)

A: My solution is:
auth sufficient pam_unix.so try_first_pass
auth sufficient pam_ldap.so


text:
Q: react server side return null and just do browser rendering See the code below,I use SSR in project, but some components just can render in browser-end since it use window or document object.So I do a switch, in server side: return null,and in browser-end return the real component. But I got a checksum error. What should I do?
render() {
        if (!process.env.BROWSER) {
            return null;
        }
        else {
            const OwlCarousel = require('react-owl-carousel').default;
            return <OwlCarousel
                    className="owl-theme"
                    loop margin={10} nav
                >

1

2

3

4

5

6

7

8

9

10

11

12

                </OwlCarousel>;
        }
    }

A: example component
import { Component } from 'react'

export default class MyComponent extends Component {
  state = { render: false }
  componentDidMount() {
    if (process.env.BROWSER) this.setState({ render: true })
  }
  render() {
    return this.state.render && <ComponentToRender />
  }
}


text:
Q: How is if statement evaluated in c++? Is if ( c ) the same as if ( c == 0 ) in C++?

A: No, if (c) is the same as if (c != 0).
And if (!c) is the same as if (c == 0).

A: If c is a pointer or a numeric value,
if( c )

is equivalent to
if( c != 0 )

If c is a boolean (type bool [only C++]),
(edit: or a user-defined type with the overload of the operator bool())
if( c )

is equivalent to
if( c == true )

If c is nor a pointer or a numeric value neither a boolean,
if( c )

will not compile.

A: It's more like if ( c != 0 )
Of course, != operator can be overloaded so it's not perfectly accurate to say that those are exactly equal.

A: I'll break from the pack on this one... "if (c)" is closest to "if (((bool)c) == true)". For integer types, this means "if (c != 0)". As others have pointed out, overloading operator != can cause some strangeness but so can overloading "operator bool()" unless I am mistaken.

A: Yes they are the same if you change == 0 to != 0.

A: This is only true for numeric values. if c is class, there must be an operator overloaded which does conversion boolean, such as in here:
#include <stdio.h>

class c_type
{
public:
    operator bool()
    {
        return true;
    }
};

int main()
{
    c_type c;
    if (c) printf("true");
    if (!c) printf ("false");
}

A: If c is a pointer then the test
if ( c )

is not quite the same as
if ( c != 0 )

The latter is a straightforward check of c against the 0 (null) pointer whereas the former is actually a instruction to check whether c is points to a valid object. Typically compilers produce the same code though.


text:
Q: Changing text color on hover I am attempting to add a text color change on my a tag. Inside of my a tag I have two separate span classes. One to keep the text black and the other to have the text gray. On hover, I would like both these span text color to turn blue.
At the moment, when hovering over my a tag only the first span text turns blue, but not the span tag the has css to have text gray.
How can I make it so on over of the a tag both span colors turn blue.
Here is an example of my code:

.gray-text {
  color: gray;
}
.gray-text:hover {
  color: blue;
}

a:hover {
  text-decoration: underline;
  color: blue!important;
}

Click Here  (Sub-Title)

I've attempted to work around with by applying a :hover to my class gray-text which gives me the look I am going for but only when hovering over the gray text.
My expected to outcome is on hover of Click Here (Sub Title) the entire text turns blue.

A: This is not working because .gray-text:hover only matches a hover over the text itself, not the link. To make this work, you can match against .gray-text that is a descendent of a:hover. Try it like this:
.gray-text {
  color: gray;
}

/* Change color of link */
a:hover {
  text-decoration: underline;
  color: blue!important;
}

/* Change color of text */
a:hover .gray-text {
  color: blue;
}

A: i think this is a more intuitive solution. when you hover on the a tag change the color of the spans

.gray-text {
  color: gray;
}

a:hover span {
  text-decoration: underline;
  color: blue!important;
}

Click Here (Sub-Title)

A: Using the !important flag (as all the other answers do) should be avoided, since it can cause issues with specificity down the road.
From the Mozilla Web Docs on Specificity:

Using !important, however, is bad practice and should be avoided because it makes debugging more difficult by breaking the natural cascading in your stylesheets.

A better solution would be to just turn all of the text blue when the anchor is hovered. The !important is not needed:

.gray-text {
  color: gray;
}
a:hover,
a:hover .gray-text {
  text-decoration: underline;
  color: blue;
}
Click Here  (Sub-Title)

A: Try this. You can update the colour of the text inside the span tag when a tag is hovered.

.gray-text {
  color: gray;
}
.gray-text:hover {
  color: blue;
}

a:hover {
  text-decoration: underline;
  color: blue!important;
}

a:hover span {
    color: blue;
}

Click Here  (Sub-Title)


text:
Q: Is there an aggregate function in mysql that just picks any value from a series? I'm writing a program to analyze stock prices. I have two MySQL tables loaded with dummy data as shown below.
mysql> select * from stock;
+----+--------+
| id | symbol |
+----+--------+
|  1 | A      |
|  2 | B      |
|  3 | C      |
|  4 | D      |
|  5 | E      |
|  6 | F      |
+----+--------+
6 rows in set (0.00 sec)

mysql> select * from stockhistory;
+----+--------------+-----------+
| id | trading_date | close     |
+----+--------------+-----------+
|  1 | 2018-01-01   | 200.00000 |
|  2 | 2018-01-02   | 150.00000 |
|  3 | 2018-01-03   | 120.00000 |
| 10 | 2018-04-28   | 105.00000 |
| 18 | 2018-05-02   | 105.00000 |
|  4 | 2018-05-03   | 105.00000 |
|  9 | 2017-05-02   | 400.00000 |
|  5 | 2017-11-11   | 200.00000 |
|  6 | 2017-11-12   | 300.00000 |
|  7 | 2017-11-13   | 400.00000 |
|  8 | 2017-11-14   | 500.00000 |
| 11 | 2018-04-28   | 105.00000 |
| 12 | 2018-04-29   | 106.00000 |
| 13 | 2018-04-30   | 107.00000 |
| 14 | 2018-05-01   | 108.00000 |
| 15 | 2018-05-02   | 109.00000 |
| 16 | 2018-05-03   | 110.00000 |
| 17 | 2018-05-04   |  90.00000 |
+----+--------------+-----------+
18 rows in set (0.01 sec)

I want to find all the stocks that made a yearly low within the past week. But to make this question more straightforward, assume that I want to see all the stocks whose lowest closing price since '2017-05-04' occurred on or after '2018-04-30'.
This is the query that does it:
mysql> select
    ->     s.symbol,
    ->     min(sh.trading_date),
    ->     min(low_table.low)
    -> from
    ->     (
    ->         select
    ->             stock_id,
    ->             min(close) as low
    ->         from
    ->             stocks_stockhistory
    ->         where
    ->             trading_date >= '2017-05-04'
    ->         group by
    ->             stock_id
    ->     ) as low_table,
    ->     stocks_stockhistory as sh,
    ->     stocks_stock as s
    -> where
    ->     sh.stock_id = low_table.stock_id
    ->     and sh.stock_id = s.id
    ->     and sh.close = low_table.low
    ->     and sh.trading_date >= '2018-04-30'
    -> group by
    ->     s.symbol
    -> order by
    ->     s.symbol asc;
+--------+----------------------+--------------------+
| symbol | min(sh.trading_date) | min(low_table.low) |
+--------+----------------------+--------------------+
| A      | 2018-05-02           |          105.00000 |
| C      | 2018-05-04           |           90.00000 |
+--------+----------------------+--------------------+
2 rows in set (0.01 sec)

My question is about the select-clause of this SQL query.
I want to de-dupe rows for stocks that hit their low more than once since 2018-04-30.

*

*To de-dupe the s.symbol field, I group by it.

*To de-dupe the sh.trading_date field, I do a min() in it. But I don't care if it is the minimum value. Any sh.trading_date value will do. Is there an aggregate function I can use instead of min() to pick any value? It seems wasteful to calculate the min if I don't need it.

*To de-dupe the low_table.low Field, I do a min() in it. But I don't care if it is the minimum value. In fact, all the values are the same. Is there an aggregate function I can use instead of min() to pick any value?

A: If  the values in low_table.low are all the same, you can just remove the aggregation function on that field. The GROUP BY will then select an arbitrary value for it, but since they are all the same it won't matter.
Note that you will need to low_table.low to your GROUP BY clause.
Since the values in sh.trading_date can differ, you will need to keep an aggregation function on that field. If you didn't you would have to add it to the GROUP BY clause, which would cause extra lines in the output. As long as you have to use one, MIN is probably as efficient as any of them.


text:
Q: Scrapy shell response returns less items than Selector Gadget extension in chrome for the same class I was scraping job applications from below portal using scrapy. But i get only 10 items in scrapy shell for the class which shows 15 items in developer tools and via selector gadget. I am confused about this difference.
Page tested on: https://www.waahjobs.com/s/software-developer-jobs-in-mumbai/
Class selected using Selector Gadget Extension: .r-95jzfe .css-1dbjc4n .r-1pn2ns4
Number of items: 15 (also counted manually.)
Scrapy shell input:
scrapy shell "https://www.waahjobs.com/s/software-developer-jobs-in-mumbai/"
obj = response.css(".r-95jzfe .css-1dbjc4n .r-1pn2ns4")
print(len(obj))
Scrapy shell output: 10
Expected output: 15
Update:
Bypassed the need to scrape data by directly hitting backend. Useful link to convert curl request to Scrapy code - https://michael-shub.github.io/curl2scrapy/
But still facing problem on some websites even after using scrapy-splash.
What i did:

*

*Integrated scrapy with splash

*Started splash on localhost using docker

*then performed command fetch('http://localhost:8050/render.html?url=https://www.hirist.com/login') on scrapy terminal.

Result: view(response) gives 404 on chrome
Expectation: https://quotes.toscrape.com/ works but https://www.hirist.com doesn't.
As you can see in this image that splash is not able to load the page. HTML is also not readable. HTML Contains correct data though
Kindly help.


text:
Q: Ajax Pagination for ajax loaded data in cakephp 3.4 I am using CAKEPHP 3.4. Ajax pagination is working fine for first loaded data. then I am using ajax filter to filter list which is working fine. When I am clicking page 2 on ajax loaded pagination it is loading all the previous data before filtering. This is the following code  which I have used for pagination.
$(".pagination a").bind("click", function (event) {
if(!$(this).attr('href'))
  return false;
$.ajax({
  dataType:"html",
  evalScripts:true,
  data:'state=1&category=6',
  success:function (data, textStatus) {$("#searchResult").html(data);},
  url:$(this).attr('href')
});
return false;

});


text:
Q: Windows machine to send email What software/package required on a new Windows machine (say Win10) to send email. My understanding is that it needs SMTP client kind of software installed to communicate with an SMTP server to able to send email. I know we can use telnet to an SMTP server on port 25 and send email. But what is not clear to me how an application will send email - does it need integration with SMTP client on that machine to communicate with SMTP server?
I think I have problem with basic concept here? Anybody can help?

A: To just send an email message open a PowerShell session and type something like this:
Send-MailMessage -From "User01 <user01@example.com>" -To "User02 <user02@example.com>" -Subject "the subject" -Body "some body" -SmtpServer "smtp.fabrikam.coz"

PowerShell is included in all current Windows versions, more information on the  Send-MailMessage cmdlet.
Under the hood PowerShell is using classes in the .NET Framework. If your application is written in .NET itself, you can just use those same classes. Otherwise you could use a COM wrapper around .NET code and use the COM Object from your code. There are also third party components available which allow you to send email, but all of this is more a question for StackOverflow.

A: https://windowsreport.com/free-mail-server-windows-10/
The above link should give you some options. In a nutshell you need to install some time of mail server software on your windows instance.
If your just trying to setup an email client on your windows machine then you want to pick a client, install it, and then follow the instructions for that client on how to setup your email account. Usually this is going to be a POP3 or IMAP type of situation.


text:
Q: Matching regex patterns in order I am building a mini parser which will take images or attachments and build an array of the data for my own use later.
I can successfully parse my data with my patterns, however, the way that I am parsing the original text is by running two separate match loops to get the data and push into an array.
As a result, the order of the data in my final array is out of order relative to the original text.   Here is an example:
Original Data
[ATTACH]1234[/ATTACH]
[IMG]http://www.google.com/abc.gif[/IMG]
[ATTACH]5678[/ATTACH]
[IMG]http://www.google.com/def.gif[/IMG]

RESULT ARRAY
0 : http://www.google.com/abc.gif
1 : http://www.google.com/def.gif
2 : 1234
3 : 5678

In actuality, I would want the result array to look like this
DESIRED RESULT ARRAY
0 : 1234
1 : http://www.google.com/abc.gif
2 : 5678
3 : http://www.google.com/def.gif

Here is a shortened version of the code I am using the do this
//Container Array of Images
var imagesContainerArray = {};
var daC = 0;
var finalData = {};

//Individual Images
var pattern = /\[IMG]([\s\S]*?)\[\/IMG\]/gi;
var match;

while (match = pattern.exec(text)) {

    finalImageUrl = match[1];

            //Other stuff i'm doing

    imagesContainerArray[daC] = finalImageUrl;

    daC++;
}

//Individual ATTACH
var pattern = /\[ATTACH]([\s\S]*?)\[\/ATTACH\]/gi;
var match;

while (match = pattern.exec(text)) {

    finalImageUrl = match[1];

            //Other stuff i'm doing

    imagesContainerArray[daC] = finalImageUrl;

    daC++;
}

A: You can put all in one pattern:
var pattern = /\[(IMG|ATTACH)]([\s\S]*?)\[\/\1\]/gi;
var match;

while (match = pattern.exec(text)) {

    finalImageUrl = match[2];

    imagesContainerArray[daC] = finalImageUrl;

    daC++;
}

To apply different treatment according to the tag name, you can use a switch/case statement. Example:
var pattern = /\[(IMG|ATTACH)]([\s\S]*?)\[\/\1\]/gi;
var match;

while (match = pattern.exec(text)) {

    finalImageUrl = match[2];

    switch (match[1].toUpperCase()) {
        case "IMG":    ...
                       break;
        case "ATTACH": ...
                       break;
        ...
    }

    imagesContainerArray[daC] = finalImageUrl;

    daC++;
}

A: If the inputs are always in pairs like that you can insert them into your "array" (noting that what you are calling an "array" is actually not, it's a plain "object") like this:
//Individual Images
var pattern = /\[IMG]([\s\S]*?)\[\/IMG\]/gi;
var match;
daC = 1;  // <=- Note starting index
while (match = pattern.exec(text)) {
    finalImageUrl = match[1];
            //Other stuff i'm doing
    imagesContainerArray[daC] = finalImageUrl;
    daC+=2;
}
//Individual ATTACH
var pattern = /\[ATTACH]([\s\S]*?)\[\/ATTACH\]/gi;
var match;
daC = 0;  // <=- Note starting index
while (match = pattern.exec(text)) {
    finalImageUrl = match[1];
            //Other stuff i'm doing
    imagesContainerArray[daC] = finalImageUrl;
    daC+=2;
}

That is, insert the "ATTACH" items with even-numbered indexes, and insert the "IMG" items with odd-numbered indexes.


text:
Q: Is there a chance that my real IP can be traced if I surf through a VPN? Is there a chance that my real IP can be traced if I surf through a VPN?
Which IP is registered to any particular website I visit?  What if I disconnect the VPN after browsing, can my real IP be still traced from the VPN I used?
I have searched for this on the web but found nothing.  Appreciate all your suggestions and answers.

A: Your 'IP address' is just one piece of the traces you leave behind when you communicate with another involved party:

*

*You do not know what the VPN-provider does once your session is over. Does it log your IP? Has someone else hacked the VPN-provider? If someone has the authority to he might just trace your communication back to the VPN-provider, then go to the provider with a piece of legal voodoo or with some bullies and force him to hand over your 'real' 'IP address'.

*If you do not communicate over encrypted channels (https, etc) to the endpoint, all the other stuff like your username or your login-email etc are all transmitted in plain-text. Have you control over all involved stations between your VPN-provider and the endpoint? Unlikely.

*Have you control over the endpoint and what they might do with the information they have about you? Unlikely.

*Somewhere in between the the VPN-provider and your endpoint might inject some malicious code into your session while you are surfing the web. Then this piece of code runs on YOUR machine and it might just disclose any information it can collect, your 'real IP' is only one tiny piece of that.

*You don't need the IP address of someone to detect with a very high rate of accuracy that it's the same person, check http://en.wikipedia.org/wiki/Behavioral_targeting
etc etc. You can use Tor to blur your identity ... but if someone want's to trace you he is able to do so. The more money is involved, the more likely this is.
'Anonymity' is not the feature you get out of using a VPN.

A: Websites will see the address of the VPN provider, and know you are emerging from said VPN provider.
Your ISP will see encrypted traffic to VPN provider, but they can't see what you are doing with it.
Some VPNs claim not to keep logs, but those that do can access your logs if they found you doing some unethical activities on the web, usually with a subpoena by police etc. But they usually don't look into users data by themselves, because their data base is big, and how can they check every single persons activity-not worth the manpower and resources.
VPN will mask your original IP, and with that no one can identify where you actually coming from. But you need to make sure that the IP you are using has strong protocols. If you are using dynamic IP then every session will give you new IP, so the chance are rare that someone can find out who you are, and what you are doing.
However, there are rumours that the NSA can penetrate VPNs, but keep in mind that this is just a rumour.


text:
Q: el contenido de mi fichero de texto se borra cuando hago print("ARCHIVO".readlines()) Las variables por si hay algo mal
# FILE #

File_Select = input("FILE DIR / FILE NAME> ")
File = open(File_Select, "r+")
FileA = open(File_Select, "a")
FileC = open(File_Select, "w")
File_Mode = input("RUN File / READ File / WRITE File / CLEAR File [FRun][FRead][FWrite][FClear] >>> ")

aqui estan las funciones que se ejecutan al segundo input que es que haras con el codigo como escribir leer borrar o run que es algo experimental y no interfiere porque esta en otro archivo por eso el [FRun]
#   FMODE FUNC  #

def READ(FILE):
    try:
        with open(FILE) as File:
            print(File.readlines())
    except:
        print("Hay problemas con el nombre del archivo")

def ADD():
    FWRITE = input(">>> ")
    FileA.writelines(FWRITE)
    print("FILE CONTENT ADDED:", FWRITE)
    FileA.close()

def Clear():
    FileC.writelines("CONTENT CLEARED")
    print("FILE CONTENT CLEAR")
    FileC.close()

detecto que quiere hacer el usuario y ejecuto la funcion
#   FMode MANAGER   #

if File_Mode.lower() == "frun": #ignorar
    File_check()

if File_Mode.lower() == "fread":
    READ(File_Select)

if File_Mode.lower() == "fwrite":
    ADD()

if File_Mode.lower() == "fclear":
    Clear()

A: debería funcionar al llamar la función, aunque la línea Archivo en la función no es necesaria, pero te aconsejo algo:
SELECCION_ARCHIVO = (input("Nombre del archivo: ")) #Uso un input para la selección de archivo

def LEER_Archivo(arch):

no opero con el nombre todavía y al crear la función le paso un parámetro que será el nombre del archivo
try:
    with open(arch) as Archivo:
        print(Archivo.readlines())
except:
    print("Hay problemas con el nombre del archivo")

dentro de la función uso try y except para capturar algún posible error, como que no exista el archivo o esté mal el nombre
y lo manejo con with ya que por defecto trae el cerrar archivo por si me olvido de declararlo
y cuando lo abro no uso el modificador 'r' ya que viene por defecto y si bien no está mal es una redundancia.
LEER_Archivo(SELECCION_ARCHIVO)

por último llamo a la función pasándole el nombre obtenido con el input.
modifico lo anterior porque cambiaron el sentido de la pregunta original y lo aplico a la nueva.
#-*- coding:utf-8 -*-
File_Select = input("FILE DIR / FILE NAME> ")
File_Mode = input("RUN File / READ File / WRITE File / CLEAR File [FRun][FRead][FWrite][FClear] >>> ").lower()

def Modo(archivo,forma):
    modos={"fread": "r+",'fwrite':"a","fclear":"w"}
    modo = modos.get(forma)
    if forma:
        try:
            with open(archivo,modo) as File:
                if forma == "fread":
                    print(File.readlines())
                if forma == "fwrite":
                    ADD(File)
                if forma == "fclear":
                    Clear(File)

        except:
            print("Hay problemas con el nombre del archivo")
def ADD(ar):
    FWRITE = input(">>> ")
    ar.writelines(FWRITE)
    print("FILE CONTENT ADDED:", FWRITE)

def Clear(ar):
    ar.writelines("CONTENT CLEARED")
    print("FILE CONTENT CLEAR")

Modo(File_Select, File_Mode)

más de lo mismo, pero usando funciones que fueron agregadas y no elimino solo para tratar de respetar la lógica de la pregunta.

A: he descubierto el error que hay en tu codigo, al parecer al principio, denominas unas variables llamadas FileA, FileC y File
Cuando eso es ejecutado, al crear la variable File, Python recrea el archivo,
asi que he quitado todo esas variables del principio, y las he denominado en las funciones donde son necesarias, su nuevo codigo es este:
File_Select = input("FILE DIR / FILE NAME> ")
File_Mode = input("RUN File / Read File / WRITE File / CLEAR File [FRun] [FRead] [FWrite] [FClear]: ")
def READ(FILE):
try:
    with open(FILE) as File:
      print(File.readlines())
  except:
    print("Hay problemas con el nombre de archivo")
def ADD():
  FileA = open(File_Select, "a")
  FWRITE = input(">>> ")
  FileA.writelines(FWRITE)
  print("FILE CONTENT ADDED:", FWRITE)
  FileA.close()
def Clear():
  FileC = open(File_Select, "w")
  FileC.writelines("CONTENT_CLEARED")
  print("file content clear")
  FileC.close()
if File_Mode.lower() == "frun":
  pass
elif File_Mode.lower() == "fwrite":
  ADD()
elif File_Mode.lower() == "fread":
  READ(File_Select)
elif File_Mode.lower() == "fclear":
  Clear()

SOlamente acuerdese de colocarle las sangrias de nuevo, es decir, poner bien los tabuladores, porque el programa de escritura de Stack Overflow no funciona bien


text:
Q: Unexpected SOQL results I am trying to learn Querying sObject Relationships through the APEX workbook (http://www.salesforce.com/us/developer/docs/apex_workbook/apex_workbook.pdf )
I have 2 objects with a master relationship, in the booklet says that I can query the parent just by specifying the relationship, but for some odd reason the result is quite unexpected
list<Line_Item__c> s = [SELECT Name, Unit_Price__c,Merchandise__r.Price__c,Merchandise__r.Name, Merchandise__r.Description__c FROM Line_Item__c];
system.debug(s);

16:42:24:062 USER_DEBUG [11]|DEBUG|(Line_Item__c:{Name=2,
  Merchandise__c=a039000000APTh3AAH, Unit_Price__c=200.00,
  Id=a029000000BuFUuAAN}, Line_Item__c:{Name=1,
  Merchandise__c=a039000000APTh2AAH, Unit_Price__c=1.50,
  Id=a029000000BuKcNAAV}, Line_Item__c:{Name=1,
  Merchandise__c=a039000000APTh2AAH, Unit_Price__c=1.50,
  Id=a029000000BtuHCAAZ}

I am quering 5 fields but only obtaining 4, and 2 of them are ids when it should be text fields

A: When writing to the debug log system.debug does not include other SObject instances, like you'd get from relationship queries. For example, Account.name and Account.OwnerId would not be logged even if queried.
The data is there however, you just need a more verbose form of writing out the data, which JSON.serialize or JSON.serializePretty does quite well.
Changing your example to:
list<Line_Item__c> s = [SELECT Name, Unit_Price__c,Merchandise__r.Price__c,Merchandise__r.Name, Merchandise__r.Description__c FROM Line_Item__c];
system.debug(JSON.serializePretty(s));

You should see the related object's (Merchandise__r) fields.


text:
Q: Converting from integer to string in C I want to convert an integer to a string in C.  I have tried the following code but the program is constantly outputting a 9-digit number. Does someone knows what is the error please and how can I fix it?
int num = 158;
char str[5];
sprintf(str, "%d" ,num);
printf("The result is: %d" , sprintf);

Thanks!

A: Either you print the integer with %d
printf("The result is: %d\n", num);

or the string representation with %s
printf("The result is: %s\n" , str);

By doing
printf("The result is: %d" , sprintf);

You are printing the decimal representation of the address of the function sprintf. Example:
#include <stdio.h>
int main() {
int num = 158;
char str[5];
sprintf(str, "%d" ,num);
printf("The result is: %d\n", sprintf);
printf("The result is: %8x\n", sprintf);

}

Compile statically in order to make it easier to locate the address of sprintf.
➜  ~ [4] [Thu 13] $ gcc file.c -o bin -static

In the code, I also print the hexadecimal representation, which is easier to locate in the binary file. Output:
The result is: 4200768
The result is:   401940

You can actually check the linear address of sprintf in the ELF executable:
➜  ~ [4] [Thu 13] $ nm bin | grep sprintf
0000000000480830 W asprintf
0000000000480830 T __asprintf
0000000000480830 T ___asprintf
0000000000401940 T _IO_sprintf
0000000000480a40 T _IO_vasprintf
00000000004019d0 T __IO_vsprintf
00000000004019d0 T _IO_vsprintf
0000000000401940 T sprintf
0000000000401940 T __sprintf
0000000000480a40 W vasprintf
00000000004019d0 W vsprintf

As expected, 0x0000000000401940.

A: Change your printf to printf("The result is: %s" , str);.
%s is the specifier for strings and your string name is str. Printing with incorrect % specifiers invoke undefined behavior.

A: printf("The result is: %d" , sprintf);

This code attempts to print sprintf which is a function. So its address is passed to printf. That's just not what you intended to do. Not to mention the fact that %d with an address leads to undefined behavior.
To print the string you made, you do this:
printf("The result is: %s", str);

Note that you must use the %s format string because the argument you supply is a string.
If all you want to do is to print the value, then you can remove str, remove the call to sprintf, and get printf to perform the formatting:
printf("The result is: %d", num);

One advantage of this is that it avoids you having to decide how large a buffer to allocate. You allocated a buffer with length 5 which can accept numbers up to 4 digits, or 3 digits if negative. For values with more digits, then your code will overrun that buffer.


text:
Q: How to select two record set only if second one was successful? I am going to report result of a stored procedure (whether it was successful or has error) using a simple select statement before sending prepared record sets. so I just simply insert this select statement before sending real records sets. But even when I wrap these two select statement in a transaction to make them atomic yet if second select statement raises an error the first select executed and gives 'ok' and 'error' at the same time. here is the code:
CREATE PROCEDURE my_procedure
  @id INT = NULL
AS
  BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;

    BEGIN TRY
      BEGIN TRANSACTION;
      SELECT 1 AS [status], 'OK' AS [message];

      SELECT 1/0;
      COMMIT;
    END TRY
    BEGIN CATCH
      ROLLBACK;
      SELECT 0 AS [status], ERROR_MESSAGE() AS [message];
    END CATCH;
  END;

How could first select statement be done only if the the second statement is successful?

A: Maybe declare a couple of variables outsite of the TRY/CATCH. Then change their values in the CATCH if an error is thrown. After the TRY/CATCH, show the values of the variables.
ALTER PROCEDURE my_procedure
  @id INT = NULL
AS
  BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;
    DECLARE @status BIT = 1; --set status variable here
    DECLARE @message VARCHAR(MAX) = 'OK'; --set message variable here

    BEGIN TRY
      BEGIN TRANSACTION;

      SELECT 1/0;
      COMMIT;
    END TRY
    BEGIN CATCH
      ROLLBACK;
      SET @status = 0; --change value of @status in the CATCH block
      SET @message = ERROR_MESSAGE();--change value of @message in the CATCH block
    END CATCH;
    --show the value of each variable
    SELECT @status AS 'Status',@message AS 'Message'
  END;

A: Have you tried using RAISERROR() or THROW()? Specifically, using RAISERROR() with a severity of 11-19 will force the execution to jump to the CATCH block. See details at https://learn.microsoft.com/en-us/sql/t-sql/language-elements/raiserror-transact-sql.
Specifically take a look at Example 1:
BEGIN TRY
    -- RAISERROR with severity 11-19 will cause execution to
    -- jump to the CATCH block.
    RAISERROR ('Error raised in TRY block.', -- Message text.
               16, -- Severity.
               1 -- State.
               );
END TRY
BEGIN CATCH
    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();

    -- Use RAISERROR inside the CATCH block to return error
    -- information about the original error that caused
    -- execution to jump to the CATCH block.
    RAISERROR (@ErrorMessage, -- Message text.
               @ErrorSeverity, -- Severity.
               @ErrorState -- State.
               );
END CATCH;


text:
Q: Better way to share memory for multiprocessing in Python? I have been tackling this problem for a week now and it's been getting pretty frustrating because every time I implement a simpler but similar scale example of what I need to do, it turns out multiprocessing will fudge it up. The way it handles shared memory baffles me because it is so limited, it can become useless quite rapidly.
So the basic description of my problem is that I need to create a process that gets passed in some parameters to open an image and create about 20K patches of size 60x40. These patches are saved into a list 2 at a time and need to be returned to the main thread to then be processed again by 2 other concurrent processes that run on the GPU.
The process and the workflow and all that are mostly taken care of, what I need now is the part that was supposed to be the easiest is turning out to be the most difficult. I have not been able to save and get the list with 20K patches back to the main thread.
First problem was because I was saving these patches as PIL images. I then found out all data added to a Queue object has to be pickled.
Second problem was I then converted the patches to an array of 60x40 each and saved them to a list. And now that still doesn't work? Apparently Queues have a limited amount of data they can save otherwise when you call queue_obj.get() the program hangs.
I have tried many other things, and every new thing I try does not work, so I would like to know if anyone has other recommendations of a library I can use to share objects without all the fuzz?
Here is a sample implementation of kind of what I'm looking at. Keep in mind this works perfectly fine, but the full implementation doesn't. And I do have the code print informational messages to see that the data being saved has the exact same shape and everything, but for some reason it doesn't work. In the full implementation the independent process completes successfully but freezes at q.get().
from PIL import Image
from multiprocessing import Queue, Process
import StringIO
import numpy

img = Image.open("/path/to/image.jpg")
q = Queue()
q2 = Queue()
#
#
# MAX Individual Queue limit for 60x40 images in BW is 31,466.
# Multiple individual Queues can be filled to the max limit of 31,466.
# A single Queue can only take up to 31,466, even if split up in different puts.
def rz(patch, qn1, qn2):
    totalPatchCount = 20000
    channels = 1
    patch = patch.resize((60,40), Image.ANTIALIAS)
    patch = patch.convert('L')
    # ImgArray = numpy.asarray(im, dtype=numpy.float32)
    list_im_arr = []
    # ----Create a 4D Array
    # returnImageArray = numpy.zeros(shape=(totalPatchCount, channels, 40, 60))
    imgArray = numpy.asarray(patch, dtype=numpy.float32)
    imgArray = imgArray[numpy.newaxis, ...]
    # ----End 4D array
    # list_im_arr2 = []
    for i in xrange(totalPatchCount):
        # returnImageArray[i] = imgArray
        list_im_arr.append(imgArray)
    qn1.put(list_im_arr)
    qn1.cancel_join_thread()
    # qn2.cancel_join_thread()
    print "PROGRAM Done"

# rz(img,q,q2)
# l = q.get()

#
p = Process(target=rz,args=(img, q, q2,))
p.start()
p.join()
#
# # l = []
# # for i in xrange(1000): l.append(q.get())
#
imdata = q.get()

A: Queue is for communication between processes. In your case, you don't really have this kind of communication. You can simply let the process return result, and use the .get() method to collect them. (Remember to add if __name__ == "main":, see programming guideline)
from PIL import Image
from multiprocessing import Pool, Lock
import numpy

img = Image.open("/path/to/image.jpg")

def rz():
    totalPatchCount = 20000
    imgArray = numpy.asarray(patch, dtype=numpy.float32)
    list_im_arr = [imgArray] * totalPatchCount  # A more elegant way than a for loop
    return list_im_arr

if __name__ == '__main__':
    # patch = img....  Your code to get generate patch here
    patch = patch.resize((60,40), Image.ANTIALIAS)
    patch = patch.convert('L')

    pool = Pool(2)
    imdata = [pool.apply_async(rz).get() for x in range(2)]
    pool.close()
    pool.join()

Now, according to first answer of this post, multiprocessing only pass objects that's picklable. Pickling is probably unavoidable in multiprocessing because processes don't share memory. They simply don't live in the same universe. (They do inherit memory when they're first spawned, but they can not reach out of their own universe). PIL image object itself is not picklable. You can make it picklable by extracting only the image data stored in it, like this post suggested.
Since your problem is mostly I/O bound, you can also try multi-threading. It might be even faster for your purpose. Threads share everything so no pickling is required. If you're using python 3, ThreadPoolExecutor is a wonderful tool. For Python 2, you can use ThreadPool. To achieve higher efficiency, you'll have to rearrange how you do things, you want to break-up the process and let different threads do the job.
from PIL import Image
from multiprocessing.pool import ThreadPool
from multiprocessing import Lock
import numpy

img = Image.open("/path/to/image.jpg")
lock = Lock():
totalPatchCount = 20000

def rz(x):
    patch = ...
    return patch

pool = ThreadPool(8)
imdata = [pool.map(rz, range(totalPatchCount)) for i in range(2)]
pool.close()
pool.join()

A: You say "Apparently Queues have a limited amount of data they can save otherwise when you call queue_obj.get() the program hangs."
You're right and wrong there. There is a limited amount of information the Queue will hold without being drained. The problem is that when you do:
qn1.put(list_im_arr)
qn1.cancel_join_thread()

it schedules the communication to the underlying pipe (handled by a thread). The qn1.cancel_join_thread() then says "but it's cool if we exit without the scheduled put completing", and of course, a few microseconds later, the worker function exits and the Process exits (without waiting for the thread that is populating the pipe to actually do so; at best it might have sent the initial bytes of the object, but anything that doesn't fit in PIPE_BUF almost certainly gets dropped; you'd need some amazing race conditions to occur to get anything at all, let alone the whole of a large object). So later, when you do:
imdata = q.get()

nothing has actually been sent by the (now exited) Process. When you call q.get() it's waiting for data that never actually got transmitted.
The other answer is correct that in the case of computing and conveying a single value, Queues are overkill. But if you're going to use them, you need to use them properly. The fix would be to:

*

*Remove the call to qn1.cancel_join_thread() so the Process doesn't exit until the data has been transmitted across the pipe.

*Rearrange your calls to avoid deadlock

Rearranging is just this:
p = Process(target=rz,args=(img, q, q2,))
p.start()

imdata = q.get()
p.join()

moving p.join() after q.get(); if you try to join first, your main process will be waiting for the child to exit, and the child will be waiting for the queue to be consumed before it will exit (this might actually work if the Queue's pipe is drained by a thread in the main process, but it's best not to count on implementation details like that; this form is correct regardless of implementation details, as long as puts and gets are matched).


text:
Q: I Want It To Save Pictures By Extension All Images Downloaded From Wallpaper Application Are Saved As JPG Extension. I want it to save images by extension. For example, if the image has png extension, I want it to save as png, if it is gif, it should save with gif extension.
private static String pictureTempPath = "";
private static final String CHOOSER_MSG = "Choose Option";
private static final String IMAGE_PREFIX = "IMG_";
private static final String IMAGE_EXTENSION = ".jpg";

        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        String timeStamp = new SimpleDateFormat(DateUtilities.DateTimeFormat.YYMMDD_HHMMSS.toString(), Locale.US).format(new Date());
        String imageFileName = IMAGE_PREFIX + timeStamp;
        File photoFile = new File(path, imageFileName + IMAGE_EXTENSION);


text:
Q: android okhttp3 post header miss httponly cookie item Implement cookiejar and print log
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
    List<Cookie> cookies = persistentCookieStore.get(url);
    for (Cookie c : cookies)
        Log.d("zzzzzzzzz", c.toString());
    return cookies;
    //return persistentCookieStore.get(url);
}

open an website

OkHttp  : <-- 200 OK https: //bbs.et8.net/bbs/forumdisplay.php?sort=dateline&order=desc&page=1&f=147 (317ms)
OkHttp  : Server: nginx/1.8.1
OkHttp  : Date: Thu, 14 Jul 2016 13:09:40 GMT
OkHttp  : Content-Type: text/html; charset=UTF-8
OkHttp  : Transfer-Encoding: chunked
OkHttp  : Connection: keep-alive
OkHttp  : Vary: Accept-Encoding
OkHttp  : X-Powered-By: PHP/5.4.41
OkHttp  : Set-Cookie: bbsessionhash=ebaf33d3eed4e3371d6a6b7013d7530e; path=/; domain=.et8.net; HttpOnly
OkHttp  : Set-Cookie: bblastvisit=1468400840; expires=Fri, 14-Jul-2017 13:09:40 GMT; path=/; domain=.et8.net; secure
OkHttp  : Set-Cookie: bblastactivity=0; expires=Fri, 14-Jul-2017 13:09:40 GMT; path=/; domain=.et8.net; secure
OkHttp  : Cache-Control: private
OkHttp  : Pragma: private
OkHttp  : X-UA-Compatible: IE=7
OkHttp  : Strict-Transport-Security: max-age=31536000; includeSubDomains
OkHttp  : X-Frame-Options: SAMEORIGIN
OkHttp  : <-- END HTTP

post data to server:

OkHttp  : --> POST https:// bbs.et8.net/bbs/login.php http/1.1
OkHttp  : Content-Type: application/x-www-form-urlencoded
OkHttp  : Content-Length: 167
OkHttp  : --> END POST
zzzzzzzzz: bblastactivity=0; expires=Fri, 14 Jul 2017 13:09:40 GMT; domain=et8.net; path=/; secure
zzzzzzzzz: bblastvisit=1468400840; expires=Fri, 14 Jul 2017 13:09:40 GMT; domain=et8.net; path=/; secure
zzzzzzzzz: bbsessionhash=ebaf33d3eed4e3371d6a6b7013d7530e; domain=et8.net; path=/; httponly
OkHttp  : <-- 200 OK https://bbs.et8.net/bbs/login.php (76ms)
OkHttp  : Server: nginx/1.8.1
OkHttp  : Date: Thu, 14 Jul 2016 13:09:49 GMT
OkHttp  : Content-Type: text/html; charset=UTF-8
OkHttp  : Transfer-Encoding: chunked
OkHttp  : Connection: keep-alive
OkHttp  : Vary: Accept-Encoding
OkHttp  : X-Powered-By: PHP/5.4.41
OkHttp  : Set-Cookie: bblastvisit=1468400840; expires=Fri, 14-Jul-2017 13:09:49 GMT; path=/; domain=.et8.net; secure
OkHttp  : Set-Cookie: bblastactivity=0; expires=Fri, 14-Jul-2017 13:09:49 GMT; path=/; domain=.et8.net; secure
OkHttp  : Cache-Control: private
OkHttp  : Pragma: private
OkHttp  : X-UA-Compatible: IE=7
OkHttp  : Strict-Transport-Security: max-age=31536000; includeSubDomains
OkHttp  : X-Frame-Options: SAMEORIGIN
OkHttp  : <-- END HTTP

why the post header miss cookie item: set-cookie:bbsessionhash  ?


text:
Q: How to find emprical PDF by using the normalized histogram? first of all, thank you for your time, here is my question;
Is it possible to find emprical PDF by using normalized histogram?
I am trying to learn discrete event simulation and what I see is there is lots of statistical models which I am not so much familiar with. More specificly;
I have data points such as ;
26.5    74.1    80.3    72.3    87.7    60.9    98.3    52.1    40.8   74.3    13.4    92.5    79.2    74.1    84.1    42.6    57.3    65.4   66.5    72.5    55.2    33.2    79.2    33.9    18.4    83.6    10.4   56.3    82.5    99.8    49.9    19.6    68.3    45.4    59.9    16.8
And I find histogram like this

From there, what I really want is find the emprical PDF by using histogram that I obtained and make a graph like this;

Please note that, this is not a homework or something like that and also I actually solving and constructing histogram by hand. After that When I find this PDF, I will compare mean and variance by using it. I am assuming that I have to look to the histogram and make an assumption maybe?
Thank you again

A: If you standardize your histogram, you get a probability density function. In your case, this pdf will be a very poor approximation of the real pdf that rendered the process you measured, since you got only 36 data points. Having so few data, I would only compute the median and the mean of the data.
Since your data are numerical, I wouldn't fit any model with less than 100 data points.


text:
Q: .htaccess mod-rewrite: Modify working RewriteRule to catch any subdomain I have the following working RewriteRule:
RewriteCond %{QUERY_STRING}#%{HTTP_HOST} ^IG([^&#]+)#(?:www\.)?([^.]+)\. [NC]
RewriteRule ^ https://www.mysite.de/link/ig/%2/%1? [L,NE,R=302]

I would like to modify the RewriteRule to catch any subdomain not just www.
I honestly don't understand this part (?:www\.)?. The second ? says that everything before could occur 0 - any times. But I don't understand the first question mark in combination with the colon.
I tried this:
RewriteCond %{QUERY_STRING}#%{HTTP_HOST} ^IG([^&#]+)#(.+\.)?([^.]+)\. [NC]

and this:
RewriteCond %{QUERY_STRING}#%{HTTP_HOST} ^IG([^&#]+)#(?:.+\.)?([^.]+)\. [NC]

Both do not work.

A: I was wrong, this does work:
RewriteCond %{QUERY_STRING}#%{HTTP_HOST} ^IG([^&#]+)#(?:.+\.)?([^.]+)\. [NC]
RewriteRule ^ https://www.mysite.de/link/ig/%2/%1? [L,NE,R=302]

Could anyone explain this part (?:www\.)? anyway please?


text:
Q: Not all my text is showing for my input fields I have a few input filed on my site however the labels are not fully displayed. When I inspect the page there is more space to the label on the left side. The text in the blue isn't showing up even though in my code it is. I am not sure why all me texts aren't showing? Below I will provide the code and what I see.

                @Html.LabelFor(model => model.ManagerComment, htmlAttributes: new { @class = "control-label" })

                <input value="Meeting Scheduled" class="btn btn-link  nopadding fontsemilabel" onclick="location.href='@Url.Action("MeetingSch", "Strategy", new {id = Model.StrategyId})'" />

                <input value="Need to schedule visit" class="btn btn-link nopadding fontsemilabel" onclick="location.href='@Url.Action("SchVisit", "Strategy", new {id = Model.StrategyId})'" />

                <input value="Need to schedule eMeeting" class="btn btn-link nopadding fontsemilabel" onclick="location.href='@Url.Action("ScheMeet", "Strategy", new {id = Model.StrategyId})'" />

                <input value="No action at this time, followup planned" class="btn btn-link nopadding fontsemilabel" onclick="location.href='@Url.Action("NoAct", "Strategy", new {id = Model.StrategyId})'" />

                <input value="Samples Requested" class="btn btn-link nopadding fontsemilabel" onclick="location.href='@Url.Action("SampReq", "Strategy", new {id = Model.StrategyId})'" />

                <input value="Evaluating Samples" class="btn btn-link nopadding fontsemilabel" onclick="location.href='@Url.Action("EvalSamp", "Strategy", new {id = Model.StrategyId})'" />

                <input value="Need to Confirm CEM location" class="btn btn-link nopadding fontsemilabel" onclick="location.href='@Url.Action("ConfirmCEM", "Strategy", new {id = Model.StrategyId})'" />

            @Html.TextAreaFor(m => m.ManagerComment, 100, 50, new { id = "questionInput", maxlength = 1000, style = "width: 100%; max-width: 100%" })

                    <input value="New Update" class="btn btn-default" onclick="location.href='@Url.Action("Update", "Strategy", new {id = Model.StrategyId})'" />

CSS below:
.right {
    text-align: right;
}

textarea {
    width: 1000px;
    height: 200px;
}

.fontsemilabel {
    font-size: 10px;
    text-align: right;
}

.nopadding {
    padding: 0 !important;
}

A: if you are not aware of CSS then
simply apply table with correspondent data like

 <input value="Meeting Scheduled" class="btn btn-link  nopadding fontsemilabel" onclick="location.href='@Url.Action("MeetingSch", "Strategy", new {id = Model.StrategyId})'" />

<input value="Need to Confirm CEM location" class="btn btn-link nopadding fontsemilabel" onclick="location.href='@Url.Action("ConfirmCEM", "Strategy", new {id = Model.StrategyId})'" />

like...


text:
Q: android custom application theme not being applied I'm trying to copy over an existing Android project to start semi-new. In my old project i was able to apply a custom theme to the application. In my new application, even though i have copied over all of the style.xml files and changed the min and target sdk versions in the manifest i can't get it to build for it's minimum/target sdk. It builds but my application still has the old style notification bar at the top, not the Action bar. I have no idea how to force IntelliJ/Android to build for the new version.
my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.app"
          android:versionCode="1"
          android:versionName="1.0">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.CALL_PHONE"/>
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <uses-sdk android:minSdkVersion="11"
              android:targetSdkVersion="16"/>
    <application
            android:label="@string/app_name"
            android:theme="@style/AppTheme"
            android:icon="@drawable/app_icon"
            android:name=".injected.C2Application"
            >
        <activity android:name=".HomeActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

my style
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!--
    Base application theme, dependent on API level. This theme is replaced
    by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <item name="android:actionBarStyle">@style/LoginActionBarStyle</item>
        <item name="android:textColorHint">#D1D1D1</item>
    </style>

    <style name="LoginActionBarStyle" parent="@android:style/Widget.Holo.ActionBar">
        <item name="android:displayOptions">showHome</item>
        <item name="android:background">#333333</item>
    </style>

    <style name="LoginFormContainer">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:padding">16dp</item>
    </style>
</resources>

What it looks like now

What it should like

I have no idea what is/isn't being set.

A: You need a second style file for V11+ that inherits from Holo.
The easiest way to see the right way to do this is just make a new hello world project and see how they did it in there.
Also worth mentioning using this technique the actionbar will only be shown on V11+ devices.
To show it on all devices you would need to use ActionBarSherlock, but since you have your min version set to 11 maybe you don't plan on supporting 2.3 phones.
Example:
styles.xml
<resources>

<!--
    Base application theme, dependent on API level. This theme is replaced
    by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Light">
    <!--
        Theme customizations available in newer API levels can go in
        res/values-vXX/styles.xml, while customizations related to
        backward-compatibility can go here.
    -->
</style>

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>

values-v11 styles.xml
<resources>

<!--
    Base application theme for API 11+. This theme completely replaces
    AppBaseTheme from res/values/styles.xml on API 11+ devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Holo.Light">
    <!-- API 11 theme customizations can go here. -->
</style>

values-v14 styles.xml
<resources>

<!--
    Base application theme for API 14+. This theme completely replaces
    AppBaseTheme from BOTH res/values/styles.xml and
    res/values-v11/styles.xml on API 14+ devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
    <!-- API 14 theme customizations can go here. -->
</style>

manifest.xml

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.test.test.com.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>


text:
Q: Basic problems in python How can you store output of any piece of code into a new variable?
number=range(20)
for number in number:
    if number%2!=0:
        print(number)

Like I want to store the output of this in a new variable called 'odd_numbers'.

A: Use a list comprehension:
number = range(20)
odd_numbers = [i for i in number if i%2]

Or append them:
number = range(20)
odd_numbers = []
for i in number:
    if i % 2:
        odd_numbers.append(i)

A: odd_numbers = []
for i in range(20):
   if i%2 != 0:
       odd_number.append(i)

Any time you want to store something you should create bucket and put values into that bucket (variable, list, dict, set).


text:
Q: Joint Probability $\lvert X-Y \rvert$ of $2$ Uniformly Distributed Random Variables Disclaimer: I know that there are multiple questions on this site about this exact same question, but none of them were helpful for my specific situation.
Here's a question I found in a probability textbook:

A man and a woman agree to meet at a certain location at about 12.30pm. If the man arrives at a time uniformly distributed between 12.15pm and 12.45pm, and if the woman independently arrives at a time uniformly distributed between 12.00pm and 1.00pm, find the probability that the first to arrive waits no longer than 5 minutes.

I'm not too sure how to obtain the answer (which is apparently $\frac{1}{6}$) to this question.
My attempt:

According to WolframAlpha, the integral evaluates to
Which differs from the answer provided, $\frac{1}{6}$.
Does anyone know where I went wrong?

A: When solving such problems, it is often helpful to make a sketch of the support and the region in which the desired event occurs.

Here, the horizontal axis represents outcomes of $X$, corresponding to the random number of minutes of the man's arrival before or after 12:30, and the vertical axis represents outcomes of $Y$, corresponding to the random number of minutes of the woman's arrival before or after 12:30.  The blue shaded region represents those outcomes satisfying the condition that they meet within five minutes of each other's arrival.
Because the joint density of their arrival times is joint uniform, it follows that the desired probability is simply the area of the blue region divided by the area of the support.  Since the blue region is a parallelogram with base $10$ and height $30$, its area is $300$; the area of the support is $(30)(60) = 1800$, so the desired probability is $1/6$ as claimed.
However, the figure also gives insight as to how best to compute the probability analytically:  your computation integrated with respect to $x$, then $y$; this amounts to partitioning the parallelogram into horizontal strips, which is why you have three cases.  But the easier approach is to integrate in vertical strips, so there is only one case.  Specifically,
$$|X - Y| \le 5 \iff -5 \le Y - X \le 5 \iff X - 5 \le Y \le X + 5.$$  Now since $-15 \le X \le 15$, it follows that $-30 < -20 \le Y \le 20 < 30$ and there is no additional casework.  We get
$$\begin{align}
\Pr[|X-Y| \le 5]
&= \frac{1}{1800} \int_{x=-15}^{15} \int_{y=x-5}^{x+5} 1 \, dy \, dx \\
&= \frac{1}{1800} \int_{x=-15}^{15} (x+5) - (x-5) \, dx \\
&= \frac{1}{180} \int_{x=-15}^{15} 1 \, dx \\
&= \frac{1}{180} (30) \\
&= \frac{1}{6}.
\end{align}$$
For completeness' sake, if we were to do it your way, how would it work?  We would need to write
$$\begin{align}
\Pr[|X-Y| \le 5]
&= \frac{1}{1800} \left( \int_{y=-20}^{-10} \int_{x=-15}^{y+5} 1 \, dx \, dy + \int_{y=-10}^{10} \int_{x=y-5}^{y+5} 1 \, dx \, dy + \int_{y=10}^{20} \int_{x=y-5}^{15} 1 \, dx \, dy \right). \\
\end{align}$$
Contrast this with what you wrote in your solution.  The error arises from the fact that when $Y < -20$ or $Y > 20$, there is no $X$ in the range $[-15,15]$ that allows both people to meet within $5$ minutes of each other.  That is why your probability is smaller than $1/6$--the value of the integrals in those regions you have included is negative.


text:
Q: Identifying certain digits The result of a measurement is $57.64$ $\pm$ $0.38$ (for the sake of simplicity, I omit the measurement unit). I would know which are the certain digits in $57.64$ $\pm$ $0.38$. I know that $57.64$ has $4$ significant digits. According to the rule

the significant figures in a measurement consist of all the certain digits in that measurement plus one uncertain or estimated digit

I should say that $57.64$ $\pm$ $0.38$ has $2$ certain digits, in particular they are $5$ and $7$. But, if I rewrite $57.64$ $\pm$ $0.38$ as the interval $[57.26; 58.02]$, I see that the only digit that remains the same is $5$. Therefore, is it still possible to say that $7$ is a certain digit ? What is the definition of "certain digit" ?
Thank you in advance.

A: Per:
https://chem.libretexts.org/Bookshelves/Introductory_Chemistry/Map%3A_Introductory_Chemistry_(Tro)/02%3A_Measurement_and_Problem_Solving/2.02%3A_Significant_Figures_-_Writing_Numbers_to_Reflect_Precision
it appears "certain digits" refers to a single measurement on a graduated analog device such as a gauge (such as a thermometer or manometer), a clock, or ruler.
In such a case you can count tic marks with certainty, and then can estimate the fraction of the gap until the next tic for an uncertain "digit" (e.g., $\frac 1 2 \rightarrow 0.5$).
This idea does not carry over the traditional measurement:
$$ \bar x \pm \sigma_x $$
in which $\bar x$ is the average of many measurements and $\sigma_x$ is their standard deviation (or unbiased estimator thereof).
Per the example:
$$ \bar x = 57.64 $$
and
$$ \sigma_x = 0.38 $$
the true value could be $x=60.0$. It a 6.2 sigma fluctuation, which is very unlikely, but it is a possibility, meaning no digit is certain.


text:
Q: How to merge "static" observable with "dynamic" in rxjs 6? I'm writing chrome extension and decided to wrap everything into streams, mostly for training and take a look into rxjs.
So I'm stuck with such a problem. I have two streams, one stream is static (don't know how to correctly name it) and one dynamic.
A static stream is that one who emits value only when you subscribe to it (getPath$), it return value from a chrome storage.
A dynamic (message$) stream is a stream which listening for events(messages).
So my goal is somehow to merge this two stream and every time when I'm receiving a message from message$ get value from a getPath$ and make some calculations based on two values.
type Handler = (
    message: any,
    sender: any,
    sendResponse: (response: any) => void
) => void;

type Values  = string | string[];

const getValues = (values: Values) => (cb) => chrome.storage.local.get(values, cb)
const getPathBinded = bindCallback(getValues('path'))
const getPath$ = getPathBinded()

const message$ = fromEventPattern(
   (handler: Handler) => chrome.runtime.onMessage.addListener(handler),
   (handler: Handler) => chrome.runtime.onMessage.removeListener(handler),
   (message, sender, sendResponse) => ({ message, sender, sendResponse })
).pipe(
    map(
       ({ message }) => message
    )
)

I found how to do this in such a way:
message$.pipe(
    switchMap(
        _ => getPath$,
        (oV, iV) => {
            //doing some calculation
        }
    )
 )

Or
combineLatest(
  message$,
  getPath$,
).pipe(
    map((a, b) => {
       //doing some calculation
    })
)

Seems like it's working, but it feels like I am doing wrong. Any suggestions or how to do it following best approaches? Also, please correct me in definitions.
UPD
Here the full code: https://gist.github.com/
And the latest version which is work
const merged$ = message$.pipe(
   switchMap(sendedPath => combineLatest(
        path$,
        unit$
    ).pipe(
        map(([path, unit]) => [sendedPath, path, unit]))
    )
)

A: If your goal is

to merge this two stream and every time when I'm receiving a message from
  message$ get value from a getPath$ and make some calculations based on two values

it looks like the switchMap approach is the right one. switchMap in this case means: any time I receive a notification from message$ I switch to the other Observable, in this case the one returned by invoking getPath$.
If you then want to do something with both values, then probably you can not afford to ignore the value notified by message$, which is what your code currently does, and you have to pipe a map into the result of getPath$ so that you can create an object containing the 2 values notified by the 2 Observables and pass such object to the following calculation. The code should look like
message$.pipe(
    switchMap(
        message => getPath$.pipe(map(path => ({message, path}))),
        map(({message, path}) => {
            //doing some calculation
        })
    )
 )

A: What you name dynamic/static is similar to Hot and Cold Observables, but not exactly the same.
Your first approach with switchMap is mostly fine, except that you should recalculate it every time:
const combined$ = messages$.pipe(
  mergeMap(() => getPathBinded(), (message, path) => { ... })
)

I have also changed switchMap to mergeMap, otherwise, you may "lost" some of the messages, see RxJS: Avoiding switchMap-Related Bugs

And also you may simplify your code a little bit:
const getStorage = bindCallback(chrome.storage.local.get);
// use it as: const path$ = getStorage("path")

const message$ = fromEvent(chrome.runtime.onMessage);
// should be enough, since you are only using default methods


text:
Q: XSLT Dynamic Columns in XML I have an example xml, below,
    <?xml version="1.0" encoding="UTF-8"?>
<Root>
<Row>
<Group>Group A</Group>
<Date>2013-09-02</Date>
<Value>200</Value>
</Row>
<Row>
<Group>Group A</Group>
<Date>2013-09-02</Date>
<Value>500</Value>
</Row>
<Row>
<Group>Group A</Group>
<Date>2013-10-02</Date>
<Value>400</Value>
</Row>
<Row>
<Group>Group B</Group>
<Date>2013-09-02</Date>
<Value>250</Value>
</Row>
</Root>

I have an xslt (version 1.0) that would be used to summarise the data, with dynamic columns. I have the code create the HTML table and the results show the correct number of columns and the correct number of rows, I cannot get the cells in the main body of the table to sum the values in the "Value" node of the XML above.
XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:lookup="http://any.com/lookup" exclude-result-prefixes="lookup">
    <xsl:output method="html" indent="yes" encoding="UTF-8" />
    <xsl:decimal-format name="NN" NaN="-" />
    <lookup:Dates>
        <Date value="2013-09-02" />
        <Date value="2013-10-02" />
        <Date value="2013-11-04" />
        <Date value="2013-12-02" />
        <Date value="2014-01-02" />
        <Date value="2014-02-03" />
        <Date value="2014-03-03" />
    </lookup:Dates>
    <xsl:key name="Dates" match="/xsl:stylesheet/lookup:Dates" use="Date" />
    <xsl:key name="Group" match="Row" use="Group" />
    <xsl:template match="/">

                        Group
                        <xsl:for-each select="document('')/*/lookup:Dates/Date">

                                <xsl:value-of select="@value" />

                        </xsl:for-each>

                    <xsl:for-each select="/Root/Row[count(. | key('Group', Group)[1])=1]">
                        <xsl:sort select="Group" data-type="text" order="ascending" />
                        <xsl:variable name="curGroup" select="key('Group', Group)" />

                                <xsl:value-of select="$curGroup/Group" />

                            <xsl:for-each select="document('')/*/lookup:Dates/Date">

                                    <xsl:value-of select="sum($curGroup[/Root/Row/Date=current()/Dates/Date]/Value)" />

                            </xsl:for-each>

                    </xsl:for-each>

    </xsl:template>
</xsl:stylesheet>

The resulting HTML is:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

Group
2013-09-02
2013-10-02
2013-11-04
2013-12-02
2014-01-02
2014-02-03
2014-03-03

Group A
0
0
0
0
0
0
0

Group B
0
0
0
0
0
0
0

Any ideas where I am going wrong? I assume it is in the xpath in the line
<xsl:value-of select="sum($curGroup[/Root/Row/Date=current()/Dates/Date]/Value)" />

Many thanks
Graham

A: If you want to add a grand total row, then doing this won't work...
<xsl:for-each select="document('')/*/lookup:Dates/Date">

      <xsl:value-of select="sum(Root/Row[Date=current()/@value]/Value)" />

</xsl:for-each>

This is because inside the xsl:for-each loop your context is the Date element, so doing the xpath expression of Root/Row will be relative to that.
The solution is simply to define a variable (before the loop) holding all Row elements, and then reference that. Try this:
<xsl:variable name="allGroups" select="//Row" />
<xsl:for-each select="//Dates/Date">

         <xsl:value-of select="sum($allGroups[Date=current()/@value]/Value)" />

</xsl:for-each>


text:
Q: Volume of $M=\{(x,y,z)\in \mathbb R^3:|x|+|y|+|z|<1\}$ Let $M=\{(x,y,z)\in \mathbb R^3:|x|+|y|+|z|<1\}$.
How can I determine the volume of $M$, that is, $\lambda_3(M)$?
I think it would work like this:
$$\lambda_3(M)=\int_{-1}^{1}\int_{|x|-1}^{1-|x|}\int_{|x|+|y|-1}^{1-|x|-|y|}1\ dz\ dy\ dx$$
Are there faster ways to do it?
I thought about doing the following:
Let $M_z=\{(x,y)\in \mathbb R^2:|x|+|y|<1-|z|\}$.
Then
$$\lambda_3(M)=\int_{(-1,1)}\lambda_2(M_z)d\lambda(z)$$
But how can I determine $\lambda_2(M_z)$, that is the area of $M_z$?

A: Think of it geometrically, rather than as an integral. As @amsmath mentioned in the comments, it is a super symmetric shape. In fact, it is a regular octahedron centered at origin. We need only find the volume in the first octant. Which is the volume enclosed by the 3 co-ordinate planes and the plane $x+y+z=1$.

Hence, it's a pyramid with base a right angled triangle of area $1/2$. Hence, it's volume is ${\text{base} \times \text{height} \over 3}={1/2 \times 1 \over 3}=1/6$.
Hence, volume of $M$ is $8 \times 1/6 = 4/3$.
Edited dumb calculation thanks to @quarague.


text:
Q: How to create an automatic nested list and sub-lists with letters and/or Roman numerals in R-markdown? I am trying to generate a nested list with numbers, letters, and Roman numerals. R-Markdown cheatsheet shows

*

*ordered list

*item 2

*

*sub-item 1

*sub-item 2

but, this generates a sub-list with an unordered bullet. Instead of this, I need sub-list with letters and sub-sub-lists with Roman numerals like this:
1. What geoms would you use to draw the followings?
   a. A line chart
      i) `geom_line()`
   b. A boxplot
      ii) `geom_boxplot()`

Is there any way to do this? Thank you,

A: Luckily, I have found the answer to my question in another R-Markdown cheatsheet. The point is to put 4 spaces or 2 indents before the sub-list items and 8 spaces or 4 indents before the sub-sub-list items. The following is my code in R-Markdown:
1. What geoms would you use to draw the followings?
    a. A line chart
        i. `geom_bar()`
        i. `geom_line()`
    a. A boxplot
        i. `geom_boxplot()`
        i. box
    a. A histogram: `geom_histogram()`
    a. An area chart: `geom_area()`

The output is like this:
1. What geoms would you use to draw the followings?
    a. A line chart
        i. `geom_bar()`
        ii. `geom_line()`
    b. A boxplot
        iii. `geom_boxplot()`
        iv. box
    c. A histogram: `geom_histogram()`
    d. An area chart: `geom_area()`


text:
Q: Avoid double bundle install when using docker I'm using docker as my dev environment for my rails app with the following docker-compose.yml :
app:
  build: .
  ports:
    - "3000:3000"
  links:
    - db
    - mail
  volumes:
    - .:/usr/src/app
    - gemrc:/etc/gemrc
db:
  image: mdillon/postgis
  ports:
    - "5432:5432"
  environment:
    - POSTGRES_USER=user
    - POSTGRES_PASSWORD=password
    - POSTGRES_DB=database
  volumes:
    - ./docker/pgdata:/var/lib/postgresql/data
mail:
  image: djfarrelly/maildev
  ports:
    - "1080:80"

And my Dockerfile :
FROM rails:onbuild

When I need to add a new gem to my Gemfile, I have to first generate my  Gemfile.lock :
docker run --rm -v gemrc:/etc/gemrc -v /home/user/project:/usr/src/app -w /usr/src/app ruby bundle install

And the rebuild the docker image:
docker-compose build
docker-compose up

Because of this I have to run bundle install twice without being able to add the --without development test flag. In order to do it quicker I added this to my gemrc file:
gem: --no-document

But is there a way to avoid the double bundle install ?

A: Perhaps you might want to try the following docker-compose workflow for development environment.

*

*Similar to database.yml our docker-compose.yml is not included in our CVS (git), providing the similar benefits for developer custom config.

*Build your image locally before starting your app container and tag it something like foo_app:latest. It makes sense because you're in dev. Just execute docker build . in your app's root directory, assuming your Dockefile is in that directory.

*Define a data volume container for bundle and mount it in your app container. Your docker-compose.yml might look something like:
app:
  image: foo_app
  ports:
    - "3000:3000"
  links:
    - db
    - mail
  volumes:
    - .:/usr/src/app
  volumes_from:
    - bundle

bundle:
  image: foo_app:latest
  volumes:
    - /home/app/bundle

db:
  image: mdillon/postgis
  ports:
    - "5432:5432"
  environment:
    - POSTGRES_USER=user
    - POSTGRES_PASSWORD=password
    - POSTGRES_DB=database
  volumes:
    - ./docker/pgdata:/var/lib/postgresql/data
mail:
  image: djfarrelly/maildev
  ports:
    - "1080:80"

*Every time you need to add a new gem, just add it to your Gemfile and execute bundle install inside your app container. For example if your app container's name is foo_app_1:
docker exec foo_app_1 bundle install
The data volume container will always have the latest/edge snapshot of your app's gems.

*Tag your releases and build the "official release image" in a central repository accessible for your staging/production/team.
With this approach every time you start/recreate your app container, all of your gems be just as they were the last time you updated them. You can also use this approach for other kind of data you want to be persisted across containers life cycles, adding "components" to manage state in your stateless applications.
See https://docs.docker.com/engine/userguide/containers/dockervolumes/ for more information


text:
Q: Bayesian Neural Network in Keras: transforming simple ANN into BNN I am starting to learn about Bayesian Neural Networks. As such, apologies if my question may be too simple.
As a first step in my learning curve, I would like to transform a traditional ANN to a BNN. The ANN is very simple: 3 hidden layers, fully connected, with activation function given by tanh except for the output layer which has linear activation function.
This network should represent a mapping between my observables (in input) and the (6) parameters of my model, in output. The input observables are one-dimensional functions, which can be regarded as time series of 2001 time components, if one considers the independent variable as time.
The ANN architecture is shown below. As I said, I would like to transform this network into a Bayesian one. Following the excellent tutorial here I would think that the main changes to implement to obtain a BNN are: the 'neg_log_lieklihood' and the 'DenseVariational' layers.
Would these be the only transformations needed?
#!/usr/bin/env python
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from keras.layers import Input, Dense, Lambda, Reshape, Conv1D, MaxPooling1D, UpSampling1D, Flatten, Dropout
from keras.models import Model
from keras import backend as K
from keras import losses
from keras import optimizers
from keras import regularizers

# np.loadtxt training and testing data
X_train = #np.loadtxt ...
X_test = # np.loadtxt ...

y_train = # np.loadtxt ...
y_test = # np.loadtxt ...

# dimension of input (and label)
n_x = X_train.shape[1] # 2001
n_y = y_train.shape[1] # 6

Dense_1 = 1500
Dense_2 = 700
Dense_3 = 200

x = Input(shape=(n_x, ))
hidden = Dense(Dense_1, activation='tanh')(x)
hidden = Dense(Dense_2, activation='tanh')(hidden)
hidden = Dense(Dense_3, activation='tanh')(hidden)

output = Dense(n_y)(hidden)

net = Model(x, output)

epochs = 400

def recon_loss(y_true, y_pred):
    return K.mean(K.square(y_true - y_pred))

optim = optimizers.Adam(lr=0.001)
net.compile(optimizer=optim, loss=recon_loss, metrics=[recon_loss])

net_hist = net.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, validation_data = (X_test, y_test))


text:
Q: first homolgy group of a disk with $n$ holes Let $D^2$ be a 2-dim disk with $n$ holes, i.e $D^2\setminus(S^0 * D^2)^n$. Then is it true that the first homology group of this space is $\mathbb{Z}^n$.

A: It is true, the fundamental group of this space is the free group generated by $n$ elements since it retracts to the bouquet of n circles, so its first homology which is the abelianization of its fundamental group is $Z^n$.


text:
Q: Problem in sending and receiving date from C# code to SQL Server procedure I am generating a report through sending some parameter from C# code to a SQL Server stored procedure. I am sending a string value and two date values as a SQL Server procedure parameters, but I having some problems with the date parameter. I have checked my SQL Server stored procedure; when manually passing a value, it is returning the correct results, but when I am passing the parameter value from my code, it is showing nothing in report.
SQL Server stored procedure:
[GetLedger]
    (@optb VARCHAR(50),
     @startsession DATE,
     @endsession DATE)
AS
    DECLARE @openingtable
    DECLARE @strtdt DATE
    DECLARE @enddate DATE
    DECLARE @query NVARCHAR(MAX)
BEGIN
    SET @openingtable = @optb
    SET @strtdt = @startsession
    SET @enddate = @endsession
    SET @query = N'SELECT  l.trandate,l.voucherno,l.itemno,l.itemname,o.opening + COALESCE(SUM(l.recieve - l.returnback - l.issue) OVER (PARTITION BY l.itemno ORDER BY l.trandate,seq ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0) AS opening,l.recieve,l.returnback,l.issue,o.opening + SUM(l.recieve - l.returnback - l.issue) OVER (PARTITION BY l.itemno ORDER BY l.trandate,seq) AS balance,l.to_dept,l.remarks
FROM @openingstock o
INNER JOIN
(
SELECT trandate,voucherno,itemno,itemname,to_dept,remarks,isnull(recieve,0) AS recieve,isnull(issue,0) AS issue,isnull(returnback,0) AS returnback,
row_number() over (partition by itemno,trandate order by itemno) as seq
FROM @ledgertable
) l
ON l.itemno = o.itemno
where l.trandate between CONVERT(Date,''' + CONVERT(VARCHAR(10),@strtdt, 101)+''', 101) and CONVERT(DATE,'''+ CONVERT(VARCHAR(10),DATEADD(DD,1,@enddate),101) + ''', 101)
ORDER BY l.itemno,trandate'

    EXECUTE(@query)
END

C# code is:
private ledgerdt GetData(string p1,string p2,string p3)
{
    string DateString = p2;
    IFormatProvider culture = new CultureInfo("en-US", true);
    DateTime pp2 = DateTime.ParseExact(DateString, "yyyy-MM-dd", culture);
    string DateString2 = p2;
    IFormatProvider culture2 = new CultureInfo("en-US", true);
    DateTime pp3 = DateTime.ParseExact(DateString, "yyyy-MM-dd", culture2);

    using (SqlConnection con = new SqlConnection(conString))
    {
        SqlCommand cmd = new SqlCommand("GetLedger", con);

        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.AddWithValue("@optb", p1);
            cmd.Parameters.AddWithValue("@startsession", pp2.ToString("yyyy-MM-dd"));
            cmd.Parameters.AddWithValue("@endsession", pp3.ToString("yyyy-MM-dd"));

            sda.SelectCommand = cmd;

            using (ledgerdt ds = new ledgerdt())
            {
                sda.Fill(ds, "ledgerdt");
                return ds;
            }
        }
}

Please tell the solution..... I know that I am doing something wrong in data type.

A: Added the code using Add instead of AddWithValue:
using (SqlConnection con = new SqlConnection(conString))
using (SqlCommand cmd = new SqlCommand("GetLedger", con))
using (SqlDataAdapter sda = new SqlDataAdapter())
{
        cmd.Connection = con;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add(new SQLParameter("@optb", Data.SqlDbType.VarChar);
        cmd.Parameters.Add(new SQLParameter("@startsession", Data.SqlDbType.DateTime));

        cmd.Parameters.Add(new SQLParameter("@endsession", Data.SqlDbType.DateTime));
        command.Parameters("@optb").Value = p1;
        command.Parameters("@startsession").Value = pp2;
        command.Parameters("@startsession").Value = pp3;

        sda.SelectCommand = cmd;

        using (ledgerdt ds = new ledgerdt())
        {
            sda.Fill(ds, "ledgerdt");
            return ds;
        }
}


text:
Q: CDI: How to debug / inspect? Since I'm new to CDI, I encounter strange behaviors now and then which I can't explain (cyclic injection until OOMError, Interceptor not invoked on some beans, etc).
Is there a (simple) way to print a tree of beans and dependencies?

A: I dump this JSP in my test applications using openwebbeans
http://people.apache.org/~covener/debug.jsp
You could probably remove the openwebbeans-isms and still get a nice cheap little rundown of the beans.  The JSR299 API gives you access to far more than what's dumped here.
(posted without any kind of cleanup)


text:
Q: Providing R/W access to phpmyadmin page How do i provide read and write access to my teammate for the php myadmin page(local host/MySQL) of the server?I am using wamp server.

A: You need to create a MySQL user with Read and Write Privileges.
Login as root user and create new user with required privileges
GRANT SELECT , INSERT , UPDATE , DELETE ON db_name.* TO 'user'@'hostname' IDENTIFIED BY 'some_password';

Explanation
GRANT - This is the command used to create users and grant rights to databases, tables, etc.
SELECT , INSERT , UPDATE , DELETE  - This tells it the user will have these privileges.
db_name.* - This instructions MySQL to apply these rights for the use onto the full dbtest database. You can replace the * with specific table names or store routines if you wish.
TO 'user'@'hostname' - 'user' is the of the user account you are creating. Note: You must have the single quotes in there. 'hostname' tells MySQL what hosts the user can connect from. If you only want it from the same machine, use localhost
IDENTIFIED BY 'password' - As you would have guessed, this sets the password for that user.
Have a look at Adding User Accounts in MySQL


text:
Q: Setting Discrete Colors in Matplotlib Imshow I have seen numerous resources for establishing unique cmap color codes, such as:
i) Merge colormaps in matplotlib
ii) Python: Invalid RGBA argument 0.0 color points according to class
iii) Defining a discrete colormap for imshow in matplotlib
None of these quite answer my question. I have 900 rows and each row has 200 data points that are either 1 or 0. In the finished product, the top 20% of the chart should have blue spikes for 1's and the bottom 80% should have red spikes for 1's. So y-axis >=720== blue and y-axis <720 = red.
The imshow cmap codes for these colors are plt.cm.Blues and plt.cm.Red
It's relatively easy to have all the spikes be coded blue:
img0 = raster[0].imshow(spikes, cmap=plt.cm.Blues, origin='lower', aspect="auto")

However, when I try to split the coding of cmap, I run into RGB errors related to the format of the input data. My code is below, and any help would be appreciated.
colors1 = plt.cm.Reds(np.linspace(0,1,int(200*900*.8)).reshape(int(900*.8),200))
colors2 = plt.cm.Blues(np.linspace(0,1,int(200*900*.2)).reshape(int(900*.2),200))
cmap = matplotlib.colors.LinearSegmentedColormap.from_list('mycmap', np.append(colors1,colors2))
img0 = raster[0].imshow(spikes, cmap=cmap, origin='lower', aspect="auto")

Final answer that works

img0 = raster[0].imshow(spikes[720:,:], cmap='Blues', extent=[0, 30, 720, 899], origin='lower', aspect="auto")
img0 = raster[0].imshow(spikes[:720,:], cmap='Reds', extent=[0, 30, 0, 719], origin='lower', aspect="auto")
raster[0].set_ylim(0, 900)

A: Based on your comments, all you want is two images with different colormaps on the same axes:

import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(900, 30)

fig, ax = plt.subplots()
img0 = ax.imshow(data[:720,:], cmap='Blues', vmin=0, vmax=1,
                  extent=[0, 30, 0, 719],
                  origin='lower', aspect="auto")
img1 = ax.imshow(data[720:,:], cmap='Reds', vmin=0, vmax=1,
                  extent=[0, 30, 720, 899],
                  origin='lower', aspect="auto")
ax.set_ylim(0, 900)
plt.show()

Something like
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

data = np.random.rand(50, 30) * 900

bottom = cm.get_cmap('Blues', 204)
top = cm.get_cmap('Reds', 52)

newcolors = np.vstack((bottom(np.linspace(0, 1, 204)),
                       top(np.linspace(0, 1, 52))))
newcmp = ListedColormap(newcolors, name='RedBlue')
img0 = plt.imshow(data, cmap=newcmp, vmin=0, vmax= 900,
                        origin='lower', aspect="auto")
plt.colorbar()
plt.show()


text:
Q: Can I debug a Grails application with a Text Editor such as Sublime Text 2? I am getting started with Grails and I watched quite a few videos where the presenters demonstrated Grails 2.X with the command line and a text editor such as textmate.
Here are my 2 questions:

*

*Is it the recommended workflow or most popular one? Or most people use STS?

*I enjoy text editors and I would like to know if it is possible to debug a Grails app with Sublime Text 2
Thanks

A: You can debug grails applications outside of an IDE with the bare bones jdb debugger that comes with the JDK.  You won't get the typical IDE debugging experience, but something more like a traditional command-line debugger like gdb on Unix.
To get started, run your application with grails -debug instead of grails.  You'll see
Listening for transport dt_socket at address: 5005

At this point, run jdb as follows:
jdb -attach localhost:5005

You should be prompted with a prompt like main[1].  Now you can set breakpoints and watches and start your app.  For example:
main[1] stop in mypackage.MyController.action()
Deferring breakpoint mypackage.MyController.action().
It will be set after the class is loaded.
main[1] run

When the breakpoint is hit, you can step through the code with step and next, and continue running with cont.


text:
Q: How can I display Arabic text in fpdf? I am using fpdf in php for developing pdf. I have to include some static Arabic or Farsi text to this pdf. I had used
$farsi_txt = iconv('UTF-8', 'ISO-8859-5', html_entity_decode('حضور محترم'));
 $pdf->Write(5,$farsi_txt);
 But the output was Blank.
 When I had displayed it directly
$pdf->Write(5,'فغانستان کابل');
then the out put was like ٕغانستان کابل
When I had created a window to insert the arabic text to database then the output was  حضور محترم

Is there any way to display this text as Arabic or Farsi in fpdf?

A: Found the answer for my question. I had replaced FPDF with TCPDF. TCPDF provides special fonts for Arabic and Farsi languages. I had got the correct output using TCPDF. I simply done this by switching font and $tpdf->setRTL(false); this sets the right to left alignment if arabic words.
TCPDF Download link

A: take a look  here. This page specifically talks about adding new Fonts and encodings, which I believe is the issue as the PDF is missing the Arabic font and is unable to find a replacement for characters.