text:
Q: neo4j + mysql in spring data transactions not working I am trying to build an application using both MySQL and neo4j.
Currently I succeed on saving an entity in both of the databases, but when I try to create a rollback only MySQL changes are rollbacked.
I'm not sure if the mode="proxy" configuration for the transactions can even work for neo4j, can someone approve/deny?
I'm using the @Transactional annotation over the relevant method, and I initiate a rollback by throwing a RuntimeException, which as I mentioned causes a rollback on MySQL.
My Configurations:
<neo4j:config graphDatabaseService="graphDatabaseService" entityManagerFactory="entityManagerFactory"/>

<bean id="graphDatabaseService" class="org.springframework.data.neo4j.rest.SpringRestGraphDatabase">
    <constructor-arg index="0" value="http://localhost:7474/db/data"/>
</bean>

<context:annotation-config/>
<context:component-scan base-package="...">
<neo4j:repositories base-package="..."/>
<jpa:repositories base-package="..."
                  entity-manager-factory-ref="entityManagerFactory"
                  transaction-manager-ref="transactionManager"/>

<tx:annotation-driven mode="proxy" transaction-manager="transactionManager"/>

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"/>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="persistenceUnitName" value="hibernatePersistenceUnit"/>
    <property name="packagesToScan" value="..."/>
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="true"/>
            <property name="generateDdl" value="true"/>
            <property name="database" value="MYSQL"/>
        </bean>
    </property>
</bean>

<!-- Database -->
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/..."/>
    <property name="lookupOnStartup" value="true"/>
    <property name="proxyInterface" value="javax.sql.DataSource"/>
</bean>

<!-- Declare a transaction manager-->
<bean id="transactionManager" class="org.springframework.data.transaction.ChainedTransactionManager">
    <constructor-arg>
        <list>
            <ref bean="transactionManagerMysql"/>
            <ref bean="transactionManagerNeo4j"/>
        </list>
    </constructor-arg>
</bean>
<bean id="transactionManagerMysql" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<bean id="transactionManagerNeo4j" class="org.springframework.data.neo4j.config.JtaTransactionManagerFactoryBean">
    <constructor-arg ref="graphDatabaseService" />
</bean>


text:
Q: How can I prove that the Hilbert transform on the 1-torus doesn't map $L^1(\mathbb{T})$ into itself? Let $\mathbb{T}$ be the 1-torus. Then, it is well defined the Hilbert transform:
$$\mathcal{H}:L^1(\mathbb{T})\to L^0(\mathbb{T}), \vartheta\mapsto\int_{-\pi}^\pi f(\vartheta-t)\cot\left(\frac{t}{2}\right) \frac{\operatorname{d}t}{2\pi}.$$
I know that $\mathcal{H}$ is weak-(1,1), i.e. that there exists a constant $C>0$ such that:
$$\forall f\in L^1(\mathbb{T}), \forall \lambda>0, \left|\left\{\vartheta\in\mathbb{T} : |\mathcal{H}(f)(\vartheta)|>\lambda \right\}\right|\le C\frac{\|f\|_1}{\lambda}.$$
In my lecture notes it is stated without proof that $\mathcal H$ doesn't map $L^1(\mathbb{T})$ into itself.
I'm thinking about how to prove this claim.
I can prove that doesn't exist an operator $\mathcal{G}: L^1(\mathbb{T})\to L^1(\mathbb{T})$ such that
$$\forall f\in L^1(\mathbb{T}), \forall n\in\mathbb{Z}, \mathcal{F}(\mathcal{G}(f))(n) = -i \operatorname{sgn}(n)\mathcal{F}(f)(n),$$
where $\mathcal{F}$ is the Fourier transform.
Also, I know that $$\forall p\in(1,+\infty), \forall f\in L^p(\mathbb{T}), \left(\mathcal{H(f)}\in L^p(\mathbb{T})\right)\land \left(\mathcal{F}(\mathcal{H}(f))(n) = -i \operatorname{sgn}(n)\mathcal{F}(f)(n)\right).$$
Now, if I only could prove that "$\mathcal{H}$ maps $L^1(\mathbb{T})$ into itself" would imply "$\mathcal{H}: L^1(\mathbb{T})\to L^1(\mathbb{T})$ with continuity", then the claim that $\mathcal H$ doesn't map $L^1(\mathbb{T})$ in itself  would follows from a density and continuity argument.
However I can't see how to prove that the only fact that $\mathcal{H}$ maps $L^1(\mathbb{T})$ into itselt would imply its continuity (I thought to use something like the closed graph theorem, but I can't see how it could apply here).
Any help?

A: (Using a plain "$H$" for the Hilbert transform; easier to type and also more standard):
Yes,
$\newcommand{\sgn}{\operatorname{sgn}}$

Prop. If $H(L^1(\Bbb T))\subset L^1(\Bbb T)$ then $H:L^1(\Bbb T)\to L^1(\Bbb T)$ is bounded.

And yes, this is immediate from the Closed Graph Theorem.
Say $m(k)=-i\sgn(k)$, so $H$ is characterized by $$\widehat{Hf}(k)=m(k)\hat f(k).$$
Suppose $f_n\to f$ in $L^1$ and also $Hf_n\to g$  in $L^1$; we need to show that $g=Hf$. But $$\widehat g(k)=\lim_n\widehat{Hf_n}(k)=\lim_n m(k)\widehat {f_n}(k)=m(k)\widehat f(k).$$
Note If we're talking about $L^1(\Bbb R)$ instead of $L^1(\Bbb T)$ then the Fourier transform makes it trivial to give a specific counterexample:

Triviality If $f\in L^1(\Bbb R)$ and $\int f\ne0$ then $Hf\notin L^1(\Bbb R)$.

Proof: Since $\widehat f(0)\ne0$ the function $m\widehat f$ is not continuous at the origin, so there cannot exist $g\in L^1(\Bbb R)$ with $m\widehat f=\widehat g$.
Edit: I tend to think of $H$ as defined by the Fourier transform. If we take it to be defined as the pointwise principal-value integral that doesn't quite work for $L^1$, because it's not at all clear that $Hf$ is something that even has a Fourier transform.
I thought I had a simple answer to that but it was wrong. Will give the simple answer if I figure it out.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ajax Request on jQuery Mobile using with Codeginiter Currently Im trying to do ajax request using jQuery Mobile. I`m trying to use example on http://www.giantflyingsaucer.com/blog/?p=2574. Yes, it works perfectly. But problems was coming when i tried to use the code inside codeigniter.
Here is my controller :
<?php
class Ajax extends CI_Controller {
    function __construct() {

    }

    function index() {
        ?>
        <!DOCTYPE html>

            <title>Submit a form via AJAX</title>
              <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a4/jquery.mobile-1.0a4.min.css" />

Call Ajax

                    <form id="callAjaxForm">

                            First Name
                            <input type="text" name="firstName" id="firstName" value=""  />

                            Last Name
                            <input type="text" name="lastName" id="lastName" value=""  />

                            <button data-theme="b" id="submit" type="submit">Submit</button>

                    </form>

GiantFlyingSaucer

        <?php
    }

    function callajax() {
        echo "ok";
    }
}

I want to display 'ok' in notification. Im trying to call function callajax instead of call from callajax.php is this possible or do I need to create callajax.php?
Ive tried to create callajax.php but it was failed.
Thank you,

A: You probably want the url to be:
 url: "ajax/callajax",

As you are calling the callajax function within the controller ajax.


text:
Q: Stylesheet linked but not loaded? rebuilding an app from rails 3.2 to 4, and all went well enough except some of my stylesheets are not being applied. When I ctru-U they seem linked ok:
<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Badge2</title>
    <meta name="description" content="Badge2">
    <link data-turbolinks-track="false" href="/assets/application.css?body=1" media="all" rel="stylesheet" />
<link data-turbolinks-track="false" href="/assets/badges.css?body=1" media="all" rel="stylesheet" />
<link data-turbolinks-track="false" href="/assets/framework_and_overrides.css?body=1" media="all" rel="stylesheet" />
<link data-turbolinks-track="false" href="/assets/home.css?body=1" media="all" rel="stylesheet" />
<link data-turbolinks-track="false" href="/assets/scaffolds.css?body=1" media="all" rel="stylesheet" />
    <link href='http://fonts.googleapis.com/css?family=PT+Sans' rel='stylesheet' type='text/css'>
    <script data-turbolinks-track="true" src="/assets/jquery.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/jquery_ujs.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/turbolinks.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/bootstrap-transition.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/bootstrap-affix.js?body=1"></script>
...
<script data-turbolinks-track="true" src="/assets/badges.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/home.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/application.js?body=1"></script>
    <meta content="authenticity_token" name="csrf-param" />
<meta content="0kPf5I9Ayz6yEM/RLbfyYmzTdixuoyf5Z4w9iPyuGaU=" name="csrf-token" />
  </head>
  <body>
    <header>

But when I click on /assets/badges.css?body=1 it is blank. (And of course its styles are not applied.) Scaffolds and framework load, but home and badges don't. (Or load blank/empty). What am I missing?

A: The answer seems to be that this line:
<link href='http://fonts.googleapis.com/css?family=PT+Sans' rel='stylesheet' type='text/css'>

needed a trailing /.
I copied it from the old rails 3.2 app, where it worked.
Oddly, there were already css comments in the badges.css file, bus sass strips out single-line comments (//...) and preserves multi-line comments (/* ... */ ).


text:
Q: Why does the jQuery script in the partial view not working? (I will left out some of the code in which I'm 100% sure in order to make the code more compact) I have a main view (the main view doesn't have any html-head-body because it is included in Layout)...

<link rel="stylesheet" href="~/css/user-files-table-style.css"/>

@section Scripts
{

}

..and a Partial view

User files ("Delete" and "Download" buttons can be clicked with invalid XML files only)

        User file
        Assigned email
        Is valid
        Delete button
        Download button

    @foreach (var userFileViewModel in Model)
    {
        @foreach (var file in userFileViewModel.UserFiles)
        {
                if (isValid == false && isXml)
                {

                        @file.FileName
                        @userFileViewModel.Email
                        @file.IsValid

                            Delete

                            <input type="button" id="@file.FileName" class="btn btn-primary download-button" value="Download" />

File has been downloaded successfully

                }
            }
        }
    }

...and some JS:
$(document).ready(function () {
    $(document).on("click", ".btn.btn-primary.download-button", function () {
        const fileName = $(this).attr("id");
        const clickedButtonRowIndex = $("input[type='button']").index(this);

        downloadUserFile(fileName, clickedButtonRowIndex);
    });
});

function downloadUserFile(fileName, rowIndex) {
    $.ajax({
        url: "/Admin/Download",
        data: { fileName: fileName },
        success: function (data) {
            processProvidedFile(data, fileName);
            showDownloadResult(rowIndex);
        },
        error: function (error) {
            alert(`An error occured: ${error.responseText}`);
        }
    });
}

function processProvidedFile(data, fileName) {
    fetch(data)
        .then(resp => resp.blob())
        .then(blob => {
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.style.display = "none";
            a.href = url;
            a.download = fileName;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
        })
        .catch(() => alert("An error occured"));
}

function showDownloadResult(rowIndex) {
    $(".download-result.active").removeClass("active");
    $(".download-result").eq(rowIndex).addClass("active");
}

...and some CSS:
.download-result {
    display: none;
}

    .download-result.active {
        display: block;
    }

In general, my task is to download the file and show that the file has been successfully downloaded. Files are downloaded normally, no problem with it. My issue is that the showDownloadResult(rowIndex) function not working as expected. Chrome debugger hits it with a correct rowIndex, but neither remove an active class nor adding it. I checked the function in JSFiddle - it works as expected there, but not in my partial view. What am I doing wrong?


text:
Q: WordPress. Adding a taxonomy both to users and other content As reported in this page adding a taxonomy to a user is very different and more complicated than doing the same job for anoter content.
That's my question: can I add the taxonomy, let's call it "skills", to my users and  to a CPT called JobOffer?
How... in case it's possible?
Many thanks

A: There are several ways. An easy solution is to use Advanced Custom Fields to add taxonomies for a custom post type to users.
Have you already registered the custom post type taxonomy and linked it to the custom post type?


text:
Q: How do I find out the Git commands used at the start of the job? I'm trying to debug some Git related stuff, but really want to know all the Git commands the runner is calling at the start of a job. How can I do this?

A: If you are running your own runners, you can set pre_clone_script to set -x. This might output all the commands in verbose mode. See also: https://docs.gitlab.com/runner/configuration/advanced-configuration.html#the-runners-section.
What gitlab does also depends on what stage the job is running. Is it at the beginning, in the middle, or towards the end? I'm using the docker runner which typically does:

*

*Download the docker image used for the build

*Login into the docker image

*Load the cache from a previous job

*Delete all the changes from the previous job, similiar to git clean -qfdx

*checkout the hash you want to build, similar to git checkout 234nsdfgow45sdfkj

*download artifacts from all previous build jobs, if there are any

*start whatever is defined in the script: section of your .gitlab-ci.yml
Look at the output of your job from the beginning. You are better off to describe what your actual problem is rather than "debug" all the git commands gitlab does for you.


text:
Q: Setting SVG start on scroll I have an animated timeline svg that comes on the last section.
http://chalke-design-ebbca1.webflow.io/our-process
The animation starts as soon as the page is loaded but I want to trigger it only when the users scrolls to that specific part of the page.
Can anyone help!
Thank you in advance!

A: Perhaps you want something that is outlined in these questions: Check if element is visible on screen or Check if element is visible after scrolling, that is, you check if the element-in-question's top offset is within the screen's bounds, and then start your animation if that condition is true.
var theElementInQuestion = document.getElementById("theElementInQuestion");

if (isScrolledIntoView(theElementInQuestion)) {
    startAnimation();
}

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}


text:
Q: Is it possible to create a view in one database from another database in oracle when databases are different machine? Lets say I have a oracle database db1(actually user)  in machine A
and another database db2 in machine B. Is it possible to create view in
db2 from db1.If possible how ?

A: Yes, by using database links. For example, in db2:
create database link db1_link connect to myuser identified by mypassword using 'db1';
create view myview as select * from mytable@db1link;
select * from myview;

Where using 'db1' refers to a TNS entry, but it could be replaced with the actual TNS descriptor.


text:
Q: C++ Overloading with default parameters i have a little question, how can i initialize default arguments in an function?
    #include <iostream>
    #include <cmath>

    using namespace std;
    float area(float a, float b, float c);
    float area(float a, float b=a, float c =a);

    int main() {

        cout << area(10) << endl;
        return 0;
    }

float area(float a, float b, float c){
    return a*b*c
    }

i am getting errors, how can i impelent correctly?

A: You are going to have to use overloading instead of default parameters:
#include <iostream>
#include <cmath>

using namespace std;
float area(float a, float b, float c);
float area(float a);

int main() {

    cout << area(10) << endl;
    return 0;
}

float area(float a, float b, float c){
  return a*b*c;
}
float area(float a){
  return area(a,a,a);
}

A: If you want default value for b and c to be the value of a then you should use overloading:
float area(float a, float b, float c){
   return a*b*c
}
float area(float a) {
   return area(a, a, a);
}

C++ does not allow to use parameters as default arguments. So this
float area(float a, float b=a, float c =a);
                           ^^          ^^

is an Error.

A: In C++
you should prototype and implement the code for only one method including the optional parameters and the default values is the optional parameter is ommitted must be a constant and not an unknown value...
    float area(float a, float b=0, float c=0);
    int main() {
        cout << area(10) << endl;
        return 0;
    }

float area(float a, float b=-1, float c =-1);){
    if(b==-1 ||c==-1)
    {
        return a*a*a;
    }else
    {
        return a*b*c;
    }
}


text:
Q: Query to select distinct name based on several factors I have a table with the following data (simplified here):
ID | PolicyName | Setting | State | Value
1 Default DiskUsage Enabled 1
2 Default Memory Enabled 1
3 Default CPU Enabled 0
4 Personal DiskUsage Enabled 0
5 Personal Memory Enabled 1
6 Personal CPU Enabled 0
7 Custom DiskUsage Enabled 1
8 Custom Memory Enabled 0
9 Custom CPU Enabled 1
I need to run a query looking for policy names that have Setting of DiskUsage Enabled and set to 1 along with Memory Enabled and set to 1.  So it should return:
PolicyName
Default
Not sure how I can go about this one.

A: Assuming the data is constrained to avoid duplicates, how about something like this?  This is assuming Microsoft SQL Server syntax.
SELECT United.PolicyName FROM
(SELECT PolicyName FROM dbo.Policies
WHERE Setting = 'DiskUsage'
  AND State = 'Enabled'
  AND Value = 1
UNION ALL
SELECT PolicyName FROM dbo.Policies
WHERE Setting = 'Memory'
  AND State = 'Enabled'
  AND Value = 1
) AS United
GROUP BY United.PolicyName
HAVING COUNT(*) = 2

RESULTS: Default
This specifically queries for each of the states that you care about.  Since there are two requirements, then the UNION will produce two rows when both selects are find a row.


text:
Q: Sun Java HttpServer - Either slow in serving requests or wasting resources (TIME_WAIT/CLOSE_WAIT) First,
I've searched a lot to find a solution but were not able to find an appropriate one.
Environment

*

*(productive) Mongoose WebServer replies to simple GET-requests (all data are transmitted via QueryString)

*Apache HttpClient (single instance!) used to make hundreds of thousands single requests sequentially.

*Apache HttpClient interacting with mongoose works quite well
// after each request
getMethod.releaseConnection();
...

Problem

*

*(Mock) implementation of WebServer with Sun HttpServer works fine with FireFox / Curl

*Using Apache HttpClient as with running against productive Server, performance is horrible (~ 1 request/second) on client

*Using Apache HttpClient with following code found on the net results in

*

*vast performance gain on client

*resource waste due to as many open sockets in CLOSE_WAIT state as requests processed (until no more FDs ara available!)

Code:
HttpConnectionManager mgr = httpClient.getHttpConnectionManager();
    if (mgr instanceof SimpleHttpConnectionManager) {
    ((SimpleHttpConnectionManager)mgr).shutdown();
}

Obviously I am mising something in the http server implementation, which causes this extreme "sloweness"
Any hint/help is appreciated.
Thanks in advance!

Code
HttpServer

public static void main(String[] args) throws Exception {
        //System.setProperty("sun.net.httpserver.maxIdleConnections", "10");
        //System.setProperty("sun.net.httpserver.idleInterval", "2000");

        HttpServer server = HttpServer.create();

        server.bind(new InetSocketAddress("localhost", 11111), -1);
        InetSocketAddress addr = server.getAddress();
        HttpContext contextSearch = server.createContext("/search.to",
                new TrufflesSearchHandler());

        contextSearch.getFilters().add(new ParameterFilter());
        server.setExecutor(null); // creates a default executor
        server.start();
    }

HttpHandler
    static class SearchHandler implements HttpHandler {
        private JSONParser jsonParser = new JSONParser();

        public void handle(HttpExchange exchange) throws IOException {
            Map<String, Object> params = (Map<String, Object>) exchange
                    .getAttribute("parameters");
            String expectedResponse = "";
            int expectedHitPlace = -1;

            try {
                expectedResponse = (String) params.get("expectedResponse");
                expectedHitPlace = Integer.parseInt((String) params
                        .get("expectedHitPlace"));
            } catch (Exception e) {
                e.printStackTrace();
            }

            JSONArray resultArray = null;
            try {
                resultArray = (JSONArray) jsonParser.parse(new String(Base64
                        .decodeBase64(expectedResponse)));
                fillResponseWithDummyData(resultArray, expectedHitPlace);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            String response = "{ \"results\": " + resultArray + "}";

            Headers headers = exchange.getResponseHeaders();
            headers.add("Connection", "keep-alive");
            headers.add("Content-Type", "text/plain");
            headers.add("Content-length", "" + response.getBytes().length);
            // headers.add("Keep-Alive", "timeout=5 max=10");
            exchange.sendResponseHeaders(200, 0);
            // exchange.sendResponseHeaders(200, response.getBytes().length);
            OutputStream os = exchange.getResponseBody();
            os.write(response.getBytes());
            os.flush();
            os.close();
            // exchange.close();
        }

ParameterFilter
@SuppressWarnings("restriction")
public class ParameterFilter extends Filter {

    @Override
    public String description() {
        return "Parses the requested URI for parameters";
    }

    @Override
    public void doFilter(HttpExchange exchange, Chain chain)
        throws IOException {
        parseGetParameters(exchange);
        parsePostParameters(exchange);
        chain.doFilter(exchange);
    }

    private void parseGetParameters(HttpExchange exchange)
        throws UnsupportedEncodingException {

        Map<String, Object> parameters = new HashMap<String, Object>();
        URI requestedUri = exchange.getRequestURI();
        String query = requestedUri.getRawQuery();
        parseQuery(query, parameters);
        exchange.setAttribute("parameters", parameters);
    }

    private void parsePostParameters(HttpExchange exchange)
        throws IOException {

        if ("post".equalsIgnoreCase(exchange.getRequestMethod())) {
            @SuppressWarnings("unchecked")
            Map<String, Object> parameters =
                (Map<String, Object>)exchange.getAttribute("parameters");
            InputStreamReader isr =
                new InputStreamReader(exchange.getRequestBody(),"utf-8");
            BufferedReader br = new BufferedReader(isr);
            String query = br.readLine();
            parseQuery(query, parameters);
        }
    }

     private void parseQuery(String query, Map<String, Object> parameters)
         throws UnsupportedEncodingException {
         String encoding = System.getProperty("file.encoding");
         if (query != null) {
             String pairs[] = query.split("[&]");

             for (String pair : pairs) {
                 String param[] = pair.split("[=]");

                 String key = null;
                 String value = null;
                 if (param.length > 0) {
                     key = URLDecoder.decode(param[0],
                         encoding);
                 }

                 if (param.length > 1) {
                     value = URLDecoder.decode(param[1],
                         encoding);
                 }

                 if (parameters.containsKey(key)) {
                     Object obj = parameters.get(key);
                     if(obj instanceof List<?>) {
                         List<String> values = (List<String>)obj;
                         values.add(value);
                     } else if(obj instanceof String) {
                         List<String> values = new ArrayList<String>();
                         values.add((String)obj);
                         values.add(value);
                         parameters.put(key, values);
                     }
                 } else {
                     parameters.put(key, value);
                 }
             }
         }
    }

}


text:
Q: Downloading a file using the Dropbox Python library Environment: Windows 7, Python Tools for Visual Studio, Python 2.7, Python Package dropbox(6.9.0), Access Token from my Dropbox account
The following code is run:
    import dropbox
    access_token = '<token value here>'
    dbx = dropbox.Dropbox(access_token)

    with open("C:\Test.txt", "w") as f:
        metadata, res = dbx.files_download(path="/Test.txt")
        f.write(res.content)

It errors on the last line with the following:
  "No disassembly available"
I don't understand the error not being a Python developer.. the file is created on the local machine but nothing is downloaded into it from the dropbox file..
Any help would be greatly appreciated.. Thanks

A: python code for dropbox download with business API:
def dropbox_file_download(access_token,dropbox_file_path,local_folder_name):
try:
    dropbox_file_name = dropbox_file_path.split('/')[-1]
    dropbox_file_path = '/'.join(dropbox_file_path.split('/')[:-1])
    dbx = dropbox.DropboxTeam(access_token)
    # get the team member id for common user
    members = dbx.team_members_list()
    for i in range(0,len(members.members)):
        if members.members[i].profile.name.display_name == logged_user_name:
            member_id = members.members[i].profile.team_member_id
            break
    # connect to dropbox with member id
    dbx = dropbox.DropboxTeam(access_token).as_user(member_id)
    # list all the files from the folder
    result = dbx.files_list_folder(dropbox_file_path, recursive=False)
    #  download given file from dropbox
    for entry in result.entries:
        if isinstance(entry, dropbox.files.FileMetadata):
            if entry.name == dropbox_file_name:
                dbx.files_download_to_file(local_folder_name+entry.name, entry.path_lower)
                return True
    return False
except Exception as e:
    print(e)
    return False

A: import dropbox
access_token = '**********************'
dbx = dropbox.Dropbox(access_token)
f = open("ABC.txt","w")
metadata,res = dbx.files_download("abc.txt")     //dropbox file path
f.write(res.content)


text:
Q: How to migrate documents with metadata to another site collection Environment: SharePoint 2013
How to migrate documents with Metadata and Content types to another site collection?

A: If you can use PowerShell than there is one ready to use PowerShell commands mentioned in below mentioned article.
How to Copy SharePoint Documents Between Site Collections Using PowerShell

A: You can try third party tools as there are many tools available in the market. These tools are very good for content migration along with item permissions and other functionalities.
Some of them are:

*

*Metalogix

*Avepoint

*Sharegate (It is giving 15 days trial also)

*Metavis

A: You can also try LepideMigrator for Documents it works very well while migrate documents with Metadata and Content types to another site collection.
However, if you want to move the contents of a SharePoint Document Library or List and be able to preserve the item's metadata/property values at the same time you should use this method:
Create a blank destination List or Document Library. Don't have to worry about recreating custom fields and whatnot. The move process will do this for you.
Then go to the 'Site Content and Structure' page. You can access this site with either Site Actions > Site Settings or http://portal/_Layouts/sitemanager.aspx
After that navigate to your source List or Document Library and mark all the items that you would like to have moved. Then click on Actions > Move
You'll then be prompted with a pop-up that will let you navigate to your destination List or Document Library. After you find that, just press the OK button and you'll be good to go!
Also you can move files between document libraries programmatically using PowerShell or by using SharePoint designer, get in detailed here: http://www.sharepointdiary.com/2014/06/move-files-between-document-libraries-with-metdata-version-history.html
Hope this helps!


text:
Q: Intuition behind biclustering I am self-studying Kevin Murphy's book Machine learning - A probabilistic perspective and stumbled upon the following paragraph on biclustering. I understand the independence assumption - but am not yet seeing how this allows one to cluster. Can someone provide the intuition behind this?

A: If I understand your question, the link between independence and clustering is this. That data points within each cluster are generated IID from a distribution belonging to the cluster.
Suppose we had a simple model, where each data point is assigned a colour token (red or blue) and a shape token (square or circle) and its colour-shape combination determines which probability distribution it is drawn from:

*

*red squares are IID Normal(0,1)

*blue squares are IID Normal(10,1)

*red circles are IID Normal(0,3)

*blue circles are IID Normal(10,3)

But when you get the data you generally aren't told which data points received which tokens. Or even how many different shapes / colours were involved. So if each combination is equally likely the resulting histogram of draws would look something like:

The inference process tries to recover this. The inference process he suggests isn't clear to me from the level of description given.


text:
Q: Get number of rows of the sum of two columns and group these rows Sorry if the title is a little weird... but basically want I want to do is... I'll do an example first then I'll post the code I have
TableA has these columns

*

*d-id (INT)

*content (TEXT)

TableB has these columns

*

*d-id (INT)

*dif_content (TEXT)

and there's a TableC that has the column d-id.
Now I'm trying to  get the number of rows from content and dif_content and SUM these two columns while grouping them based on the d-id
TableC has main_content where I wanted the number of content and dif_content like so:

*

*a row(1)

*another row(5)

*another row again(3)

The number in the rows is how many rows of content and dif_content I have for that row.
This is the code I have right now
    $query = $this->db->query(
            'SELECT TableA.d-id , TableB.d-id , count(TableA.content) as num_content , count(TableB.dif_content) AS num_dif_content
             FROM TableA , TableB
             WHERE TableA.d-id = TableB.d-id
             SUM(num_content + num_dif_content) as content_total'

and just to for more detail, I'm using Codeigniter, so if you got a way to do this using Active Record, that would be nice.
This is the most complex query I have ever done. (for the few years that I've been programming)
I apologize if you can't understand what I'm trying to do, just comment if you need to know more, and I'll happily edit the post.

A: Humm, maybe I do not understant your question clearly. If I am right, this can be the query you need:
SELECT
    *, count_t1 + count_t2 as count_all
FROM
    (SELECT d_id, COUNT(content) as count_t1 FROM TableA GROUP BY d_id) t1
    LEFT JOIN
    (SELECT d_id, COUNT(dif_content) as count_t2 FROM TableB GROUP BY d_id) t2
    ON t1.d_id = t2.d_id;

You can preview using this sqlfiddle link


text:
Q: Rails Acts as Taggable On--Multiple Context Tag filter I am using acts-as-taggable-on to tag a Car model. I have three different tag contexts: Make, Color & Features. The first two Make & Color are predefined in an ENV variable and the last context is user generated(automatic windows, heated seats  etc.)
What I'd like to do is make it so that from my index page Cars can be filtered by multiple tags at a time. So for instance, I'd like a series of checkboxes at the top of the index page a separate set for each context where a user can check Hyundai & Red and the index of cars would populate with only red Hyundais. At the moment I have a route and some code in my Cars Controller that allows me to filter by one tag but I'd like to modify it to filter by whatever a user selects.
routes.rb
  get 'tags/:tags', to: 'cars#index', as: :tag

controller
def index
 if params[:keyword].present?
  @cars = Car.tagged_with(params[:keyword])
 else
  @cars = Car.all.order(:cached_weighted_score => :desc)
 end
end

A: The @selected_tag is tags that have been selected as parameter in index page.
Controller
def index
 if params[:keyword].present?
  @selected_tag = params[:keyword]
  @cars = Car.tagged_with(params[:keyword])
 else
  @cars = Car.all.order(:cached_weighted_score => :desc)
 end
end

View
It's only prototype view so you have to combine with your own code.
<% @tags.each do |tag| %>
    <div>
      <%= check_box_tag "keywords[]", tag.name, @selected_tag.present? ? @selected_tag.include?(tag.name) : '' %>
      <%= tag.name %>
    </div>
<% end %>

I hope I can give a general overview with my description.
For more information to  prepopulate data in checkbox


text:
Q: Javascript date in specified timezone I have a Unix timestamp and I'd like to create Date object in Europe/Paris TZ. Is there any simple way to do that (Opera, Chrome and FF supported)?
var stamp = 1470565421;
var date = new Date(stamp * 1000);
date = date.toParisTZ(); // convert TZ


text:
Q: what is the output and why the pointer in function does not affect the code? why the op is 20 ?? not 10 ? I think the op should be 10 but I don't know what happened? can you please explain it step by step
void fun(int *ptr)
{
    int q=10;
    ptr=&q;
}

int main()
{
    int r=20;
    int *p=&r;
    fun(p);
    printf("%d",*p);
    return 0;
}

A: *

*Values of function arguments are copies of what is passed from caller. Modifying in callee will not affect caller's local variables.

*Non-static local variables will vanish on exiting its scope. Therefore, you must not dereference pointers to them after that.

To obtain 10, your code should be:
#include <stdio.h>

void fun(int **ptr) /* pass a pointer to modify caller's local variable */
{static int q=10; /* add static to prevent it from vanishing */
*ptr=&q; /* dereference the pointer */
}

int main()
{int r=20;
int *p=&r;
fun(&p); /* pass the pointer */
printf("%d",*p);
return 0;
}

A: This is p and r (addresses are for instance based)
 ----------------      ----------------      ----------------
 | r         20 |      | p       1234 |      | q         10 |
 ----------------      ----------------      ----------------
 ^                     ^                     ^
 |_ Address of r       |_ Address of p       |_ Address of q
    = 1234                = 9876                = 12121

To fun(),
void fun(int *ptr) {
   int q = 10;
   ptr = &q;
}

you provide p as ptr (ie 1234), then set ptr to the address of q
fun:  ptr = 12121

then fun ends, and ptr dies with it, the memory didn't change for r
To change something you have to pass the address of that thing. Even if it is a pointer.
Giving the address of p to fun
fun( &p );

and changing fun() to accept a pointer to pointer
void fun(int **ptr) {  // <== pointer to pointer
   int q = 10;
   *ptr = &q;          // <== change r indirectly
}

here, ptr has the address of the pointer p, ie 9876
*ptr = &q; // changes the value of `r`

A: It´s basically because of two reasons:

*

*p in main() and ptr in fun() are two different pointers, and

*You pass p by value, not by reference.

At the function call:
fun(p);

you just pass p by value; Means it passes the address of r (what is actually the value of p) to ptr.
With ptr = &q; in fun() you just assign the address of q to ptr, but not to p.
Therefore, the output of dereferencing p at:
printf("%d",*p);

is of course 20, as p still point to r -> the value of p didn´t changed.

If you instead pass p by reference and declare ptr as pointer to pointer (**), plus qualify q with static qualifier (because function-local automatic variables will be destroyed after the function is executed once):
void fun(int **ptr)            // ptr is declared as pointer to pointer to int.
{
    static int q = 10;         // q is static -> It won´t get destroyed after returning from `fun()`.
    *ptr = &q;                 // dereferencing ptr to assign the address of q to p.
}

int main()
{
    int r = 20;
    int *p = &r;
    fun(&p);                   // Notice the `&` to gain the address of `p`, not `r`.
    printf("%d",*p);
    return 0;
}

The output would be 10 as we actually assigned the address of q to p.
As a side note: It is considered as bad programming style to refer to static-qualified function-local variables from a caller. I just showed this to you for the educational purpose and to show the difference to your provided code.
Try to assign an object pointed to in the caller, here f.e. r, by a passed pointer inside of the called function, here ptr, with the actual value of the object in the called function, here q.


text:
Q: C# WPF DataGrid Header Style Not Updating after On Click event handling I have a C# WPF project using a DataGrid to display a DataTable.
The DataTable was populated by reading in a CSV file (unknown number of headers) and populating it using the CSVHelper nuget package.
using (FileStream? stream = fileInfo.OpenRead())
{
    using (StreamReader? reader = new(stream))
    using (CsvReader? csv = new(reader, csvConfiguration))
    {
        using CsvDataReader? dr = new(csv);
        dataTable.Load(dr);
    }
}

I am displaying this DataTable using the following XAML setup.
<DataGrid x:Name="DataGrid"
            ItemsSource="{Binding Data, UpdateSourceTrigger=PropertyChanged}"
            HorizontalScrollBarVisibility="Visible"
            VerticalScrollBarVisibility="Visible"
            AlternatingRowBackground="AliceBlue"
            AlternationCount="2"
            CanUserSortColumns="False"
            AutoGeneratingColumn="Data_AutoGeneratingColumn"
            IsReadOnly="True"
            CanUserReorderColumns="False"
            Loaded="Data_Loaded"
          >

    <DataGrid.ColumnHeaderStyle>
        <Style BasedOn="{StaticResource {x:Type DataGridColumnHeader}}" TargetType="DataGridColumnHeader">
            <EventSetter Event="Click" Handler="DataGridColumnHeader_Click"/>
        </Style>
    </DataGrid.ColumnHeaderStyle>
</DataGrid>

I have added code to the Loaded Event for the DataGrid that cycles through all the DataGridColumn entries from DataGrid.Columns and will set their HeaderStyle depending on if they exist in a List<string> to either:

*

*SelectedHeaderStyle

*UnSelectedHeaderStyle

foreach (DataGridColumn column in grid.Columns)
{
    string headerText = column.Header.ToString();
    if (cSVConfigureContext.SelectedColumns.Contains(headerText))
    {
        column.HeaderStyle = selectedHeaderStyle;
    }
    else
    {
        column.HeaderStyle = notSelectedHeaderStyle;
    }
}

I am also handling the Click event for TargetType DataGridColumnHeader which will toggle the HeaderStyle between 1 and 2.
private void DataGridColumnHeader_Click(object sender, RoutedEventArgs e)
{
    var columnHeader = sender as DataGridColumnHeader;
    if (columnHeader != null)
    {
        string headerText = columnHeader.Content.ToString();
        if (cSVConfigureContext.SelectedColumns.Contains(headerText))
        {
           columnHeader.Style = notSelectedHeaderStyle;

           cSVConfigureContext.SelectedColumns.Remove(headerText);
        }
        else
        {
            columnHeader.Style = selectedHeaderStyle;
            cSVConfigureContext.SelectedColumns.Add(headerText);
        }
    }
    e.Handled = true;
}

This part all seems to work.
However, adding a "Reset Headers" button to return to a default set of selected columns, is where things are not working.
If I load the window with the DataGrid and press the Reset button (which runs the same code used in the Loaded event, it works fine. But if I first click on any header to switch its state, the style on the column header does not change. I see the change in the SelectedColumns list of strings but no visual update in the DataGrid until I close that window and re-open a new DataGrid. But I can still click headers to change their state.
I've spent a couple hours googling options for forcing a redraw of the column headers but so far no luck.
Any ideas why the Reset button doesn't work after a Click event?

A:
Any ideas why the Reset button doesn't work after a Click event?

The Style of the DataGridColumnHeader apparently overrides or take precedence over the HeaderStyle of the DataGrid.
Setting the Style property of all DataGridColumnHeader elements to null before setting the HeaderStyle property of the DataGrid will probably fix your issue.


text:
Q: Java - how to convert a XML string into an XML file? I am wanting to convert a xml string to a xml file. I am getting a xml string as an out put and I have the following code so far:
public static void stringToDom(String xmlSource)
    throws SAXException, ParserConfigurationException, IOException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new StringReader(xmlSource)));
        //return builder.parse(new InputSource(new StringReader(xmlSource)));
    }

However Im not too sure where I go from here. I am not creating the file anywhere, so how do I incorporate that into it?
I am passing my xml string into xmlSource.

A: If you just want to put the content of a String in a file, it doesn't really matter whether it is actually XML or not. You can skip the parsing (which is a relatively expensive operation) and just dump the String to file, like so:
public static void stringToDom(String xmlSource)
        throws IOException {
    java.io.FileWriter fw = new java.io.FileWriter("my-file.xml");
    fw.write(xmlSource);
    fw.close();
}

If you want to be on the safe side and circumvent encoding issues, as pointed by Joachim, you would need parsing however. Since its good practice to never trust your inputs, this might be the preferable way. It would look like this:
public static void stringToDom(String xmlSource)
        throws SAXException, ParserConfigurationException, IOException {
    // Parse the given input
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(xmlSource)));

    // Write the parsed document to an xml file
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);

    StreamResult result =  new StreamResult(new File("my-file.xml"));
    transformer.transform(source, result);
}

A: public static void stringToDom(String xmlSource) throws SAXException, ParserConfigurationException, IOException, TransformerException{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(xmlSource)));
    // Use a Transformer for output
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();

    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File("c:/temp/test.xml"));
    transformer.transform(source, result);
}

Source : http://docs.oracle.com/javaee/1.4/tutorial/doc/JAXPXSLT4.html

A: If your XML string is clean and ready to be written, why don't you copy it into a file with .xml at the end ?
With Java 1.7 :
Path pathXMLFile = Paths.get("C:/TEMP/TOTO.XML");
Files.write(pathXMLFile, stringXML.getBytes(), StandardOpenOption.WRITE, StandardOpenOption.APPEND, StandardOpenOption.CREATE);

Easy and quick :)

A: Just copy the contents of XML string to another file with extension .xml . You can use java.io for the same .


text:
Q: Different spark working directory for spill, sort, shuffle Does spark support multiple directories for each of its components that rely on disk?
e.g. spill, external sorting & storing shuffle files?
e.g. we want spill & external sorting to happen on fast SSD's whereas shuffle files can be stored on a EBS attached volume
Currently the only config i see is spark.local.dirs

A: As you can see in the documentation of the getConfiguredLocalDirs function, there are currently 5 ways of specifying local dirs to spill to (with java.io.tmpdir as a fallback):

*

*If running in YARN mode, this will return a directory chosen by YARN.

*If the SPARK_EXECUTOR_DIRS environment variable is set, this will return a directory from it.

*If the SPARK_LOCAL_DIRS environment variable is set, this will return a directory from it.

*If running in Mesos mode and SHUFFLE_SERVICE_ENABLED = false, this will return a directory chosen by Mesos.

*Otherwise, if the spark.local.dir is set, this will return a directory from it.

*Otherwise, this will return java.io.tmpdir.

This getConfiguredLocalDirs function is used in the getLocalDirs function, which is finally used to define what the local directories are. So there are different ways of specifying directories to spill to, but no ways to choose which types of spill go to which directories.
Finally, and this is an opinion, I'm not sure this would ever be interesting. Any type of disk spill results from a lack of memory from the same storage pool (the execution memory, see this page for more info), so prioritizing one type of spill w.r.t. the other will only add complexity for no gain.
Hope this helps!


text:
Q: Trouble with pagination while scraping NodeJS I am writing a little script that scrapes some information from public directories. I have it being saved to CSV but I'm having trouble with automating the pagination.
My Source is:
const rp = require('request-promise');
const request = ('request');
const otcsv = require('objects-to-csv');
const cheerio = require('cheerio');

// URL To scrape
const baseURL = 'xx';
const searchURL = 'xxx';

// scrape info
const getCompanies = async () => {
    // Pagination test

    for(let index = 0; index <= 2; index = index + 1) {
        const html = await request.get("xxx" + index);
        const $ = await cheerio.load(html);
        console.log("Loading Pages....");
        // console.log("At page number" + index);
        // end pagination test
        const htmls = await rp(baseURL + searchURL);
        const businessMap = cheerio('a.business-name', htmls).map(async (i, e) => {
            const link = baseURL + e.attribs.href;
            const innerHtml = await rp(link);
            const emailAddress = cheerio('a.email-business', innerHtml).prop('href');
            const name = e.children[0].data || cheerio('h1', innerHtml).text();
            const phone = cheerio('p.phone', innerHtml).text();

            return {
                emailAddress: emailAddress ? emailAddress.replace('mailto:', '') : '',
                //  link,
                name,
                phone,
            }

        }).get();
        return Promise.all(businessMap);
    }
};

// save to CSV
getCompanies()
  .then(result => {
    const transformed = new otcsv(result);
    return transformed.toDisk('./output.csv');
  })
  .then(() => console.log('SUCCESSFULLY COMPLETED THE WEB SCRAPING SAMPLE'));

The error that's appearing is request.get isn't a function.
EDIT
Second part to this question is located here: Nodejs Scraper isn't moving to next page(s)

A: request.get should be rp.get, since request module does not return a Promise.
In any case you're getting the error, because you're not requireing request, but just assigning a string to request variable:
const request = ('request');

Change it to:
const request = require('request');

Since you're working with Promises, I recommend to just require, request-promise
const request = require('request-promise');


text:
Q: I Cannot Install Pillow (Using python 2.7.10 on macOS 10.12.6) So, I am really struggling with this one and I have searched everywhere including Stack Overflow for the last 3 hours or so. My problem is I cannot install Pillow using pip (or any other installation package). Here is what I have done so far:
I have managed to install pip itself from the terminal. I used the sudo easy_install pip. This was also problematic but I am sure it was installed. When I run pip --version in the terminal, I get pip 10.0.1 from /Users/revogatustesha/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pip (python 2.7), so pip is installed for sure.
Now I cannot install Pillow. I have tried lots of commands but no luck. I have done easy_install Pillow in the command line which I think worked, but when I do from Pillow import image (and import image), it says there is no module named image. I have also done sudo pip install Pillow in the terminal and never worked.
I have also tried using homebrew to install it. I installed homebrew, ran the line brew install libtiff libjpeg webp little-cms2 and then brew install freetype harfbuzz fribidi. I don't know what to do from here.
Yeah, so this is where I am. Any help will be very appreciated. Thanks!


text:
Q: Is there a way to log the queries executed by a Oracle UCP? I have a Oracle UCP connection Pool responsible for executing queries from the  Java application. I want to see all the  queries in the logs that this UCP takes care of.
I followed this guide https://docs.oracle.com/cd/E11882_01/java.112/e12265/dgn_conpool.htm#CIHIGBIJ to use the property of 'oracle.ucp.level' to set the log level to FINEST.
I couldnt see the sql queries in logs. I could see all other information like getting a connection, DB URL etc in the logs but I couldnt see the SELECT query that was executed by this connection pool.
Is there a way we could see the SELECT, INSERT and UPDATE queries executed by the Oracle UCP ?
If not the whole query , Atleast can we see whether it is a SELECT or INSERT or UPDATE ?


text:
Q: How to rename a variable which respects the name scope? Given x, y are tensors, I know I can do
with tf.name_scope("abc"):
    z = tf.add(x, y, name="z")

So that z is named "abc/z".
I am wondering if there exists a function f which assign the name directly in the following case:
with tf.name_scope("abc"):
    z = x + y
    f(z, name="z")

The stupid f I am using now is z = tf.add(0, z, name="z")

A: If you want to "rename" an op, there is no way to do that directly, because a tf.Operation (or tf.Tensor) is immutable once it has been created. The typical way to rename an op is therefore to use tf.identity(), which has almost no runtime cost:
with tf.name_scope("abc"):
    z = x + y
    z = tf.identity(z, name="z")

Note however that the recommended way to structure your name scope is to assign the name of the scope itself to the "output" from the scope (if there is a single output op):
with tf.name_scope("abc") as scope:
    # z will get the name "abc". x and y will have names in "abc/..." if they
    # are converted to tensors.
    z = tf.add(x, y, name=scope)

This is how the TensorFlow libraries are structured, and it tends to give the best visualization in TensorBoard.

A: It seems it works also without tf.name_scope only with z = tf.identity(z, name="z_name"). If you run additionally z = tf.identity(z, name="z_name_new") then you can access the same tensor using both names: tf.get_default_graph().get_tensor_by_name("z_name:0") or tf.get_default_graph().get_tensor_by_name("z_name_new:0")


text:
Q: ReactJS: How to change value of specific field in an object array? constructor (props) {
    super(props)
    this.state = { items: this.props.items }
    // items props is: [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}]
}

onClick () {
    const myArray = this.state.items
    const ids = ['45', '73']
    ids.forEach((id, index) => {
        myArray.find(x => x.id === id).foo = index
    })
}

I need to change foo value to index value. So the result should look like
myArray = [{'id':'73','foo': 1},{'id':'45','foo': 0}]

I think with this, I do get the current value, but the syntax is wrong to change its value:
myArray.find(x => x.id === '45').foo = 'new'

I do get the error Uncaught TypeError: Cannot assign to read only property 'foo' of object '#<Object>'

A: You can use map to change the property you want:

const myArray = [{ id: '73', foo: 'bar' }, { id: '45', foo: 'new' }, { id: '46', foo: 'do not change me' }]

const ids = ['45', '73']

const newArr = myArray.map(item => {
  if (ids.indexOf(item.id) !== -1) {
    return {
      ...item,
      foo: 'newFooValue'
    }
  }

  return item
})

console.log(newArr)

It's also important to note that change object properties directly (such as myArray.find(x => x.id === '45').foo) is not a good practice though.
In case itemsis in you state, you can simple change it by:
this.setState(prevState => ({
   items: prevState.items.map(/* same code as in the snippet above */),
}))


text:
Q: Complex Analysis Sketch the image under the function $w = e^z$ of each of the following subsets of the z plane: (a) $\{z \in \Bbb C: Re (z) = -2\}$
(b) $\{z \in \Bbb C: Im (z) = 5\pi\}$
(c) $\{z = x + iy : 0 \le x \le 1, 0 \le y \le \pi\}$
(d) $\{z = x + iy : -2 \le x \le -1, -\pi \le y \le 4\pi\}$
(e) $\{z : Im z \ge 0\}$
I know that (a) is mapped onto a circle of radius $\frac{1}{e^2}$, and b is mapped onto a ray from the origin with argument of $\pi$ (or 5$\pi$)
For the rest of the questions, I am unsure of what to do. Any help appreciated, and thanks in advance!

A: a)$z = -2 + iy\\
w = e^z = e^{-2} e^{iy} = e^{-2}(\cos y + i\sin y)$
$(\cos y + i\sin y)$ desribes a circle
b) $z = x + 5\pi i\\
w = (e^x)e^{5\pi i} = -e^x$
The image of $w$  is the negative real numbers
c)
$x = e^x(\cos y + i\sin y)$
and I will let you guess what that maps to as the limits of $x,y$ change


text:
Q: Complexity of rational $\mathrm{GL}_{n(r)}$-modules Let $k$ be an algebraically closed field of characteristic $p>0$, and let $G=\mathrm{GL}_n(k)$ for some natural number $n$.  For any integer $r\ge 1$, let $G_{(r)}$ denote the $r$th Frobenius kernel of $G$, that is, the kernel of the Frobenius endomorphism which sends each entry of a matrix to its $p^r$th power.  The coordinate algebra of $G_{(r)}$ is
$$k[G_{(r)}]=k[x_{ij},t]/(\det(x_{ij})t-1,x_{ij}^{p^r}-\delta_{ij})$$
Let $M$ be a finitely generated rational $G_{(r)}$-module, and let $\ldots P_2\to P_1\to P_0\to M$ be a minimal projective resolution.  The complexity of $M$, denoted $c(M)$, is the smallest integer $s$ such that there is a constant $\kappa>0$ with $\dim_kP_m\le\kappa m^{s-1}$ for all $m\ge 0$.
I'm interested in $G_{(r)}$-modules of large complexity.  More specifically, in terms of $r$ and $n$, do we know anything about the value of
$$\max_{M}c(M)$$
where the maximum is taken over finitely generated rational $G_{(r)}$-modules?  I'd be happy with a nontrivial lower bound if one is known.

A: I don't recall seeing an explicit answer to your question in the literature, but the basic outline starts with the (restricted) Lie algebra or first Frobenius kernel: here an upper bound on the complexity of any finite dimensional module is given by the dimension of the "restricted nullcone", which for $p$ at least the Coxeter number is the full nilpotent variety in the Lie algebra.
For higher Frobenius kernels $G_r$ (a less cumbersome notation than yours), where
$G$ can be any reductive group, the study of complexity seems to be much less direct than for $G_1$.   But you might get some help from Theorem 2.4 in an old paper by Dan Nakano which is freely available online here.    This kind of result suggests strongly that for finite dimensional $G_r$-modules the best possible upper bound should be something like $r$ times the dimension of the nilpotent variety.    For a general linear group $\mathrm{GL}_n$, the latter dimension would be $n^2-n$.
I don't have time at the moment to look further into the recent literature (which extends to work on related quantum groups and Lusztig's analogue of Frobenius kernels), but there have been quite a few relevant papers ranging from the early work of Jantzen and Friedlander-Parshall to work of Carlson-Lin-Nakano, Drupieski, etc.   Roughly speaking, complexity 0 corresponds to projective modules whereas the largest complexity for a simple module tends to occur for the trivial module.   But along the way a lot of cohomology is involved.


text:
Q: Inheritance in the Room Persistence Library TL;DR: How can I store and retrieve objects of type ClassA and ClassB which both inherit from ClassP in the same "list", using the Room Persistence Library?
In other words, How should I store a List<? extends BaseAnimal> in my Room DB?

I have Animals, for the purpose of this question.
public abstract class BaseAnimal {
    @PrimaryKey(autoGenerate = true)
    private long id;

    public BaseAnimal(long id){this.id = id;}

    public abstract void func(int param);

    public long getId() {
        return id;
    }
}

An animal has an id and implements some function func. There will likely be many kinds of animals. To start with, I have an Elephant which additionally has a trunkLength property, and a Giraffe which additionally has a neckLength property.
public class Giraffe extends BaseAnimal {
    public long neckLength;

    public Giraffe(long id) {
        super(id);
    }

    @Override
    public void func(int param) {

    }
}

I have several instances of Elephant and Giraffe in my application. How can I, using the Android Room Persistence Library, store and retrieve them sorted by BaseAnimal.id?

Expectations
At first, I hoped that it would be as simple as this:

*

*Annotate the BaseAnimal class with @Entity(tableName = "base_animal_table")

*Annotate my extension of the RoomDatabase with
    @Database(entities = {BaseAnimal.class }, version = 1)

*Add a function for inserting to the Data Access Object
@Insert
    void insertAnimal(BaseAnimal animal);

*Add a method to the Repository
public void insertAnimal(BaseAnimal animal){
        new insertAnimalAsyncTask(recipeDAO).execute(animal);
    }

private static class insertAnimalAsyncTask extends AsyncTask<BaseAnimal, Void, Void> {

    private RecipeDAO mAsyncTaskDao;

    insertAnimalAsyncTask(RecipeDAO dao) {
        mAsyncTaskDao = dao;
    }

    @Override
    protected Void doInBackground(final BaseAnimal... params) {
        mAsyncTaskDao.insertAnimal(params[0]);
        return null;
    }
}

I expected that this would lead to room generating a table named base_animal_table which would look somewhat like this (with some sample data):
| id | ElephantTrunkLength | GiraffeNeckLength |
| 0  | NULL                | 12                |
| 12 | 1337                | NULL              |

I also expected that I could retrieve the data from this table something like this:
// this is in the DAO
@Query("SELECT * from `base_animal_table` ORDER BY id ASC")
LiveData<List<BaseAnimal>> getAllAnimals();

and then get a list that contains both, entities of type Elephant with their trunkLength property set, and entities of type Giraffe with their neckLength set.
This seems not to be straightforward. How can I implement this?

One approach I see is the following, but I am not sure whether it is the best way. And I am also starting to doubt that Room makes this any easier than using plain SQLite. I tried to produce a working example for this approach with room, but there are still some unresolved issues.
One Approach
Create a table base_animals which only contains the id and other base animal attributes, along with an indicator of their child type:
// base_animals
| id | animalType |
| 0  | "GIRAFFE"  |
| 12 | "ELEPHANT" |

Use this table to keep a list of all animals and their ids. Create a table elephants and a table giraffes with the id and their specific properties (trunkLength and neckLength, respectively).
Then we can store an animal in the DB by creating an entry in both the base table and the child table.
To retrieve a specific animal by id, we can now find the animalType in the base_animals table and with that decide in which child table - elephants or giraffes we need to search.
The problem I have with this approach is that it requires that I have to write quite some code and I have to update it whenever I create a new animal entity - e.g. a Dolphin.
So, my question is: How should I store a List<? extends BaseAnimal> in my Room DB?
I would prefer it if I could leave BaseAnimal an abstract class.

A: I'm not sure that using inheritance is a good idea here.
I would suggest using composition instead.
Keep a class named Animal (not BaseAnimal).
The animal should have a type just like you suggested.
Another table (AnimalProperties) would hold the properties of each animal.
It will have a foreign key to the Animals table and a property name and property value.
Now...
If this is all that you need, meaning a class with type and properties then you're all set.
But if you also need the class to behave differently like implementing a fly() method for a bird and run() a dog then you should consider using Composition to add behaviors to the Animal.
If you are not familiar with Composition have a look here for a simple explanation.


text:
Q: session is lost when i use window.open in IE9 I'm using window.open to open a new window and this is my code sample
var path = '<%=request.getContextPath()%>';
var page = path+"/jsp/displayCompareResult.jsp";
window.open(page, 'displayCompareResult','');

This works absolutely fine in IE8, but in IE9 window.open gets created in new session.
My application runs only on IE browser.

A: It happened in my chrome also.I solved this by adding
<link rel="shortcut icon" href="../../img/favicon.ico">

A: If "new session" means that IE is opening your window to the new tab, your have to change this setting. It is found in IE Settings General-tab (the leftmost tab) and above the last field there is a field called Tabs (or sth). Click Settings-button in this field, and in opened window you can find a field called Pop-up windows. Pick "Open pop-up windows in new window" and save settings.


text:
Q: How do I enter data into a form input in an iframe using cypress? I have been trying to test a stripe checkout form using cypress.io
If anyone has managed to get this to work please let me know. I found a thread on the matter here https://github.com/cypress-io/cypress/issues/136 and based on this I came up with:
   cy.get('iframe.stripe_checkout_app')
      .wait(10000)
      .then($iframe => {
        const iframe = $iframe.contents()
        const myInput0 = iframe.find('input:eq(0)')
        const myInput1 = iframe.find('input:eq(1)')
        const myInput2 = iframe.find('input:eq(2)')
        const myButton = iframe.find('button')

        cy
          .wrap(myInput0)
          .invoke('val', 4000056655665556)
          .trigger('change')
        cy
          .wrap(myInput1)
          .invoke('val', 112019)
          .trigger('change')

        cy
          .wrap(myInput2)
          .invoke('val', 424)
          .trigger('change')

        cy.wrap(myButton).click({ force: true })
      })

But the problem is that the stripe form still does not register the input values. Here is a little gif of what happens http://www.giphy.com/gifs/xT0xeEZ8CmCTVMwOU8. Basically, the form does not register the change input trigger.
Does anyone know how to enter data into a form in an iframe using cypress?

A: The '.Input .InputElement' selector from @user8888 did not work for me.  Instead, I'm accessing each input by it's name attribute.
        cy.get(".__PrivateStripeElement > iframe").then(($element) => {
                const $body = $element.contents().find("body");

                let stripe = cy.wrap($body);
                stripe
                    .find('[name="cardnumber"]')
                    .click()
                    .type(MOCK_CC_NUMBER);

                stripe = cy.wrap($body);
                stripe
                    .find('[name="exp-date"]')
                    .click()
                    .type(MOCK_CC_EXP);

                stripe = cy.wrap($body);
                stripe
                    .find('[name="cvc"]')
                    .click()
                    .type(MOCK_CC_CVC);

                stripe = cy.wrap($body);
                stripe
                    .find('[name="postal"]')
                    .click()
                    .type(MOCK_CC_ZIP);
            });

A: I just spent way too long trying to get this working, none of the answer I found would work completely.  I added my solution to the cypress github issue for iframes (there is a bit more context there), also putting it here to hopefully save others some time.
I stole the onIframeReady() function from this stackoverflow answer.
Basically what it is doing is checking if the iframe has loaded, if the iframe has loaded it will do $iframe.contents().find("body"); to switch to the contents. If it has not loaded it will hook that same code into the load event so it will run as soon as the iframe loads.
This is written as a custom command to allow use of cypress chaining after switching to the iframe, so put the following into your support/commands.js file:
Cypress.Commands.add("iframe", { prevSubject: "element" }, $iframe => {
  Cypress.log({
    name: "iframe",
    consoleProps() {
      return {
        iframe: $iframe,
      };
    },
  });

  return new Cypress.Promise(resolve => {
    onIframeReady(
      $iframe,
      () => {
        resolve($iframe.contents().find("body"));
      },
      () => {
        $iframe.on("load", () => {
          resolve($iframe.contents().find("body"));
        });
      }
    );
  });
});

function onIframeReady($iframe, successFn, errorFn) {
  try {
    const iCon = $iframe.first()[0].contentWindow,
      bl = "about:blank",
      compl = "complete";
    const callCallback = () => {
      try {
        const $con = $iframe.contents();
        if ($con.length === 0) {
          // https://git.io/vV8yU
          throw new Error("iframe inaccessible");
        }
        successFn($con);
      } catch (e) {
        // accessing contents failed
        errorFn();
      }
    };

    const observeOnload = () => {
      $iframe.on("load.jqueryMark", () => {
        try {
          const src = $iframe.attr("src").trim(),
            href = iCon.location.href;
          if (href !== bl || src === bl || src === "") {
            $iframe.off("load.jqueryMark");
            callCallback();
          }
        } catch (e) {
          errorFn();
        }
      });
    };
    if (iCon.document.readyState === compl) {
      const src = $iframe.attr("src").trim(),
        href = iCon.location.href;
      if (href === bl && src !== bl && src !== "") {
        observeOnload();
      } else {
        callCallback();
      }
    } else {
      observeOnload();
    }
  } catch (e) {
    // accessing contentWindow failed
    errorFn();
  }
}

Then you would call this like so from your tests:
cy.get('iframe.stripe_checkout_app')
  .iframe()
  .find('input:eq(0)')
  .type("4000056655665556")

You can .alias() after calling .iframe() to refer to it for the rest of your inputs or .get() the iframe several times, I'll leave that up to you to figure out.

A: The solution in this link is working for me. Basically, the steps are as below:

*

*Set chromeWebSecurity to false in cypress.json

*Add cypress command to get the iframe in command.js

*Use the iframe command in the script

A: The following snippet should work for you. I copied/pasted it from @izaacdb's post in this thread.
cy.wait(5000)
cy.get('.__PrivateStripeElement > iframe').then($element => {

  const $body = $element.contents().find('body')

  let stripe = cy.wrap($body)
  stripe.find('.Input .InputElement').eq(0).click().type('4242424242424242')
  stripe = cy.wrap($body)
  stripe.find('.Input .InputElement').eq(1).click().type('4242')
  stripe = cy.wrap($body)
  stripe.find('.Input .InputElement').eq(2).click().type('424')
})

However, in order for the above to work, you need to do the following (copied/pasted from @nerdmax's post from the same thread linked above):

Big Thanks to @Vedelopment @brian-mann !
I tested with react-stripe-checkout component and it works.
Just add some solution details so it may save others some time.
chromeWebSecurity disable:
// cypress.json

{
  "chromeWebSecurity": false
}

--disable-site-isolation-trials:
Check: https://docs.cypress.io/api/plugins/browser-launch-api.html#
  AND #1951
// /plugins/index.js

module.exports = (on, config) => {
  on("before:browser:launch", (browser = {}, args) => {
    if (browser.name === "chrome") {
      args.push("--disable-site-isolation-trials");
      return args;
    }
  });
};

A: The iframe workflow is still pretty clunky (until this feature is implemented). For now, you can try forcing pretty much every DOM interaction:
cy.visit("https://jsfiddle.net/1w9jpnxo/1/");
cy.get("iframe").then( $iframe => {

    const $doc = $iframe.contents();
    cy.wrap( $doc.find("#input") ).type( "test", { force: true });
    cy.wrap( $doc.find("#submit") ).click({ force: true });
});

A: This doesn't directly answer your question, but after several days of trying to wrangle manipulating elements in the iframe using jQuery, re-implementing a bunch of stuff that Cypress already did, I smacked myself and started doing this:
Cypress.Commands.add('openiframe', () => {
    return cy.get("iframe[src^='/']").then(iframe => {
        cy.visit(Cypress.$(iframe).attr('src'), { timeout: Cypress.config("pageLoadTimeout") });
    });
});

That allowed me to just cy.openiframe().then(() => {}); and proceed as if the site I was testing didn't put a bunch of functionality in an iframe in the first place.
The downside is that you've got to finish up what you're doing not in the iframe before doing anything in the iframe, so you can't go back and forth too easily.
It might not work for your use case, but if/when it does, it's the easiest workaround I've found.

A: in order to avoid using:
cy.wait(5000)

I found a better way to do it following the instructions cypress provides in this tutorial about how to work with iframes
   cy.get('iframe[name="__privateStripeFrame5"]')
    .its("0.contentDocument.body")
    .should("not.be.empty")
    .then((body) => {
      cy.wrap(body)
        .find("[name=cardnumber]")
        .type("6011111111111117", { force: true });
   });

A: I released a plugin yesterday that adds a simple Cypress API for filling in Stripe Elements:
cy.fillElementsInput('cardNumber', '4242424242424242');

This plugin avoids cy.wait() calls, peeking into <iframe>s manually, and other awkward selectors.

A: For me, this iframe has a random behavior, so I used some of the code, but finally tried with force: true because the last value was failing. The name was not valid for me, I had to use a different attribute which is more specific.
    cy.get(".__PrivateStripeElement > iframe").then(($element) => {
        const $body = $element.contents().find("body");

    cy.wrap($body)
        .find('[data-elements-stable-field-name="cardNumber"]')
        .click()
        .type('value')

    cy.wrap($body)
        .find('[data-elements-stable-field-name="cardExpiry"]')
        .click()
        .type('value')

    cy.wrap($body)
        .find('[data-elements-stable-field-name="cardCvc"]')
        .click()
        .type('value', { force: true });

A: The other answers didn't work for me because the name attribute has changed. Here's what I used:
cy.get('.__PrivateStripeElement > iframe').then(($element) => {
      const $body = $element.contents().find('body')

      let stripe = cy.wrap($body)
      stripe.find('input[name="number"]').click().type('4242424242424242')
      stripe = cy.wrap($body)
      stripe.find('input[name="expiry"]').click().type('4242')

      stripe = cy.wrap($body)
      stripe.find('input[name="cvc"]').click().type('424')

      stripe = cy.wrap($body)
      stripe.find('input[name="postalCode"]').click().type('92222')
})


text:
Q: function not defined inside a function wrapper that is sent over an onClick callback ReactJS there is this thread that I tought it was my solution. Basically what I want to do is to send multiple function inside one that is sent  over an onClick callback. The console returns an error saying that my functions inside wrapper function are not defined.
This is my code:
function1(){
 this.setState({
      ...
 });
}
function2(){
 ...
}
mainFunction(e){
 function1();
 function2();
}

<Component2 clickHandler={this.mainFunction}/>

I also bind the functions in my constructor method just in case. When I fire the event clicking in my second component i get return that function1 is not defined. Any ideas?


text:
Q: Pandas DataFrame Drop 0.000000 values after .sum() How can you drop rows with 0.000000 values from a dataframe?
For instance:
PassengerId    0.000000
Survived       0.000000
Pclass         0.000000
Name           0.000000
Sex            0.000000
Age            0.198653
SibSp          0.000000
Parch          0.000000
Ticket         0.000000
Fare           0.000000
Cabin          0.771044
Embarked       0.002245

How to drop all columns with 0.000000?

A: Try
out = df.loc[:,df.sum().ne(0)]

Then try with numpy isclose
out = df.loc[:,np.isclose(df.sum(),0)]

A: It is not quite clear what the result you exactly want, if you want to have the only columns from the dataframe for which sum is not 0, then @BENY's solution is what you are looking for.
If you want to filter out from the result of sum that you have in above example in the quesiton, then you can try this:
>>> s = df.sum() # The sum that you have in above example
>>> s[s.ne(0)]

Age         0.198653
Cabin       0.771044
Embarked    0.002245
Name: 1, dtype: float64


text:
Q: Using a method as data inside the app parent So I'm still learning Vue.js and I got my list working well and I have one question. I will explain what I'm trying to do below as best as possible and I wanted to see if someone could help me with my issue.

So here is the component that I have on the HTML side:
<favorites-edit-component
    v-for="(favorite, index) in favorites"
    v-bind:index="index"
    v-bind:name="favorite.name"
    v-bind:key="favorite.id"
    v-on:remove="favorites.splice(index, 1)"
></favorites-edit-component>

Here is the vue.js portion that I have:
Vue.component('favorites-edit-component', {
   template: `

      <button class="button is-fullwidth is-danger is-outlined mb-0">
        {{ name }}

      </button>

   `,
    props: ['name'],
});

new Vue({
    el: '#favorites-modal-edit',
    data: {
        new_favorite_input: '',
        favorites: [
            {
                id: 1,
                name: 'Horse',
                url: 'www.example.com',
            },
            {
                id: 2,
                name: 'Sheep',
                url: 'www.example2.com',
            },
            {
                id: 3,
                name: 'Octopus',
                url: 'www.example2.com',
            },
            {
                id: 4,
                name: 'Deer',
                url: 'www.example2.com',
            },
            {
                id: 5,
                name: 'Hamster',
                url: 'www.example2.com',
            },
        ],
        next_favorite_id: 6,
    },
    methods: {
        add_new_favorite: function() {
            this.favorites.push({
                id: this.next_favorite_id++,
                name: this.new_favorite_input
            })
            this.new_favorite_input = ''
        },
        get_favorite_menu_items: function() {
            wp.api.loadPromise.done(function () {
                const menus = wp.api.collections.Posts.extend({
                    url: wpApiSettings.root + 'menus/v1/locations/favorites_launcher',
                })
                const Menus = new menus();
                Menus.fetch().then(posts => {
                    console.log(posts.items);
                    return posts.items;
                });
            })
        }
    }
});

So as you can see, I have the data: { favorites: [{}] } called inside the vue app and I get this console.log:

Now I built a method called get_favorite_menu_item and this is the return posts.items output inside console.log:

Problem: I don't want to have a manual array of items, I want to be able to pull in the method output and structure that - How would I take a approach on pulling the items?
Could I call something like this:
favorites: this.get_favorite_menu_items?
Here is a JFiddle with all the items: https://jsfiddle.net/5opygkxw/
All help will be appreciated on how to pull in the data.

A: First I will init favorites to empty array.
then on get_favorite_menu_items() after I will init data from post.item to favorites.
on created() hooks i will call get_favorite_menu_items() to fetch the data when the view is created.
new Vue({
    el: '#favorites-modal-edit',
    data: {
        new_favorite_input: '',
        favorites: [],
        next_favorite_id: 6,
    },
    methods: {
        add_new_favorite: function() {
            this.favorites.push({
                id: this.next_favorite_id++,
                name: this.new_favorite_input
            })
            this.new_favorite_input = ''
        },
        get_favorite_menu_items: function() {
            wp.api.loadPromise.done(function () {
                const menus = wp.api.collections.Posts.extend({
                    url: wpApiSettings.root + 'menus/v1/locations/favorites_launcher',
                })
                const Menus = new menus();
                Menus.fetch().then(posts => {
                    console.log(posts.items);
                    // need map key also
                    this.favorites = posts.items;
                });
            })
        }
    },
    created () {
       // fetch the data when the view is created
       this.get_favorite_menu_items();
    },
});


text:
Q: How well does an Nvidia 9800 work with Unity? Hi I looked at upgrading to 12.10 today, and got the warning that my graphics hardware may not be fully supported.
I'm using an HP Pavilion dv5000 laptop with a Nvidia 9800 graphics card.
Has anyone upgraded despite the warning and had un-fixable problems, or does anyone have any tips for getting round this problem, perhaps using unity 2d, or some idea about the timescale this is likely to be fixed on.

A: I received the same message trying to upgrade from 12.04 to 12.10 on a Vizio ultrabook. But running 12.10 from a dvd (which I'm doing right now) seems to work fine. Have you tried running from a dvd or usb drive? I'm assuming if 12.10 runs fine from a dvd or usb drive, it should be fine after being installed.
This is the only info I have on the graphics controller in the Vizio:
VGA compatible controller: Intel Corporation 3rd Gen Core processor Graphics Controller (rev 09)


text:
Q: Existence of a subgroup of order $pq$
Let $G$ be a finite group and assume $G$ has a single $p$-Sylow subgroup. Let $q\neq p$ be prime for which $q$ divides the order of $G$. Show that there exists a subgroup of $G$ with order $pq$.

Following are some of my attempts at solving this:
if $P<G$ is a $p$-Sylow group then $P\vartriangleleft G$ from Sylow's theorems.
From Cauchy's theorem we have a $Q<G$ cyclic such that $\mid{Q}\mid = q$
Because $P$ is normal in $G$ I know that $PQ < G$, let's assume $\mid{PQ}\mid = p^{k}q$ for $k\geq 1$
My attempt mainly consisted from this point on taking a group of order $p$ from $PQ$, say $P'$ and showing that $P'Q<PQ$. I know that $\mid{P'Q}\mid = pq$ so that would conclude my proof (if it were the right approach, that is).
This approach didn't work for me because I can't show that if $h\in Q$ and $g \in P'$ then $gh = h'g' \in P'Q$.
I do know that $gh = hg' \in QP$ because $P$ is also normal in $QP=PQ$.
Am I even in the right direction?
I am not interested in a full proof but merely in a (good solid) hint.
Many thanks.

A: You can't prove that there is a subgroup of order $pq$ in general, with just these hypotheses. For example, consider the case when $G$ is the alternating group $A_4$ of order $12,$ with $p=2,q = 3.$ Then $G$ has a single Sylow $2$-subgroup, but $G$ has no subgroup of order $6.$ Similar examples can be constructed for every choice of primes $p$ and $q$ such that $q$ does not divide $p-1.$

A: You were pretty much on the right track. Except that you need to notice the following:
To Prove that $PQ$ is a subgroup of $G$:
Given $P\trianglelefteq G$ and $Q<G$, We claim that $PQ=\{pq|p\in P; q \in Q\}$ is a subgroup of $G$.
There are two ways of looking at this: One way of doing is to prove that $PQ$ is a subgroup if and only if $PQ=QP$.(Try Proving this and then show that this is true here!) Another way is to show through direct methods, which I'll show here:

*

*Note that identity of $G$ exists here in $PQ$.

*If $pq, p_1q_1 \in PQ$, $pq(p_1q_1)^{-1}=pqq_1^{-1}p^{-1}=p\cdot qq_1^{-1}p^{-1}(qq_1^{-1})^{-1}\cdot qq_1^{-1}$ Note that the term sandwiched between the dots is an element in $P$, because, $P$ is a normal subgroup in G. So, this completes the proof, thanks to the subgroup Test.

If $P$ and $Q$ are subgroups of $G$, then the subgroup $PQ$ is of cardinality, $$|PQ|=\dfrac{|P|\cdot |Q|}{|P \cap Q|}$$
Since $P$ and $Q$ are groups with co-prime orders, they intersect trivially.
(Does this not require a proof? It certainly does! Consider an element $x$ from the intersection $P \cap Q$, Since $P\cap Q$ is both a subgroup of $P$ and $Q$, by Lagrange's Theorem, $o(x)|p$ and $o(x)|q$ This forces that $o(x)=1$ which necessarily means that $x$ is the trivial element.)
So, $|P \cap Q|=1$ and hence $|PQ|=|P|\cdot |Q|=pq$.
This completes the proof!
I would like to point a few glaring errors in your way of proving.

My attempt mainly consisted from this point on taking a group of order $p$ from $PQ$, say $P'$ and showing that $P'Q<PQ$. I know that $∣P'Q∣=pq$ so that would conclude my proof (if it were the right approach, that is).

How will this prove that $k=1$. Are there not groups of order $p^2q$ with subgroups of order $pq$?

This approach didn't work for me because I can't show that if $h\in Q$ and $g\in P'$ then $gh=h'g'\in P'Q$. I do know that $gh=hg'\in QP$ because $P$ is also normal in $QP=PQ$.

Where are all these elements $(\cdot)'$ coming from? It's hard to comprehend that! From the sentence that, $gh=hg'\in QP$, I believe $g'=h^{-1}gh$.
The rest is fine!

A: so first off, what makes you assume that the order of your q-sylow subgroup is of order q? Also you have that your sylow subgroups must have a non-trivial center.  This would be an abelian p-subgroup of P, so it must have a subgroup of order p.  The same goes for Q. Not sure if that leads to a proof, but it should at least be on the right track.  You seem to be on the right track though, looking at product of subgroups.  As for the last comment, thats definitely an important fact but does not constitute a proof, as you have not found subgroups of order p and q.


text:
Q: Failure to authenticate SSH keys I'm in the process of setting up a virtual server via Amazon AWS.  I followed their tutorial regarding setting up a Linux based virtual server on OS X.  Everything goes well until I get to the .ssh pair key file.  I download AWS's key as a .pem file.  It saves as a .pem.txt file.  Which seems odd from what I'm reading.  So, I duplicate and change the extension to .pem only.
   Then I go to copy the file from downloads to the ~/.ssh folder and get no problems using cp ~/Downloads/FileName.pem ~/.ssh.  When I try to use chmod 400 to adjust the security parameters of the folder it returns "Not a directory".  When I try to authenticate it fails.  I suspect because it has something to do with the chmod 400 code line, but I'm not certain.  I also wanted to verify to make sure the file copied into the .ssh folder, but all of the suggestions online about unhiding the hidden folders on a Mac were a no-go.
   It is a Linux set up so the user name is the one listed in the tutorial (I already researched this problem).  I double check to see if there was a file .ssh and there seems to be.  When I type ssh in the terminal I do get feedback, so I'm assuming there is a file there.

A: Create an ssh folder in your home folder, if one is not present. Then copy the PEM file to that folder. Then change permissions of the PEM file to protect it. Something like this:
mkdir -p ~/.ssh
cp fred.pem.txt ~/.ssh/fred.pem
chmod 400 ~/.ssh/fred.pem


text:
Q: Why is it valid to not fully expand the inequality in the convergence in probability definition? Let $X_1,\ldots,X_n$ be iid random variables with common pdf
$$f(x) = e^{−(x−\theta)}\quad,  x > \theta ,\, − \infty < \theta < \infty\,;
\quad 0 \quad\text{elsewhere}$$
Let $Y_n = \min({X_1,\ldots,X_n})$. Prove
that $Y_n\to\theta$ in probability, by first obtaining the cdf of $Y_n$.
By definition, we want to show that $\lim_{n\to\infty}$ $P[|Y_n-\theta|\le\epsilon]=1$.
$$\lim_{n\to\infty}P[-\epsilon<Y_n-\theta\le\epsilon]=\lim_{n\to\infty}P[-\epsilon+\theta<Y_n\le\epsilon+\theta]\tag{1}$$
$$\lim_{n\to\infty}P[Y_n-\theta\le\epsilon]=\lim_{n\to\infty}P[Y_n\le\epsilon+\theta]\tag{2}$$
I know that $(2)$ helps me prove this, but why is it ok to skip $(1)$ ?

A: From the definition of $f$ it is clear that $X_i \geq \theta$ for each $i$. Hence $Y_n \geq \theta $. Now $P(|Y_n-\theta| \geq \epsilon)= P(Y_n \geq \theta+\epsilon)=(P(X_1 \geq \theta+\epsilon))^{n}=(1-e^{-\epsilon})^{n} \to 0$ as $ n \to \infty$.
The reason you can skip $Y_n \leq \theta -\epsilon$ is $Y_n \geq \theta $ almost surely.


text:
Q: How to find longest substring without repeating characters? I am solving a problem on leetcode.Here is the question link
https://leetcode.com/problems/longest-substring-without-repeating-characters/
Below is my solution which is not passing some test-cases:

*

*abcabcbb -- not correct

*pwwkew -- correct

*bbbbb -- not correct

Any help would be thankful:)
And also I am a newbie here so you can suggest me about my problem statement.
class Solution {
    public int lengthOfLongestSubstring(String s) {

        int i,max=0;
        List<Character> list = new ArrayList<>();
        String x = "";
        for(i=0;i<s.length();i++)
        {
            if(!list.contains(s.charAt(i)))
            {
                x += s.charAt(i);
                list.add(s.charAt(i));
                 System.out.println(x);
            }
            else
            {
                if(x != null && x.length() > max)
                {
                    max = x.length();
                    System.out.println(max);
                    x = "";
                    list.clear();
                    System.out.println("x : "+ x);
                    System.out.println("list : "+ list);
                }
                // else
                // {
                //     list.add(s.charAt(i));
                //     x += s.charAt(i);
                //     System.out.println("x in else : "+ x);
                //     System.out.println("list in else : "+ list);
                // }
                list.add(s.charAt(i));
                x += s.charAt(i);
                System.out.println("x in else : "+ x);
                System.out.println("list in else : "+ list);
            }
        }
        return max;
    }
}

A: Sometimes it's helpful to remain in the problem domain as much as possible.  This approach creates a solution before any thought of coding.  This approach leaves us with a set of minimally complex logical operations which then require implementation.
First our initial condition.  Columns should be clear: Input (always same), Current (the current substring without repeating characters), Answer (the current answer in String form) and Logic (what logic is applied for this step:

So first iteration starts the same as rest : get next character in Input.  Check if it is in the Current substring and since it is not add to Current.  Here we also ask the question: Is Answer shorter than Current and if so set Answer to Current.
Note in the Logic column we are developing operations which we'll need to implement in the solution.

Repeat for second character input (no new operations):

And again for third - (no new operations):

Ok now we find next CH in the current substring so we need a new operation: 'Remove chars in current up to but not including CH.  Note that "add CH to current" is done in this case as well.  Note also some new logic (answer was as long or longer than current so "Do Nothing").

And finish things out - no new operations.

So now we reach the end of input and simply ask the question "How long is the Answer" and that is the result.

So now looking at the Logic column we see operations to perform:
// Initial condition
String answer = "";
String current = "";

Let's work completely in Strings to keep things simple - optimization can come later..
Let's define the "next CH (nextChar)" operation:
// Get the ith character (0-based) from 's' as a String.
private static String nextChar(String s, int i) {}

We'll need an operation which "checks if 'Current contains CH'":
// Does the 'current' String contain the 'nextChar' String?
private static boolean currentContainsCh(String current, String nextChar) {}

We'll need to check if current Answer is shorter than Current:
// True if the 'answer' String is short in length than the 'current' string.
private static boolean isAnswerShorterThanCurrent(String current, String answer) {}

And the ability to append the nextChar to Current:
// Append the 'nextChar' to the 'current' String and return the String.
private static String addChToCurrent(String current, String nextChar) {}

And finally the ability to remove all characters up to but not including current char in Current:
// @return a String which has all characters removed from 'current' up to but not including 'ch'
private static String removeUpToChar(String current, String ch) {}

So putting it all together (essentially still in the problem domain since we haven't implemented any operations but just projected the problem into structure):
public int lengthOfLongestSubstring(String s) {

    String answer = "";
    String current = "";

    for (int i = 0; i < s.length(); i++) {
      String nextChar = nextChar(s,i);

      if (currentContainsCh(current, nextChar)) {
        current = removeUpToChar(current, nextChar);
      }

      current = addChToCurrent(current,nextChar);

      if (isAnswerShorterThanCurrent(current,answer)) {
          answer = new String(current);
      }

    }
    return answer.length();
}

And now implementing the "operations" becomes easier (and fun) since they are isolated and not complex.  This is left for you.  When implemented it passes the problem.
The next logical step after verifying correctness is to consider optimizations - if needed.

A: Although the pictures in answer by Andy are useful and mostly correct, the code is sub-optimal.
The code in the question, as well as in both current answers, builds a lot of substrings, using string concatenation. That is detrimental to performance.
Here is an O(n) solution that doesn't build any substrings:
public static int lengthOfLongestSubstring(String s) {
    Map<Character, Integer> lastPos = new HashMap<>();
    int start = 0, maxLen = 0, i = 0;
    for (; i < s.length(); i++) {
        Integer pos = lastPos.put(s.charAt(i), i);
        if (pos != null && pos >= start) {
            if (i > start + maxLen)
                maxLen = i - start;
            start = pos + 1;
        }
    }
    return (i > start + maxLen ? i - start : maxLen);
}

This works by remembering the last position of each character, so the potential longest substring's starting position can be adjusted to start right after the previous position of a repeating character.
Since HashMap.put(...) is O(1) (amortized), the solution is O(n).

Since it would be nice to see the substring, we can easily modify the code to return the (first1) longest substring:
public static String longestSubstring(String s) {
    Map<Character, Integer> lastPos = new HashMap<>();
    int start = 0, maxStart = 0, maxLen = 0, i = 0;
    for (; i < s.length(); i++) {
        Integer pos = lastPos.put(s.charAt(i), i);
        if (pos != null && pos >= start) {
            if (i > start + maxLen) {
                maxStart = start;
                maxLen = i - start;
            }
            start = pos + 1;
        }
    }
    return (i > start + maxLen ? s.substring(start) : s.substring(maxStart, maxStart + maxLen));
}

1) To return the last of multiple longest substrings, change both i > to i >=

The above solutions cannot handle strings with Unicode characters from the supplemental planes, e.g. emoji characters.
Emoji's such as  and  are stored as "\uD83D\uDE00" and "\uD83D\uDE01", so the char value '\uD83D' will be seen as a repeating character.
To make it correctly handle all Unicode characters, we need to change it to:
public static String longestSubstring(String s) {
    Map<Integer, Integer> lastPos = new HashMap<>();
    int start = 0, maxStart = 0, maxLen = 0, i = 0;
    for (int cp; i < s.length(); i += Character.charCount(cp)) {
        cp = s.codePointAt(i);
        Integer pos = lastPos.put(cp, i);
        if (pos != null && pos >= start) {
            if (i > start + maxLen) {
                maxStart = start;
                maxLen = i - start;
            }
            start = pos + Character.charCount(cp);
        }
    }
    return (i > start + maxLen ? s.substring(start) : s.substring(maxStart, maxStart + maxLen));
}

Test
for (String s : new String[] { "abcabcbb", "pwwkew", "bbbbb", "aab", "abba", "xabycdxefghy", "aXbXcdXefgXh", "" }) {
    String substr = longestSubstring(s);
    System.out.printf("%s: %s (%d)%n", s, substr, substr.length());
}

Output
abcabcbb: abc (3)
pwwkew: wke (3)
bbbbb: b (1)
aab: ab (2)
abba: ab (2)
xabycdxefghy: abycdxefgh (10)
aXbXcdXefgXh: cdXefg (6)
:  (6)


text:
Q: Persisting Session of Tomcat Server Application between re deploymets from Myeclipse IDE All
I am developing an web application using Tomcat 6.X and My Eclipse.
When i do some changes in existing java files (Java Class, SERVLETS , Filter) , i have to redeploy it to the tomcat server . but, when i redeploy the application the

existing session becomes null .

is there any way that i can persist the existing session between re deployments from the MY ECLISPE.

A: From Tomcat Docs
Check here for tutorial on JDBC persistence , tomcat-6-session-persistence-through-jdbcstore

*

*FileBased

*JDBC Based Store

Restart Persistence
Whenver Catalina is shut down normally and restarted, or when an
  application reload is triggered, the
  standard Manager implementation will
  attempt to serialize all currently
  active sessions to a disk file located
  via the pathname attribute. All such
  saved sessions will then be
  deserialized and activated (assuming
  they have not expired in the mean
  time) when the application reload is
  completed.
In order to successfully restore the state of session attributes, all
  such attributes MUST implement the
  java.io.Serializable interface. You
  MAY cause the Manager to enforce this
  restriction by including the
   element in your web
  application deployment descriptor
  (/WEB-INF/web.xml).


text:
Q: Using Java scanner get line number I'm using the code below to compare two file input streams and compare them:
        java.util.Scanner scInput1 = new java.util.Scanner(InputStream1);
        java.util.Scanner scInput2  = new java.util.Scanner(InputStream2);

        while (scInput1 .hasNext() && scInput2.hasNext())
        {
         // do some stuff
         // output line number of InputStream1
         }
       scInput1.close();
       scInput2.close();

How can I output the line number inside the while loop?

A: Use LineNumberReader on an InputStreamReader. As it is precisely made for that sole purpose.
try (LineNumberReader scInput1 = new LineNumberReader(new InputStreamReader(
        inputStream1, StandardCharsets.UTF_8));
    LineNumberReader scInput2 = new LineNumberReader(new InputStreamReader(
        inputStream2, StandardCharsets.UTF_8))) {

    String line1 = scInput1.readLine();
    String lien2 = scInput2.readLine();
    while (line1 != null && line2 != null) {
        ...
       scInput1.getLineNumber();
       line1 = scInput1.readLine();
       line2 = scInput2.readLine();
    }
}

Here I have added the optional CharSet parameter.
A Scanner has additional tokenizing capabilities not needed.


text:
Q: Push local traffic "outside" the nat I have a server functioning as my nat that hosts some services. When I locally connect via UDP to this server it my client uses the public ip but the server answers with its local ip.
So the question is: How can I force all traffic that is directed to the public ip to be routed through the NAT too?
Or is there some even simpler method to achieve the conversation taking place on the public ip (without letting the traffic "leak" out into the public)

A: You have to add a MASQUERADE rule for this traffic on the nat box. This makes it so that traffic to any of the DNAT services will appear to come from the nat box. That way when the DNAT service replies, the traffic goes back to the nat box so it can be properly sent back to the client (with the correct source IP address).
For example, if your private network were 192.168.0.0/24 and the nat box has this network on eth1:
iptables -t nat -A POSTROUTING -o eth1 -s 192.168.0.0/24 -d 192.168.0.0/24 -j MASQUERADE

(You could use SNAT instead of MASQUERADE, either works)