text:
Q: virtual machine object cannot find or load Main class so i have problem where i am trying to open a file through my own written  virtual machine object in java but the problem is that the virtual machine is not running and causing an error.
Error: Could not find or load main class C:\Users\dell\Trace\Main.java
we also tried modifying the CLASSPATH & PATH with no success
below is the code of the main
import com.sun.jdi.Bootstrap;
import com.sun.jdi.connect.*;

import java.util.Map;
import java.util.List;
import java.util.Iterator;

import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.IOException;

public class Trace {

    // Running remote VM
    private final VirtualMachine vm;

    // Thread transferring remote error stream to our error stream
    private Thread errThread = null;

    // Thread transferring remote output stream to our output stream
    private Thread outThread = null;

    // Mode for tracing the Trace program (default= 0 off)
    private int debugTraceMode = 0;

    //  Do we want to watch assignments to fields
    private boolean watchFields = false;

    // Class patterns for which we don't want events
    private String[] excludes = {"java.*", "javax.*", "sun.*",
                 "com.sun.*"};

    /**
     * main
     */
    public static void main(String[] args) {
    new Trace(args);
    }

    /**
     * Parse the command line arguments.
     * Launch target VM.
     * Generate the trace.
     */
    Trace(String[] args) {
    PrintWriter writer = new PrintWriter(System.out);
    int inx;
    for (inx = 0; inx < args.length; ++inx) {
        String arg = args[inx];
        if (arg.charAt(0) != '-') {
        break;
        }
        if (arg.equals("-output")) {
        try {
            writer = new PrintWriter(new FileWriter(args[++inx]));
        } catch (IOException exc) {
            System.err.println("Cannot open output file: " + args[inx]
                       + " - " +  exc);
            System.exit(1);
        }
        } else if (arg.equals("-all")) {
        excludes = new String[0];
        } else if (arg.equals("-fields")) {
        watchFields = true;
        } else if (arg.equals("-dbgtrace")) {
        debugTraceMode = Integer.parseInt(args[++inx]);
        } else if (arg.equals("-help")) {
        usage();
        System.exit(0);
        } else {
        System.err.println("No option: " + arg);
        usage();
        System.exit(1);
        }
    }
        if (inx >= args.length) {
        System.err.println("<class> missing");
            usage();
            System.exit(1);
        }
        StringBuffer sb = new StringBuffer();
        sb.append(args[inx]);
        for (++inx; inx < args.length; ++inx) {
            sb.append(' ');
            sb.append(args[inx]);
        }
        vm = launchTarget(sb.toString());
        generateTrace(writer);
    }

    /**
     * Generate the trace.
     * Enable events, start thread to display events,
     * start threads to forward remote error and output streams,
     * resume the remote VM, wait for the final event, and shutdown.
     */
    void generateTrace(PrintWriter writer) {
        vm.setDebugTraceMode(debugTraceMode);
        EventThread eventThread = new EventThread(vm, excludes, writer);
        eventThread.setEventRequests(watchFields);
        eventThread.start();
        redirectOutput();
        vm.resume();

        // Shutdown begins when event thread terminates
    try {
        eventThread.join();
        errThread.join(); // Make sure output is forwarded
        outThread.join(); // before we exit
    } catch (InterruptedException exc) {
        // we don't interrupt
    }
    writer.close();
    }

    /**
     * Launch target VM.
     * Forward target's output and error.
     */
    VirtualMachine launchTarget(String mainArgs) {
    LaunchingConnector connector = findLaunchingConnector();
    Map arguments = connectorArguments(connector, mainArgs);
        try {
        return connector.launch(arguments);
        } catch (IOException exc) {
            throw new Error("Unable to launch target VM: " + exc);
        } catch (IllegalConnectorArgumentsException exc) {
            throw new Error("Internal error: " + exc);
        } catch (VMStartException exc) {
            throw new Error("Target VM failed to initialize: " +
                exc.getMessage());
        }
    }

    void redirectOutput() {
        Process process = vm.process();

        // Copy target's output and error to our output and error.
        errThread = new StreamRedirectThread("error reader",
                                             process.getErrorStream(),
                                             System.err);
        outThread = new StreamRedirectThread("output reader",
                                             process.getInputStream(),
                                             System.out);
        errThread.start();
        outThread.start();
    }

    /**
     * Find a com.sun.jdi.CommandLineLaunch connector
     */
    LaunchingConnector findLaunchingConnector() {
        List connectors = Bootstrap.virtualMachineManager().allConnectors();
        Iterator iter = connectors.iterator();
        while (iter.hasNext()) {
            Connector connector = (Connector)iter.next();
            if (connector.name().equals("com.sun.jdi.CommandLineLaunch")) {
                return (LaunchingConnector)connector;
            }
        }
        throw new Error("No launching connector");
    }

    /**
     * Return the launching connector's arguments.
     */
    Map connectorArguments(LaunchingConnector connector, String mainArgs) {
        Map arguments = connector.defaultArguments();
        Connector.Argument mainArg =
                       (Connector.Argument)arguments.get("main");
        if (mainArg == null) {
            throw new Error("Bad launching connector");
        }
    mainArg.setValue(mainArgs);

    if (watchFields) {
        // We need a VM that supports watchpoints
        Connector.Argument optionArg =
        (Connector.Argument)arguments.get("options");
        if (optionArg == null) {
        throw new Error("Bad launching connector");
        }
        optionArg.setValue("-classic");
    }
    return arguments;
    }

    /**
     * Print command line usage help
     */
    void usage() {
    System.err.println("Usage: java Trace <options> <class> <args>");
    System.err.println("<options> are:");
    System.err.println(
"  -output <filename>   Output trace to <filename>");
    System.err.println(
"  -all                 Include system classes in output");
    System.err.println(
"  -help                Print this help message");
    System.err.println("<class> is the program to trace");
    System.err.println("<args> are the arguments to <class>");
    }
}


text:
Q: CAN Bus termination with CAN transceiver I want to correctly wire a CAN bus. The problem is that both nodes are internally terminated with 120 Ω, and so is the CAN transceiver.
This way I have three 120 Ω resistors.
Would it be a way to solve this, by switching the transceiver with one that isn't terminated, and place it between both terminated controllers?
Or does the transceiver need to be at one end of the circuit?

A: The device which can be configured to turn off the termination should be in the middle. Only ends of the bus must be terminated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: apply or be applied? If I'm talking about a promotional offer that one can take advantage of more than once within a given period, should I say "The offer can apply multiple times" or "The offer can be applied multiple times"?
Is there anything unusual about "can apply multiple times"?
I've found a few Google hits like the following:
Select this check box if the offer can apply multiple times. This is normally used for duration discounts when the contract says that for each block of 7 nights the customer gets one free.
http://downloads.dolphind.com/training/traininglibrarybmm/Product Database User Guide - Land.pdf
The promotional offer cannot be used cumulatively with customer conditions. Only one offer can apply.
The offer will not apply or be extended outside of the promotional date or uplift date ranges.
http://www.sustaingain.co.nz/Content/PhaSedNQST&Cs.pdf
These come from a British and a New Zealand business, respectively.
Could this be a British thing, given that New Zealand is a member of the British Commonwealth?
I'd appreciate your help.

A: The phrase "the offer can apply multiple times", when googled in quotation marks, is found only in one document on the web (the one you linked to), and in your questions that you have posted here and also on wordreference forums. You should never base yourself on something coming up in only one document, especially when it is supposed to describe something that happens thousands of times every day all over the internet (offers being made). Whoever wrote that document might not have been a professional writer, could be a non-native speaker, etc.
Native speakers that told you that they wouldn't use the active version are counfused by the addition of "multiple times". What they are thinking of is the phrase "the coupon (or promotion code) can be applied multiple times" (which is what people have also told you on wordreference). Native users, if they are not professional linguists or editors, can also become confused about things and use a word that is wrong in a particular context.
An offer is a single situation provided by a company. A company decides, "We'll give you a 10% discount if you enter the promotion code FRIEND10. You can use this code multiple times from next Monday to next Friday."
This is all one single offer. The buyer doesn't apply the offer. S/he is making use of one offer by applying a promotion code.
In cases where "an offer applies", we are not talking about the act of a user/buyer making use of it. The phrase "this offer applies" describes some rules of the offer, provides its characteristics. E. g. an offer can be characterized by a certain duration (as in the phrase "The offer will not apply or be extended outside of the promotional date") which you've quoted. It is another way of saying the offer will not be valid. It is a characteristic/rule given by those who provide the offer (the company), not by those who make use of it.
This is why the phrase "the offer can be applied multiple times" is not correct.

A: Now, after sticking to my guns with correct language use based of semantics, I need to make a caveat. I found an example of a certainly native-English-speaking corporation that uses the phrase "an offer can be applied" (though only once). It happens to be Amazon in its how-to for promotional codes. Note that when the process is described, the how-to shows where to enter a promotional code (not offer) and then click "apply." You can't enter an offer into a field. The phrase in question (the questionable phrase) appears further down amidst a whole lot of legalese. The thing is, the document specifically defines, for the purposes of the document, what the word "offer" will mean for the purposes of this particular document, and it's one heck of a intricate ball of attributes: "promotional claim code offer."
And where the "offer is applied", it is an example of catachresis, that is, a semantic error. It can be used by native speakers, sometimes as high literature—there it would be a deliberate "skewing" of the language landscape for poetic purposes, like the example in the Wikipedia article, "Mow the beard, Shave the grass."
This is not a reason, however, to expect a phrase like "My wife wants me to mow my beard" to be okayed for everyday use.
Which is why answers both on wordreference and here were suggesting to substitute something else either for "offer" ("promo code"), or for "applied" ("be used").
The correct semantics of this, I have detailed in the discussion to my previous answer.
An important factor in what to use in a language is established usage. Established usage is that it's the promo codes and the discounts that are "applied", overwhelmingly. The possibility of buying something with such a discount is an offer by a company, which is a meta-term, and it would be a semantic/stylistical mistake to use it metonymically.
The correct usage would be "This 20% sale is a nice offer by this company. You can take advantage of it by using a promo code. You apply it in your shopping cart when checking out".
Awkward language happens to all native speakers, especially when an intersection of legal matters and software use is involved.

A: Let's use rule instead of "offer".

This rule applies  on Monday, Wednesday, and Friday.
This rule can be applied only on weekends.

In the intransitive version, "this rule applies", there is no agent applying the rule.
With the transitive version, "can be applied", there's an implicit agent who applies the rule.

You apply this rule on weekends.

The same thing can be stated using the verb intransitively or transitively. When transitive, it is a passive (or quasi-passive) construction.

The rule is applicable.

P.S. As is shown in this example,  offer applies is standard disclaimer-speak. The thing that's giving your native speakers of AmE pause here  is the modal can apply.  can apply is not disclaimer-speak (in a disclaimer something either applies or it does not apply). So can apply must default to general-speak, and it refers to how the offer can be used, that is, to how the customer can use the offer, and so the passive form would be preferred: can be applied [by the customer]


text:
Q: common.exception.SfdcSqlException: ORA-30006: resource busy; acquire with WAIT timeout expired I am trying to update the CaseOwner field using a scheduled flow. The flow is able to update the CaseOwner Field for few cases. And for few cases, I am facing the following error in Production. In lower environments (exact replica of Prod), everything works fine, No errors.
SQLException while executing plsql statement: {call cCustomMetadata.lock_row_for_save(?)}(m0t1I000000fxXM)).
The flow tried to update these records: 5001I00000dETDJQA4.
This error occurred: FIELD_CUSTOM_VALIDATION_EXCEPTION: Validation Formula "EHSer_Pharamacy_DIVCode" Invalid (common.exception.SfdcSqlException: ORA-30006: resource busy; acquire with WAIT timeout expired
ORA-06512: at "SNEEZY.CCUSTOMMETADATA", line 71
ORA-06512: at "SNEEZY.CCUSTOMMETADATA", line 92
ORA-06512: at line 1
How to resolve this?


text:
Q: Getting POST https://content.dropboxapi.com/2/files/get_thumbnail_batch 400 (Bad Request) I am trying to fetch data using dbx.getThumbnailsBatch:
 const response = await fetch(`https://content.dropboxapi.com/2/files/get_thumbnail_batch`, {
      mode: 'no-cors',
      method: "POST", // *GET, POST, PUT, DELETE, etc.
      headers: {
        "Authorization": "Bearer <REDACTED>",
        "data": `{\"entries\":[{\"path\":\"${JSON.stringify(folders)}\"}]}`,
        "Content-Type": "application/json"

      },
    });

    const json = await response.json();
    console.log(json)

And I'm getting these errors:
POST https://content.dropboxapi.com/2/files/get_thumbnail_batch 400 (Bad Request)
Uncaught (in promise) SyntaxError: Unexpected end of input (at App.js:73:1)
    at nextImgs (App.js:73:1)

Can anyone tell why is this happening?


text:
Q: Regex for list number and allow empty space The sample i wanna past through the regex is with follow requirement

*

*list of number seperate by comma

*at least input 10 number in list

*only accept numbers but could allow empty space in both front and back
Here is my sample regex code:

^(?:(\-|\+|)\d+(?:\.\d*)?|(\-|\+|)\.\d+)+(?:,(?:(\-|\+|)\d+(?:\.\d*)?|(\-|\+|)\.\d+)){9,}$

This regex test code could pass list number seperate by comma,
however when i add empty space in front and on the back it will not work
The following testing Code is failed
'  2,2.5,.5,  .678   ,39,1.4.4.8,2.4,2.5,2.6,2.7'

A: You might use
^\s*[+-]?\d*\.?\d+(?:\.\d+)*(?:\s*,\s*[+-]?\d*\.?\d+(?:\.\d+)*){9,}\s*$

The pattern matches:

*

*^ Start of string

*\s*[+-]?\d*\.?\d+ Match an optional plus or minus sign, optional digits and optional dot followed by 1 or more digits

*(?:\.\d+)* As there are digits with multiple dot parts, you can optionally repeat that

*(?:\s*,\s*[+-]?\d*\.?\d+(?:\.\d+)*){9,} That first part of the pattern matches 1 time. As you want to match at least 10 times you can repeat the first pattern 9 or more times, starting with a comma between optional whitespace chars

*\s*$ Optional trailing whitespace chars and assert end of string

Regex demo
Note that \s can also match a newline.
If you don't want that, you could use for example a mere space or [ \t]


text:
Q: How can I avoid div from executing new line if one line is already full? How can I avoid
 tags from executing new line if one line is already full.
Let's assume that this div has group of images.
------------------------------------
|                                  |
|     Image 1           Image 2    |
|                                  |
|                                  |
|     Image 3           Image 4    |
|                                  |
------------------------------------

The images in the
 executes new line during the php loop and appears a scroll bar because of the overflow: scroll; code in CSS. My desired output is:
|----------------------------------|
|                                  |
|     Image 1      Image 2     Imag|
|                                  |
|                                  |
|----------------------------------|

Note: Image 3 and 4, prints if you scroll the div to the side.
That's my desired output wherein there will be a horizontal scroll bar and the view of the scroll would be horizontal. Any idea on how to do this?

A: Apply white-space: nowrap; to your div.
div{
  white-space: nowrap;
}

A: Added white-space: nowrap; display:inline-block; to your div

A: Just try this:

.imgbox {
    height:300px;
    width:100%;
    overflow-y:hidden;
    overflow-x:auto;
    border:1px solid red;
    white-space: nowrap;
}

img
{
    height:300px;
}

Note: If you want only horizontal scroll, you must specify overflow-y:hidden; & overflow-x:auto; so it would hide vertical scroll-bar and will give horizontal scroll-bar only if required.

Hope this might help you.


text:
Q: Two gridviews within a gridcontrol - Cannot get focused row handle for the inner grid Using DevExpress 10.2 within Visual Studio 2008 with VB.Net I have created a single gridcontrol that contains two different gridviews. The gridviews are related using an id column. Basically if there are related details about a row in the first gridview then the user can click on the plus sign to see all the related details. When I have any row on the first gridview I am able to get the focused row. Yet when I have the focus on any of the rows in the second gridview I am unable to get the focused row or the content of the row.
gridview2.focusedRowHandle = -2147...
gridview2.getRowCellValue(gridview2.FocusedRowHandle, "id") = Nothing
gridview2.GetFocusedRowCellValue("id") = Nothing

Is there any way to get the value in id from the focused inner gridview? Or at least figure out the parent row and grab the id value from there?

A: The code you are using is wrong because the DetailViews are separate objects, CLONEs of the detail GridView object assigned to a level.  So, to make the code work, you should use
Dim detailRowHandle as integer = CType(gridControl1.FocusedView, ColumnView).FocusedRowHandle

For more details, please refer to the What can cause the properties, methods, and events of a detail grid view to fail?


text:
Q: Second book on linear algebra Having gone through most of howard anton and chris rorres elementary linear algebra at my school. We have gone through some proofs, but the main focus was how to turn problems into matrices and then compute.
We covered
Vector spaces, determinants, linear transformations, diagonalization eigenvectors and inner products.
Im interestes in having a stronger background in linear algebra. Especially in terms of proofs in vector spaces and linear mappings, could someone suggest a book for this?

A: According to me book written by Hall and Knight is awesome. But just see the edition. Insel is also good one.


text:
Q: TikZ: anchors of special node "current page" seem to be incorrect in landscape I've got a document that I wish to format in landscape in conjunction with some material added as an overlay via TikZ.  I can get everything correct if I create a portrait page, but not if I create a landscape page.
Here's my MWE for portrait which shows what I want (except for page orientation)
\documentclass{article}
\usepackage[margin=0.5in]{geometry}
\usepackage{tikz}
\usepackage{lipsum}
\begin{document}

\lipsum[1-4]

\begin{tikzpicture}[remember picture,overlay]
    \node at (current page.south west) [text width=5cm,fill=red!20,above right] { This material is in the south west corner of the page };
\end{tikzpicture}

\end{document}

But when I try to get the same effect in landscape, the .south west anchor is apparently off the page.  This seems to happen regardless of whether I pass landscape through the optional argument to the class declaration or through geometry.
Here's my malfunctioning MWE:
\documentclass{article}
\usepackage[margin=0.5in,landscape]{geometry}
\usepackage{tikz}
\usepackage{lipsum}
\begin{document}

\lipsum[1-4]

\begin{tikzpicture}[remember picture,overlay]
    \node at (current page.south west) [text width=5cm,fill=red!20,above right] { This material is in the south west corner of the page };
\end{tikzpicture}

\end{document}

Any ideas?
Following @HarishKumar's suggestion, I can see that my compilation route is part of the problem:  I'm compiling by: latex → dvips → ps2pdf instead of just pdflatex.  However, I was under the impression that I need to go the more round about way if I'm incorporating PostScript commands in my LaTeX document.  Does anyone know anything about this and care to explain why I should always use pdflatex?

A: pdflatex (and also lualatex) relies on the value of \pdfpageheight to calculate the position, but geometry doesn't set this value if the dvi-mode is used. If you adjust the lengths the nodes are placed correctly:
\RequirePackage[T1]{fontenc} %for dvilualatex
\RequirePackage{luatex85}     % for current lualatex
\documentclass{article}
\usepackage[margin=0.5in,landscape]{geometry}
\pdfpageheight\paperheight
\pdfpagewidth\paperwidth %not sure if needed but can't harm
\usepackage{tikz}
\usepackage{lipsum}
\begin{document}

\lipsum[1-4]

\begin{tikzpicture}[remember picture,overlay]
    \node at (current page.south west) [text width=5cm,fill=red!20,above right] { This material is in the south west corner of the page };
\end{tikzpicture}

\end{document}

A: I'm a bit hesitant about calling this a bug in pdflatex, but from my not-very-extensive investigations, it would appear that the position returned by the primitive \pdfsavepos is offset when in landscape mode and producing dvi.  One way to explain the behaviour (though I've no idea how accurate this picture is) is that it is as if when \pdfsavepos runs then it actually computes the coordinates relative to the bottom left of the page.  But TeX wants the coordinates relative to the top left so then pdflatex has to compute (0,paperheight) - (saved x, saved y) and return that via \pdfsavepos.  However (still conjecturing) it's as if pdflatex when running in dvi mode does not know the actual page size of the shipped out page.  So when it computes paperheight then it uses its "standard" paper height.  This is based on the fact that the difference in the recorded positions in the aux file between a run with latex and a run with pdflatex is precisely \paperheight-\paperwidth:
pdflatex produces: \pgfsyspdfmark {pgfid1}{10467319}{17617993}
latex produces: \pgfsyspdfmark {pgfid1}{10467319}{29458709}
The difference is 11840716 (the units are sp).
And (in landscape mode) we can compare that with the paper dimensions via:
\newdimen\stuff
\stuff=11840716sp
\showthe\stuff

\stuff=\paperwidth
\advance\stuff by -\paperheight
\showthe\stuff

then this produces:
> 180.67499pt.
l.9 \showthe\stuff

?
> 180.67499pt.
l.13 \showthe\stuff

This explanation can't be completely right because although I get a similar story (in that there is a consistent y-shift) when I try \usepackage[a5paper]{geometry} then the numbers don't add up in the same way.
For situations where one is going between two tikzpicture environments then this offset doesn't matter because it is consistent, and therefore the relative separation of the pictures is the same.  It only matters for the current page node as that is "absolutely" positioned.  To fix the current page, it suffices to fix where pgf thinks the page origin lies.  This is held in the macro \pgf@sys@pdf@mark@pos@pgfpageorigin so we need to redefine that.
Ideally, we should redefine it to be aware of the current page size and geometry but as my experiments with a5paper showed me, I don't fully understand the computation involved.  So here's the fix for landscape a4paper when set using the geometry package.  If doing a mixed document, you could make the macro itself contain the conditional.  By surrounding it in \ifpdf ... \fi we get a system that works for both latex and pdflatex.
\makeatletter
\ifpdf
\else
\ifGm@landscape
\def\pgf@sys@pdf@mark@pos@pgfpageorigin{\pgfqpoint{0sp}{11840716sp}}
\fi
\fi
\makeatother

In an adaptation of your MWE:
\documentclass{article}
%\url{http://tex.stackexchange.com/q/91105/86}
\usepackage[landscape]{geometry}
\usepackage{tikz}
\usepackage{lipsum}

\makeatletter
\ifpdf
\else
\ifGm@landscape
\def\pgf@sys@pdf@mark@pos@pgfpageorigin{\pgfqpoint{0sp}{11840716sp}}
\fi
\fi
\makeatother

\begin{document}

\lipsum[1-4]

\begin{tikzpicture}[remember picture,overlay]
\foreach \anchor in {north west,north east,south west,south east} {
    \node[anchor=\anchor] at (current page.\anchor) {some stuff at \anchor};
}
\end{tikzpicture}
\end{document}

With pdflatex this produces:

With latex; latex; dvips; pstopdf (note the double run of latex) this produces:


text:
Q: How to redirect output to STDERR? Suppose that I passed in 2 parameters to my function. How can I redirect a message to stderr?
#!/bin/bash
if [ $# = 0 ]; then
    dir="."
elif [ $# = 1 ]; then
    dir=$1
elif [ $# -ge 2 ]; then
    echo "Too many operands." 2>> err.txt //???
    exit 1
fi

A: Just add >&2 to the statement producing the output:
echo "Too many operands." >&2

and if you want it to be appended to a file named err.txt too:
echo "Too many operands." | tee -a 'err.txt' >&2

FWIW I'd write your code using a case statement instead of nested ifs (and tidy up a couple of things):
#!/bin/env bash
case $# in
    0 ) dir='.' ;;
    1 ) dir="$1" ;;
    * ) printf 'Too many operands: %d\n' "$#" | tee -a 'err.txt' >&2
        exit 1 ;;
esac


text:
Q: make sql command by date object python I want to write a 'select' command of mysql through python and I want to use date-time object of python:
cnxn = pyodbc.connect('DSN=aaa;')
cursor = cnxn.cursor()
cursor.execute("select * from tableA where time>" + str(CurrentTime)+ " order by time asc")

where type of CurrentTime is datetime.datetime.
When I print the above string, it looks fine, but when I run this, it gives me an error:

pyodbc.ProgrammingError: ('42000', "[42000] [MySQL][ODBC 5.3(w)
  Driver][mysqld-5.5.16-log]You have an error in your SQL syntax; check
  the manual that corresponds to your MySQL server version for the right
  syntax to use near '11:17:07 order by time asc' at line 1 (1064)
  (SQLExecDirectW)")

Solved:
cursor.execute("""select * from tablea where time> ? order by time asc""" , str(CurrentTime))

A: Use parameters:
cnxn = pyodbc.connect('DSN=aaa;')
cursor = cnxn.cursor()
cursor.execute("select * from tableA where time > ? order by time asc",
               CurrentTime)

I don't have MySQL to test with, so maybe I'm missing something.


text:
Q: Subsonic 3 LeftOuterJoin I have a problem. I want to create sql question
select * from Firma left outer join FirmaAdres on FirmaAdres.Typ = 1 and FirmaAdres.FirmaID = Firma.ID
in subsonic
I have written
SelectColumns("Firma.*").From().LeftOuterJoin(FirmaTable.IDColumn, FirmaAdresTable.FirmaIDColumn).And(FirmaAdresTable.AdresTypIDColumn).IsEqualTo(1)
When I checked what sql question is created I noticed then left outer join is changed to Inner join!!!
Could anyone help me??

A: Subsonic doesn't support LeftOuterJoin.  You need to emulate the left join in LINQ (see http://www.devsource.com/c/a/Languages/Defining-a-Left-Join-with-LINQ-Queries/ for more details)  In my opinion the effort don't deserves the pain that is wating for you.  I suggest you to use a simple, boring and traditional stored procedure here.


text:
Q: Cohomology of the sphere $S^{n}$ with coefficients in abelian group $G$ I am doing this with the long exact sequence of the pair $(D^{n}/\partial D^{n})$.
For $n >0$, using the fact that $(D^{n},\partial D^{n})$ is a good pair we have $H^{i}(D^{n},\partial D^{n};G)\simeq \tilde{H^{i}}(D^n/\partial D^n;G)\simeq\tilde{H^{i}}(S^n;G)$, and the fact that $D^n$ is contractible, a portion of the long exact sequence yields
$0 \leftarrow \tilde{H^{i}}(S^n;G) \leftarrow \tilde{H}^{i-1}(S^{n-1};G)\leftarrow 0$
This gives the isomorphisms $\tilde{H^{i}}(S^n;G) \simeq \tilde{H}^{i-1}(S^{n-1};G)$ for $i >0$.
I compute $\tilde{H}^{0}(S^{0},G)$ using the fact that $\tilde{H}^{0}(X,G)$ can be described as the group of all functions that are constant on path components modulo the functions that are constant on all of $X$; I denote this space by $F_{X}$. In the case $S^{0}=\{-1,1\}$, the map $\varphi:F_{S^{0}} \rightarrow G$ given by $\varphi(f)=f(1)-f(-1)$ is surjective with kernel the functions constant on $S^{0}$ so will give an isomorphism of $\tilde{H}^{0}(S^{0},G)$ with $G$.
This gives me $G \simeq \tilde{H}^{0}(S^{0},G) \simeq \tilde{H}^{1}(S^{1},G) \simeq \tilde{H}^{2}(S^{2},G)\simeq ...$

I'm having trouble showing that $H^{k}(S^{n},G)=0$ for all $n \neq k$. It's pretty clear but is there a nice way to write this?

A: Use long exact sequences and go by induction. You've done the base case. In order to compute cohomology groups for $\mathbb{S}^{n+1}$, use the long exact sequence in cohomology for the good pair $(\mathbb{D}^{n+1},\partial(\mathbb{D}^{n+1})\cong\mathbb{S}^n)$. Starting at $H^{k-1}(\mathbb{S}^{n})$, we get:
\begin{align*}
     \dots\to H^{k-1}(\mathbb{S}^n)\to H^k(\mathbb{S}^{n+1})\to H^k(\mathbb{D}^n)\to H^{k}(\mathbb{S}^n)\to H^{k+1}(\mathbb{S}^{n+1})\to\dots
\end{align*}
Here, we used the fact that since $(\mathbb{D}^{n+1},\mathbb{S}^n)$ is a good pair its cohomology is isomorphic to  that of $\mathbb{D}^{n+1}/\mathbb{S}^n$, which is $\mathbb{S}^{n+1}$. By the inductive hypothesis and the fact that the cohomology of a disk is just that of a point, this gives us the sequence (where $k<n-1$)
\begin{align*}
    \dots\to 0\to H^k(\mathbb{S}^{n+1})\to 0\to 0\to H^{k+1}(\mathbb{S}^{n+1})\to\dots
\end{align*}
So, $H^{k}(\mathbb{S}^{n+1})=0$ as well. The LES for $H^{n}$ is slightly different, but try to write out the LES and the same result should follow.


text:
Q: SQL Insert into statement strSQL = "INSERT INTO Accounts UserName, Password VALUES ('" & txtUsername.Text & "', '" & txtEncryptedPassword & "');"

When the code is executed and error is thrown, but there is no visible problem that i can see. Help!

A: The word PASSWORD is reserved in MS-Access.
You need to use square brackets around that name (Or change it to something different)
strSQL = "INSERT INTO Accounts (UserName, [Password]) VALUES (......

Said that, please use a parameterized query to build sql commands.
A string concatenation like yours is easily attacked by hackers using SQL Injection
Also, if the username or password contains a single quote, the resulting sql text built using string concatenation will be invalid.
strSQL = "INSERT INTO Accounts (UserName, [Password]) VALUES (?, ?)"
OleDbCommand cmd = new OleDbCommand(strSQL, connection);
cmd.Parameters.AddWithValue("@p1",txtUsername.Text);
cmd.Parameters.AddWithValue("@p2",txtEncryptedPassword);
cmd.ExecuteNonQuery();

A: You forgot parentheses:
strSQL = "INSERT INTO Accounts (UserName, Password) VALUES ('" & txtUsername.Text & "', '" & txtEncryptedPassword & "');"

A: your doing () this mistake and you should must add:
your code:
strSQL = "INSERT INTO Accounts UserName, Password VALUES ('" & txtUsername.Text & "', '" & txtEncryptedPassword & "');"

you should must change code following as:
strSQL = "INSERT INTO Accounts (UserName, Password) VALUES ('" & txtUsername.Text & "', '" & txtEncryptedPassword & "');"

update1:
"INSERT INTO `test`.`users` ( `username`, `password`) " & _
                  "VALUES ('" & txtUsername.Text & "', '" & txtPassword.Text & "');"

update2:
   "INSERT INTO users ( `username`,`password`)VALUES(@txtUsername.Text,@txtPassword.Text);"

"INSERT INTO users (Username,Password)VALUES(?,?);"

note:test means database name you should change your databasename.

A: try this code:
 Dim strSQL As String = "INSERT INTO tblDetail VALUES('" & strPersonCode _
         & "','" & strForename & "','" & strSurname & "','" & strDateOfBirth & "'," & strCurrentlyWith & ",'" & strConditions & "')"

Do it like that but change to your names.
Declare the values of text boxes as strings and just use those.


text:
Q: Strip tags on pasting into a contenteditable DOM element My aim is to strip all tags on pasting into a contenteditable DOM element. I'm using WordPress Front-end Editor which is a featured plugin that may graduate into the WordPress core.
When pasting content into the title editable region, the plugin currently strips tags onblur. This results in the formatting being visible until focus is lost (then tags are stripped out). For how this is current done, see:
https://github.com/avryl/wp-front-end-editor/blob/master/js/wp-front-end-editor.js#L118
I need the tags to be stripped out when pasting so that the copied styles and formatting aren't displayed. I thought about using the paste event to strip tags on paste but am unsure exactly how to implement it.
I tried replacing 'blur' with 'paste' but that didn't work.
Hoping somebody can help?

A: Paste this after 117 line:
.on('paste', function (e) {
    e.preventDefault();
    var contentOnBlur = (e.originalEvent || e).clipboardData.getData('text/plain') || prompt('Paste something..');
    contentOnBlur = contentOnBlur.replace(/(<([^>]+)>)/ig,'');
    document.execCommand('insertText', false, contentOnBlur);
})

Paste the same block after 171 line (don't forget that the previous paste could move it lower).


text:
Q: GR breaks down at Planck Mass I have heard a lot of times (see e.g. papers like [1, 2]) that GR is not renormalizable and breaks down at energies at the scale of the Planck Mass $M_{\text{Planck}}\sim 10^{19}$ GeV. What is the (simple) explanation for these two statements?

*

*On the possibility of laboratory evidence for quantum superposition of geometries

*General relativity as an effective field theory: The leading quantum corrections


text:
Q: FBSDKLoginManagerLoginResult valueForUndefinedKey when trying to get user's email I'm trying to get user's name , email and id from FBSDKLoginManagerLoginResult and get an error:

Terminating app due to uncaught exception 'NSUnknownKeyException',
  reason: '[
  valueForUndefinedKey:]: this class is not key value coding-compliant
  for the key email.'

Here's the code :
   class ViewController: UIViewController, FBSDKLoginButtonDelegate {

        @IBOutlet weak var fbLogin: FBSDKLoginButton!
        override func viewDidLoad() {
            super.viewDidLoad()
       fbLogin.readPermissions = ["public_profile", "email"]
            fbLogin.delegate = self
    }

        func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {

            if ((error) != nil)
            {
                NSLog("User Logged In")
            }
            else if result.isCancelled {
                 NSLog("User cancels")
            }
            else {
                if result.grantedPermissions.contains("email")
                {
                   let userEmail : String = result.valueForKey("email") as! String //here I get crash
                    NSLog("User Email is: \(userEmail)")
                }
            }
        }
    }

Also, I can't find list of available keys

A: Looks like you need to make a FBSDKGraphRequest. I have
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: NSError!) {

    if ((error) != nil) {
        // Process error
    } else if result.isCancelled {
        // Handle cancellations
    } else {
        let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields" : "id, email, name"])
        graphRequest.start(completionHandler: { (connection, result, error) -> Void in
            if ((error) != nil) {
                print("Error: \(error)")
            } else {
                if let user : NSString = result!.value(forKey: "name") as? NSString {
                    //print("user2: \(user)")
                    self.userLabel.text = "Logged in as \(user)"
                }
                if let id : NSString = result!.value(forKey: "id") as? NSString {
                    self.fbId = id
                    //print("id: \(id)")
                }
                if let email : NSString = result!.value(forKey: "email") as? NSString {
                    print("email: \(email)")
                }
            }
        })
    }
}

This example is using swift ver. 3 (xcode beta 3).

A: In Swift 4:
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
        if ((error) != nil) {
           // ERROR
        }
        else if result.isCancelled {
            // CANCELATION
        }
        else {
            let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields" : "id, email, name"])
            graphRequest.start(completionHandler: { (connection, result, error) -> Void in
                if ((error) != nil) {
                    FBSDKLoginManager().logOut()
                } else {
                    if let idfb : NSString = (result! as AnyObject).value(forKey: "id") as? NSString {
                        print("ID FROM FACEBOOK: \(idfb)")
                    }
                    if let name : NSString = (result! as AnyObject).value(forKey: "name") as? NSString {
                        print("NAME IN FACEBOOK: \(name)")
                    }
                    if let email : NSString = (result! as AnyObject).value(forKey: "email") as? NSString {
                        print("EMAIL IN FACEBOOK: \(email)")
                    }
                }
            })
        }
    }


text:
Q: Jquery ui style not displaying when load content on ajax I have 2 pages: index.php and form1.php.
In my index.php I have a button which has function to load content of form1.php on div:
$("#btnLoadContent").button().click(function(){
$("#divcontent").empty().load("form1.php")});

On form1.php y have a form and a button named btnSend.
On index i'm using this:
$("#btnSend").button();

but when loaded, this button doesn't have the style or functionality of the implemented script. And I haven't realized why.

A: You probably need to use the live function in jQuery.
Also, if the ajax loaded content is within an iframe, the styles need to be called from within the loaded site again.

A: I think that the .button() will have already been executed when index.php loads. It will not execute again after form1.php has loaded. The .load() function has a callback parameter which will execute after the content has loaded. You should add the $("#btnSend").button() to that callback function instead.
For example:
$("#divcontent").empty().load('form1.php', function(response, status, xhr) {
    $("#btnSend").button();
});

A: I Found the answer.
Just tried this code
$("#btnLoadContent").button().click(function(){
    $.ajax({
        url:"form1.php",
        success:function(data){
            $("#divcontent").empty().append(data);
            $("#btnSend").button();
        }
    });
});


text:
Q: "I forgot" or "I forget" I am from Philadelphia and I grew up saying, I forget when trying to recall something unsuccessfully. When I came in contact with people from other states, mostly in the mid-Atlantic region, I heard people say under the same circumstances, I forgot in the past tense.  The latter implies that the forgetting happened at a certain point in time in the past, while the former seems to imply that as long as you don't remember, you are  continuously forgetting.
Which is the more widely used, and does it break down along regional lines?


text:
Q: Extract text under div class using Selenium and Python I am trying to extract text from this element:

북일여자고등학교

I am trying to extract the text after href -
'북일여자고등학교'

So far I tried:
content = driver.find_element_by_css_selector('div._pac')

for i in content:
 i.get_attribute('text')

However, it is not returning anything. How can I extract the text?

A: The desired text 북일여자고등학교 is within a child  node within the parent
 node.
To print the text 북일여자고등학교 you have to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

*

*Using CSS_SELECTOR and .get_attribute("innerHTML"):
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div._pac>a[href^='https://www.facebook.com/pages']"))).get_attribute("innerHTML"))

*Using XPATH and text attribute:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='_pac']/a[starts-with(@href, 'https://www.facebook.com/pages')]"))).text)

*Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

*Console Output of two back to back execution:
북일여자고등학교

You can find a relevant discussion in How to retrieve the text of a WebElement using Selenium - Python

Outro
Link to useful documentation:

*

*get_attribute() method Gets the given attribute or property of the element.

*text attribute returns The text of the element.

*Difference between text and innerHTML using Selenium

A: It seems there are multiple div with the class _pac on you page. In your case it is locating first element and that has no text.
find_element methods locates the verify first element in case multiple occurrence is there of same element.
Try to make you locator more unique and specific to locate the single element. Refer below code :
content = driver.find_element_by_xpath("//div[contains(@data-bt,'sub_headers')]/a")
content.text

It seems you are looping the content but you have used find_element instead of find_elements so replace it with find_elements method
loop through all the text present in same kind of element use below code:
content = driver.find_elements_by_css_selector('div._pac')
for element in content:
   print(element.text)

A: To extract text from  tag like you mean, use this css selector div._pac > a. Please try this solution:
content = driver.find_element_by_css_selector('div._pac > a')
print(content.text)

#or use '.get_attribute'
print(content.get_attribute("innerHTML"))

If there are multiple elements with same classification on the page, you can use .find_elements_*, it will return a list of webelemet, and extract them with loop:
content = driver.find_elements_by_css_selector('div._pac > a')
for el in content:
    print(el.text)

    #or use '.get_attribute'
    print(el.get_attribute("innerHTML"))

A: Just remember to do that extraction BEFORE closing driver!
I had that issue because I had loop after driver.close() even when my variable element was filled with data!
So loop BEFORE .close().
Example:
driver = webdriver.Chrome()
...
LOOP for(..)...
...loop does smth...
driver.close()


text:
Q: How to save each element of a list to an independent new file? I have a function that Pos-tag a number of documents and prints each pos-tagged document in a list as follows:
    [u'I\tPP\tI', u'am\tVBP\tbe', u'an\tDT\tan', u'amateur\tJJ\tamateur']
....

    [u'good\tJJ\tgood', u'camera\tNN\tcamera', u'for\tIN\tfor', u'a\tDT\ta', u'good\tJJ\tgood']

How can I save or write each list as a new .txt document in a new directory?, for example:
new_directory
    ---->list1.txt
    ....
    ---->listn.txt

Now, if we look inside each new file it would look like this:
good JJ good
camera NN camera
for IN for
a DT a
good JJ good

thanks in advance guys.

A: As one way you can iterate over your lists (I assumed they're in a nested list here) and then open a file and write the contents of that list to the file.
You could hardcode the path with the appropriate seperators, but I just used os.path.join here as it's typically good to use this. How you're specifying the new directory wasn't mentioned. You could take this in from sys.argv, a file dialog, input, or any other numerous options.
import os

nested_list=[
    [u'I\tPP\tI', u'am\tVBP\tbe', u'an\tDT\tan', u'amateur\tJJ\tamateur'],
    [u'good\tJJ\tgood', u'camera\tNN\tcamera', u'for\tIN\tfor', u'a\tDT\ta', u'good\tJJ\tgood']
]

for i, a_list in enumerate(nested_list):
    #new_dir_path is path to dir you want.
    path = os.path.join(new_dir_path, "list%d.txt" % i) #or "list{}.txt".format(i)
    with open(path, "w") as f:
        for item in a_list:
            f.write(item+"\n") #\n if you want each item on a new line


text:
Q: c# detect mousedown without controls I'm new in c# and want to code a click bot for a game, which should click when I hold my mouse button down and stop clicking when I'm releasing the mouse button. Now My question is how to check if a mouse button is held down and click when I'm in another window.

A: You can add a message filter:
Application.AddMessageFilter(new MyMessageFilter());

where MyMessageFilter is a class implementing IMessageFilter. Example:
class MyMessageFilter : IMessageFilter
{
    public bool PreFilterMessage(ref Message m)
    {
        const int WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202;

        switch (m.Msg) {
            case WM_LBUTTONDOWN:
                System.Diagnostics.Debug.WriteLine("Left button down " + DateTime.Now);
                return false;
            case WM_LBUTTONUP:
                System.Diagnostics.Debug.WriteLine("Left button up " + DateTime.Now);
                return false;
        }
        return false;
    }
}

If you return true, this signals that you have processed the message and that you don't want any controls to get this message. I.e. true inactivates the corresponding Form or Control event.
The HWnd property of the Message structure returns the Window handle of the affected window.
Here, you can find a reference for Mouse Input Notifications.


text:
Q: Результаты выполнения CompareTo Почему в случае
string s1 = "раз два три";
string s2 = "раз";
int result;

result = s1.CompareTo(s2);

Console.WriteLine(result);

в результате получаю 1.
А в случае
string s1 = "раз два три";
string s2 = "три";
int result;

result = s1.CompareTo(s2);

Console.WriteLine(result);

в результате получаю -1.
Почему во втором случае отрицательное значение?
A: Потому что строки сравниваются лексикографически:

*

*сначала сравниваются первые символы, если они не равны, возвращается результат

*затем сравниваются вторые символ, если они не равны, возвращается результат

*и т. д. до конца одной из строк. если начала совпадают, более длинная строка считается больше

*в противном случае строки совпадают и значит равны

В первом случае сравнение идёт до конца первой строки, поскольку она длиннее, получаете ответ «больше». Во втором случае сравнение останавливается на первом символе, 'р' < 'т', поэтому первая строка считается «меньше».


text:
Q: Submit Buttons in while loop my problem may be easy for experienced users, but I'm stucked on it. So, here's the problem. I have submit buttons in while loop, they draw, but they don't react on click. Here's my piece of code.
`<?php
$zap_cmember = count_query("SELECT * FROM `users` WHERE `clan` = '".$member['id']."' AND clan_stat != 'Призывник'");
while ($cmember = mysql_fetch_array($zap_cmember))
{
$zap_gold = mysql_result(mysql_query("SELECT SUM(gold) FROM klog WHERE name = '".$cmember['name']."'"), 0);
$zap_online = mysql_num_rows(count_query("SELECT * FROM `online` WHERE `id_session`='".$cmember['id_user']."'"));
if ($zap_online > 0)
{
    $img_on = "	";
}
else
{
    $img_on = "	";
}
$i = 'set';
echo '

      '.$cmember['name'].' ['.lvl($cmember['exp']).']
      '.$cmember['clan_stat'].'
      -
      '.$zap_gold.'
      '.$cmember['glory'].'
      '.$img_on.'';
        if($boss)
        {echo '<input type="submit" name="bSet" value="Назначить">	'; }
        $i++;
        $player = $cmember;
    '
';

    if (isset($_POST['bSet']))
    {
    echo 'works';
    count_query("UPDATE users SET clan_stat='Вождь' WHERE id_user='".$player['id_user']."'");
    $time = date('j.n.y H:i');
    count_query("INSERT INTO `message` (`time`, `to`, `text`, `metka`) VALUES ('".$time."', '".$player['name']."', 'Вас выбрали главой клана ".$clan['name']."', '6')");
    echo "";
    }
}
?>

`

A: You need to put everything that you want to submit to a <form id="yid">... </form>, after that to put on the button the onclick="javascript:$('#yid').submit()" and  the yid= the particular id of the form you want the button to submit.


text:
Q: Able to transfer files from phone to PC via USB, but not vice versa Just as the title states, I am encountering a very strange issue with USB transfer between my PC (Win10) and android devices. While I am able to transfer files from my android devices to my PC, I am unable to move files to them (the transfer gets stuck at 0%). I've tried different cables, USB ports, heck even multiple devices (OnePlus 6, Xperia XA Ultra and Galaxy S9) and the same problem crops up across all of them. I am beyond frustrated and any help would be much appreciated.

A: Did you set the USB mode to file transfer? When you connect your phone via USB, you should get a notification on the phone (phone has to be unlocked), choose "Use USB for: File Transfer" Then you should be able to transfer files. Make sure the directory you are trying to write to is not write protected.
You can also try to enable developer / debugging mode if it doesnt work.
More information can be found here:
https://support.google.com/android/answer/9064445?hl=en


text:
Q: Filter content with multiple tags but only allow user to select one tag at a time I'm building a page for an academic website meant to sort papers by tags. Each paper should be able to be tagged with multiple topics (e.g., ad hoc and metaphor) but the user should only be able to select one tag.
Here's how it is currently: http://www.casasanto.com/homeRevamp/index.html. As it is now, the user can select more than one tag to narrow the search. We want to simplify it so that clicking on metaphor after clicking ad hoc will show you every paper tagged with metaphor, not everything tagged with ad hoc AND metaphor.
HTML and CSS:

    <meta charset="UTF-8">

    <title>Tagsort Demo</title>

    <link href="tagsort.css" rel="stylesheet" type="text/css"></link>
    <link rel="stylesheet" href="filterTagsortStylesheet.css" type="text/css">

Selected Papers

Click on a topic to see all papers tagged under that heading.

                Casasanto, D. (in press). Temporal language and temporal thinking may not go hand in hand. In B. Lewandowska-Tomaszczyk (Ed.), Conceptualizations of time. Amsterdam: John Benjamins.

                Casasanto, D., & Lupyan, G. (2015). All concepts are ad hoc concepts. In E. Margolis & S. Laurence (Eds.), The conceptual mind: New directions in the study of concepts (pp. 543-566). Cambridge: MIT Press.

                R., Crepaldi, D., Casasanto, D., Crollen, V. & Collignon, O. (2015). Space and time in the sighted and blind. Cognition, 141, 67-72.

                Casasanto, D., & Gijssels, T. (2015). What makes a metaphor an embodied metaphor? Linguistics Vanguard. doi:10.1515/lingvan-2014-1015

JavaScript:
;(function($) {
  $.fn.tagSort = function(options) {
      var defaults = {
        selector: '.item-tagsort',
        displaySelector: false,
        displaySeperator: ' ',
        inclusive: false,
        fadeTime: 200
      };
      options = $.extend(defaults, options);

      var tagSortEngine = {
        generateTags: function(elements) {
          var tags_inclusive = {};
          var tags_exclusive = {elements: [], tags: []};
          elements.each(function(i){
            $element = $(this)
            ;
            var tagsData = $element.data('item-tags'),
            elementTags = tagsData.match(/,\s+/) ? tagsData.split(', ') : tagsData.split(',');

            $.each(elementTags, function(i, v){
              var tagName = v.toLowerCase();
              if(!tags_inclusive[tagName]){
                tags_inclusive[tagName] = [];
                tagSortEngine.container.append(''+v+'');

              }
              if(options.displaySelector !== false){
                $element.find(options.displaySelector).append(i > 0 ? options.displaySeperator + v : v);
              }
              tags_inclusive[tagName].push($element);
            });

            tags_exclusive.elements.push($element);
            tags_exclusive.tags.push(elementTags);
          });
          return options.inclusive == true ? tags_inclusive:tags_exclusive;
        },
        exclusiveSort: function(tags, elements){
          var display = [[],[]];
          $.each(tags.elements, function(element_key, element){
            var showElement = true;
            tagSortEngine.container.find('.tagsort-active').each(function(i){
              if(tags.tags[element_key].indexOf($(this).text()) == -1){
                showElement = false;
                display[0].push(element);
              }
            });

            if(showElement == true) {
              display[1].push(element);
            }
          });
          return display;
        },
        inclusiveSort: function(tags, elements){
          var display = [[],[]]
          $container.find('.tagsort-active').each(function(i){
            $.each(tags[$(this).text().toLowerCase()],function(element_key, element){
              display[1].push(element);

            });
          });
          return display;
        },

        inititalize: function(tagsContainer){
          tagSortEngine.container = tagsContainer;
          tagSortEngine.container.addClass('tagsort-tags-container');
          var elements = $(options.selector);
          tagSortEngine.tags = tagSortEngine.generateTags(elements, tagSortEngine.container);
          var tagElement = tagSortEngine.container.find('span');
          tagElement.click(function(){
            $(this).toggleClass('tagsort-active');
            if(!tagElement.hasClass('tagsort-active')){
              elements.fadeIn(options.fadeTime);
            }
            else {
              elements.fadeOut(options.fadeTime);
              var display = options.inclusive == true ? tagSortEngine.inclusiveSort(tagSortEngine.tags, elements):tagSortEngine.exclusiveSort(tagSortEngine.tags, elements);
              if(display[0].length > 0){
                $.each(display[0], function(hide_key, toHide){
                  if(toHide.is(':visible')){
                    toHide.fadeOut(options.fadeTime);
                  }
                });
              }
              if(display[1].length > 0){
                $.each(display[1], function(hide_key, toShow){
                  if(!toShow.is('visible')){
                    toShow.fadeIn(options.fadeTime);
                  }
                });
              }
            }
          });
        }
      }
      tagSortEngine.inititalize(this);
      return $(this);
    }
})(jQuery);

A: Javascript below. The solution is that in tagElement.click, you need to remove the "tagsort-active" class from all of the elements, then toggle it in the desired one.
;(function($) {
  $.fn.tagSort = function(options) {
      var defaults = {
        selector: '.item-tagsort',
        displaySelector: false,
        displaySeperator: ' ',
        inclusive: false,
        fadeTime: 200
      };
      options = $.extend(defaults, options);

      var tagSortEngine = {
        generateTags: function(elements) {
          var tags_inclusive = {};
          var tags_exclusive = {elements: [], tags: []};
          elements.each(function(i){
            $element = $(this)
            ;
            var tagsData = $element.data('item-tags'),
            elementTags = tagsData.match(/,\s+/) ? tagsData.split(', ') : tagsData.split(',');

            $.each(elementTags, function(i, v){
              var tagName = v.toLowerCase();
              if(!tags_inclusive[tagName]){
                tags_inclusive[tagName] = [];
                tagSortEngine.container.append(''+v+'');

              }
              if(options.displaySelector !== false){
                $element.find(options.displaySelector).append(i > 0 ? options.displaySeperator + v : v);
              }
              tags_inclusive[tagName].push($element);
            });

            tags_exclusive.elements.push($element);
            tags_exclusive.tags.push(elementTags);
          });
          return options.inclusive == true ? tags_inclusive:tags_exclusive;
        },
        exclusiveSort: function(tags, elements){
          var display = [[],[]];
          $.each(tags.elements, function(element_key, element){
            var showElement = true;
            tagSortEngine.container.find('.tagsort-active').each(function(i){
              if(tags.tags[element_key].indexOf($(this).text()) == -1){
                showElement = false;
                display[0].push(element);
              }
            });

            if(showElement == true) {
              display[1].push(element);
            }
          });
          return display;
        },
        inclusiveSort: function(tags, elements){
          var display = [[],[]]
          $container.find('.tagsort-active').each(function(i){
            $.each(tags[$(this).text().toLowerCase()],function(element_key, element){
              display[1].push(element);

            });
          });
          return display;
        },

        inititalize: function(tagsContainer){
          tagSortEngine.container = tagsContainer;
          tagSortEngine.container.addClass('tagsort-tags-container');
          var elements = $(options.selector);
          tagSortEngine.tags = tagSortEngine.generateTags(elements, tagSortEngine.container);
          var tagElement = tagSortEngine.container.find('span');
          tagElement.click(function(){
            $.each(tagElement, function(i,v){
              v.removeAttribute("class");
            });
            $(this).toggleClass('tagsort-active');
            if(!tagElement.hasClass('tagsort-active')){
              elements.fadeIn(options.fadeTime);
            }
            else {
              elements.fadeOut(options.fadeTime);
              var display = options.inclusive == true ? tagSortEngine.inclusiveSort(tagSortEngine.tags, elements):tagSortEngine.exclusiveSort(tagSortEngine.tags, elements);
              if(display[0].length > 0){
                $.each(display[0], function(hide_key, toHide){
                  if(toHide.is(':visible')){
                    toHide.fadeOut(options.fadeTime);
                  }
                });
              }
              if(display[1].length > 0){
                $.each(display[1], function(hide_key, toShow){
                  if(!toShow.is('visible')){
                    toShow.fadeIn(options.fadeTime);
                  }
                });
              }
            }
          });
        }
      }
      tagSortEngine.inititalize(this);
      return $(this);
    }
})(jQuery);


text:
Q: Core Data - NSManagedObject returning nil I wrote two seperate functions fetchRecords and displayRecords written in Appdelegate Class. fetchRecords function will fetch all records from the entity and it is working fine.displayRecords function accepts the return value from fetchRecords function and prints all the records one by one.
I have one view controller which calls these two functions to do the desired task. My problem is result.count in displayRecords shows the total number of records available in fetched records.While printing the records one by one the value is nil.
override func viewDidLoad() {
super.viewDidLoad()
    let fetchedRecords = AppDelegate().fetchRecords(fromEntity: "Dashboard")
    AppDelegate().displayRecords(fromFetchedRecords: fetchedRecords)
}

And here is the fetchRecords and displayRecords functions written in AppDelegate Class
  func fetchRecords(fromEntity entity:String) -> Array<AnyObject> {
    var fetchedResult:Array<AnyObject> = []
    let fetchRequest = NSFetchRequest()
    let entityDescription = NSEntityDescription.entityForName(entity, inManagedObjectContext: self.managedObjectContext)!
    fetchRequest.entity = entityDescription
    do{
        fetchedResult = try self.managedObjectContext.executeFetchRequest(fetchRequest)
    }catch{
        let fetchError = error as NSError?
        print(fetchError!)
    }
   return fetchedResult
}

func displayRecords(fromFetchedRecords result:Array<AnyObject>) {
    print("Total records:\(result.count)")
    if (result.count > 0) {
        for data in result {
        let dashboard = data as! NSManagedObject
        print("Value: \(dashboard.valueForKey("count"))")
        }
    }
}

Adding my data model here

I will share the data insertion code also.
func saveDashBoardData(dictionary: Dictionary<String, String>) {
    print(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask))

    //Create Manage Object
    let entityDescription: NSEntityDescription = NSEntityDescription.entityForName("Dashboard", inManagedObjectContext: self.managedObjectContext)!
    for data in dictionary {
        let dashboardObject = Dashboard(entity: entityDescription,insertIntoManagedObjectContext: self.managedObjectContext)
        dashboardObject.type  = data.0
        dashboardObject.count = data.1
        do {
            try self.managedObjectContext.save()
            print("Data saved succesfully")
        }
        catch {
            print(error)
        }
    }
}

A: The issue is that AppDelegate() creates always a new instance of the class which is not the same as the "hard-coded" delegate instance of the application.
You have to write
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let fetchedRecords = appDelegate.fetchRecords(fromEntity: "Dashboard")
appDelegate.displayRecords(fromFetchedRecords: fetchedRecords)

Since you have created a custom subclass of NSManagedObject use it as type rather than NSManagedObject or – worse – the unspecified AnyObject. It makes many things much easier:
func fetchRecords(fromEntity entity:String) -> [Dashboard] {
  let fetchRequest = NSFetchRequest()
  let entityDescription = NSEntityDescription.entityForName(entity, inManagedObjectContext: self.managedObjectContext)!
  fetchRequest.entity = entityDescription
  do {
     return try self.managedObjectContext.executeFetchRequest(fetchRequest) as! [Dashboard]
  } catch let fetchError as NSError {
     print(fetchError!)
  }
  return [Dashboard]()
}

func displayRecords(fromFetchedRecords result:[Dashboard]) {
    print("Total records:\(result.count)")

    for dashboard in result { // the check for empty is not needed
       print("Value: \(dashboard.count)")
    }
}

A: Try this one..
let dashboard = Dashboard as! NSManagedObject

print("Value: \(dashboard.count)")

I think it might work. Because you have taken your ManagedObject as data. Better you take it as kind of Dashboard. So that you can access count by dashboardObj.count ..
Hope you created Core Data NSManagedSubclass for the Entity.
Hope it helps..

A: Create a NSManagedObject subclass of Dashboard from your coredata model.
func displayRecords(fromFetchedRecords result:Array<AnyObject>) {

    print("Total records:\(result.count)")
    if (result.count > 0) {
        for data in result {
        let dashboard = data as! Dashboard
        print("Value: \(dashboard.valueForKey("count"))")
        }
    }
}

Key change here is   let dashboard = data as! Dashboard.
Dashboard is managed object subclass which you need to create with core data model help.


text:
Q: How to count common characters in two strings in JavaScript? Given two strings s1 and s2 consisting of lowercase English alphabets, the task is to count all the pairs of indices (i, j) from the given strings such that s1[i] = s2[j] and all the indices are distinct i.e. if s1[i] pairs with some s2[j] then these two characters will not be paired with any other character.
Input: s1 = 'abcd', s2 = 'aad'
Output: 2

Input: s1 = 'geeksforgeeks', s2 = 'platformforgeeks'
Output: 8

I tried to like this:

function getSameCount(str, str2) {
  var o = {},
    o2 = {};
  for (var i = 0; i < str.length - 1; i++) {
    if (str[i] in o) {
      o[str[i]] = parseInt(o[str[i]] + 1)
    } else {
      o[str[i]] = 0
    }
  }
  console.log(o);

  for (var i = 0; i < str2.length - 1; i++) {
    if (str[i] in o2) {
      o2[str[i]] = parseInt(o2[str[i]] + 1)
    } else {
      o2[str[i]] = 0
    }
  }

  console.log(o2);
}

getSameCount('abcd', 'aad')

A: Use for..in loop and includes method

var s1 = "abcd";
var s2 = "aad";

function match(s1, s2) {
    var count = 0;

    for(let i in s1) {
        s2.includes(s1[i]) ? count++ : false;
    }

    return count;
}

console.log(match(s1,s2));

A: We can convert the second input string to an array, then the next step is to iterate over the first input string and find a match in the second input string's character array.
If a match is found, increment the counter and remove that character from the second input string's character array so that it is not considered in the next match:

//Solution:
function getSameCount(str1, str2) {
  let count = 0;
  const obj = str2.split("");
  for(str of str1){
    let idx = obj.findIndex(s => s === str);
    if(idx >= 0){
      count++;
      obj.splice(idx, 1);
    }
  }
  return count;
}

//Test:
console.log(getSameCount("abcd", "aad"));
console.log(getSameCount("geeksforgeeks", "platformforgeeks"));
console.log(getSameCount("aad", "abcd"));
console.log(getSameCount("platformforgeeks", "geeksforgeeks"));

A: You can create a custom method on the array and find the number of characters which are common in all the words. Below steps are list of procedure to find the common characters in all the string

*

*Create a prototype method on Array , findCommonWord in this case.

*This method accepts an array of string, so input will be like
[ "abcd", "aad","geeksforgeeksda","platdformforgeeks"].findCommonWord()

*First step is to modify the input, to remove duplicate characters from a string using Set then sort it by ascending order of the length of string. This is because number of loop will be least if we have to find common character , that also have to present in string with least length.

*Then create a new array  with out the first string and split the first string. split will create a new array and iterate over it and check if this character is present in rest of the string.

var s1 = "abcd",
  s2 = "aad",
  s3 = "geeksforgeeksda",
  s4 = "platdformforgeeks";

Array.prototype.findCommonWord = function() {
  let tempArray = this.map(function(item) {
    return [...new Set(item.split(''))].join('');
  }).sort(function(a, b) {
    return a.length - b.length
  })

  let count = 0;
  let firstElm = tempArray[0].split('');
  let restElem = tempArray.splice(1);
  let countObject = {}

  for (let i = 0; i < firstElm.length; i++) {
    let z = findIfIncludes(restElem, firstElm[i]);
    if (z.length === restElem.length) {
      countObject[firstElm[i]] = 1;
    } else {
      countObject[firstElm[i]] = 0
    }
  }

  function findIfIncludes(arr, char) {
    return arr.filter(item => item.includes(char))
  }
  console.log(countObject)
  let totalCount = 0;
  for (let keys in countObject) {
    if (countObject[keys] > 0) {
      totalCount += 1;
    }
  }
  return totalCount;
};
console.log([s1, s2, s3, s4].findCommonWord());

A: function numberOfSameChars(s1, s2) {
    let obj = {};
    let counter = 0;
    for (let i=0; i<s1.length; i++){
        if(s1[i] in obj) {
            obj[s1[i]]++;
        } else {
            obj[s1[i]] = 1;
        }
    }
    for (let i=0; i<s2.length; i++) {
        if(s2[i] in obj && obj[s2[i]] > 0) {
            obj[s2[i]]--;
            counter++;
        }
    }
    return counter;
}

A: Try this code:
function countMatch(s1,s2){
    var count = 0;
    while(s1.length && s2.length){
        if(s2.includes(s1.charAt(0))){
            count++;
            s2 = s2.replace(s1.charAt(0),"");
            s1 = s1.slice(1);
        }
        else {
            s1 = s1.slice(1);
        }
    }
    return count;
}

console.log(countMatch("abcd","aad"));
//2

A: I used objects to do this, and I was kind of curious about there being another way, as I wanted to take an algorithmic approach as well, but whatever works works.
Anyways, here's the code:
function commonCharacterCount(s1, s2) {
  let string1Counter = {};
  let string2Counter = {};
  let commonCount = 0;
  for(let i = 0; i < s1.length; i++){
      if(!string1Counter.hasOwnProperty(s1[i])){
        string1Counter[s1[i]] = 0;
      }
      string1Counter[s1[i]]++;
  }
  for(let i = 0; i < s2.length; i++){
      if(!string2Counter.hasOwnProperty(s2[i])){
        string2Counter[s2[i]] = 0;
      }
      string2Counter[s2[i]]++;
  }
  for(let key in string1Counter){
     if(string2Counter.hasOwnProperty(key)){
       if(string1Counter[key] < string2Counter[key]){
           commonCount += string1Counter[key];
       }
       else{
           commonCount += string2Counter[key];
       }
     }
  }
  return commonCount;
}

The logic is basically to just save all of the characters of each string and their count,check for similarities, and compare the count of common characters. Whichever has the fewer amount of common characters will be the amount shared by both.
O(3N) time complexity, O(2N) space complexity (because of the stored objects).
I guess I can also do "delete object" but seems redundant on just an algorithm IDE because it's not like it's running on a server for any extended period of time.

A: function commonSameCount(s1, s2) {
    var s1Array = s1.split("");
    var s2Array = s2.split("");
    var count = 0;
    let index = 0;

    s1Array.filter(s1 => {
        index = s2Array.findIndex(s2 => s2 == s1);
        if(index >= 0){
            count++;
            s2Array.splice(index, 1);
        }
    });
    return count;
}

A: A simple solution using Regex:
index.js
function getSameCount(s1,s2) {

  for (let i in s2) {
    s1 = s1.replace(s2[i], "1")
  }
  const result = s1.replace(/[^1]/g, '').length

  return result
}


text:
Q: Using Node.js with Gulp, Babel, Webpack? Some Node.js projects use things like Babel, Gulp, Webpack. Other Node.js projects don't use such things. Do I have to use them in my Node.js projects and why? Perhaps you know different cases when I should take one of these decision?

A: No, you do not need.
Webpack is a bundler, it is intended to help packing up multiple files into one single file. Throughout this process you can transpile the code to apply modifications on it, eg: convert from es6 to es5 (if needed).
To transpile your code from es6 to es5, you are going to need babel, where you can do a lot of stuff with that.
Gulp is a task runner/manager, not used that often since most of people use webpack nowadays. But still useful for a bunch of stuff.
If you are going to develop pure node.js projects, you don't have to worry about this. For web you should be aware of all of these tools.

A: I've found Babel, Gulp, Webpack can be used in Node.js projects with cases:

*

*you need to minimize production code.

*you'd like to use all ES6+ features (like 'export' and 'import', decorators).

*you want to use JavaScript extensions like TypeScript.

*If for some reason your project contains  .js files are intended to run in different environments (Node.js, casperjs, browsers), you would like to use ES6+ inside all .js files.


text:
Q: Como organizar o código PHP e HTML para fazer um e-commerce? Estou fazendo um e-commerce e terminei de fazer o planejamento do site. O site terá que ser feito cadastro antes de se fazer a compra dos produtos, que será feita usando o PayPal.
Minha dúvida é: eu faço as páginas com o login e sem login em HTML e depois coloco o PHP, ou eu faço o PHP e coloco o HTML dentro do PHP?

A: Leonardo, realmente de fato, a ordem dos fatores não irá alterar o resultado final de seu projeto, porém para melhor visualização e identação de seu código, melhor que seja HTML no PHP quando o PHP predomine no arquivo em questão e vice-versa.

A: Em termos de ordem, a única que deves ter em mente é a própria estrutura. Separar os scripts PHP dos HTML, e assim por diante.
Deves também ter em mente que os scripts HTML serão apenas responsáveis pelo conteúdo estático, se dizes tu que isto se trata de uma loja online, não tem porque forçares o uso de HTML e JS para tarefas do PHP, e do mesmo jeito, não há razões para forçar o PHP a gerar grandes quantidades de código  HTML, visto que podes usar, e recomendo que uses ficheiros com a extensão .php, mesmo que estes sejam responsáveis apenas pelo formulário de login, creio que alguns bytes não vão fazer tanta diferença.
De qualquer das formas não estarias propriamente a organizar o teu código, estarias era a organizar os ficheiros. Para organizar os códigos recomendo que utilizes classes ou simplesmente funções, por se tratar de uma loja online toda a segurança é pouca, apenas lembra-te disto.
Se quiseres, e com certeza vais querer aperfeiçoar a estrutura, deves então usar estruturas já prontas, porque além de terem sido programadas por profissionais, já milhares de pessoas as avaliaram, ou então se preferires ir à antiga, vais ter de fazer muito mais esforço do que escolher onde colocar o formulário de login.


text:
Q: Creating a method to increase 4 family members age by 1 I am trying to create a method that increases the family age by one. Passing arguments to method is extremely difficult for me, especially with this problem. I believe there is a better way of doing this, but this is the only way that can come to mind. I am currently having trouble trying to display all 4 of the families age into one label, after their age is increased by one. This is currently what I have:
// Create a method using the increment operator that increates the age of 4 family members by 1
private void TotalAge (int age1/*, int age2, int age3, int age4*/)
{
    age1++;
   /* age2++;
    age3++;
    age4++; */
}

private void calculateButton_Click(object sender, EventArgs e)
{
    // Variables to hold family member ages
    int member1 = 0, member2 = 0, member3 = 0, member4 = 0;

    // Conver the ages into a string, using tryparse method
    if (int.TryParse(ageTextBox1.Text, out member1))
    {
        if (int.TryParse(ageTextBox2.Text, out member2))
        {
            if (int.TryParse(ageTextBox3.Text, out member3))
            {
                if (int.TryParse(ageTextBox4.Text, out member4))
                {
                    displayAge.Text = Convert.ToString(TotalAge(member1))
                }
            }
        }
    }
}

A: you should create a FamilyMember class that will contain all the properties of a family member (age, name, etc.) then you simply pass a list or an array of family members to a function that will increment in 1  the age of every FamilyMember in the array.
Public class FamilyMember
{
    public string Name {private set; get;}
    public int Age { private set; get; }

    public FamilyMember(string name, int age)
        {
            Name = name;
            Age = age;
        }
    public void IncrementAge()
    {
        Age++;
    }
}

Public void IncrementAgeOfFamilyMembers(List<FamilyMember> FamilyMembers)
{
     foreach (var fmember in FamilyMembers)
         fmember.IncrementAge();
}

if you want it to be for exactly 4 family members just change the List<FamilyMember> to FamilyMember[4] (but then you should check for nulls)


text:
Q: Creating a seperator in react native I'm trying to create a separator line between text.
Here is my Separator component
import { View, StyleSheet } from "react-native";

const Seperator = () => {
  return <View style={styles.seperator} />;
};

const styles = StyleSheet.create({
  seperator: {
    borderBottomColor: "red",
    borderBottomWidth: StyleSheet.hairlineWidth,
    marginVertical: 1,
  },
});

export default Seperator;

Here is the settings screen I'm trying to use seperator.
import { View, Text, StyleSheet } from "react-native";
import Seperator from "../components/Seperator";

const SettingsScreen = () => {
  return (
    <View style={styles.container}>
      <Text>I'm a SettingsScreen</Text>
      <Seperator />
      <Text>I'm a SettingsScreen</Text>
      <Seperator />

      <Text>I'm a SettingsScreen</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "blue",
  },
});

export default SettingsScreen;

I have done many searches but could not find a solution.

A: Try this in your Separator component
const styles = StyleSheet.create({
  seperator: {
    height: 1,
    backgroundColor: "red",
    marginVertical: 1,
  },
});

or you can give
I added height + you can give height: StyleSheet.hairlineWidth and removed borderBottomColor: "red"
I hope that helps.


text:
Q: How to modify plist in swift I want to be able to modify values from my plist in swift but I'm having trouble figuring it out. So far I can read the values in my array but that's it.
var playersDictionaryPath = NSBundle.mainBundle().pathForResource("PlayersInfo", ofType: "plist")

var playersDictionary = NSMutableDictionary(contentsOfFile: playersDictionaryPath!)

var playersNamesArray = playersDictionary?.objectForKey("playersNames")? as NSArray

[println(playersNamesArray)][1]

A: Firstly, you can't write to a plist file inside your app resources. So you will need to save your edited plist to another directory. Like your NSDocumentDirectory.
As in this answer mentioned you can get the document-path like that:
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString

But to answer your question, you can edit an NSMutableDictionary like that:
//add entries:
playersDictionary.setValue("yourValue", forKey: "yourKey")

//edit entries:
playersDictionary["yourKey"] = "newValue" //Now has value 'newValue'

//remove entries:
playersDictionary.removeObjectForKey("yourKey")

If you want to edit your NSArray on the other hand, you should use an NSMutableArray instead.

A: I found how to do it:
    var playersDictionaryPath = NSBundle.mainBundle().pathForResource("PlayersInfo", ofType: "plist")

    var playersDictionary = NSMutableDictionary(contentsOfFile: playersDictionaryPath!)

    var playersNamesArray = playersDictionary?.objectForKey("playersNames")? as NSMutableArray

    //this is a label I have called player1Name
    playersNamesArray[0] = "\(player1Name.text)"

    playersDictionary?.writeToFile(playersDictionaryPath!, atomically: true)

btw, thanks for the NSMutableArray, I wasn't thinking about that.


text:
Q: How to find maximal number of Fourier terms in ARIMA with harmonic regressors? I'm trying to forecast future load and renewable load factors of the French power system.
I have a database of 61368 hourly observations (8 years * 8760 hours or so) from 2012 to 2018 for each variable (Consumption, Wind load factor, PV load factor). I want to use these past observations to forecast them until 2024.
To do this, I read from Hyndman's book that I could use an ARIMA model with Fourier terms as aggressors since my variables present multiple seasonalities and periods over 200 (at least for the annual seasonality).
The problem I have is to find the optimal number of K's aka number of Fourier terms in a reasonable amount of time.
I tried to use auto.arima(consumption, seasonal = FALSE, xreg = fourier(consumption, K = c(12, 84, 4380), h = 8760*6)) but it takes hours to solve.
So here's what I'm trying now :
#Creating msts objects for main variables
demand <- msts(dataset$Consommation, seasonal.periods = c(24,168,8760))

#Seasonality detection for main variables
ndiffs(demand)
p_demand <- periodogram(demand)
data.table(period=1/p_demand$freq, spec=p_demand$spec)[order(-spec)][1:2]

#Splitting time series into train and test sets
train_demand <- ts(demand[1:55230])
test_demand <- demand[55231:61368]

#Creation of a base model
fit0_demand <- auto.arima(train_demand)
(bestfit_demand <- list(aicc=fit0_demand$aicc, i=0, j=0, fit_demand=fit0_demand))

#Forecasting and ploting base model
fc0_demand <- forecast(fit0_demand, h= 8760*6)
plot(fc0_demand)

#Choosing the best maximal number of Fourier terms by AICc
for (i in 1:5) {
   for (j in 1:5) {
      z1_demand <- fourier(ts(train_demand, frequency = 8777.143), K = i)
      z2_demand <- fourier(ts(train_demand, frequency = 24), K = j)
      fit_demand < auto.arima(train_demand, xreg = cbind(z1_demand,z2_demand), seasonal = FALSE)

        if(fit_demand$aicc < bestfit_demand$aicc){
            bestfit_demand <- list(aicc=fit_demand$aicc,i=i,j=j, fit_demand=fit_demand)
    }
  }
}
bestfit_demand

#Forecasting with best fits
fc_demand <- forecast(bestfit_demand$fit, xreg=cbind(fourier(ts(train_demand, frequency = 8777.143), K = bestfit_demand$i, h = 6*8760), fourier(ts(train_demand, frequency = 24), K = bestfit_demand$j, h = 6*8760)))
plot(fc_demand)

Actually there are no error messages but my for loop take hours and hours (I launched the code 17h ago and still working on the loop) to solve. Is there any faster way to to this ? I have an i5, 8GB RAM laptop btw.
Thanks for the help !
PS : I didn't include the loading packages and data code parts.


text:
Q: Issue saving data in Excel I just want save data in Excel, I found this code and it worked perfectly:
import xlsxwriter

# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook('zzzzz.xlsx')
worksheet = workbook.add_worksheet()

date = "17/08/2015"
bill = 001
item = "something"
customer = "Luis"
price = 100

# Start from the first cell. Rows and columns are zero indexed.
row = 0
col = 0

# Iterate over the data and write it out row by row.

worksheet.write(row, col, date )
worksheet.write(row, col + 1, bill)
worksheet.write(row, col + 2, item )
worksheet.write(row, col + 3, customer )
worksheet.write(row, col + 4,price)

workbook.close()

The problem I have are when I try to save info with spaces, if:
customer = "JOSE LUIS FEBRERO LOPEZ"

error:
    >>>

Traceback (most recent call last):
  File "C:\Python27\crearexcel.py", line 28, in <module>
    workbook.close()
  File "C:\Python27\lib\site-packages\xlsxwriter\workbook.py", line 296, in close
    self._store_workbook()
  File "C:\Python27\lib\site-packages\xlsxwriter\workbook.py", line 520, in _store_workbook
    xml_files = packager._create_package()
  File "C:\Python27\lib\site-packages\xlsxwriter\packager.py", line 140, in _create_package
    self._write_shared_strings_file()
  File "C:\Python27\lib\site-packages\xlsxwriter\packager.py", line 280, in _write_shared_strings_file
    sst._assemble_xml_file()
  File "C:\Python27\lib\site-packages\xlsxwriter\sharedstrings.py", line 53, in _assemble_xml_file
    self._write_sst_strings()
  File "C:\Python27\lib\site-packages\xlsxwriter\sharedstrings.py", line 83, in _write_sst_strings
    self._write_si(string)
  File "C:\Python27\lib\site-packages\xlsxwriter\sharedstrings.py", line 110, in _write_si
    self._xml_si_element(string, attributes)
  File "C:\Python27\lib\site-packages\xlsxwriter\xmlwriter.py", line 122, in _xml_si_element
    self.fh.write("""<si><t%s>%s</t></si>""" % (attr, string))
  File "C:\Python27\lib\codecs.py", line 694, in write
    return self.writer.write(data)
  File "C:\Python27\lib\codecs.py", line 357, in write
    data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 11: ordinal not in range(128)

I tried to convert to string str(customer) but that doesn't work.
The only solution I found are replace spaces " " for "_"
Any idea how I can save data with spaces in Excel?
This all my code, I get all files from folder, later I convert to text, after extract some data and later I try to create a excel file.
I try to coding utf-8 but don`t work
# -*- coding: cp1252 -*-
# -*- coding: UTF-8 -*-
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from cStringIO import StringIO
import os
import xlsxwriter

# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook('zzzzz.xlsx')
worksheet = workbook.add_worksheet()

files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:

    z = 0

e = (len(files) - 1)

def convert_pdf_to_txt(path):
    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
    fp = file(path, 'rb')
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    password = ""
    maxpages = 0
    caching = True
    pagenos=set()
    fstr = ''
    for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages,    password=password,caching=caching, check_extractable=True):
        interpreter.process_page(page)

        str = retstr.getvalue()
        fstr += str

    fp.close()
    device.close()
    retstr.close()
    return fstr

row = 0
col = 0

while z<e:

    factura = files[z]
    #ejemplo 1

    string = convert_pdf_to_txt(factura)
    lines = list(filter(bool,string.split('\n')))
    custData = {}
    for i in range(len(lines)):
        if 'EMAIL:' in lines[i]:
            custData['Name'] = lines[i+1]
        elif 'FACTURA' in lines[i]:
            custData['BillNumber'] = lines[i+1]
        elif 'Vencimientos:' in lines[i]:
            custData['price'] = lines[i+2]
        elif 'Banco:' in lines[i]:
            custData['paymentType'] = lines[i+1]

    #ejemplo 2
    txtList = convert_pdf_to_txt(factura).splitlines()
    nameIdx, billNumIdx, priceIdx, expirDateIdx, paymentIdx = -1, -1, -1, -1, -1

    for idx, line in enumerate(txtList):
        if line == "EMAIL: buendialogistica@gmail.com":
            nameIdx = idx +2 # in your example it should be +2...

        if line == "FACTURA":
            billNumIdx = idx + 1

        if "Vencimientos:" in line:
            priceIdx = idx + 2
            expirDateIdx = idx + 1

        if "Banco:" in line:
            paymentIdx = idx + 1

    name = txtList[nameIdx] if nameIdx != -1 else ''
    billNum = txtList[billNumIdx] if billNumIdx != -1 else ''
    price = txtList[priceIdx] if priceIdx != -1 else ''
    expirDate = txtList[expirDateIdx] if expirDateIdx != -1 else ''
    payment = txtList[paymentIdx] if paymentIdx != -1 else ''

    print expirDate

    billNum = billNum.replace("  ", "")

    print billNum

    custData['Name'] = custData['Name'].replace("Â", "")

    print custData['Name']

    custData['paymentType'] = custData['paymentType'].replace("Â", "")

    print custData['paymentType']

    print price
    nombre = str(custData['Name'])

    formadepago = custData['paymentType']

    z+=1
    columna2 = str(billNum) + ", " + nombre + ", " + formadepago

    worksheet.write(row, col, expirDate)
    worksheet.write(row, col + 1, columna2)
    worksheet.write(row, col + 2, price)
    row+=1

workbook.close()

Hi,
I add this code after all import.... and now I'm able to save nonbreaking space.
import sys
reload(sys)
sys.setdefaultencoding('Cp1252')

A: sys.setdefaultencoding('Cp1252') - this is a nasty fix-all hack. It masks other issues and makes your code brittle and platform specific.
"JOSE LUIS FEBRERO LOPEZ" contains a Windows-1252 encoded Non-breaking space (0xA0).
xlsxwriter requires that you pass Unicode objects when using non-ASCII characters. In fact, it's good practice to use Unicode objects for all strings.
Create a Unicode object by appending a u to the front of the string:
u"JOSE LUIS FEBRERO LOPEZ"

As your Python source code is encoded as Windows-1252, you will need to add the following to the top of your source file:
# coding=cp1252

This will tell Python how to decode the strings in your source file into Unicode objects.

A: You could try and set the encoding of your script to utf-8 by including
# coding=utf-8

as the first line. Then you can set the string encoding to utf-8 by adding a small letter u in front of it:
customer = u"JOSE LUIS FEBRERO LOPEZ"

Then it should even be possible to have non-ascii letters like Ñ in your text.
Or - as mentioned before - use normal spaces instead of non-breaking spaces (0xa0) in your text.


text:
Q: Question about divisors on curves. A divisor on a nonsingular irreducible projective curve $X$ is defined as a formal sum $D=\sum_{P\in X}n_P P$, with only finite nonzero $n_P$. If the curve is defined by $f$, and denotes its function field $K$. For any $z\in K$, we can define a divisor div$(z)=\sum_{P\in X} Ord_P(z) P$. And it's said that, since $z$ has only finite zeros and poles, this is a well defined divisor.
I am not sure why it has finite zeros? If we write $z=g/h$, $g,h \in \Gamma(X)$, then zeros can be written as V$(f,g)$, which is an algebraic set, thus is finite, right? Hope someone could help. Thanks!

A: First, one should require that the $z\in K$ be nonzero: taking $0$ certainly doesn't give you a finite number of zeros. Secondly, you're missing justification about why $V(f,g)$ should be finite. Clearly it's not true that if you just pick two homogeneous polynomials in three indeterminants, they determine a finite set of points in $\Bbb P^2$: consider $X$ and $XY$, for instance. (You're also missing an explanation of why you can talk about $V(f,g)$ - $f$ and $g$ belong to different rings here, so you need to explain how they end up in the same place. It can be done, but it's important to try to be clear about these things if you're not sure about them.)
The features of this problem do let us make this argument, though. From the condition that $C$ is irreducible, it's defining equation has to be irreducible as a polynomial in $k[x_0,x_1,x_2]$. Then, as $g$ is a nonzero element of the domain $k[x_0,x_1,x_2]/(f)$, it's not a zero-divisor, and any lift of it to a function $g'\in k[x_0,x_1,x_2]$ won't share any common factors with $f$. As $f$ and $g'$ share no common factor, the curves they determine in $\Bbb P^2$ don't share any common components, and by Bezout's theorem, they have a finite number of intersection points. As these intersection points exactly correspond to points on $C$ with $g=0$, there must be finitely many of them and we are finished.


text:
Q: r save multiple files with for error I have a big character vector and I want to split it into several small files.
The code I´m using is:
blogs<-file("./en_US.blogs.txt", open="rb")
blogData<-readLines(blogs, encoding="latin1")
nLines.blog<-NROW(blogData)
close(blogs)
quintil<-round(nLines.blog/19)
qBlog<-split(blogData, ceiling(seq_along(blogData)/quintil))
for(n in names(qBlog))
  write.table(qBlog[[n]],
              file = paste("qBlog",qBlog[[n]], ".txt"))

An I get the following error:

Error in file(file, ifelse(append, "a", "w")) :
    invalid 'description' argument
    In addition: Warning message:
    In if (file == "") file <- stdout() else if (is.character(file)) { :
      the condition has length > 1 and only the first element will be used

what I'm doing wrong?


text:
Q: How to execute Blackberry OS 6 app in Blackberry 10 OS I developed one application in Blackberry OS 6.I deployed that app in to Blackberry world successfully.But it is not working in Blackberry OS 10.I am getting following error:
Unsupported for this device
Please help me how to run application in OS 10.
Thanks in Advance.

A: OS10 is a completely different system.  It no longer supports the BB6/7 Java environment. You will need to port your app to one of the new supported platforms:
http://developer.blackberry.com/develop/platform_choice/index.html

*

*Cascades (c++ & qml)

*Webworks

*Android

*Adobe Air

A: With WebWorks it is possible to run your application in both BlackBerry 6 and BlackBerry 10, you may need to make some changes to your code, but it is certainly possible and there are plenty of resources available.
You can start from here.
Specifically BlackBerry states:

Your BlackBerry WebWorks app can be targeted to run on a variety of
BlackBerry device models or ported to a different OS, such as iOS or
Android.
Developing your app with BlackBerry WebWorks gives you the flexibility
to target users of the latest BlackBerry devices and those who are
using older models. Depending on the OS you want to target, versions
of the BlackBerry WebWorks SDK available for:

*

*BlackBerry 10

*BlackBerry PlayBook

*BlackBerry 7 and earlier

See here for a tutorial on creating an application which is able to work on old and new BB devices (Simple Hello World application).
A good article to look at can be found here, which explains some of the fundamentals and differences with webworks.


text:
Q: datepicker first date in array initial The purpose of this code is to include only the dates within the array and to activate the first date as initial in the datepicker.
I was able to get the first key of the array, which in the case is the first date I need to be as initial.
I believe the problem is in the format of the date, since it is deconfiguring the datepicker.
Follow my code:
JAVASCRIPT
// datepicker
var availableDates = {
"19102017": [
    "09:00",
    "09:15",
    "09:45",
    "11:45",
    "14:00"
],
"20102017": [
    "09:30"
],
"21102017": [
    "14:00"
],
"22102017": [
    "11:45"
],
"23102017": [
    "09:00"
],
"24102017": [
    "09:15"
],
"25102017": [
    "09:30"
],
"26102017": [
    "09:45"
],
"27102017": [
    "10:00"
],
"28102017": [
    "10:15"
]
};

getMinDate(Object.keys(availableDates)[0]);

function returnavailableDates(){
    return availableDates;
}
function getMinDate(date) {
    console.log(date);
    return date;
}

function checkDateis(d) {
    var check = false;
    $.each(availableDates, function( key, value ) {
        if (d === key) {
            check = true;
        }
    });
    if(check) return true;
}
function available(date) {
    var dmy = $.datepicker.formatDate('dmyy', date);
    var check = checkDateis(dmy);

    if (check) {
        return [true, "", "Available"];
    }
    else {
        return [false, "", "unAvailable"];
    }
}

$("#datepicker").datepicker({
    showOtherMonths   : true,
    selectOtherMonths : true,
    minDate           : 0,
    nextText          : '',
    prevText          : '',
    dateFormat        : 'dd-mm-yy',
    beforeShowDay     : available
})

.datepicker('setDate', getMinDate(Object.keys(availableDates)[0]))

fiddle for tests: https://jsfiddle.net/n2n4udkf/

A: Yes the problem is format of the date being passed to setDate.
You can fix the issue by formatting the date before passing it to setDate
function formatDate(date) {
    return date.slice(0,2) + '-' + date.slice(2,4) + '-' + date.slice(4);
}

$("#datepicker").datepicker({
    showOtherMonths   : true,
    selectOtherMonths : true,
    minDate           : 0,
    nextText          : '',
    prevText          : '',
    dateFormat        : 'dd-mm-yy',
    beforeShowDay     : available
})

.datepicker('setDate', formatDate(getMinDate(Object.keys(availableDates)[0])))

A: You should just change dateFormat in datepicker's init options:
$("#datepicker").datepicker({
    ...
    dateFormat        : 'ddmmyy',
    ...
})

Documentation: formatDate().
Added: Also, there is an error in available() function:
var dmy = $.datepicker.formatDate('dmyy', date);

It should be:
var dmy = $.datepicker.formatDate('ddmmyy', date);

It works now, because all of your date have two digits in both day and month components, but it will fail with dates like 01122017, for example: this function will produce 1122017 key and checkDateis(dmy) call will always return false.


text:
Q: Printing polar and trigonometric coordinates in Matlab I am trying to write a function which takes the value x and y in cartesian coordinates as the input and outputs the polar and trigonometric forms. I would like the output to contain the exponential and sin/cos rather than the actual value. For example, if the cartesian is z=1i, I would like the function to output z=sqrt(2)e^(ipi/4) and z=sqrt(2)(cos(pi/4)+Isin(pi/4). How can I do this?

function coordinates(x,y)
r=sqrt(x.^2+y.^2);
theta=atan(y./x);
polarcoord=rexp(itheta)
trigcoord=r*(cos(theta)+i*sin(theta))
end

This gives me the following output :
polarcoord =
1.0000 + 1.0000i
trigcoord =
1.0000 + 1.0000i
thanks

A: Welcome to SO! You are using functions (sqrt(x) calculates the actual square root of x, exp(x) the exponential, ... So that is why you get the actual value, not the formula expression.
So, a possible way to output the formula is using strings to print the functions without calling them. Then, what you need to do is calculate the values you want inside the sqrt() and the fraction which * pi and add them to a string array. We can do that using square brackets [ ], the function num2string() and the operator + to add strings in the same string array:
function coordinates(x,y)

[num,dem] = rat(atan(y./x)/pi);
    % rat converts theta to fraction
    % divide by pi to extract pi from theta

root = ["sqrt(" + num2str(x^2+y^2) + ")"]; % i.e "sqrt(2)"
pi_value = ["(" + num2str(num) + "*pi/" + num2str(dem) + ")"];
    % i.e "(1*pi/4)" o "(2*pi/5)"...

polarcoord = ["z = " + root + "e^(i" + pi_value]

trigcoord = ["z = " + root + "(cos" + pi_value + ")+i*sin" + pi_value]

end

Example:
coordinates(1,1)

Outputs:

polarcoord = "z = sqrt(2)e^(i(1*pi/4)"

trigcoord = "z = sqrt(2)(cos(1pi/4))+isin(1*pi/4)"

To calculate the fraction we use rat() function to obtain numerator and denominator from the double output of atan(y./x) and we divide by pi to extract its value from the theta value (we are representing pi already in the string).