text:
Q: table-join selection performance: get members from nested groups (large amount) I have three tables which define member & group profiles like so:

[tbMember] (1M records): MemberID(PK) | MemberName | Age | Sex
[tbGroup] (10K records): GroupID(PK) | GroupName | ParentGroupID
[tbMemberGrouopRelation] (2M records): MemberID | GroupID

Groups are ordered in hierarchical structure:
     /--- 2
1 --/---- 3    /--- 5
    \---- 4 --/---- 6
              \---- 7

When I grab some members from particular group (and all its subgroups), I write my SQL like (in SQL Server 2012):
SELECT m.MemberID, m.MemberName, m.Age, m.Sex
FROM tbMember m
  LEFT JOIN tbMemberGroupRelation mg ON (mg.MemberID = m.MemberID)
WHERE mg.GroupID IN (
    SELECT GroupID FROM FN_GetAllSubgroups(1)
  )
ORDER BY m.MemberID DESC
OFFSET 1000 ROWS FETCH NEXT 40 ROWS ONLY

Where FN_GetAllSubgroups implemented like this:
CREATE FUNCTION [dbo].[GetAllSubgroups] (@parentID int)
RETURNS @t TABLE(GroupID int, ParentID int, GroupName nvarchar(128))
BEGIN
    WITH GroupList
    AS
    (
        SELECT GroupID, ParentID, GroupName
        FROM dbo.tbGroup
        WHERE GroupID = @parentID UNION ALL
        SELECT a.GroupID, a.ParentID, a.GroupName
        FROM tbGroup a
            INNER JOIN GroupList b on a.ParentID = b.GroupID
    )
    INSERT INTO @t
    SELECT a.GroupID, a.ParentID, a.GroupName FROM dbo.tbGroup a
        INNER JOIN GroupList b on a.GroupID = b.GroupID
    ORDER BY a.ParentID, a.DisplayOrder
    RETURN
END

GO

-- index on tbGroup is ParentID (INCLUDE[GroupID, GroupName, DisplayOrder])

The function itself processes quite fast, even selecting from a top node group (returns 10k subgroups), processing time is within 200ms
However, when I do table join selection that select members from particular subgroup collections, it becomes extremely slow (look at my first SQL). I checked execution plan and it tells me Clurster Index Seek on tbMember takes up to 97% of time, Estimate rows = 1 and actual rows usually >= 20K
Are there any solutions to make it faster ?
Highly appreciate your help !
======================================
UPDATE: Execution result pasted below

(40 row(s) affected)
Table '_tbMember'. Scan count 0, logical reads 4679267, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table '_tbMemberGroupRelation'. Scan count 9516, logical reads 32484, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table '#AC4BBD06'. Scan count 1, logical reads 51, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
(1 row(s) affected)
SQL Server Execution Times:
CPU time = 2953 ms,  elapsed time = 9143 ms.
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 0 ms.
SQL Server Execution Times:
CPU time = 0 ms,  elapsed time = 0 ms.

A: You could try transforming your function into an iTVF:
CREATE FUNCTION [dbo].[GetAllSubgroups] (
    @parentID int
)
RETURNS TABLE
AS
RETURN

WITH GroupList AS (
    SELECT
        GroupID,
        ParentID,
        GroupName
    FROM dbo.tbGroup
    WHERE GroupID = @parentID
    UNION ALL
    SELECT
        a.GroupID,
        a.ParentID,
        a.GroupName
    FROM tbGroup a
    INNER JOIN GroupList b
        ON a.ParentID = b.GroupID
)
SELECT
    a.GroupID,
    a.ParentID,
    a.GroupName
FROM dbo.tbGroup a
INNER JOIN GroupList b
    ON a.GroupID = b.GroupID


text:
Q: Unable to compile my C file using gcc48 I am trying to compile a few C programs on my new virtualBox with FreeBSD operating system.
I have installed the gcc48.
I am trying to compile this basic program (saved as hello.c):
#!/usr/local/bin/

#include <stdio.h>

main()
{
   printf("Hello");
}

I am running the following command in my terminal:
gcc48 -c hello.c -o hi

Upon entering this command, I get the following error:
hello.c:1:2: error: invalid preprocessing directive #!
 #!/usr/local/bin/
  ^

I have confirmed that the bash directory is in the correct place by doing the following command:
find /* -iname "bash"

With the following results:
/usr/local/share/doc/bash
/usr/local/bin/bash
/usr/ports/shells/bash

Hence, I do not see why I am getting an invalid preprocessing directive error...
On a side note:
If I remove the #! line and compile, it compiles successfully, and outputs the file named "hi"
But, if I try to run this file with ./hi  -  I get the following error:
./hi: Exec format error. Binary file not executable.

Can anyone help me with this please?
Thanks

A: remove this line:
#!/usr/local/bin/

this is for shell scripting not c

A: Ok. Well MichaelPetch was the closest the answer, but @amdixon's idea played a part.
So, I removed the #! line, saved, and compiled using (excluding -c)
    gcc hello.c -o hi
This was successfully compiled.
And running with ./hi is also working...
Thanks...!

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ cout output explanation please
Possible Duplicate:
why is initializing an integer in VC++ to 010 different from initialising it to 10?

This got me very confused, and I hope one of you can answer my question. How come this code will produce the output "116"?
#include <iostream>

int main()
{
    std::cout << 0164 << std::endl;
    return 0;
}

The code has been compiled with MSVC++ 2010 and g++ under Mac OS X.
"cout" can print '0' alone and '164' alone, but as soon '0' is the first digit in the number the output changes.

A: In C and its brethren, a number with 0 on the front is octal, not decimal.
Hence your number is 1 * 82 (1 * 64 = 64) plus 6 * 81 (6 * 8 = 48) plus 4 * 80 (4 * 1 = 4) which equates to 116.
See here for a large treatise on what hexadecimal and octal are in C.

A: Because the 0 in front makes the number be interpreted as octal.
0164 =
 4 * 1 +
 6 * 8 +
 1 * 64
 = 116

Or, via binary:
 0164 =
   0   1   6   4 =
 000 001 110 100 =
 1110100 =
 116

The same goes for hexadecimal numbers, you write them as 0x1FA for example.


text:
Q: change table column width I'm using react library that constructs table in the following template:

                BLA_Column

                BLA_Body

I'm able to set the width of the th and the td to auto, but, the result is that I get two different sizes (one for the th and one for the td).
When I try to use the following selector (for example), nothing happens:
table > thead > th {
    width: 100px;
}

Also when I try to change directly the width using the chrome dev-tools, there is no change at all.
Thanks ahead!

A: CSS character > select only direct childs. Change your CSS with :
table > thead th {
    width: 100px;
}

or
table > thead > tr > th {
    width: 100px;
}


text:
Q: Flutter - Configuración de Firebase FAILURE: Build failed with an exception.

*

*What went wrong:
Execution failed for task ':app:checkDebugAarMetadata'.

Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
Could not find com.google.firebase:firebase-core:.
Required by:
project :app > project :firebase_core

*

*Try:

Run with --stacktrace option to get the stack trace.
Run with --info or --debug option to get more log output.
Run with --scan to get full insights.

*

*Get more help at https://help.gradle.org
BUILD FAILED in 1s
Exception: Gradle task assembleDebug failed with exit code 1
FAILURE: Build failed with an exception.

*

*What went wrong:
Execution failed for task ':app:checkDebugAarMetadata'.

Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
Could not find com.google.firebase:firebase-core:.
Required by:
project :app > project :firebase_core

*

*Try:

Run with --stacktrace option to get the stack trace.
Run with --info or --debug option to get more log output.
Run with --scan to get full insights.

*

*Get more help at https://help.gradle.org
BUILD FAILED in 1s
Exception: Gradle task assembleDebug failed with exit code 1


text:
Q: makeheadrule in the memoir class I have been trying to get the makeheadrule and makefootrule directives to work in a memoir class document. Here is an MWE
\documentclass[10pt]{memoir}
\usepackage{lipsum}

\copypagestyle{memoirStylePages}{headings}
\makerunningwidth{memoirStylePages}{\textwidth}

\makeheadrule{memoirStylePages}{\textwidth}{\normalrulethickness}
\makefootrule{memoirStylePages}{\textwidth}{\normalrulethickness}{}

\nouppercaseheads

\makeevenhead{memoirStylePages}{\thepage}{}{}
\makeoddhead{memoirStylePages}{}{}{\itshape\leftmark}

\makeevenfoot{memoirStylePages}{}{}{}
\makeoddfoot{memoirStylePages}{}{}{}

\makepsmarks{memoirStylePages}{%
  \createmark{chapter}{left}{nonumber}{}{}
}

\pagestyle{memoirStylePages}

\begin{document}
\chapter{A chapter}
\section{A section}
\lipsum[1-10]
\end{document}

I am unable to understand why I get the errors.

A: The last argument of makefootrule mustn't be empty. So use:
\makefootrule{memoirStylePages}{\textwidth}{\normalrulethickness}{0pt}

The command \makefootrule has the following syntax:
\makefootrule{ style }{ width }{ thickness }{ skip }

Specifies the width and thickness of the rule drawn skip (see
  \footskip) above the footers of the style pagestyle.

Here your modifed MWE:
\documentclass[10pt]{memoir}
\usepackage{lipsum}
\copypagestyle{memoirStylePages}{headings}
\makerunningwidth{memoirStylePages}{\textwidth}
\makeheadrule{memoirStylePages}{\textwidth}{\normalrulethickness}
\makefootrule{memoirStylePages}{\textwidth}{\normalrulethickness}{0pt}
\nouppercaseheads
\makeevenhead{memoirStylePages}{\thepage}{}{}
\makeoddhead{memoirStylePages}{}{}{\itshape\leftmark}
\makeevenfoot{memoirStylePages}{}{}{}
\makeoddfoot{memoirStylePages}{}{}{}

\makepsmarks{memoirStylePages}{%
  \createmark{chapter}{left}{nonumber}{}{}
}

\pagestyle{memoirStylePages}
\begin{document}
\chapter{A chapter}
\section{A section}
\lipsum[1-10]
\end{document}


text:
Q: Java Html parser to extract specific data? I have a html file like the following
...
234
...
690
...

In this i want to extract values as A and B.
Can u suggest any html parser library for java that can do this easily?

A: Personally, I favour JSoup over JTidy. It has CSS-like selectors, and the documentation is much better, imho. With JSoup, you can easily extract those values with the following lines:
Document doc = Jsoup.connect("your_url").get();
Elements spans = doc.select("span[itemprop]");

for (Element span : spans) {
  System.out.println(span.text()); // will print 234 and 690
}

A: http://jsoup.org/
JSoup is the way to go.

A: JTidy is a confusingly named yet respected HTML parser.


text:
Q: How to visit a link which is in inbox of Gmail? I have written code to login to the mail. How to get a response from the given link (https://nationalskillsregistry.com) in Gmail inbox?
import imaplib
import getpass
import email
import datetime

detach_dir = '.' # directory where to save attachments (default: current)
user = "something@gmail.com"
pwd = "password"
subject_filter='(SUBJECT "Daily News ")'

# connecting to the gmail imap server
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user,pwd)
print "logged in successfully..."
m.select()
typ, data = m.search(None, subject_filter)
for num in data[0].split():
    rv, data = m.fetch(num, '(RFC822)')
    if rv != 'OK':
      print "ERROR getting message", num
      #return

msg = email.message_from_string(data[0][1])
print msg.get_payload(decode=True)
m.close()
m.logout()

This is the mail which I have:

Subject : Daily News - Announcing
Body :
Kindly note, if you are making online payment you do not need to visit
any POS centre. Your account will be immediately renewed.  If your
account is not renewed immediately then wait for 24 hours and check if
the validity has been extended.  Kindly do not make multiple online
payments. Visit us at https://nationalskillsregistry.com.

A: There are 2 steps you'll want to do -- extract the URL from the email, and then open it in a browser.
Step 1 will be the hard part. I'd recommend using Regular expressions to try and parse the email to pull out the URL. There are a lot of resources online that can help you with this. One of my favorites for testing regexs is RegExr.
The code should be pretty straightforward.
import re
 ...
expr = r'((http)s?:\/\/((\.)?\w+)+(\/\S*)*)'
#Parse with regex: Grabs possible URL (first only). Case insensitive.
matches = re.match( expr, msg, re.I)
url = matches[0]

Step 2 is easy enough --
import webbrowser

...

webbrowser.open(url)

Or, if you want to download the raw HTML:
import urllib2

...

response = urllib2.urlopen(url)
html = response.read()

If you need to download a file, you can use urllib to do the lifting.
import urllib

...

urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")

As for that regex, let's break it out a bit:
(  (http)s?:\/\/((\.)?\w+)+(\/\S*)*  )

First off, note that it's all in parentheses. Parentheses mean that it's a capture group, so we'll be able to get to it later.
(http)s?

This will look for the string 'http', which may or may not have an 's' following it.
:\/\/

This will look for '://' -- the '\' are there because the '/' need to be escaped.
(\.)?\w+)+    #Grab everything between :// and /

This bit's fun. It'll look for a period (that is optional), followed by ''word characters'' -- letters or numbers, not punctuation or whitespace.
It will repeat this 1 or more times. In doing so, it'll grab strings like
    amazon.com
    amazon.co.uk
(\/\S*)*

This will grab any number of strings that begin with a '/', and may have words following them. This is things like
    /
    /home/
    /foo.html?q=bar


text:
Q: How to append '/' to URL if the user removes '/' from url in ASP.NET MVC 4 IF this is my url http://localhost:55070/Server/1-Server
A link in that page will became
http://localhost:55070/Server/2-Instance_12

If I change the URL like this http://localhost:55070/Server/1-Server/
the link will be like this .http://localhost:55070/Server/1-Server/1-Instance_11
I want seconde type (http://localhost:55070/Server/1-Server/1-Instance_11/) always. If the user enters the URL like this http://localhost:55070/Server/1-Server it may cause some issues.
If this is the URL http://localhost:55070/Server/1-Server how can I append / to this http://localhost:55070/Server/1-Server/. So the links in next views are also append to it.
It is possible for user to remove the '/' and then also i need to add '/'.
This is the Razor for creating the URL.

A: You could adapt this solution Lower case URLs in ASP.NET MVC to redirect the user when the url does not end with a /
Or put it in a HttpModule like so:
public class UrlMessingModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += Application_BeginRequest;
    }

    public void Dispose() { }

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        var application = (HttpApplication) sender;
        var request = application.Request;
        var response = application.Response;

        var url = request.Url.AbsolutePath;

        if (url.Length > 1 && !url.EndsWith("/"))
        {
            response.Clear();
            response.Status = "301 Moved Permanently";
            response.StatusCode = (int)HttpStatusCode.MovedPermanently;
            response.AddHeader("Location", url + "/");
            response.End();
        }

    }
}


text:
Q: Built-in way of getting SuppressFBWarnings value for error message I have configured Eclipse to find bugs using FindBugs. Now I get some error messages in the Markers window. I reviewed them and for a few, I'd like to introduce a SuppressFBWarnings annotation.
How do I obtain the ID for the value attribute of SuppressFBWarnings in Eclipse?
I know I can go to the FindBugs description page, click the item and get the ID, but I wonder whether there's a shorter built-in way. I have already checked whether there is an additional column to be displayed in the Markers window, but there isn't.

A: *

*Right-click the item in the "Markers" window

*Choose "Show Bug Info" from the menu

*Scroll to the bottom and get the text near "Pattern:"


text:
Q: R X13binary missing in docker build I have a docker file where i'm trying to install the R seasonal library:
FROM continuumio/miniconda3:4.5.12 # Debian

. . .

# Install packages not on conda
RUN conda activate r_env && \
    R -e "install.packages(c('RUnit', 'seasonal'), dependencies=TRUE, repos='https://cran.case.edu')"

Everything looks like it installs correctly, however when I get into the container and run library(seasonal) I get the error:
> library(seasonal)
The binaries provided by 'x13binary' do not work on this
machine. To get more information, run:
  x13binary::checkX13binary()

> x13binary::checkX13binary()
Error in x13binary::checkX13binary() : X-13 binary file not found

After some googling it looks like I can manually set the path for the binary and a findutil shows that the binary exists on the machine:
(r_env) root@89c7265d9316:/# find / -name "*x13*"
/opt/conda/envs/arimaApiR/lib/R/library/x13binary
/opt/conda/envs/arimaApiR/lib/R/library/x13binary/help/x13binary.rdx
/opt/conda/envs/arimaApiR/lib/R/library/x13binary/help/x13binary.rdb
/opt/conda/envs/arimaApiR/lib/R/library/x13binary/html/x13path.html
/opt/conda/envs/arimaApiR/lib/R/library/x13binary/html/x13binary-package.html
/opt/conda/envs/arimaApiR/lib/R/library/x13binary/bin/x13ashtml.exe
/opt/conda/envs/arimaApiR/lib/R/library/x13binary/R/x13binary.rdx
/opt/conda/envs/arimaApiR/lib/R/library/x13binary/R/x13binary.rdb
/opt/conda/envs/arimaApiR/lib/R/library/x13binary/R/x13binary
/opt/conda/envs/arimaApiR/conda-meta/r-x13binary-1.1.39_2-r36h6115d3f_0.json
/opt/conda/pkgs/r-x13binary-1.1.39_2-r36h6115d3f_0
/opt/conda/pkgs/r-x13binary-1.1.39_2-r36h6115d3f_0/lib/R/library/x13binary
/opt/conda/pkgs/r-x13binary-1.1.39_2-r36h6115d3f_0/lib/R/library/x13binary/help/x13binary.rdx
/opt/conda/pkgs/r-x13binary-1.1.39_2-r36h6115d3f_0/lib/R/library/x13binary/help/x13binary.rdb
/opt/conda/pkgs/r-x13binary-1.1.39_2-r36h6115d3f_0/lib/R/library/x13binary/html/x13path.html
/opt/conda/pkgs/r-x13binary-1.1.39_2-r36h6115d3f_0/lib/R/library/x13binary/html/x13binary-package.html
/opt/conda/pkgs/r-x13binary-1.1.39_2-r36h6115d3f_0/lib/R/library/x13binary/bin/x13ashtml.exe
/opt/conda/pkgs/r-x13binary-1.1.39_2-r36h6115d3f_0/lib/R/library/x13binary/R/x13binary.rdx
/opt/conda/pkgs/r-x13binary-1.1.39_2-r36h6115d3f_0/lib/R/library/x13binary/R/x13binary.rdb
/opt/conda/pkgs/r-x13binary-1.1.39_2-r36h6115d3f_0/lib/R/library/x13binary/R/x13binary
/opt/conda/pkgs/r-x13binary-1.1.39_2-r36h6115d3f_0.tar.bz2

However no matter whatever I set the path to be, the library still throws errors on where the actual path is:
(r_env) root@89c7265d9316:/# export X13_PATH=/opt/conda/envs/arimaApiR/lib/R/library/x13binary
(r_env) root@89c7265d9316:/# R -e "library(seasonal)"

The system variable 'X13_PATH' has been manually set to:
  /opt/conda/envs/arimaApiR/lib/R/library/x13binary
Since version 1.2, 'seasonal' relies on the 'x13binary'
package and does not require 'X13_PATH' to be set anymore.
Only set 'X13_PATH' manually if you intend to use your own
binaries. See ?seasonal for details.
Binary executable file /opt/conda/envs/arimaApiR/lib/R/library/x13binary/x13as or /opt/conda/envs/arimaApiR/lib/R/library/x13binary/x13ashtml not found.
See ?seasonal for details.

I feel like I'm running in circles.  Has anyone had luck running this inside a container?

A: I've prepared my own container but I didn't use continuumio/miniconda since I don't know how it works inside.
This is the Dockerfile I've prepared:
FROM r-base:3.6.1

RUN apt-get update \
    && apt-get install -y libxml2-dev

RUN R -e "install.packages('RUnit', dependencies=TRUE, repos='https://cran.case.edu')"
RUN R -e "install.packages('x13binary', dependencies=TRUE, repos='https://cran.case.edu')"
RUN R -e "install.packages('seasonal', dependencies=TRUE, repos='https://cran.case.edu')"

CMD [ "bash" ]

If I run your test commands, I receive this:
> library(seasonal)
> x13binary::
x13binary::checkX13binary     x13binary::supportedPlatform  x13binary::x13path
> x13binary::checkX13binary
x13binary::checkX13binary
> x13binary::checkX13binary()
x13binary is working properly
>

NOTE: the Dockerfile can be improve, e.g. you can put together the packages c(RUnit, x13binary, seasonal) and you can remove the apt cache after installing the package but I just wanted to run a test to see if it'd work.


text:
Q: Rename an image file if already exists on the server PHP I'd like to add suffix to the filename if the file already exists on the server.
For example: if the file image.jpg exists on the server the new file to be renamed to image_1.jpg, image_2.jpg etc.
Any help would be much appreciated!
$max_file_size = 1024*100000; // 100000kb
    $valid_exts = array('jpeg', 'jpg', 'png', 'gif');
    // thumbnail sizes
    $sizes = array(250 => 150);

    if (isset($_FILES["$fileime"])) {
      if( $_FILES["$fileime"]['size'] < $max_file_size ){
        // get file extension
        $ext = strtolower(pathinfo($_FILES["$fileime"]['name'], PATHINFO_EXTENSION));
        if (in_array($ext, $valid_exts)) {
          /* resize image */
          foreach ($sizes as $width => $height) {
            /* Get original image x y*/
                  list($w, $h) = getimagesize($_FILES["$fileime"]["tmp_name"]);
                  /* calculate new image size with ratio */
                  $ratio = max($width/$w, $height/$h);
                  $h = ceil($height / $ratio);
                  $x = ($w - $width / $ratio) / 2;
                  $w = ceil($width / $ratio);
                  /* new file name */
                  $path = '../thumbs/'.$_FILES["$fileime"]['name'];
                  /* read binary data from image file */
                  $imgString = file_get_contents($_FILES["$fileime"]['tmp_name']);
                  /* create image from string */
                  $image = imagecreatefromstring($imgString);
                  $tmp = imagecreatetruecolor($width, $height);
                  imagecopyresampled($tmp, $image,
                    0, 0,
                    $x, 0,
                    $width, $height,
                    $w, $h);

A: Why not just add the timestamp at the end of your file name?
$max_file_size = 1024*100000; // 100000kb
    $valid_exts = array('jpeg', 'jpg', 'png', 'gif');
    // thumbnail sizes
    $sizes = array(250 => 150);

    if (isset($_FILES["$fileime"])) {
      if( $_FILES["$fileime"]['size'] < $max_file_size ){
        // get file extension
        $ext = strtolower(pathinfo($_FILES["$fileime"]['name'], PATHINFO_EXTENSION));
        if (in_array($ext, $valid_exts)) {
          /* resize image */
          foreach ($sizes as $width => $height) {
            /* Get original image x y*/
                  list($w, $h) = getimagesize($_FILES["$fileime"]["tmp_name"]);
                  /* calculate new image size with ratio */
                  $ratio = max($width/$w, $height/$h);
                  $h = ceil($height / $ratio);
                  $x = ($w - $width / $ratio) / 2;
                  $w = ceil($width / $ratio);
                  /* new file name */
                  $filename_array = explode('.', $_FILES["$fileime"]['name']);
                  $extension = array_pop($filename_array);
                  $new_name = implode('.',$filename_array).'_'.time().'.'.$extension;
                  $path = '../thumbs/'.$new_name;
                  /* read binary data from image file */
                  $imgString = file_get_contents($_FILES["$fileime"]['tmp_name']);
                  /* create image from string */
                  $image = imagecreatefromstring($imgString);
                  $tmp = imagecreatetruecolor($width, $height);
                  imagecopyresampled($tmp, $image,
                    0, 0,
                    $x, 0,
                    $width, $height,
                    $w, $h);


text:
Q: How do you edit mongo.conf file in bash (if it is running inside the container in local environment) URL: https://www.percona.com/blog/2018/05/23/deploy-mongodb-replica-set-with-transport-encryption-part-2/
if the percona mongodb setup is running in the local machine with different port ids, how do you edit the file mongod.conf which will be in bash state.

A: You have considered the next options to approach:

*

*Build your own image inherits from percona/official image:

*

*Write Docker file, COPY needed config file and build new image

*Copy config file into running container and commit to the new image

*Mount volume contains config file from local disk into a running container.


text:
Q: Dafny: Using "forall" quantifiers with the "reads" or "modifies" clauses So I am trying to implement Dijkstra's single source shortest paths algorithm in Dafny based directly on the description of the algorithm in the CLRS algorithms book as part of an undergraduate project. As part of the implementation, I have defined a "Vertex" object with two fields representing the current length of shortest path from source and the predecessor vertex:
    class Vertex{
    var wfs : int ;
    var pred: Vertex;
    }

As well as a "Graph" object that contains an array of "Vertex"-es:
    class Graph{
    var vertices: array<Vertex>;
    ....

I am trying to state some properties of the fields in each "Vertex" of the vertices array using a predicate in the "Graph" object:
    predicate vertexIsValid()
    reads this;
    reads this.vertices;
     {
       vertices != null &&
       vertices.Length == size &&
       forall m :: 0 <= m < vertices.Length ==> vertices[m].wfs != 900000 &&
       vertices[m].pred != null
     }

To my understanding, the "reads" and "modifies" clauses in Dafny only work on one layer and I'd have to specify to Dafny that I would be reading each entry in the vertices array ( reads this.vertices[x] ) . I tried using a "forall" clause to do it:
   forall m :: 0 <= m < vertices.Length ==> reads this.vertices[m]

but this doesn't seem to be a feature in Dafny. Does anyone know if there is a way to use quantifiers with the "reads" clause or otherwise tell Dafny to read the fields in each entry of an array containing objects?
Thanks for the help.

A: You can do that most easily by using a set as a reads clause.
For your example, this additional reads clause on vertexIsValid worked for me:
reads set m | 0 <= m < vertices.Length :: vertices[m]

You can think of this set expression as saying "the set of all elements vertices[m] where m is in bounds".


text:
Q: How to compute: $ \lim\limits_{a\to \infty}\frac1a\int_1^a a^{\frac1x} dx$ Help me to compute the following limit
$$
\lim_{a\to \infty}\frac1a\int_1^a a^{\frac1x} dx$$

I failed to apply the mean value theorem. And this the feature i had in mind when I saw this first

Any Hint?

A: For $a>1$, by letting $t=\ln(a)/x$, then $dx=-\ln(a)dt/t^2$ and
$$\frac1a\int_1^a a^{\frac1x} dx=\frac{\ln(a)}{a}\int_{\ln(a)/a}^{\ln(a)} \frac{e^{t}}{t^2} dt=\frac{F(\ln(a))-F(\ln(a)/a)}{a/\ln(a)}$$
where $F(s)=\int_{1}^se^{t}/t^2 dt$.
Then by L'Hôpital's rule (note that $a/\ln(a)\to +\infty$ as $a\to+\infty$), it suffices to evaluate the limit
$$\frac{F'(\ln(a))(\ln(a))'-F'(\ln(a)/a)(\ln(a)/a)'}{(a/\ln(a))'}
=\frac{e^{\ln(a)/a}(\ln(a)-1)+1}{\ln(a)-1}
\to 1.
$$

A: Under $x=(a-1)t+1$, one has
\begin{eqnarray}
&&\frac1a\int_1^a a^{\frac1x} dx\\
&=&\frac{a-1}a\int_0^1 a^{\frac1{(a-1)t+1}} dt\\
&=&\frac{a-1}a\int_0^1 \exp\left({\frac{\ln a}{(a-1)t+1}}\right) dt.
\end{eqnarray}
Since, for large $a>0$,
\begin{eqnarray}
1&\le&\int_0^1 \exp\left({\frac{\ln a}{(a-1)t+1}}\right) dt\\
&=&\int_0^1 \sum_{n=0}^\infty\frac1{n!}\left({\frac{\ln a}{(a-1)t+1}}\right)^n dt\\
&=&1+\int_0^1\frac{\ln a}{(a-1)t+1}dt+\sum_{n=2}^\infty\frac{(\ln a)^n}{(a-1)^nn!}\int_0^1\left({\frac{1}{t+\frac{1}{a-1}}}\right)^n dt\\
&=&1+\frac{\ln a}{a-1}+\sum_{n=2}^\infty\frac{(\ln a)^n(1-a^{-n+1})}{(a-1)(n-1)n!}\\
&\le&1+\frac{\ln a}{a-1}+\sum_{n=2}^\infty\frac{(\ln a)^n}{(a-1)(n-1)n!}\\
&\le&1+\frac{\ln a}{a-1}+\frac{a}{(a-1)\ln a}
\end{eqnarray}
one has
\begin{eqnarray}
\lim_{a\to \infty}\int_0^1 \exp\left({\frac{\ln a}{(a-1)t+1}}\right) dt=1
\end{eqnarray}
or
$$ \lim_{a\to \infty}\frac1a\int_1^a a^{\frac1x} dx=\lim_{a\to \infty}\frac{a-1}{a}\int_0^1 \exp\left({\frac{\ln a}{(a-1)t+1}}\right) dt=1.$$

A: Consider:
$$\int_1^a a^{1/x}\, dx = \int_1^a \exp (x^{-1}\ln a )\, dx $$ $$= \int_1^a (\sum_{n=0}^{\infty}(x^{-1}\ln a)^n/n!\,)\, dx = \sum_{n=0}^{\infty} (\ln a)^n/n! \int_1^a x^{-n}\,dx$$ $$ = a-1 + (\ln a)^2 +\sum_{n=2}^{\infty} (\ln a)^n/n! \int_1^a x^{-n}\,dx.$$
Now
$$\sum_{n=2}^{\infty} (\ln a)^n/n! \int_1^a x^{-n}\,dx < \sum_{n=2}^{\infty} (\ln a)^n/n! \int_1^\infty x^{-n}\,dx $$ $$\tag 1= \sum_{n=2}^{\infty} \frac{1}{n-1}\frac {(\ln a)^n}{n!}.$$
Prove yourself a little lemma: For $x>0, \sum_{n=2}^{\infty} \dfrac{1}{n-1}\dfrac {x^n}{n!} \le 3\dfrac{e^x}{x}.$ It follows that $(1)$ is bounded above by $3\dfrac{a}{\ln a}.$
Summarizing, we have
$$a-1 \le \int_1^a a^{1/x}\, dx \le a-1 + (\ln a)^2 + 3\dfrac{a}{\ln a}.$$
Dividing by $a
$ shows the desired limit is $1.$


text:
Q: React-router TypeError: _this.props.history is undefined I am using react-router with react js and i following their documentation but facing this error
while compiling it shows the error,
TypeError: _this.props.history is undefined

this is my index.js file
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';

ReactDOM.render(
  <Router history={browserHistory}>
    <Route path="/" component={App}>

    </Route>
  </Router>
  ,
  document.getElementById('root')
);

and this is my App.js file
import React, { Component } from 'react';
import './App.css';

class App extends Component {
    constructor(props){
        super(props);

        this.state = {
            headerText: "Props from Header.",
            contentText: "Props from content."
        };
    }
    render() {
        return (

Home

Home

Home

        );
    }
}

export default App;

A: Are you using npm? I had the same problem  with "react-router": "^4.0.0" in my package.json. Changing it to "react-router": "^3.0.2" solved my problem.

A: I have problems with my Form component.

this.props.history.push('/') is undefined.
to solve this i've added import {withRouter} from 'react-router-dom'
And then export default component as:
export default withRouter(connect(mapStateToProps)(CustomForm));

import React from "react";
import { Form, Input, Button } from "antd";
import { connect } from "react-redux";
import {withRouter} from 'react-router-dom'
import axios from "axios";

const FormItem = Form.Item;

class CustomForm extends React.Component {

  handleFormSubmit = async (event, requestType, articleID, ) => {
    event.preventDefault();

const postObj = {
  title: event.target.elements.title.value,
  content: event.target.elements.content.value
}

axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
axios.defaults.xsrfCookieName = "csrftoken";
axios.defaults.headers = {
  "Content-Type": "application/json",
  Authorization: `Token ${this.props.token}`,
};

if (requestType === "post") {
  await axios.post("http://127.0.0.1:8000/api/create/", postObj)
    .then(res => {
      if (res.status === 201) {
        this.props.history.push(`/`);
      }
    })
} else if (requestType === "put") {
  await axios.put(`http://127.0.0.1:8000/api/${articleID}/update/`, postObj)
    .then(res => {
      if (res.status === 200) {
        this.props.history.push(`/`);
      }
    })
}

};

  render() {
    return (

        <Form
          onSubmit={event =>
            this.handleFormSubmit(
              event,
              this.props.requestType,
              this.props.articleID
            )
          }
        >
          <FormItem label="Title">
            <Input name="title" placeholder="Put a title here" />
          </FormItem>
          <FormItem label="Content">
            <Input name="content" placeholder="Enter some content ..." />
          </FormItem>
          <FormItem>
            <Button type="primary" htmlType="submit">
              {this.props.btnText}
            </Button>
          </FormItem>
        </Form>

    );
  }
}

const mapStateToProps = state => {
  return {
    token: state.token
  };
};

export default withRouter(connect(mapStateToProps)(CustomForm));

I hope this is useful for someone. I am using Django as a backend

A: you can use window.location.href = '/somePath' as your last resort

A: I was trying to use history in the functional component and it was undefined because I was trying to access it with props.
According to the docs, we need to use useHistory hook to access the history. Here is the sample code according to the docs.
import { useHistory } from "react-router-dom";
function HomeButton() {

 let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

You can check this link for more understanding.

A: This is because things changed in React Router starting with 4.0.0. You should now use BrowserRouter from react-router-dom package when you were using browserHistory. So your code will looks like:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
import { BrowserRouter, Route } from 'react-router-dom';

ReactDOM.render(
    <BrowserRouter>
        <Route path="/" component={ App }/>
    </BrowserRouter>, document.getElementById('root')
);

Of course, you'll need to install react-router-dom first.
Also note that if you're using more than one Route element, you'll have to use a Switch as explained in this answer.

A: It seems to me that this.props.history is not defined, because you did not pass the routeProps to the component you want to render.
Change your routes as follows:
 <Route path="/home" render={(routeProps) => <Home {...routeProps}/>} />

You can also pass other props to the rendered components using this method.

A: This works for me >>>
import { Router, Route, browserHistory, IndexRoute } from 'react-router';

change the 'react-router' with 'react-router-dom', and Router with BrowserRouter as Router.
Like this >>>
import { BrowserRouter as Router, Route, browserHistory, IndexRoute } from 'react-router-dom';

A: I encountered this problem when trying to instantiate my own Router rather than using one of the built-in ones, to deal with an issue of having access to the history:
history.js
import { createHashHistory as createHistory } from 'history'

export default createHistory()

root.jsx
import { Router, Route } from 'react-router-dom'
import history from './history'

...

  <Router history={history}>
    <Route path="/test" component={Test}/>
  </Router>

In my case, the trouble was that I had a version of the history package locked at v2.1.2, while react-router was depending on a v4.x version of history in its own dependencies. So the built-in routers instantiated fine using the newer history, but when I tried to do it myself I was pulling in the older history and getting an incompatible object.

A: I had something like:
<Router>
   <HeaderComponent/>
   <Router exact path="/" component={Home}/>
   <Router path="/auth" component={AuthLayout}/>
   <FooterComponent/>
 </Router>

and AuthLayout was a component in which I was switching between SignIn and SignUp components, like below:

  { login ? <SignIn/> : <SignUp/> }

I faced this error of this.props.history is not a function inside these components. It was because I hadn't used those components directly inside the router. I had access to this.props.history inside the AuthLayout and I had to pass it to its children.
So I did it:

  { login ? <SignIn history={this.props.history}/> :  <SignUp history={this.props.history}/> }

and the problem solved.

A: For me the solution was to change
1) component as child
<Route path="/path">
 <MyComponent/>
</Route>

to
2) component as the "component" prop
<Route path="/path" component={MyComponent}>
</Route>

In both ways it renders, so it was very confusing for me, in examples they provide code as in first example.
(I used the version 5.1.2  of the "react-router-dom" package at the moment).
Update
You can also use this way (for child components (children of "MyComponent") works only this one)
import {withRouter} from 'react-router-dom';

const componentClassWithHistory = withRouter(ChildComponent);
export {componentClassWithHistory as ChildComponent};

or for default export
export default withRouter(ChildComponent)

or for typescript
const componentClassWithHistory = (withRouter(ChildComponent as any) as any);
export {componentClassWithHistory as ChildComponent};

Source: https://reacttraining.com/react-router/core/api/withRouter
Hope it helps someone.

A: The below solution works for me in ReactDOM.render:
 <BrowserRouter>
  <Switch>
    <Route path="/home" component={Home} />
    <Route path="/user" component={User} />
    <Route path="*" component={page404} />
  </Switch>
 </BrowserRouter>

It use multiple Routing.

A: This should be done in the component that is being routed to. In this case, it is App component. Therefore, in App.js, import "createBrowserHistory" and do it as follows:
import React, { Component } from 'react';
import './App.css';
import { createBrowserHistory } from "history";

class App extends Component {
    constructor(props){
        super(props);

        this.history = createBrowserHistory();;

        this.state = {
            headerText: "Props from Header.",
            contentText: "Props from content."
        };
    }
    render() {
        return (

Home

Home

Home

        );
    }
}

export default App;

A: Check that if there are any components that you haven't linked to router or any links that is not necessary among your components.
Besides if you have <Router><Link>...</Link></Router> in one of your clickable components it might crash your work.
Hope it might help.

A: I was getting this issue because I was trying to use props.history.push() with RRD v6, but v6 has scrapped the useHistory hook and instead uses the useNavigate hook.
For example:
import {useNavigate} from 'react-router-dom';
const navigate = useNavigate();
navigate('/path');

See this link for more info: https://reactrouter.com/en/main/hooks/use-navigate


text:
Q: Pandas - Plotly stacked area graph not producing the desired results I'm having trouble with Plotly and trying to graph a stacked area graph. I have the following data frame and we should see the graph reaching 200 in the load column.
,Group,Label,time,load
0,Group,col1,0.0,0.0
1,Group,col1,15.0,0.0
2,Group,col1,16.0,100.0
3,Group,col1,106.0,100.0
4,Group,col1,116.0,0.0
5,Group,col2,0.0,0.0
6,Group,col2,0.0,0.0
7,Group,col2,30.0,100.0
8,Group,col2,90.0,100.0
9,Group,col2,100.0,0.0

but when using the following code to produce a stacked graph, the graphs are not stacked and seems to be dropping to zero at 2 particular points.
fig = px.area(df, x="time", y="load", color="Label")
fig.show()

When i look at the graphs individually it looks correct.

A: Problem is with data. You need to be careful with missing x values for one or another column.
The values for the x axis have to be shared by both col1 and col2 values. Otherwise, when you add an x value for col1 and not for col2 (or the other way round), the value by default travels down to zero, thus showing the results you have in your plot.
Try to specify at leat all the points in x axis both col1 and col2 share (0,15,16,30,90,106,116 although is not a bad practice with time series using a specific time resolution and stick with it as in 1,2,3,4,5,..., 114, 115, 116 and get the load value for all of them).
A working example (assuming load values for col1 between 16 and 106 are always 100 and for col2 load values between 30 and 90 are also 100) would be:
import sys
if sys.version_info[0] < 3:
    from StringIO import StringIO
else:
    from io import StringIO

import pandas as pd

TESTDATA = StringIO(''',Group,Label,time,load
0,Group,col1,0.0,0.0
1,Group,col1,15.0,0.0
2,Group,col1,16.0,100.0
3,Group,col1,30.0,100.0
4,Group,col1,90.0,100.0
5,Group,col1,100.0,100.0
6,Group,col1,106.0,100.0
7,Group,col1,116.0,0.0

8,Group,col2,0.0,0.0
9,Group,col2,15.0,0.0
10,Group,col2,16.0,0.0
12,Group,col2,30.0,100.0
13,Group,col2,90.0,100.0
14,Group,col2,100.0,0.0
15,Group,col2,106.0,0.0
16,Group,col2,116.0,0.0

''')

df= pd.read_csv(TESTDATA, sep=",")

import plotly.express as px
fig = px.area(df, x="time", y="load", color="Label")
fig.show()

which outputs:


text:
Q: How to sort list of jobs by submitted time/job name? In LAVA or LSF, how to sort the output of bjobs command by submitted time/job name?
Bare bjobs usually gives a mess. I cannot find the right option in manuals, e.g., in this one.

A: There isn't an option to sort bjobs' output by time or job name. You could manually parse the specific column.
Depending on what information you are interested in... you can look into bjobs -r, -p, -u flags.


text:
Q: How do I set start and end times for an embedded youtube video buried in a playlist parameter? I want to embed a custom YouTube playlist made up of only clips of videos using HTML. I know how to modify the first video in the playlist using the parameters listed on Google's developer website (developers[dot]google[dot]com/youtube/player_parameters), but I don't know how to modify the rest of the videos in the playlist queue.
Things I Would Fix:
1) I would only show 30 seconds of the second video (YouTube ID 4A6Bu96ALOw) in the playlist, starting at 21 seconds.
2) I would also command the player to auto-select the "English - Worry About Yourself" closed captions.
My current code:
http://www.youtube.com/v/Bpu0TIXzI1w?version=3&start=52&end=127&autoplay=1&hl=en_US&rel=0&loop=0&playlist=IQIgy6-PS0A,RwlhUcSGqgs,4A6Bu96ALOw
Hypothesized solution: It must have something to do with creating arrays within the "playlist" parameter
Here is a link to the rest of my research: https://docs.google.com/document/d/1O_ZBzqTe3fpVQ8Lu7r0TBcksTcr95QwaKB_pBpfpKnE/edit?usp=sharing


text:
Q: Crash while sending ARFrame CVPixelBuffer as byte array over network using gstreamer I want to send ARFrame pixel buffer data over network, i have listed my setup below. With this setup if i try to send the frames app crashes in gstreamers C code after few frames, but if i send camera's AVCaptureVideoDataOutput pixel buffer instead, the stream works fine. I have set AVCaptureSession's pixel format type to

kCVPixelFormatType_420YpCbCr8BiPlanarFullRange

so it replicates the same type ARFrame gives. Please help i am unable to find any solution. I am sorry if my english is bad or i have missed something out, do ask me for it.
My Setup

*

*Get pixelBuffer of ARFrame from didUpdateFrame delegate of ARKit

*Encode to h264 using VTCompressionSession

- (void)SendFrames:(CVPixelBufferRef)pixelBuffer :(NSTimeInterval)timeStamp
{
  size_t width = CVPixelBufferGetWidth(pixelBuffer);
  size_t height = CVPixelBufferGetHeight(pixelBuffer);

  if(session == NULL)
  {
      [self initEncoder:width height:height];
  }

  CMTime presentationTimeStamp = CMTimeMake(0, 1);

  OSStatus statusCode = VTCompressionSessionEncodeFrame(session, pixelBuffer, presentationTimeStamp, kCMTimeInvalid, NULL, NULL, NULL);
  if (statusCode != noErr) {

      // End the session
      VTCompressionSessionInvalidate(session);
      CFRelease(session);
      session = NULL;
      return;
  }

  VTCompressionSessionEndPass(session, NULL, NULL);
}

- (void) initEncoder:(size_t)width  height:(size_t)height
{
  OSStatus status = VTCompressionSessionCreate(NULL, (int)width, (int)height, kCMVideoCodecType_H264, NULL, NULL, NULL, OutputCallback, NULL, &session);

  NSLog(@":VTCompressionSessionCreate %d", (int)status);

  if (status != noErr)
  {
    NSLog(@"Unable to create a H264 session");
    return ;
  }

  VTSessionSetProperty(session, kVTCompressionPropertyKey_RealTime, kCFBooleanTrue);
  VTSessionSetProperty(session, kVTCompressionPropertyKey_ProfileLevel, kVTProfileLevel_H264_Baseline_AutoLevel);
  VTCompressionSessionPrepareToEncodeFrames(session);
}

*Get sampleBuffer from callback, convert it to elementary stream

void OutputCallback(void *outputCallbackRefCon, void *sourceFrameRefCon, OSStatus status, VTEncodeInfoFlags infoFlags,CMSampleBufferRef sampleBuffer)
{
    if (status != noErr) {
        NSLog(@"Error encoding video, err=%lld", (int64_t)status);
        return;
    }

    if (!CMSampleBufferDataIsReady(sampleBuffer))
    {
        NSLog(@"didCompressH264 data is not ready ");
        return;
    }

    // In this example we will use a NSMutableData object to store the
    // elementary stream.
    NSMutableData *elementaryStream = [NSMutableData data];

    // This is the start code that we will write to
    // the elementary stream before every NAL unit
    static const size_t startCodeLength = 4;
    static const uint8_t startCode[] = {0x00, 0x00, 0x00, 0x01};

    // Write the SPS and PPS NAL units to the elementary stream
    CMFormatDescriptionRef description = CMSampleBufferGetFormatDescription(sampleBuffer);

    // Find out how many parameter sets there are
    size_t numberOfParameterSets;
    int AVCCHeaderLength;
    CMVideoFormatDescriptionGetH264ParameterSetAtIndex(description,
                                                       0, NULL, NULL,
                                                       &numberOfParameterSets,
                                                       &AVCCHeaderLength);

    // Write each parameter set to the elementary stream
    for (int i = 0; i < numberOfParameterSets; i++) {
        const uint8_t *parameterSetPointer;
        int  NALUnitHeaderLengthOut = 0;

        size_t parameterSetLength;
        CMVideoFormatDescriptionGetH264ParameterSetAtIndex(description,
                                                           i,
                                                           &parameterSetPointer,
                                                           &parameterSetLength,
                                                           NULL, &NALUnitHeaderLengthOut);

        // Write the parameter set to the elementary stream
        [elementaryStream appendBytes:startCode length:startCodeLength];
        [elementaryStream appendBytes:parameterSetPointer length:parameterSetLength];

    }

    // Get a pointer to the raw AVCC NAL unit data in the sample buffer
     size_t blockBufferLength;
     uint8_t *bufferDataPointer = NULL;
     size_t lengthAtOffset = 0;
     size_t bufferOffset = 0;

    CMBlockBufferGetDataPointer(CMSampleBufferGetDataBuffer(sampleBuffer),
                                bufferOffset,
                                &lengthAtOffset,
                                &blockBufferLength,
                                (char **)&bufferDataPointer);

    // Loop through all the NAL units in the block buffer
    // and write them to the elementary stream with
    // start codes instead of AVCC length headers

    while (bufferOffset < blockBufferLength - AVCCHeaderLength) {
        // Read the NAL unit length
        uint32_t NALUnitLength = 0;
        memcpy(&NALUnitLength, bufferDataPointer + bufferOffset, AVCCHeaderLength);
        // Convert the length value from Big-endian to Little-endian
        NALUnitLength = CFSwapInt32BigToHost(NALUnitLength);

        // Write start code to the elementary stream
        [elementaryStream appendBytes:startCode length:startCodeLength];
        // Write the NAL unit without the AVCC length header to the elementary stream
        [elementaryStream appendBytes:bufferDataPointer + bufferOffset + AVCCHeaderLength
                               length:NALUnitLength];
        // Move to the next NAL unit in the block buffer
        bufferOffset += AVCCHeaderLength + NALUnitLength;
    }

    char *bytePtr = (char *)[elementaryStream mutableBytes];
    long maxSize = (long)elementaryStream.length;

    CMTime presentationtime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);

    vidplayer_stream(bytePtr, maxSize, (long)presentationtime.value);
}


text:
Q: How to purge unused source/class files from Directory tree We have about 280 Java source code spread over 10 packages, and a bunch of txt and image files for a software project. Quite a few of them are not being used currently. They do not break the system, since we can just do a "javac //*.java" and "jar cmf metafile " to build up the executable jar which works. The question:
How do we find the class files never accessed, or image/txt files never used as resources in the jar?

A: It would be very hard to determine which image/txt files are never used, as they can be loaded in a variety of manners.  A good bet for the image/txt files is to search for the name of each file in your code; if it is not there, it might not be being used; remember, the name of the file could be being generated programmatically and then loaded.
I recently had to do something similar for a game project.  Because content could be brought in via a variety of means, removing unused content took a lot of trial and error.
There are plugins for eclipse that can find unused code.

A: It has been answered in How to find unused/dead code in java projects.
For the images, I would write a small program, pseudocode would look like:
//list image names
//for each image name
    //find ocurrences in other files

A: Use the Unused Code detector: http://www.ucdetector.org/


text:
Q: An Ideal Related to a Polynomial Ring: Theorem 3.4 of Chapter XXI of Lang's "Algebra" (Revised Third Edition) Let $n\in\mathbb N$. Let $x$ and $y$ be distinct indeterminates. Let $R$ be an integral domain.  Let $\big(f_1(x),\dots,f_n(x)\big)\in R[x]^n$ be such that the ideal in $R[x]$ generated by $f_1(x),\dots,f_n(x)$ is $R[x]$.  Also assume that $f_i(x)$ is monic for some $i\in\{1,\dots,n\}$.
If $g_1(x,y),\dots,g_n(x,y),h_1(x,y),\dots,h_n(x,y)\in R[x,y]$ and there exists an invertible $n\times n$ matrix $M$ with entries in $R[x,y]$ such that
$\begin{gather}
 \begin{bmatrix} g_1\\ \dots \\ g_n \end{bmatrix}
 =
 M
  \begin{bmatrix} h_1\\ \dots \\ h_n \end{bmatrix}
\end{gather}$
then we write $(g_1,\dots,g_n)\sim(h_1,\dots,h_n)$.
Let $J$ be the set $\{c\in R\mid \big(f_1(x+cy),\dots,f_n(x+cy)\big)\sim \big(f_1(x),\dots,f_n(x)\big)\}$.  Prove that if $c,d\in J$, then $c+d\in J$.  Lang says this can be proven "easily."

A: By assumption
\begin{align}
\big(f_1(x+cy),\dots,f_n(x+cy)\big)&\sim \big(f_1(x),\dots,f_n(x)\big)\\
\big(f_1(x+dy),\dots,f_n(x+dy)\big)&\sim \big(f_1(x),\dots,f_n(x)\big)
\end{align}
By substituting $x+cy$ at in $x$ in the second expression, we get
$$\big(f_1((x+cy)+dy),\dots,f_n((x+cy)+dy)\big)\sim \big(f_1(x+cy),\dots,f_n(x+cy)\big)$$
Consequently,
\begin{align}
\big(f_1(x+(c+d)y),\dots,f_n(x+(c+d)y)\big)
&=\big(f_1((x+cy)+dy),\dots,f_n((x+cy)+dy)\big)\\
&\sim \big(f_1(x+cy),\dots,f_n(x+cy)\big)\\
&\sim \big(f_1(x),\dots,f_n(x)\big)
\end{align}
thus proving the assertion.


text:
Q: :contain / start by Is there a "start by" filter in jQuery, something like :contain but with a string beginning condition ?

A: No, but you can do it yourself using filter, as pulse suggested:
$('a').filter(function(){
    return $(this).text().indexOf('start') == 0 }
)

You may want to use a regular expression here, to ignore case, or for more advanced searches:
$('a').filter(function(){
    return $(this).text().match(/^start/i) }
)

A: Not that I know of, but you can easily implement your own selector for jQuery:
$.extend($.expr[':'], {
    startsWith: function(elem,match) {
        return (elem.textContent || elem.innerText || "").indexOf(match[3]) == 0;
    }
});

Now you can use it like this:
$("p:startsWith(Hello)").css("color","red")

A: I think you can use
indexOf function in javascript
var str = "test string print";

str.indexOf ( "test" ) returns 0

and
str.indexOf ( "print" ) returns 12

So you can check for the return value of indexOf function and if it is 0 then it is at the start position.

A: Start With: ^=

The ^= operator will filter elements whose attribute starts with the given value.
More info here:
http://www.bennadel.com/blog/1003-Cool-jQuery-Predicate-Selectors.htm
jQuery Return elements where ID begins with a certain string


text:
Q: matplotlib find_peaks I need to ignore spureous peaks I generate a graph like this, it measures the content of a transparent tube but the edges of the tube appear like that, you can see the peaks on the edges of the tube... Any suggestion on how to avoid this "extra" peaks? Any suggestion is welcome.

The image of the tube is this one

A: This is in fact not a matplotlib-specific question. From my understanding of your question, you would like to keep red peaks while remove blue ones. This task can be done by scipy.signal.find_peaks, you can specifiy a height value to control the peaks the algorithm finds. Here are some minimum code (adapted from scipy docs):
import matplotlib.pyplot as plt
from scipy.misc import electrocardiogram
from scipy.signal import find_peaks
x = electrocardiogram()[2000:4000]
peaks, _ = find_peaks(x, height=0.5)

fig, ax = plt.subplots(1, 1, figsize=(7.2, 7.2))
ax.plot(x)
ax.plot(peaks, x[peaks], "x")
ax.axhline(y=0.5, ls="--", color="gray")


text:
Q: CryptoKit - Encrypt with public key? To give you the context, there is a developer who develops the API of the project and there is a part of the json that will be encrypted.
So I have to decipher his content.
He has listed all the functions that I will need on the iOs side.
So I have his javascript code and I have to redo the equivalent in swift.
He uses the JS library (SJCL) : https://github.com/bitwiseshiftleft/sjcl/
I'm trying to encrypt some text with a public key, but I can't.
First, I generated the private/public keys
let keypair = P256.Signing.PrivateKey() // generation of a key pair

 let private_key = keypair.rawRepresentation.base64EncodedString()   // private key
 print(private_key)
 print("------------")

 let public_key = keypair.publicKey // public key - DATA
 print(public_key)
 print("------------")

 let publicKeyString = public_key.rawRepresentation.base64EncodedString() // public key - STRING - easy to share
 print(publicKeyString)

Now, I'm trying to encrypt a text with the public key..
Here, his javascript code :
var c256 = sjcl.ecc.curves.c256;
var publickeyBas64ToBits = sjcl.codec.base64.toBits(publickey);

console.log(c256);
console.log(publickey);
console.log(publickeyBas64ToBits);

var pub = new sjcl.ecc.elGamal.publicKey(
                    c256,
                    publickeyBas64ToBits
                )
var ciphertext = sjcl.encrypt(pub, message)
return ciphertext

I don't understand how to do the same thing in swift with CryptoKit :/
Can you help me please ? :)

A: Given two KeyPairs, lets call them Alice and Bob - Alice would like to encrypt a message M that only Bob should be able to decrypt (and Alice too):
You are given Bobs public key as either 33 or 64 or possibly 65 bytes (compressed form, X||Y form (raw) or uncompressed 04||X||Y), construct a P256.KeyAgreement.PublicKey from the bytes. This assumes that the bytes are not base64 encoded, but rather on hex format (see this for hex String to Data conversion: https://gist.github.com/nicklockwood/81b9f122f3db9e7132be7bd61d0c0cea ). If Base64 instead of hex, decode it first and ensure 33, 64, or 65 bytes. If 65 bytes, drop the first byte and use this initializer if 33 bytes use this initializer instead
Having access to Alice private key, P256.KeyAgreement.PrivateKey - if you have earlier created a signing private key (P256.Signing.PrivateKey), you can simply convert back and forth between them using the property rawRepresentation and the initializer init(rawRepresentation on both - perform the keyagreement to form a SharedSecret. By calling
let sharedSecret = aliceKeyAgreementPrivateKey.sharedSecretFromKeyAgreement(with: bobsKeyAgreementPublicKey)
Now lets create an AES.GCM.SealedBox from the message bytes
let encryptedMessage = try AES.GCM.SealedBox(combined: messageData)
Where messageData is Data from either base64 decoding a base64 encoded string or Data from hex string.
Now lets create a SymmetricKey we can use to AES.GCM decrypt - "open" - the sealedBox.
let aesDecryptionKey = sharedSecret.withUnsafeBytes { SymmetricKey($0) }
Or using this method instead of withUnsafeBytes  or this method, but then you need to come up with a good salt. These methods are much much safer then withUnsafeBytes, but makes my explaination a bit longer and more complex, so I leave it to your system to determine salt.this have to match what the sender used to encrypt the message of course!! As in both the SharedSecret by KeyAgreement AND the derivation of the SymmetricKey for encryption/decryption has to match..
Finally we can open the SealedBox!
let decryptedData = try AES.GCM.open(sealedBox, using: aesDecryptionKey)
And if the data was some plaintext message you might wanna decode it so it becomes readable, e.g. If it was UTF8 encoded:
let decryptedMessage = String(data: decryptedData, encoding: .utf8)!


text:
Q: Why can't I establish SQL connection despite setting driver (JDBC) path? I've been trying to connect my Java code to SQL for hours now, I've followed blogs, seen tutorials and I'm still for my own some stupidest mistake can't get it to work. I've even enabled the TCP/IP connection.
import com.sun.jdi.connect.spi.Connection;

public class SQLTestClass {
public static void main(String[] args) {
   String url;
   url = "jdbc:sqlserver:sqlsrv\\sqlexpress;database=sqlJavaTest";

   String username = "sa";
   String password = "pass";

   Connection con;

   con = DriverManager.getConnection(url, username, password);

    }
}

The error reads:
Cannot establish a connection to jdbc:sqlserver://localhost:1433;databaseName=sqlJavaTest using com.microsoft.sqlserver.jdbc.SQLServerDriver (The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connect timed out. Verify the connection properties, check that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port, and that no firewall is blocking TCP connections to the port.".)


text:
Q: identify patterns within an array in python I've got a question on identifying patterns within an array. I'm working with the following array:
A = [1.0, 1.1, 9.0, 9.2, 0.9, 9.1, 1.0, 1.0, 1.2, 9.2, 8.9, 1.1]

Now, this array is clearly made of elements clustering about ~1 and elements about ~9.
Is there a way to separate these clusters? I.e., to get to something like:
a_1 = [1.0, 1.1, 0.9, 1.0, 1.0, 1.2, 1.1]  # elements around ~1
a_2 = [9.0, 9.2, 9.1, 9.2, 8.9]  # elements around ~9

Thanks a lot. Best.

A: You can do that by comparing each element with which is closer. Is it closer to 1 or 9:
a_1 = [i for i in A if abs(i-1)<=abs(i-9)]
a_2 = [i for i in A if abs(i-1)>abs(i-9)]

But of course this is not a general solution for clustering. It only work in this case when you know the center of the cluster (1 and 9).
If you don't know the center of the cluster, I think you should use a clustering algorithm like K-Means
This is a simple K-Means implementation (with k=2 and 100 as limit iteration). You didn't need to know the center of the cluster, it picks randomly at first.
from random import randint

A = [1.0, 1.1, 9.0, 9.2, 0.9, 9.1, 1.0, 1.0, 1.2, 9.2, 8.9, 1.1]

x = A[randint(0,len(A)-1)]
y = A[randint(0,len(A)-1)]
for _ in range(100):
    a_1 = [i for i in A if abs(i-x)<=abs(i-y)]
    a_2 = [i for i in A if abs(i-x)>abs(i-y)]
    print(x,y)
    x = sum(a_1)/len(a_1)
    y = sum(a_2)/len(a_2)

print a_1
print a_2


text:
Q: Firebase not working in electron app when packed using electron packager I recently built an electron application which utilizes firebase. It works well in the dev environment but when I package it as an exe, the firebase does not work.
How to resolve this ?
My package.json
{
  "name": "powerplant",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "electron": "electron ."
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "electron": "^9.1.2",
    "electron-log": "^4.2.2",
    "firebase": "^7.17.2",
    "html-to-text": "^5.1.1",
    "messagebird": "^3.5.0",
    "msg91": "0.0.6",
    "node-telegram-bot-api": "^0.50.0",
    "sendotp": "^1.2.9",
    "speakeasy": "^2.0.0",
    "springedge": "^1.0.5",
    "twilio": "^3.48.2"
  },
  "devDependencies": {
    "electron-packager": "^15.0.0"
  }
}

My app.js
I have imported firebase in my app.js
It works perfectly in development, but doesn't work in production.
//  ---------------- IMPORTS ----------------------------------------------

const electron = require('electron');
const {app,BrowserWindow,ipcMain} = electron;

// replace the value below with the Telegram token you receive from @BotFather
const TelegramBot = require('node-telegram-bot-api');
const token = '';
const bot = new TelegramBot(token, {polling: true});

//  ------------- FIREBASE IMPORT AND INITIALIZE ----------------------
var firebase = require('firebase');
const { DataSessionPage } = require('twilio/lib/rest/wireless/v1/sim/dataSession');
var firebaseConfig = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
  };
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
var database=firebase.database();

 // this is sorta overall process(Electron App)
let mainWindow;
app.on('ready', () => {

    let senderPhoneNumber
    let senderName;

    console.log('App is now ready!!!');
    mainWindow=new BrowserWindow({webPreferences:{
        nodeIntegration: true
    }});
    mainWindow.loadURL(`file://${__dirname}/templates/loginform.html`)
    mainWindow.webContents.openDevTools()

    ipcMain.on("register:form",(event,data)=>{
        mainWindow.loadURL(`file://${__dirname}/templates/registerform.html`)
    })

    ipcMain.on("submit:register",(event,data)=>{
        var employeeId=data['empid']
        var phone=data['phone']
        var name=data['name']
        var password=data['password']
        var confirm=data['confirm']
        if(password==confirm){
            database.ref('users/'+employeeId).on('value',(snapshot)=>{
                if(snapshot.val()==null){
                    database.ref('users/'+employeeId).set({
                        'phone':phone,
                        'name':name,
                        'password':password,
                    })
                }
            })
            mainWindow.loadURL(`file://${__dirname}/templates/loginform.html`)
        }
    })

    ipcMain.on("submit:login",(event,data)=>{
        var employeeId=data["empid"];
        var password=data["password"];
        database.ref('users/'+employeeId).on('value',(snapshot)=>{
            if(snapshot.val()!=null){
                if(snapshot.val()['password']==password){
                     senderName=snapshot.val()['name']
                     senderPhoneNumber=snapshot.val()['phone']
                     mainWindow.loadURL(`file://${__dirname}/templates/index.html`)
                }
            }
        })
    })
    ipcMain.on("submit:data",(event,data)=>{
        // var text=
        // `
        // Sir,
        // ${senderName}

        // ${senderPhoneNumber}

        // `;
        // for(key in data){
        //     text+=`${key}   ${data[key]} \n`
        // }

        var text=`
        ${data["DATE"]} ${data["SHIFT"]} Shift Report

        Stage 1&2

        DC D/M/Y ${data["Stage 1&2 DC/D"]}/${data["Stage 1&2 DC/M"]}/${data["Stage 1&2 DC/Y"]}
        SG D/M/Y ${data["Stage 1&2 SG/D"]}/${data["Stage 1&2 SG/M"]}/${data["Stage 1&2 SG/M"]}

        Stage 3

        DC D/M/Y ${data["Stage 3 DC/D"]}/${data["Stage 3 DC/M"]}/${data["Stage 3 DC/Y"]}
        SG D/M/Y ${data["Stage 3 SG/D"]}/${data["Stage 3 SG/M"]}/${data["Stage 3 SG/M"]}

        Day Gen : ${data["Day Gen"]}
        Day PLF: ${data["Day PLF"]}
        Monthly PLF : ${data["Monthly PLF"]}
        Yearly PLF : ${data["Yearly PLF"]}
        APC: ${data["APC"]}

        Coal Receipt/Consumption/Stock
        ${data["RECEIPT"]}/${data["CONS"]}/${data["STOCK"]}

        1% Ramp Rate Status
        Stage 1&2 : ${data["RAMP RATE STAGE 1&2"]}
        Stage 3: ${data["RAMP RATE STAGE 3"]}

        U1 : ${data["MAJOR ISSUES UNIT 1"]}
        U2 : ${data["MAJOR ISSUES UNIT 2"]}
        U3 : ${data["MAJOR ISSUES UNIT 3"]}
        U4 : ${data["MAJOR ISSUES UNIT 4"]}
        U5 : ${data["MAJOR ISSUES UNIT 5"]}
        U5 : ${data["MAJOR ISSUES UNIT 6"]}
        U5 : ${data["MAJOR ISSUES UNIT 7"]}

        Stage 1 Offsites
        Ash Series: ${data["ASH SERIES"]}
        ATs: ${data["ATs"]}
        ASH TRUCKS: ${data["ASH TRUCKS"]}
        Silo levels: ${data["Stage 1 Silo Levels"]}
        St 1 RW Level: ${data["St 1 RW Level"]}
        St 2 CW sump level : ${data["St2 CW sump level"]}

        Stage 2 Offsites
        Dry Ash Sys I/s: ${data["Dry ash sys I/S"]}
        Ash Lines not avl: ${data["Ash Lines not avl"]}
        Vessels NA: ${data["Vessels NA"]}
        Silo Levels: ${data["Silo levels"]}
        BAS: ${data["BAS"]}
        FAS: ${data["FAS"]}

        Stage 3 Offsites
        ESP Passes Dry : ${data["ESP Passes Dry"]}
        ESP Passes Wet : ${data["ESP Passes Wet"]}
        Series Avl : ${data["Series Avl"]}
        Series Not Avl: ${data["Series Not Avl"]}
        Ash Trucks: ${data["Ash Trucks"]}
        Silo Levels : ${data["Stage 3 Silo Levels"]}

        Regards
        SCE NAME : ${data["SCE NAME"]}
        SCE GROUP: ${data["SCE GROUP"]}

        `

        bot.sendMessage("@ntpcrgdm",text)
    })

});

// the above listener that is attached can be broken down to three -
// app - thing we are listening to
// ready - event we are listening for
// function to call when event occurs


text:
Q: Frame Processor threw an error: Value is undefined, expected an Object In react native Project i installed react-native-vision-camera and react-native reanimated and then react-native-hole after running the project it gives me the error   Frame Processor threw an error: Value is undefined, expected an Object
though camera is opened but it comes repeatedly the error, Please help to overcome the solution...i want to make the QR Code Scanner ...the react native QRScanner is getting deprecated please help for making QR Scanner in React Native ..Please help

A: I solved this issue by following these steps-

*

*Change in your babel config-

  module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    [
      // <-- this
      'react-native-reanimated/plugin',
      {
        globals: ['__scanCodes'],
      },
    ],
  ],
};

*npm start -- --reset-cache

*add  import 'react-native-reanimated'; at the top on index.js file


text:
Q: Characterising exact sequence in terms of (quasi-)identities First of all, hello everyone and thanks in advance of any kind of help.
I am currently working on automated proofs of diagram chases. To this end, I have to characterise the property of $A \overset{f}{\to}B \overset{g}{\to} C$ being an exact sequence, where $f,g$ are morphisms between $R$-modules, in terms of algebraic (quasi-)identities. So, I am trying to find identities or implications of identities involving $f$, $g$ (and possible other, auxiliary morphisms) that characterise $\text{im}(f) = \ker(g)$.
Characterising the inclusion $\text{im}(f) \subseteq \ker(g)$ is pretty straight forward. This simply translates into $gf = 0$. But so far, I could not characterise the other inclusion $\ker(g) \subseteq \text{im}(f)$ in terms of algebraic (quasi-)identities.
Maybe someone can help me out here.


text:
Q: Using Java to parse record with new lines I would like to write a method to parse the following records from a file. It is possible for me read each line, start the record at "{" and end it at "}" and process each line in between. However, I was wondering if there was a more elegant way of processing records.
{\n
    "name": "Jeff Hamilton",\n
    "address": "101 Main St.",\n
    "id":"701"\n
},\n
{\n
    "name": "Peet Rizzo",\n
    "address": "109 Main St.",\n
    "id": "1003"\n
}\n

A: You can split this string into an array.
String newArray[]= str.split("\n },\n {\n");

You can also use a regex here.
Alternatively, a better approach would be to use JSON parsers.
I usually use GSON for serialization/deserialization but you can use any.


text:
Q: "Proofs" in logic. I am asked to show the following:
(a) $p \vee q \vee r$, $s \vee \neg q \vee t$ $\vdash p \vee r \vee s \vee t$
(b)$ \varphi(x) \vdash \forall \theta(x)$ if and only if $\exists x \varphi(x) \vdash \theta(x)$
For the first one I can only think of doing the truth table but that seems like a really long way to do it.
For the second one I don't really know what to do since I am not given whether x occurs free or not in the formulas and I don't really know how to come up with these types of proofs.

A: Here is a proof using a Fitch-style proof checker for the first part:

Most of this is an exercise in using disjunction introduction and elimination rules. Note that I added parentheses to disambiguate the propositions. This put a constraint on how I would have to construct the proof.
For the second part, various attempts to bind the variables generated countermodels in a tree proof generator. Here is an example of one of them:

Kevin Klement's JavaScript/PHP Fitch-style natural deduction proof editor and checker http://proofs.openlogicproject.org/
Tree Proof Generator. https://www.umsu.de/logik/trees/


text:
Q: Primary problems with authentication process in jcmanager? 1:

2:

3:

The above pictures attached to the question to ask my questions base on them!
1-As we know and mentioned in GP Specification, the card challenge has 8 byte length, but in the first photo, JCManager show a six byte card challenge! why?
2-The derivation data that will made based on GP Specification is not equal with the dervation data in JCManager! why?!
3-base on picture 2 , if static S_ENC and static S_MAC have an equal value,we conclude that the session S_ENC and session S_MAC must have an equal value. is that right? if yes, why in JCManager there are difference between them?
4-I use this site and encrypt the Derivation data that highlighted in JCManager by a ECB(DES) encryption, But output is not that expected! and again why!?

A: The card uses SCP02 as indicated in the key information returned for the INITIALIZE UPDATE command. Thus the card challenge has 6 bytes and key derivation data based on a key-specific constant (01 82 for S_ENC) and the sequence counter (00 16 as sent by the card in the INITIALIZE UPDATE response). The values you see in JCManager are correct.
The diagrams you are showing do not reflect the key derivation mechanism of SCP02. Instead this seems to be the key derivation mechanism for SCP01.


text:
Q: Increase VectorDrawable icon stroke in xml I have some svg icons for my android project. How to increase stroke-width of these icons.
One icon xml as example:
<vector android:height="28dp" android:viewportHeight="58.365"
    android:viewportWidth="58.365" android:width="28dp" xmlns:android="http://schemas.android.com/apk/res/android">
    <path android:fillColor="#000000"  android:pathData="M57.2641,26.6852l-8.4997,-7.8927L48.7644,5.8623l-9.7912,0l0,3.8391L29.182,0.6093L1.1008,26.6852c-0.3956,0.3681 -0.4191,0.9879 -0.0509,1.3845c0.3672,0.3956 0.987,0.4181 1.3845,0.0509l3.2497,-3.0176l0,32.6527l15.6659,0l15.6659,0l15.6659,0L52.6819,25.102l3.2497,3.0176c0.188,0.1753 0.4279,0.2614 0.6668,0.2614c0.2634,0 0.5248,-0.1048 0.7167,-0.3123C57.6832,27.6732 57.6597,27.0534 57.2641,26.6852zM40.9314,7.8205l5.8747,0l0,9.1538l-5.8747,-5.4547L40.9314,7.8205zM23.3073,55.7974L23.3073,35.1742c0,-0.5062 0.4112,-0.9174 0.9174,-0.9174l9.9146,0c0.5062,0 0.9174,0.4112 0.9174,0.9174l0,20.6232L23.3073,55.7974zM50.7226,55.7974l-13.7077,0L37.015,35.1742c0,-1.5862 -1.2895,-2.8757 -2.8757,-2.8757L24.2247,32.2985c-1.5862,0 -2.8757,1.2895 -2.8757,2.8757l0,20.6232l-13.7077,0L7.6414,23.2838l21.5406,-20.0024l13.9818,12.9831l5.6006,5.2001l0,0l1.9582,1.8182L50.7226,55.7974z"/>
</vector>

A: as simple as adding these two fields to path tag
android:strokeColor="@color/red"
android:strokeWidth="1"

A: Please try below code
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="28dp"
    android:height="28dp"
    android:viewportWidth="58.365"
    android:viewportHeight="58.365">
    <path
        android:fillColor="#000000"
        android:strokeWidth="1"
        android:strokeColor="#000000"
        android:pathData="M57.2641,26.6852l-8.4997,-7.8927L48.7644,5.8623l-9.7912,0l0,3.8391L29.182,0.6093L1.1008,26.6852c-0.3956,0.3681 -0.4191,0.9879 -0.0509,1.3845c0.3672,0.3956 0.987,0.4181 1.3845,0.0509l3.2497,-3.0176l0,32.6527l15.6659,0l15.6659,0l15.6659,0L52.6819,25.102l3.2497,3.0176c0.188,0.1753 0.4279,0.2614 0.6668,0.2614c0.2634,0 0.5248,-0.1048 0.7167,-0.3123C57.6832,27.6732 57.6597,27.0534 57.2641,26.6852zM40.9314,7.8205l5.8747,0l0,9.1538l-5.8747,-5.4547L40.9314,7.8205zM23.3073,55.7974L23.3073,35.1742c0,-0.5062 0.4112,-0.9174 0.9174,-0.9174l9.9146,0c0.5062,0 0.9174,0.4112 0.9174,0.9174l0,20.6232L23.3073,55.7974zM50.7226,55.7974l-13.7077,0L37.015,35.1742c0,-1.5862 -1.2895,-2.8757 -2.8757,-2.8757L24.2247,32.2985c-1.5862,0 -2.8757,1.2895 -2.8757,2.8757l0,20.6232l-13.7077,0L7.6414,23.2838l21.5406,-20.0024l13.9818,12.9831l5.6006,5.2001l0,0l1.9582,1.8182L50.7226,55.7974z" />
</vector>

A: Simple but care to be taken to remove Tint tag as well like this:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:tint="@color/colorPrimary"--> This line should be removed
    android:viewportWidth="24"
    android:viewportHeight="24">
    <path
        android:fillColor="@android:color/white"
        android:pathData="M7,2v11h3v9l7,-12h-4l4,-8z"
        android:strokeWidth="1"--> Add This line
        android:strokeColor="@color/colorPrimary" -->This as well
    />

</vector>


text:
Q: Speeding up the felm command in R (lfe library) I am using the felm from the lfe library, and am running into serious speed issues when using a large data set. By large I mean 100 million rows. My data consists of one dependent variable and five categorical variables (factors). I am running regressions with no covariates, only factors.
The felm algorithm does not converge. And I also tried some of the tricks used in this short article, but it did not improve. My code is as follows:
library(lfe)
my_data=read.csv("path_to//data.csv")
attach(data.frame(my_data))

lev1 = unique(my_data$fac1)
my_data$fac1 <- factor(my_data$fac1, levels = lev1)
lev2 = unique(my_data$fac2)
my_data$fac2 <- factor(my_data$fac2, levels = lev2)
lev3 = unique(my_data$fac3)
my_data$fac3 <- factor(my_data$fac3, levels = lev3)

and now I run the regression, without covariates (because I'm only interested in the residuals), and with interactions as follows:
est <- felm(y ~ 0|fac1:fac2+fac1:fac3, my_data)

This line takes forever and does not converge. Note the dimension of the are as follows:

*

*fac1 has about 6000 unique values

*fac2 has about 100 unique values

*fac3 has about 10 unique values

(and remember there are 100 million rows). I suspect there must be something wrong with how I use the factors, because I imagine that R should be able to handle such sizes (stata's reghdfe command handles it without problems). Any suggestions are highly appreciated.


text:
Q: Net::IMAP fails: Connection Closed When I try to open a connection to my Office 365 service, it fails as so:
2.2.0 :001 >     require 'net/imap'
=> true
2.2.0 :002 >     port = '993'
=> "993"
2.2.0 :003 >     imap = Net::IMAP.new('outlook.office365.com', port)

Net::IMAP::Error: connection closed
  from /Users/cameronaziz/.rvm/rubies/ruby-2.2.0/lib/ruby/2.2.0/net/imap.rb:1077:in `initialize'
  from (irb):3:in `new'
  from (irb):3

What else do I need to set?
This is the code in my controller:
require 'net/imap'
port = '993'
imap = Net::IMAP.new('outlook.office365.com', port)
imap.authenticate('LOGIN', '***@***.com', '***')
imap.examine('INBOX')

It fails on the new command (same as the console) before I actually set the username / password.
~~~~~~~
Setting the :ssl => true works. But now I still can not connect, as I get:
controller:
imap = Net::IMAP.new('outlook.office365.com', {:port => '993', :ssl => true } )
imap.authenticate('LOGIN', '***@***.com', '***')

error on view:
Net::IMAP::BadResponseError in EmailsController#connect
 Command Argument Error. 11

And the highlighted line in the view is on the authenticate method line now.
When I run imap.capability:
 ["IMAP4", "IMAP4REV1", "AUTH=PLAIN", "AUTH=XOAUTH2", "SASL-IR", "UIDPLUS", "ID", "UNSELECT", "CHILDREN", "IDLE", "NAMESPACE", "LITERAL+"]

A: Port 993 is usually the way t connect via SSL IMAP so you need to tell ruby you need to connect via SSL such as:
imap = Net::IMAP.new('outlook.office365.com', 993, ssl: true)

Then you can use login or authenticate to connect to your user's mailbox.
The ruby doc state that if you use authenticate method, you need to make sure the imap server can support "LOGIN" or "CRAM-MD5" but in the list you provided i don't see any of those.
["IMAP4", "IMAP4REV1", "AUTH=PLAIN", "AUTH=XOAUTH2", "SASL-IR", "UIDPLUS", "ID", "UNSELECT", "CHILDREN", "IDLE", "NAMESPACE", "LITERAL+"]
So the only way to login to outlook imap is to use map.login method such as:
imap.login(login, password)

A: IMAP is probably closing the connection because you aren't authenticating in time (or at all).
You should authenticate with either the Net::IMAP#login or the Net::IMAP#authenticate method.
From the docs:
imap.authenticate('LOGIN', 'username', password)
This should also work:
imap.login('username', 'password')
Keep in mind that LOGIN may not be the authentication method in your case. You may want to call imap.capability first and determine whether to proceed with either LOGIN or CRAM-MD5.


text:
Q: Expected behavior when Private Memory Limit in IIS exceeds machine RAM So I have a couple of questions re: Private Memory Limit in IIS using a C# web app.
When we set the Private Memory Limit to 0, per the docs here it should have no limit.  However we saw behavior that the app would trigger an IIS reset when reaching approximately 60% of the machine RAM which seems counter intuitive.  Does this grok?
The second issue is expected behavior when the Private Memory Limit is set to a value that exceeds the amount of RAM available on the machine.  A co-worker solved the above problem by setting the Private Memory Limit above the system memory and it did perform well.  However this seems like it could have ramifications about proper GC times.
For example if the system RAM is 32 GB and the memory limit is set to 35, will it not trigger Gargbage Collection when it gets close to 32 because it THINKS it can get to 35?  Or are we guaranteed a garbage collection will happen before then?
Additionally this requires a config change if you ever change the size of the machine (we are an AWS shop so this can happen at a relatively high frequency).


text:
Q: Error in adding objective-c files to firebreath. unable to call obj-c from c++ I'm working on building a plugin for mac using Firebreath, I coded in c++ so far, but i want to use obj-c too. I'm new to objective c and Firebreath.I have no clue how to add .m or .mm files. please tell me how to do this, I need to call the functions written in objective c from c++ using firebreath.

A: This is the basic flow i know off.
Objective C  ->  .mm file implementation -> c++ calls.

A: This is mostly unrelated to firebreath, it's more a question of how to use objective c++ and c++ in the same project.
Basic rules of thumb:

*

*To include a .m or .mm file in the project, just configure cmake to include them.  it'll do the rest.

*You cannot include any objective c/c++ code in a .h file that will be included by normal .c or .cpp files unless you protect it with #ifdef __OBJC__

*You can use objective C from a c++ class inside a .mm file

*Basically what you're doing is creating a c++ class that can be used by other cpp files but wraps the objective c functionality that you need.  Anything that must be in the .h file that is specific to obj c goes in the #ifdef and everything else is in the .mm file

Hope that helps.  See WebViewMac.h and WebViewMac.mm in the FireBreath source for an example of this technique.


text:
Q: How can I read characters until a specific one in Java? I want to read a few words from a file. I didn't found any method to do this, so I decided to read char by char, but I need to stop at the spaces to store the read word in my array and go to the next one.
I'm making an external sorting aplication, that's why I have a memory limitation, and, in that case, I can't just use readLine() and then split(), I need to have a control of what I read.
The read() method returns an int and I have no idea of what can I do to read() method return a char and stop reading after a space.
This is my code this far:
protected static String [] readWords(String arqName, int amountOfWords) throws IOException {
    FileReader arq = new FileReader(arqName);
    BufferedReader lerArq = new BufferedReader(arq);

    String[] words = new String[amountOfWords];

    for (int i = 0; i < amountOfWords; i++){
        //words[i] = lerArq.read();
    }

    return words;
}

Edit 1: I used a Scanner and the next() method, it worked. Scanner's initialization is at Main.
static String [] readWords(int amountOfWords, Scanner leitor) throws IOException {
    String[] words= new String[amountOfWords];

    for (int i = 0; i < amountOfWords; i++){
        words[i] = leitor.next();
    }

    return words;
}

A: Maybe this will be helpful.
It's not a problem to use read(). Just cast the result to a character:
...
for (int i = 0; i < memTam; i++) {
      // this should work. you will get the actual character
      int current = lerArq.read();
      if (current != -1) {
          char c = (char) current;
          // then you can do what you need with this character
      }
}
...

The method returns character read, as an integer in the range 0 to 65535 or -1 if the end of the stream has been reached.
I won't add a lot of theory about encodings, how it's done in Java, etc. because I am not aware of some very low-level details. I have a basic high-level understanding of how it works.
Every single key on your keyboard has a number associated with it. Every single character that you type can be translated into a decimal number. For example, A becomes the number 65. This is a standard and it is globally recognized.
At this point, I hope you can agree it's not that weird that read() method returns a number and not the actual character :)
There is something called the ASCII table which represents all those codes(numbers) for all the keys on your keyboard.
Here it is just to show how ot looks:
Dec  Char                           Dec  Char     Dec  Char     Dec  Char
---------                           ---------     ---------     ----------
  0  NUL (null)                      32  SPACE     64  @         96  `
  1  SOH (start of heading)          33  !         65  A         97  a
  2  STX (start of text)             34  "         66  B         98  b
  3  ETX (end of text)               35  #         67  C         99  c
  4  EOT (end of transmission)       36  $         68  D        100  d
  5  ENQ (enquiry)                   37  %         69  E        101  e
  6  ACK (acknowledge)               38  &         70  F        102  f
  7  BEL (bell)                      39  '         71  G        103  g
  8  BS  (backspace)                 40  (         72  H        104  h
  9  TAB (horizontal tab)            41  )         73  I        105  i
 10  LF  (NL line feed, new line)    42  *         74  J        106  j
 11  VT  (vertical tab)              43  +         75  K        107  k
 12  FF  (NP form feed, new page)    44  ,         76  L        108  l
 13  CR  (carriage return)           45  -         77  M        109  m
 14  SO  (shift out)                 46  .         78  N        110  n
 15  SI  (shift in)                  47  /         79  O        111  o
 16  DLE (data link escape)          48  0         80  P        112  p
 17  DC1 (device control 1)          49  1         81  Q        113  q
 18  DC2 (device control 2)          50  2         82  R        114  r
 19  DC3 (device control 3)          51  3         83  S        115  s
 20  DC4 (device control 4)          52  4         84  T        116  t
 21  NAK (negative acknowledge)      53  5         85  U        117  u
 22  SYN (synchronous idle)          54  6         86  V        118  v
 23  ETB (end of trans. block)       55  7         87  W        119  w
 24  CAN (cancel)                    56  8         88  X        120  x
 25  EM  (end of medium)             57  9         89  Y        121  y
 26  SUB (substitute)                58  :         90  Z        122  z
 27  ESC (escape)                    59  ;         91  [        123  {
 28  FS  (file separator)            60  <         92  \        124  |
 29  GS  (group separator)           61  =         93  ]        125  }
 30  RS  (record separator)          62  >         94  ^        126  ~
 31  US  (unit separator)            63  ?         95  _        127  DEL

So, imagine you have a .txt file with some text - all the letters have corresponding numbers.
The problem with ASCII is that ASCII defines 128 characters, which map to the numbers 0–127 (all of the upper-case letters, lower-case letters, 0-9 digits and a few more symbols).
But there are many more different characters/symbols in the world (different alphabets, emoji, etc.), so there has to be another encoding system to represent them all.
It is called Unicode. Unicode is exactly the same thing for characters whose codes are 0-127. But in general, Unicode can represent a much much wider range of symbols.
In Java, the char data type (and therefore the value that a Character object encapsulates) are based on the original Unicode specification, which defined characters as fixed-width 16-bit entities. You can check more details in this javadoc.
In other words, all Strings in Java are represented in UTF-16.
Hope, after this long story, it makes some sense why you get numbers when read, but you can cast them to type char. And again, it's just a kind of high-level overview. Happy Coding :)

A: If you want to read it char by char (so you have more control over what you want to store and what you don't), you could try something like this:
import java.io.BufferedReader;
import java.io.IOException;

[...]

public static String readNextWord(BufferedReader reader) throws IOException {
    StringBuilder builder = new StringBuilder();

    int currentData;

    do {
        currentData = reader.read();

        if(currentData < 0) {
            if(builder.length() == 0) {
                return null;
            }
            else {
                return builder.toString();
            }
        }
        else if(currentData != ' ') {
            /* Since you're talking about words, here you can apply
             * a filter to ignore chars like ',', '.', '\n', etc. */

            builder.append((char) currentData);
        }

    } while (currentData != ' ' || builder.length() == 0);

    return builder.toString();
}

And then call it like this:
String[] words = new String[amountOfWordsToRead];

for (int i = 0; i < amountOfWordsToRead; i++){
    words [i] = readNextWord(yourBufferedReader);
}


text:
Q: How to send List of objects and image from jQuery to ASP.NET MVC controller I have some model classes:
public class Research
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Abstract { get; set; }
    public string Body { get; set; }
    public string Image { get; set; }
    [NotMapped]
    public HttpPostedFileWrapper ImageFile { get; set; }
    public virtual List<ResearchAuthors> ResearchAuthors { get; set; }
}

public class ResearchAuthors
{
    public int Id { get; set; }
    public int AuthorId { get; set; }
    public int ResearchId { get; set; }
    public Research Research { get; set; }
    public Author Author { get; set; }
}

This is the jQuery code how I'm getting the data to be sent to the controller
        var Research = {
            Id: idInput.val(),
            Title: titleInput.val(),
            Abstract: abstractInput.val(),
            ImageFile: imageInput.get(0).files[0],
            Body: bodyInput.val()
        };

        // Research Authors
        var ResearchAuthors = [];
        $('#authors-tbody tr').each(function () {
            var AuthorId = $(this).children('.id-td').text();
            var Id = $(this).children('.researchAuthorsId-td').text();
            var ResearchAuthor = {
                AuthorId: AuthorId,
                Id: Id,
                ResearchId: idInput.val()
            }
            ResearchAuthors.push(ResearchAuthor)
        });

The controller is waiting for this
public ActionResult Create(SaveResearchViewModel viewModel)
{
      return Json(new { success = true, message = "Created Successfully" });
}

The SaveResearchViewModel code:
public class SaveResearchViewModel
{
    public Research Research { get; set; }
    public List<ResearchAuthors> ResearchAuthors { get; set; }
}

I have used formdata but it won't work because of List of ResearchAuthors even can't stringify because of there is image with data to be send
So what is the proper way to use with all different data types [Object, Object.Image, Arr[Object]] in order to receive in the controller?

A: You can use ajax to pass 1 string to Controller. Then serializer into an object.
var Research = {
Id: idInput.val(),
Title: titleInput.val(),
Abstract: abstractInput.val(),
ImageFile: imageInput.get(0).files[0],
Body: bodyInput.val()};

$.ajax({
url:'/Controller/Action',
data: {
    strResearch: JSON.stringify(Research)
},
type: 'POST',
dataType: 'json',
success: function(res){
    if(res.success)
    {
        alert(res.message)
    }
}

//Controller
    public JsonResult Create(string strResearch)
    {
        SaveResearchViewModel saveResearchViewModel = new SaveResearchViewModel();
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        Research objResearch = serializer.Deserialize<Research>(strResearch);
        //save db

        return Json(new { success = true, message = "Created Successfully" });
    }

A: form data can't add list of objects so instead you can use 2 ajax request first ajax save the Research and ReseachAuthors second ajax Save the image
like this
 $.ajax({
                type: "POST",
                dataType: "json",
                url: "/Researches/Create",
                data: viewModel,
                success: function (data) {
                    if (data.success) {
                        $.ajax({
                            url: "/Researches/SaveImage",
                            method: "POST",
                            processData: false,
                            contentType: false,
                            data: data,
                            success: function (data) {
                                if (data.success) {
                                    toastr.success(data.message);
                                    window.location.replace("/Researches/");
                                }
                            },
                            error: function () {
                                toastr.error("Image Ajax error");
                            }
                        })
                    }
                    else {
                        toastr.error(data.message)
                    }
                },
                error: function () {
                    toastr.error("Ajax Error")
                }


text:
Q: yii2 name field attribute using variable I'm trying to create in an activeform a series of controls using a loop for not being to declare the various fields of the model in order to have a generic template to which I pass only the name of the table and it creates the edit form.
So that if I pass the table A and it has 3 fields it creates three fields, the b has 5 fields it creates 5 fields etc etc.
$tfields= Array ( [0] => id [1] => brand_id [2] => group_id)
and i create this code
foreach($tfields as $key => $value) {
    if (strlen($value)>0){
 echo $form->field($model,  $value)->textInput();
}
  }

but when i run the code i get this error
Calling unknown method: yii\data\ActiveDataProvider::isAttributeRequired()
any ideas?
tks a lot!

A: the problem was tha i use an ActiveDataProvider as model, using instead  and DynamicModel
in the controller
$model2= new \yii\base\DynamicModel([
   ]);

in the form
 foreach(explode(',',$fields) as $item){
    if (strlen($item)<>0){ //to avoid empty
   echo $form->field($model2, $item)->textInput();
     }
  }


text:
Q: Google Docs Search entire document and bold words I have a google doc and there are several instance of the words Description, Rationale, and Inheritance that I want to set as bold. From searching here I built this from other suggestions:
    function searchAndReplace() {

    let doc = DocumentApp.getActiveDocument();
    let body = doc.getBody();

    // Set some elements to bold
    let target1 = "Description"
    let searchResult1 = body.findText(target1);
    if (searchResult1 !== null) {
      let thisElement1 = searchResult1.getElement();
      let thisElement1Text = thisElement1.asText();
      thisElement1Text.setBold(searchResult1.getStartOffset(), searchResult1.getEndOffsetInclusive(), true);
   }

    let target2 = "Rationale"
    let searchResult2 = body.findText(target2);
   if (searchResult2 !== null) {
      let thisElement2 = searchResult2.getElement();
      let thisElement2Text = thisElement2.asText();
      thisElement2Text.setBold(searchResult2.getStartOffset(), searchResult2.getEndOffsetInclusive(), true);
    }

    let target3 = "Inheritance"
    let searchResult3 = body.findText(target3);
    if (searchResult3 !== null) {
      let thisElement3 = searchResult3.getElement();
      let thisElement3Text = thisElement3.asText();
      thisElement3Text.setBold(searchResult3.getStartOffset(), searchResult3.getEndOffsetInclusive(), true);
    }
}

When I run this it only bolds the first instance of Rationale. I tried changing the if to a while but that just ran and did not complete.
Any ideas?

A: This should do. Credits to this post. The laste line inside the while is the key.
function searchAndReplace() {

  let doc = DocumentApp.getActiveDocument();
  let body = doc.getBody();

  // Set some elements to bold
  let target1 = "blandit"
  let searchResult1 = body.findText(target1);
  while (searchResult1 !== null) {
    let thisElement1 = searchResult1.getElement();
    let thisElement1Text = thisElement1.asText();
    thisElement1Text.setBold(searchResult1.getStartOffset(), searchResult1.getEndOffsetInclusive(), true);

    searchResult1 = body.findText(target1, searchResult1)
  }
}

A: function highlight_words() {
  var doc   = DocumentApp.getActiveDocument();
  var words = ['Description','Rationale','Inheritance']; // <-- put your words here
  var style = { [DocumentApp.Attribute.BOLD]: true };
  var pgfs  = doc.getParagraphs();

  for (var word of words) for (var pgf of pgfs) {
    var location = pgf.findText(word);
    if (!location) continue;
    var start = location.getStartOffset();
    var end = location.getEndOffsetInclusive();
    location.getElement().setAttributes(start, end, style);
  }
}

Note: unlike the accepted answer my code changes all the words of the given array at once.
If you want to highligth the words with yellow color here is my previous solution: https://stackoverflow.com/a/69420695/14265469


text:
Q: Regular Expressions - match a string containing "+" and "-" I have a string, say 1+++-3--+++++2 that includes + and - sign.
What I want to do is to represent the + and - part with + or - sign.
If there are an odd number of - sign in the string, I will replace it with -, and + if that is an even number. How can I do that using regex?
For example, I have a math expression, say 1+-+-2-+--+3. It will be replaced by 1+2-3

A: You can create an array of the operators and use a for loop to count all occurrences of one character. For example:
String expression = "1+++-3--+++++2";
String[] str = expression.split("[0-9]+");

for(op : str) {
    int count = 0;
    for(int i =0; i < str.length(); i++)
        if(op.charAt(i) == '-')
            count++;

    if(count % 2 == 0) {
        op = "-";
    }
    else {
        op = "+";
    }
}

After assigning the modified one-character operators in str[], it should be relatively simple to write the new expression.

A: based on the assumption that the format will be from that calculator example.
//assumed format for input: <any number><any number of `-` and/or `+`><any number>

// 1++---+22+--1 will be 1-22+1
String input = "1++---+22+--1";
for (String s : input.split("[^-+]+");) {
    s = s.trim();
    if (!"".equals(s)) {
        String newStr = s.matches("[+]*-([+]*-[+]*-)*[+]*") ? "-" : "+";
        input = input.replace(s, newStr);
    }
}
System.out.println(input);


text:
Q: org.apache.spark.SparkException: Job aborted due to stage failure with Yarn and Docker I developed a Spark application on local and got no problems. But when I wanted to push it in a Yarn Cluster in a docker Image, I got the following messages :

Exception in thread "main" org.apache.spark.SparkException: Job aborted due to stage failure: Task 2 in stage 0.0 failed 4 times, most recent failure: Lost task 2.3 in stage 0.0 (TID 26, sandbox): ExecutorLostFailure (executor 1 lost)
  Driver stacktrace:
      at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1203)
      at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1192)
      at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1191)
      at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
      at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47)
      at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1191)
      at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:693)
      at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:693)
      at scala.Option.foreach(Option.scala:236)
      at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:693)
      at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1393)
      at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1354)
      at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
  uote

The command used to launch the app is:
spark-submit --class myapp.myapp_spark.App --master yarn-client /opt/myapp/myapp_spark.jar

My application is using a Mongo database. Is it linked to a memory problem, to the connection with Mongo or something else ? Thanks in advance