text:
Q: What does git fetch exactly do? Edit: I have checked this What does FETCH_HEAD in Git mean?    before asking the question.
Sorry for the original inaccurate question.
My question is how does fetch really work?  Does fetch drop all current log?
This is my situation: my teammates and I are using the same repository which only has one branch. So we have to do fetch before push anything up.
We typically do it this way:
git status
git add .
git commit -m message1
git fetch origin
git reset head
git status
git add .
git commit -m message
git push

But after reset, it seems that my previous commit (with message1) is gone.
Is this normal or is there anything wrong?
How can I access my local history?
They are synced but my local history is gone.
Old staff ,forget it: I have been learning  Git CLI recently.
Someone told me to type "git fetch head" to keep track of remote branch.
But I wonder what does this do ? Does this command override my local log?
And what is the difference between "git fetch" and "git fetch head" ?

A: git fetch itself is really quite simple.  The complicated parts come before and after.
The first thing to know here is that Git stores commits.  In fact, this is essentially what Git is about: it manages a collection of commits.  This collection rarely shrinks: for the most part, the only thing you ever do with this collection of commits is add new commits.
Commits, the index, and the work-tree
Each commit has several pieces of information, such as the author's name and email address and a time-stamp.  Each commit also saves a complete snapshot of all the files you told it to: these are the files stored in your index (also known as your staging area) at the time you ran git commit.  This is also true of commits you obtain from someone else: they save the files that were in the other user's index at the time the other user ran git commit.
Note that each Git repository has just the one index, at least initially.  This index is linked with the one work-tree.  In newer Git versions, you can use git worktree add to add additional work-trees; each new work-tree comes with one new index/staging-area.  The point of this index is to act as an intermediate file-holder, situated between "the current commit" (aka HEAD) and the work-tree.  Initially, the HEAD commit and the index normally match: they contain the same versions of all the committed files.  Git copies the files from HEAD into the index, and then from the index into the work-tree.
It's easy to see the work-tree: it has your files in their ordinary format, where you can view and edit them with all the regular tools on your computer.  If you write Java or Python code, or HTML for a web server, the work-tree files are usable by the compiler or interpreter or web-server.  The files stored in the index, and stored in each Git commit, do not have this form and are not usable by the compilers, interpreters, web-servers, and so on.
One other thing to remember about commits is that once a file is in a commit, it cannot be changed.  No part of any commit can ever change.  A commit is therefore permanent—or at least, permanent unless it is removed (which can be done but is difficult and usually undesirable).  What is in the index and work-tree, however, can be modified at any time.  This is why they exist: the index is almost a "modifiable commit" (except that it's not saved until you run git commit), and the work-tree keeps the files in the form that the rest of the computer can use.1

1It's not necessary to have both the index and the work-tree.  The VCS could treat the work-tree as the "modifiable commit".  This is what Mercurial does; this is why Mercurial does not need an index.  This is arguably a better design—but it's not the way Git works, so when using Git, you have an index.  The presence of the index is a large part of what makes Git so fast: without it, Mercurial has to be extra-clever, and is still not as fast as Git.

Commits remember their parent; new commits are children
When you make a new commit by running git commit, Git takes the index contents and makes a permanent snapshot of everything that is in it right at that point.  (This is why you must git add files: you copy them from your work-tree, where you have changed them, back into your index, so that they are ready to be "photographed" for the new snapshot.)  Git also collects a commit message, and of course uses your name and email address and the current time, to make the new commit.
But Git also stores, in the new commit, the hash ID of the current commit.  We say that the new commit "points back to" the current commit.  Consider, for instance, this simple three-commit repository:
A <-B <-C   <-- master (HEAD)

Here we say that the branch name master "points to" the third commit, which I have labeled C, rather than using one of Git's incomprehensible hash IDs like b06d364....  (The name HEAD refers to the branch name, master.  This is how Git can turn the string HEAD into the correct hash ID: Git follows HEAD to master, then reads the hash ID out of master.)  It's commit C itself that "points to"—retains the hash ID of—commit B, though; and commit B points to commit A.  (Since commit A is the very first commit ever, there is no earlier commit for it to point to, so it doesn't point anywhere at all, which makes it a bit special.  This is called a root commit.)
To make a new commit, Git packages up the index into a snapshot, saves that with your name and email address and so on, and includes the hash ID of commit C, to make a new commit with a new hash ID.  We will use D instead of the new hash ID since we don't know what the new hash ID will be:
A <-B <-C <-D

Note how D points to C.  Now that D exists, Git alters the hash ID stored under the name master, to store D's hash ID instead of C's.  The name stored in HEAD itself does not change at all: it's still master.  So now we have this:
A <-B <-C <-D   <-- master (HEAD)

You can see from this diagram how Git works: given a name, like master, Git simply follows the arrow to find the latest commit.  That commit has a backwards arrow to its earlier or parent commit, which has another backwards arrow to its own parent, and so on, throughout all its ancestors leading back to the root commit.
Note that while children remember their parents, the parent commits do not remember their children.  This is because no part of any commit can ever change: Git literally can't add the children to the parent, and it does not even try.  Git must always work backwards, from newer to older.  The commit arrows all automatically point backwards, so normally I do not even draw them:
A--B--C--D   <-- master (HEAD)

Distributed repositories: what git fetch does
When we use git fetch, we have two different Gits, with different—but related—repositories.  Suppose we have two Git repositories, on two different computers, that both start out with those same three commits:
A--B--C

Because they start out with the exact same commits, these three commits also have the same hash IDs.  This part is very clever and is the reason the hash IDs are the way they are: the hash ID is a checksum2 of the contents of the commit, so that any two commits that are exactly identical always have the same hash ID.
Now, you, in your Git and your repository, have added a new commit D.  Meanwhile they—whoever they are—may have added their own new commits.  We'll use different letters since their commits will necessarily have different hashes.  We'll also look at this mostly from your (Harry's) point of view; we'll call them "Sally".  We'll add one more thing to our picture of your repository: it now looks like this:
A--B--C   <-- sally/master
       \
        D   <-- master (HEAD)

Now let's assume that Sally made two commits.  In her repository, she now has this:
A--B--C--E--F   <-- master (HEAD)

or perhaps (if she fetches from you, but has not yet run git fetch):
A--B--C   <-- harry/master
       \
        E--F   <-- master (HEAD)

When you run git fetch, you connect your Git to Sally's Git, and ask her if she has any new commits added to her master since commit C.  She does—she has her new commits E and F.  So your Git gets those commits from her, along with everything needed to complete the snapshots for those commits.  Your Git then adds those commits to your repository, so that you now have this:
        E--F   <-- sally/master
       /
A--B--C
       \
        D   <-- master (HEAD)

As you can see, what git fetch did for you was to collect all of her new commits and add them to your repository.
In order to remember where her master is, now that you have talked with her Git, your Git copies her master to your sally/master.  Your own master, and your own HEAD, do not change at all.  Only these "memory of another Git repository" names, which Git calls remote-tracking branch names, change.

2This hash is a cryptographic hash, in part so that it's difficult to fool Git, and in part because cryptographic hashes naturally behave well for Git's purposes.  The current hash uses SHA-1, which was secure but has seen brute-force attacks and is now being abandoned for cryptography.  Git will likely move to SHA2-256 or SHA3-256 or some other larger hash.  There will be a transition period with some unpleasantness. :-)

You should now merge or rebase—git reset is generally wrong
Note that after you have fetched from Sally, it is your repository, and only your repository, that has all the work from both of you.  Sally still does not have your new commit D.
This is still true even if instead of "Sally", your other Git is called origin.  Now that you have both master and origin/master, you must do something to connect your new commit D with their latest commit F:
A--B--C--D   <-- master (HEAD)
       \
        E--F   <-- origin/master

(I moved D on top for graph-drawing reasons, but this is the same graph as before,
Your main two choices here are to use git merge or git rebase.  (There are other ways to do this but these are the two to learn.)
Merge is actually simpler as git rebase does something that involves the verb form of merging, to merge.  What git merge does is to run the verb form of merging, and then commit the result as a new commit that is called a merge commit or simply "a merge", which is the noun form of merging.  We can draw the new merge commit G this way:
A--B--C--D---G   <-- master (HEAD)
       \    /
        E--F   <-- origin/master

Unlike a regular commit, a merge commit has two parents.3  It connects back to both of the two earlier commits that were used to make the merge.  This makes it possible to push your new commit G to origin: G takes with it your D, but also connects back to their F, so their Git is OK with this new update.
This merge is the same kind of merge you get from merging two branches.  And in fact, you did merge two branches here: you merged your master with Sally's (or origin's) master.
Using git rebase is usually easy, but what it does is more complicated.  Instead of merging your commit D with their commit F to make a new merge commit G, what git rebase does is to copy each of your commits so that the new copies, which are new and different commits, come after the latest commit on your upstream.
Here, your upstream is origin/master, and the commits that you have that they don't is just your one commit D.  So git rebase makes a copy of D, which I will call D', placing the copy after their commit F, so that D''s parent is F.  The intermediate graph looks like this:5
A--B--C--D   <-- master
       \
        E--F   <-- origin/master
            \
             D'   <-- HEAD

The copying process uses the same merging code that git merge uses to do the verb form, to merge, of your changes from commit D.4  Once the copy is done, however, the rebase code sees that there are no more commits to copy, so it then changes your master branch to point to the final copied commit D':
A--B--C--D   [abandoned]
       \
        E--F   <-- origin/master
            \
             D'   <-- master (HEAD)

This abandons the original commit D.6  This means we can stop drawing it too, so now we get:
A--B--C--E--F   <-- origin/master
             \
              D'   <-- master (HEAD)

It's now easy to git push your new commit D' back to origin.

3In Git (but not Mercurial), a merge commit can have more than two parents.  This doesn't do anything you cannot do by repeated merging, so it's mainly for showing off. :-)
4Technically, the merge base commit, at least for this case, is commit C and the two tip commits are D and F, so in this case it's literally exactly the same.  If you rebase more than one commit, it gets a little more complicated, but in principle it's still straightforward.
5This intermediate state, where HEAD is detached from master, is usually invisible.  You see it only if something goes wrong during the verb-form-of-merge, so that Git stops and has to get help from you to finish the merge operation.  When that does occur, though—when there is a merge conflict during rebasing—it's important to know that Git is in this "detached HEAD" state, but as long as the rebase completes on its own, you don't have to care about this so much.
6The original commit chain is retained temporarily through Git's reflogs and via the name ORIG_HEAD.  The ORIG_HEAD value gets overwritten by the next operation that makes a "big change", and the reflog entry eventually expires, typically after 30 days for this entry.  After that, a git gc will really remove the original commit chain.

The git pull command just runs git fetch and then a second command
Note that after git fetch, you usually have to run a second Git command, either git merge or git rebase.
If you know in advance that you will, for certain, immediately use one of those two commands, you can use git pull, which runs git fetch and then runs one of those two commands.  You pick which second command to run by setting pull.rebase or supplying --rebase as a command-line option.
Until you are quite familiar with how git merge and git rebase work, however, I suggest not using git pull, because sometimes git merge and git rebase fail to complete on their own.  In this case, you must know how to deal with this failure.  You must know which command you actually ran.  If you run the command yourself, you will know which command you ran, and where to look for help if necessary.  If you run git pull, you may not even know which second command you ran!
Besides this, sometimes you might want to look before you run the second command.  How many commits did git fetch bring in?  How much work will it be to do a merge vs a rebase?  Is merge better than rebase right now, or is rebase better than merge?  To answer any of these questions, you must separate the git fetch step from the second command.  If you use git pull, you must decide in advance which command to run, before you even know which one is the one to use.
In short, only use git pull after you're familiar with the way the two parts of it—git fetch, and the second command you choose—really work.

A: You don't have to do two separate commits, and git fetch won't drop any log.
 --o--o--o (origin/master)
          \
           x--x (master: my local commits)

What you should do is rebase your local commit on top of any new commit fetched by the git fetch command:
git fetch

--o--o--o--O--O (origin/master updated)
         \
          x--x (master)

git rebase origin/master

--o--o--o--O--O (origin/master updated)
               \
                x'--x' (master rebased)

git push

--o--o--o--O--O--x'--x' (origin/master, master)

Even simpler, since Git 2.6, I would use the config:
git config pull.rebase true
git config rebase.autoStash true

Then a simple git pull would automatically replay your local commits on top of origin/master. Then you can git push.


text:
Q: QGraphicsItem scaling produces too large bounding rect Problem: When using a QGraphicsItem with the flag QGraphicsItem::ItemIgnoresTransformations, the View does not scale properly and shows unnecessary scroll bars.
To reproduce, place a QGraphicsView on a Form and use this code:
#include <QGraphicsScene>
#include <QGraphicsTextItem>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QGraphicsScene* scene = new QGraphicsScene();

    // Set the scene to the view. Has to be done before
    // transformation in order for the problem to occur.
    ui->graphicsView->setScene(scene);

    // Add some text, make it transformation-invariant.
    QGraphicsTextItem* txt = scene->addText("Hello World!");
    txt->setFlag(QGraphicsItem::ItemIgnoresTransformations);

    // Scale the scene, re-calculate the bounding rect.
    ui->graphicsView->scale(10, 5);
    QRectF rect = scene->itemsBoundingRect();
    scene->setSceneRect(rect);
}

This also works with other Items like QGraphicsEllipseItem or QGraphicsRectItem.
Without setting the flag (simply comment out the line txt->setFlag...), the output is as expected:

However, when the flag is set, I would expect the scroll bar to disappear, because the text clearly fits into the view. But instead it looks like this:

I know that the Scene does only automatically grow, but not shrink to its content, so I am explicitly setting the Scene Rect at the end. But even this does not help.
It seems to me like this is a bug in Qt, but maybe I also simply misunderstood something. Any idea what the problem (and solution) is?
Using Qt 5.5, Ubuntu 14.04.
PS: Yes, the scene is never freed. This is of course no production code ;-)

A: I had a similar issue with addLine and addEllipse on top of an QImage.
The problem seems to come from the QGraphicsItem::ItemIgnoresTransformations flag that seems to enlarge the scene to hold the "transformed" object placement, but then ignores the transform for placement and size, however the damage is already done because it has incorrectly changed the scene scale.
I have a work-around that might be able to help you.
If you reset the scene scale to a known correct value after positioning the objects that ignore the transform. It will avoid your problem.
For example:
m_firstImageScene->setSceneRect(m_firstImageRect);

redpajama_set_name: RedPajamaStackExchange


text:
Q: how can I access S3 using jets3t? Hi, I'm trying to access S3 using jets3t library.
I just followed an sample code supported by AWS(here's url)
here's my simple code
import org.jets3t.service.S3Service;
import org.jets3t.service.S3ServiceException;
import org.jets3t.service.impl.rest.httpclient.RestS3Service;
import org.jets3t.service.model.S3Bucket;
import org.jets3t.service.security.AWSCredentials;

public class Test1 {

    /**
     * @param args
     */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    String awsAccessKey = "******************";
    String awsSecretKey = "*********************************";

    System.out.println("0");
    AWSCredentials awsCredentials = new AWSCredentials(awsAccessKey, awsSecretKey);

    try{
    S3Service s3Service = new RestS3Service(awsCredentials);

    System.out.println("1");

    S3Bucket testBucket = s3Service.getOrCreateBucket("first_test_bucket");
    System.out.println("Created test bucket: " + testBucket.getName());

    S3Bucket[] myBuckets = s3Service.listAllBuckets();

    System.out.println("2");

    System.out.println("How many buckets to I have in S3? " + myBuckets.length);

    System.out.println("3");

    }
    catch (Exception e){

        System.out.println("exception: " + e.toString());

    }

}

}
but I encountered an problem like this
0
15:24:39 DEBUG (service.Jets3tProperties - getBoolProperty:315) - s3service.https-only=true
15:24:39 DEBUG (service.Jets3tProperties - getIntProperty:297) - storage-service.internal-error-retry-max=5
15:24:39 DEBUG (service.Jets3tProperties - getIntProperty:297) - httpclient.connection-timeout-ms=60000
15:24:39 DEBUG (service.Jets3tProperties - getIntProperty:297) - httpclient.socket-timeout-ms=60000
15:24:39 DEBUG (service.Jets3tProperties - getBoolProperty:315) - httpclient.stale-checking-enabled=true
15:24:39 DEBUG (service.Jets3tProperties - getIntProperty:297) - httpclient.max-connections=20
15:24:39 DEBUG (service.Jets3tProperties - getIntProperty:297) - httpclient.max-connections-per-host=0
15:24:39 DEBUG (service.Jets3tProperties - getStringProperty:261) - httpclient.useragent=null
15:24:39 DEBUG (utils.RestUtils - initHttpConnection:320) - Setting user agent string: JetS3t/0.8.0 (Windows 7/6.1; x86; ko; JVM 1.6.0_20)
15:24:39 DEBUG (service.Jets3tProperties - getIntProperty:297) - httpclient.retry-max=5
15:24:39 DEBUG (service.Jets3tProperties - getLongProperty:279) - httpclient.connection-manager-timeout=0
15:24:39 DEBUG (service.Jets3tProperties - getStringProperty:261) - s3service.s3-endpoint=null
15:24:39 DEBUG (service.Jets3tProperties - getStringProperty:261) - s3service.default-storage-class=null
15:24:39 DEBUG (service.Jets3tProperties - getBoolProperty:315) - httpclient.proxy-autodetect=true
15:24:39 DEBUG (service.Jets3tProperties - getStringProperty:261) - s3service.s3-endpoint=s3.amazonaws.com
15:24:39 DEBUG (service.Jets3tProperties - getStringProperty:261) - devpay.user-token=null
15:24:39 DEBUG (service.Jets3tProperties - getStringProperty:261) - devpay.product-token=null
15:24:39 DEBUG (service.Jets3tProperties - getBoolProperty:315) - httpclient.requester-pays-buckets-enabled=false
1
15:24:39 DEBUG (service.Jets3tProperties - getStringProperty:261) - s3service.default-bucket-location=US
15:24:39 DEBUG (httpclient.RestStorageService - listAllBucketsImpl:1180) - Listing all buckets for user: AKIAI6TCJ7BDPCPTHV2A
15:24:39 DEBUG (service.Jets3tProperties - getBoolProperty:315) - s3service.disable-dns-buckets=false
15:24:39 DEBUG (service.Jets3tProperties - getStringProperty:261) - s3service.s3-endpoint=s3.amazonaws.com
15:24:39 DEBUG (service.Jets3tProperties - getStringProperty:261) - s3service.s3-endpoint-virtual-path=
15:24:39 DEBUG (service.Jets3tProperties - getIntProperty:297) - s3service.s3-endpoint-https-port=443
15:24:39 DEBUG (httpclient.RestStorageService - setupConnection:1053) - S3 URL: https://s3.amazonaws.com:443/
15:24:39 DEBUG (httpclient.RestStorageService - performRequest:340) - Performing GET request for 'https://s3.amazonaws.com/', expecting response codes: [200]
15:24:39 DEBUG (httpclient.RestStorageService - authorizeHttpRequest:591) - Adding authorization for Access Key 'AKIAI6TCJ7BDPCPTHV2A'.
15:24:39 DEBUG (service.Jets3tProperties - getStringProperty:261) - s3service.s3-endpoint=s3.amazonaws.com
15:24:39 DEBUG (httpclient.RestStorageService - authorizeHttpRequest:643) - Canonical string ('|' is a newline): GET|||Wed, 06 Apr 2011 06:24:39 GMT|/
15:25:01 DEBUG (utils.RestUtils$1 - retryMethod:345) - Retrying GET request with path '/' - attempt 1 of 5
15:25:01 DEBUG (httpclient.RestStorageService - authorizeHttpRequest:591) - Adding authorization for Access Key 'AKIAI6TCJ7BDPCPTHV2A'.
15:25:01 DEBUG (service.Jets3tProperties - getStringProperty:261) - s3service.s3-endpoint=s3.amazonaws.com
15:25:01 DEBUG (httpclient.RestStorageService - authorizeHttpRequest:643) - Canonical string ('|' is a newline): GET|||Wed, 06 Apr 2011 06:25:01 GMT|/
15:25:01  INFO (httpclient.HttpMethodDirector - executeWithRetry:439) - I/O exception (java.net.ConnectException) caught when processing request: Connection timed out: connect
15:25:01  INFO (httpclient.HttpMethodDirector - executeWithRetry:445) - Retrying request
15:25:22 DEBUG (utils.RestUtils$1 - retryMethod:345) - Retrying GET request with path '/' - attempt 2 of 5
15:25:22 DEBUG (httpclient.RestStorageService - authorizeHttpRequest:591) - Adding authorization for Access Key 'AKIAI6TCJ7BDPCPTHV2A'.
15:25:22 DEBUG (service.Jets3tProperties - getStringProperty:261) - s3service.s3-endpoint=s3.amazonaws.com
15:25:22 DEBUG (httpclient.RestStorageService - authorizeHttpRequest:643) - Canonical string ('|' is a newline): GET|||Wed, 06 Apr 2011 06:25:22 GMT|/
15:25:22  INFO (httpclient.HttpMethodDirector - executeWithRetry:439) - I/O exception (java.net.ConnectException) caught when processing request: Connection timed out: connect
15:25:22  INFO (httpclient.HttpMethodDirector - executeWithRetry:445) - Retrying request
15:25:43 DEBUG (utils.RestUtils$1 - retryMethod:345) - Retrying GET request with path '/' - attempt 3 of 5
15:25:43 DEBUG (httpclient.RestStorageService - authorizeHttpRequest:591) - Adding authorization for Access Key 'AKIAI6TCJ7BDPCPTHV2A'.
15:25:43 DEBUG (service.Jets3tProperties - getStringProperty:261) - s3service.s3-endpoint=s3.amazonaws.com
15:25:43 DEBUG (httpclient.RestStorageService - authorizeHttpRequest:643) - Canonical string ('|' is a newline): GET|||Wed, 06 Apr 2011 06:25:43 GMT|/
15:25:43  INFO (httpclient.HttpMethodDirector - executeWithRetry:439) - I/O exception (java.net.ConnectException) caught when processing request: Connection timed out: connect
15:25:43  INFO (httpclient.HttpMethodDirector - executeWithRetry:445) - Retrying request
    15:26:04 DEBUG (utils.RestUtils$1 - retryMethod:345) - Retrying GET request with path '/' - attempt 4 of 5
15:26:04 DEBUG (httpclient.RestStorageService - authorizeHttpRequest:591) - Adding authorization for Access Key 'AKIAI6TCJ7BDPCPTHV2A'.
15:26:04 DEBUG (service.Jets3tProperties - getStringProperty:261) - s3service.s3-endpoint=s3.amazonaws.com
15:26:04 DEBUG (httpclient.RestStorageService - authorizeHttpRequest:643) - Canonical string ('|' is a newline): GET|||Wed, 06 Apr 2011 06:26:04 GMT|/
15:26:04  INFO (httpclient.HttpMethodDirector - executeWithRetry:439) - I/O exception (java.net.ConnectException) caught when processing request: Connection timed out: connect
15:26:04  INFO (httpclient.HttpMethodDirector - executeWithRetry:445) - Retrying request
15:26:25 DEBUG (utils.RestUtils$1 - retryMethod:345) - Retrying GET request with path '/' - attempt 5 of 5
15:26:25 DEBUG (httpclient.RestStorageService - authorizeHttpRequest:591) - Adding authorization for Access Key 'AKIAI6TCJ7BDPCPTHV2A'.
15:26:25 DEBUG (service.Jets3tProperties - getStringProperty:261) - s3service.s3-endpoint=s3.amazonaws.com
15:26:25 DEBUG (httpclient.RestStorageService - authorizeHttpRequest:643) - Canonical string ('|' is a newline): GET|||Wed, 06 Apr 2011 06:26:25 GMT|/
15:26:25  INFO (httpclient.HttpMethodDirector - executeWithRetry:439) - I/O exception (java.net.ConnectException) caught when processing request: Connection timed out: connect
15:26:25  INFO (httpclient.HttpMethodDirector - executeWithRetry:445) - Retrying request
15:26:46 DEBUG (httpclient.RestStorageService - performRequest:538) - Releasing HttpClient connection after error: Connection timed out: connect
exception: org.jets3t.service.S3ServiceException: Request Error. GET '/'

I guess this is a problem about firewall since I'm excuting this code at my company. Does anybody knows this problem? help!

A: In your - not so easy to read - log there are some  "Connection timed out: connect exception: ...". So, yes, it may be because you are behind a proxy (Amazon S3 Rest services listen on port 443).
You may want to configure JetS3t to use a proxy.
Create a jets3t.properties property file and add the following properties:
httpclient.proxy-host=your proxy host
httpclient.proxy-port=your proxy port
httpclient.proxy-user=proxy user
httpclient.proxy-password=password

more info here: http://jets3t.s3.amazonaws.com/toolkit/configuration.html#jets3t
Also, please note that there is a somehow stable S3 test stub that you can use for testing:
https://github.com/technoweenie/parkplace

A: You need to set the Jets3t configurations in a text file format and give the Jets3t class properties as follows:
Jets3tProperties jets3=new Jets3tProperties();
jets3.loadAndReplaceProperties(new FileInputStream("/root/Desktop/jets3t.properties"), "jets3t.properties");


text:
Q: Xamp mysql already running
When xamp starts mysql shows already running..
I cant access mysql. what will do
when access php myadmin it shows #2002 - Connection refused
The server is not responding (or the local server's socket is not correctly configured).


text:
Q: Memory leak with Fragment and data binding LeakingInstance(referenceKey=1e607240-1c36-4bf0-a385-980207f9b712, referenceName=, instanceClassName=com.test.android.dashboard.DashboardFragment, watchDurationMillis=5191, excludedLeak=false, leakTrace=
┬
├─ android.widget.Toast
│    Leaking: NO (it's a GC root)
│    ↓ Toast.mContext
├─ com.test.android.main.MainActivity
│    Leaking: NO (Activity#mDestroyed is not true)
│    ↓ MainActivity.contentView
├─ com.test.android.views.FragmentContainerLayout
│    Leaking: NO (View#mAttachInfo is not null)
│    View.mID=R.id.content (2131362081)
│    View.mWindowAttachCount=1
│    ↓ FragmentContainerLayout.mPreSortedChildren
│                              ~~~~~~~~~~~~~~~~~~
├─ java.util.ArrayList
│    Leaking: UNKNOWN
│    ↓ ArrayList.elementData
│                ~~~~~~~~~~~
├─ java.lang.Object[]
│    Leaking: UNKNOWN
│    ↓ array Object[].[0]
│                     ~~~
├─ androidx.constraintlayout.widget.ConstraintLayout
│    Leaking: UNKNOWN
│    View.mID=R.id.dashboard (2131362134)
│    View.mWindowAttachCount=1
│    ↓ ConstraintLayout.mKeyedTags
│                       ~~~~~~~~~~
├─ android.util.SparseArray
│    Leaking: UNKNOWN
│    ↓ SparseArray.mValues
│                  ~~~~~~~
├─ java.lang.Object[]
│    Leaking: UNKNOWN
│    ↓ array Object[].[0]
│                     ~~~
├─ com.test.android.databinding.DashboardFragmentBindingImpl
│    Leaking: UNKNOWN
│    ↓ DashboardFragmentBindingImpl.mLifecycleOwner
│                                   ~~~~~~~~~~~~~~~
├─ androidx.fragment.app.Fragment$3
│    Leaking: UNKNOWN
│    Anonymous class implementing androidx.lifecycle.LifecycleOwner
│    ↓ Fragment$3.this$0
│                 ~~~~~~
╰→ com.test.android.dashboard.DashboardFragment
     Leaking: YES (Fragment#mFragmentManager is null)
, retainedHeapSize=null)```

A: This bug has been logged and is being worked on: https://issuetracker.google.com/issues/119661177


text:
Q: wordpress webpack javascript function not found from Theme my alertHi.js will be loaded but i cant use it from the Theme.
JS-Source alertHi.js:
this ( inc/Components/Darkmode/src/alertHi.js )
will be executed when i load the page:
function alertHi(){ alert('hi') }
alertHi();
console.log('is loaded');

But
html-Source
☀

creates this error:
Error: alertHi is not defined
but if i call the function alertHi() from the page i get Error:
Uncaught ReferenceError: alertHi is not defined
    onclick http://localhost/wordpress/:1

Any idea?
JS-Min-Source dist/alertHi.min.js:
webback has generated dist/alertHi.min.js
/******/ (() => { // webpackBootstrap
/******/    // The require scope
/******/    var __webpack_require__ = {};
/******/
/************************************************************************/
/******/    /* webpack/runtime/make namespace object */
/******/    (() => {
/******/        // define __esModule on exports
/******/        __webpack_require__.r = (exports) => {
/******/            if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/                Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/            }
/******/            Object.defineProperty(exports, '__esModule', { value: true });
/******/        };
/******/    })();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other entry modules.
(() => {
/*!*************************************************!*\
  !*** ./inc/Components/Darkmode/src/alertHi.js ***!
  \*************************************************/
function alertHi() {
  alert('alertHi says hello :)');
}
alertHi();
console.log('script loaded');
})();

// This entry need to be wrapped in an IIFE because it need to be in strict mode.
(() => {
"use strict";
/*!***************************************************!*\
  !*** ./inc/Components/Darkmode/src/alertHi.scss ***!
  \***************************************************/
__webpack_require__.r(__webpack_exports__);
// extracted by mini-css-extract-plugin

})();

/******/ })()
;
//# sourceMappingURL=alertHi.min.js.map

was reading before:

*

*Cannot call javascript function in wordpress

*Hiding Javascript Function File from WordPress Theme Footer
and tried a tip read here Cannot call javascript function in wordpress
but get the error jQuery is not defined
will also not be found if i using
(function($) {
    function alertHi(){
       alert('hi')
    }
})(jQuery);

A: webpack by default wraps all of the bundle internally, you can't access it externally unless explicitly setting it in the webpack config as a library.
you can also hack it out and add window.alertHi = alertHi in your js code but this is not recommended.
please refer to webpack's configuration API and set your bundle output to be a library. (preferably - UMD/commonjs library)

A: inspired by answers below this question ( Define global variable with webpack ) and this answer here https://stackoverflow.com/a/35825562/2891692 i found a solution:
Use the global window object
window.alertHi = function (){ alert('hi') }


text:
Q: Why do we refer to Lyapunov exponents as a characteristic of the system, telling us about its chaoticity, when it is only referred to a point? Lyapunov exponents are defined as indicators of the sensibility to initial conditions. In fact, they give the mean rate of exponential separation of trajectories. They are, however, specific of a given point, in which the Jacobian matrix that defines the exponent is indeed calculated, so I don't understand why we say that the fact that the exponent is positive can give us an information regarding the whole system, which we can say is therefore chaotic.

A: One way to think about this is that even though Lyapunov exponents of a system (say the iterates of a diffeomorphism or the flow of a first order ODE) are defined with reference to a basepoint at first, they can be considered as (partially defined) functions defined on the phase space $M$ with $d$ dimensions. Moreover, the classical Oseledets theorem guarantees that there is a subset $M_0$ of the phase space that is full measure with respect to any Borel probability measure invariant under the time evolution such that for any basepoint $x\in M_0$ Lyapunov exponents $\chi^1_x,\chi^2_x,...,\chi^{d}_x\in\mathbb{R}$ (possibly with multiplicity) are well-defined, and indeed uniquely defined by the system. Furthermore, considered as functions they are Borel measurable, and they are invariant under the time evolution.
For diffeomorphisms or flows a classical theorem by Krylov-Bogoliubov guarantees the existence of invariant Borel probability measures, and each such measure has a so-called "ergodic decomposition". With respect to such an ergodic measure one can take the integrals of the Lyapunov exponents (which are invariant measurable functions) to obtain numerical Lyapunov exponents (which are now attached to not only the dynamical system but to the dynamical system paired with a certain "optimal" way of observing it). In this way one can also keep the system fixed and vary the ergodic invariant measure to think of the Lyapunov exponents of the systems as functions that associate to each ergodic measure (one "optimal" way of observing) how surprising the observed behavior is.
Thus either by thinking of Lyapunov exponents as functions defined on the phase space, or as functions defined on the space of invariant ergodic measures, one can take them as global objects.

A: Your premise is not correct. When people speak of the Lyapunov exponent, they usually mean the largest Lyapunov exponent averaged along a given trajectory, such as a limit cycle or a chaotic attractor.
There are also local Lyapunov exponents, but even those are more intricate to be computed simply from the Jacobian of the dynamics.


text:
Q: trying to call a class but it gives me errors: actual and formal argument lists differ in length I created a class called PlacePiece which will be called in the Game class. but when I call it in Game Class it gives me the error:

actual and formal argument lists differ in length.

how do I fix it and what's causing it? I do not know how to fix it and been trying to solve it for eternity. I'm also new to coding so any feedback can help
public class Game {
    private Board gBoard;
    private PlacePiece placePiece;

    public Game() {
        gBoard = new Board();
        PlacePiece.placePiece();
   }
}

import java.util.Scanner;

public class PlacePiece {

    public void placePiece(char[][] gBoard) {

        System.out.print("Game has begun, please enter where you would like to place (1~9):");
        Scanner scan = new Scanner(System.in);
        int placement = scan.nextInt();

        System.out.println(placement);

        char piece = ' ';
        switch(placement){
            case 1: gBoard[0][0] = piece;
                break;
            case 2: gBoard[0][2] = piece;
                break;
            case 3: gBoard[0][4] = piece;
                break;
            case 4: gBoard[2][0] = piece;
                break;
            case 5: gBoard[2][2] = piece;
                break;
            case 6: gBoard[2][4] = piece;
                break;
            case 7: gBoard[3][0] = piece;
                break;
            case 8: gBoard[3][2] = piece;
                break;
            case 9: gBoard[3][4] = piece;
                break;
        }
        for(char[] row : gBoard){
            for(char c : row){
                System.out.print(c);
            }
            System.out.println();
        }
    }
}

A: You haven't actually initialized any PlacePiece variable and your method isn't static, so how do you want to call it? Also in your placePiece function you should pass char[][] gBoard, that you aren't passing.
My guess is that you are trying to make a game and don't know how, sou you just copied some function from internet without knowing the function.
So, in your Board class I bet that you have something like this:
public class Board {
    private char[][] board; // you should initialize it in constructor

    public char[][] getBoard() {
        return board;
    }
}

Then you should create your placePiece variable in Game class and use it:
public class Game {
    private Board gBoard;
    private PlacePiece placePiece;

    public Game() {
        gBoard = new Board();
        placePiece = new PlacePiece();
        placePiece.placePiece(gBoard.getBoard()); // you have to pass variable to placePiece() function
    }
}

I don't think you know, what you're doing otherwise you wouldn't have made these mistakes, so I highly recommend you taking some Java tutorial, so you have some foundation and then start doing more complex tasks.


text:
Q: Can you parameterize sort order in a sql server prepared statement? I've got a .Net web system with a VB.Net front end talking to a SQL Server 2005 back end over ADO.Net.  Essentially, what I want to do is this:
Dim command As SqlCommand = New SqlCommand("", connection)
command.CommandText = "SELECT * FROM someTable ORDER BY orderValue @SortOrder"
Dim sortParam As SqlParameter = New SqlParameter("@SortOrder", SqlDbType.varChar, 3)
sortParam.Value = "ASC"
command.Parameters.Add(sortParam)
command.Prepare()
reader = command.ExecuteReader()

Where the sort order would be passed in via a query string or some such.  This code throws  "Incorrect syntax near '@SortOrder'. Statement(s) could not be prepared."
Is this even possible, or do I have some really dumb syntax error I'm not seeing?
(And, yes, the client is only running .net 2.0, so LINQ-based solutions won't work, sadly.
Thanks, all!
Update / Response:
Well, that's what I thought.  Thanks for the sanity check, everybody.  (For some context, the command string is currently being built dynamically, but we're moving the system in a more prepared statement direction, and this was one of the edge cases I didn't know was possible.
Thanks again!

A: No, that won't work.
There are two possibilities that I can think of right off the top of my head to do what you're trying to do:

*

*Build the SQL string dynamically

*Return a Data Table from your query, and then use a View to do your sorting.

With another 6 years or so of experience (plus SQL Server Versions), I have a way of accomplishing this.
DECLARE @SortByIdASC AS INT;
SET @SortByIdASC = 1;
WITH cte AS (
SELECT Id, Foo, Bar
      , ROW_NUMBER() OVER (ORDER BY Id ASC) AS IdSortAsc
      , ROW_NUMBER() OVER (ORDER BY Id DESC) AS IdSortDesc
   FROM MyTable
)

SELECT Id, Foo, Bar
   FROM cte
   ORDER BY CASE WHEN @SortByIdASC = 1 THEN IdSortAsc
                 WHEN @SortByIdASC = 2 THEN IdSortDesc
                 ELSE ''
                 END
           , Foo, Bar

This also allows for Sorting up,down, or even excluding that particular column from the given sort order.

A: While it is possible to update the columns used in a sort. Take the following example:
declare @fname int,@lname int

select @fname=1,@lname=0

select * from [user]
order by case when @Fname=1 then firstname when @lname=1 then lastname end

I don't think you can use this technique to modify the sort order but you can at least change the columns your sorting on. At least when I try get complaints about syntax with SQL 2005

A: You can in a similar manner to an existing post.
declare @firstSortField int, @secondSortField int
set @firstSortField = 1
set @secondSortField = 3

select firstName, lastName, phoneNumber
from customers
order by
    case @firstSortField when 1 then firstName when 2 then lastName when 3 then phoneNumber else null end,
    case @secondSortField when 1 then firstName when 2 then lastName when 3 then phoneNumber else null end

A: I don't think that is possible, only parameter values can be prepared.

A: Nope, you'd need to build it into the SQL query each time, or if you have a sub set of sort orders, cache the command object for these and re-use as suites.
The short ansswer to the question though is "No"

A: This does exactly what you asked, and never puts user-entered strings anywhere near the database.

//get the requested order from the query string
string sortOrderRequest = request["SortOrder"].ToUpper();
string sortParam = "";
if ( sortOrderRequest.Equals("ASC"))
  sortParam = " order by ordervalue ASC ";
else if (sortOrderRequest.Equals("DESC"))
  sortParam = " order by ordervalue DESC ";

Dim command As SqlCommand = New SqlCommand("", connection)
command.CommandText = "SELECT * FROM someTable " + sortParam;
command.Prepare()
reader = command.ExecuteReader()

A: Sure can do. Create two aliased columns, SortASC and SortDESC, fill these with whatever you want, and sort on them.
-- Testcase setup
DECLARE @OrderASC bit
SET @OrderASC = 0

-- Statement required
SELECT
    Users.*,
    CASE @OrderASC WHEN 1 THEN Users.Alias ELSE null END AS _SortASC,
    CASE @OrderASC WHEN 0 THEN Users.Alias ELSE null END AS _SortDESC
FROM Users
ORDER BY _SortASC, _SortDESC DESC

A: I extended the accepted answer to reach an effective solution for parameterizing order clause in a SQL query. Here is a sample code :
DECLARE @Sorting VARCHAR(200) = 'CreationTime ASC'

SELECT v.*,
CASE WHEN @Sorting = 'CreationTime ASC' THEN ROW_NUMBER() OVER (ORDER BY v.CreationTime ASC)
     WHEN @Sorting = 'CreationTime DESC' THEN ROW_NUMBER() OVER (ORDER BY v.CreationTime DESC)
                                         ELSE ROW_NUMBER() OVER (ORDER BY v.Id ASC) END AS rownum

FROM Vehicles v ORDER BY rownum


text:
Q: List items should create sharepoint group I am facing one problem from last one week. I have one list having clients name. So when i add new client to the list then sharepoint user group should be created with client name as group name.
So is it possible to do that? if yes then how can i do this?

A: You can do that using three possibles methods :

*

*Design a workflow that is fired on item creation and which is attached to the list

*Create an EventReveiver to handle ItemAdded event, and create the SP group

*Modify the new form of the list. I don't recommend this way because if customers are created from another place, the logic won't be fired.
Another way to solve such problems, but it requires more background of your need, is to split your data into several site collections, one for each customer. Each site collection can have a "Customer" group (maybe created from a site template), which contains the customer. As each site collections have distinct users and groups, it can avoid cross customer data leaking (due to misconfiguration of authorizations).


text:
Q: Possible to restore wordpress database from mysql56 and sqlite files? I was building a small personal site on my local host using MAMP. I had a bunch of content and post entries that I had put in (notes I had taken for school) but something went wrong and one day (I don't remember changing any settings prior to this) I got an error saying it couldn't access the database. The only solution I could find to this problem was to uninstall and then reinstall MAMP and WP. Before I uninstalled I copied the contents of MAMP/db/ which contained two directories called 'mysql56' and 'sqlite'. I assumed this was the mysql database for both of the sites that I was running (I'm running two different sites on localhost, both through MAMP). I have those files saved, but now I can't figure out how to get my DB back or if it's even possible at this point to recover all that content. I wasn't able to make any other type of back up of the database. Am I out of luck or is there a way to get my notes back?
I tried just copying the directories and files I saved into the new /MAMP/db/ directory, but I get a similar error saying it can't connect to the database.


text:
Q: How to simulate a spreadsheet I am working with Sigma grid, populating it from PHP. Sigma is supposed to have a formula handling function, but it only seems to work with JS loaded datasets. So I was wondering if it was possible to modify some of the cells after load of page, do include spreadsheet-like formulae?
This is the code produced by Sigma (one row of it):

19
2012-02-11
Bob
LB
128
0
    0
    0

So the effect I want to have is to take the last cell, and add the previous 3 cell values (inside td and div each).
Ideas?

A: Have figured it out. This code will only roughly apply to someone else using Sigma grid.
Load this as a separate JS file in the header. It will initiate a recalculation
every time a cell is changed, thereby offering the ability to have programmable formulae.
//now load the values from the retrieved table, after a change initiated by user
$(window).change(function() {

    //all formulae go below here:
// Ordered trays formula
$('table.gt-table tbody tr').each(function() {
    var tray = 0;
    var ordcell = 0;

var traycode= $(this).find("td.gt-col-mygrid1-trays_code div").html();
 var ordcells= $(this).find("td.gt-col-mygrid1-ordered_cells div").html();
 if (parseInt(traycode) >0) {
     tray = parseInt(traycode);
     } else {
     tray = 0;
 }
   if (parseInt(ordcells) >0) {
     ordcell = parseInt(ordcells);
     } else {
     ordcell = 0;
 }
 if (tray > 0 && ordcell > 0)  var ordtrays = ordcell/tray;
if (ordtrays > 0){
    $(this).find("td.gt-col-mygrid1-ordered_trays div").html(ordtrays);
}
});
// end Ordered trays formula

}); // end the window change function

A: Add the following to the gridoption
onCellClick: function(value, record , cell, row,  colNo, rowNo,columnObj,grid){

overRowNo=rowNo;
overColNo=colNo;
cellValue=value;

},
afterEdit: function(  value,  oldValue,  record,  col,  grid){
// ordered trays calculation
    if(overColNo == 5 || overColNo == 6){
    var text = $(this.activeCell).find('div.gt-inner').text();console.log(text);
    if (!$.isNumeric(text)){ //jquery's isnumeric function
         alert ('Please enter a valid number.');
         // because cell 5 is a drop down select we don't need to scan for bad input; this is only for cell 6 - ordered cells
         text = 0;
     }
            var traycode = mygrid.getColumnValue(5,overRowNo);
            var ordcells = mygrid.getColumnValue(6,overRowNo);
             if (parseInt(traycode) >0) {
             tray = parseInt(traycode);
             } else {
                tray=text;

         }
           if (parseInt(ordcells) >0) {
             ordcell = parseInt(ordcells);
             } else {
                 ordcell= $('input.gt-editor-text').first().val();
         }
         //alert(tray+' '+ordcell);
         if (tray > 0 && ordcell > 0)  var ordtrays = Math.ceil(ordcell/tray);
        if (ordtrays > 0){
        mygrid.setColumnValue('ordered_trays',overRowNo,ordtrays);
         mygrid.updateEditState();
           mygrid.activeRecord.ordered_trays = ordtrays;

    mygrid.refresh();
    }
    }


text:
Q: How to scrape time from http://time.is/New_York using PHP? I don't have any knowledge of PHP but am stuck with scraping time of http://time.is/New_York.
I have used this code:
<?php
$contents = file_get_contents('http://time.is/New_York');
preg_match('/<div id="twd\d+" [^>]*>([^<]+)<\/div>/im', $contents, $matches);

$title = $matches[0];
print_r($title);
?>

A: $page = file_get_contents("http://time.is/New_York");
$pattern = '#id="twd">(.*)<#U';

preg_match_all($pattern, $page, $matches);

echo $matches[1][0];

A: Why would you "scrape" time of other website? You can get date and time in PHP for any timezone:
$dt = new DateTime('now', new DateTimezone('America/New_York'));
echo $dt->format('l, F j, Y, \w\e\e\k W'); # Friday, November 29, 2013, week 48

See the list for other timezones available in PHP.
Demo


text:
Q: Сверстать элемент страницы
Здравствуйте. Мне нужно сверстать элемент представленный выше. В фотошопе видно, что font-size кавычек равен 337px. Проблема в том, что тогда создается огромный отступ вниз и небольшой уже вверх, из-за чего сама надпись "Dhavan" поднимается высоко. Пытался заключить в ограничивающий контейнер эти кавычки. Примерный код:

 .quote-jail {
 position: relative;
 height: 150px;
 width: 150px;
 overflow: hidden;
}
.quote {
 font-size: 337px;
 position: absolute;
 top: -35px;
 left: -25px;

}
 .name {
 text-transform: uppercase;
 font-size: 26px;
 position: absolute;
 top: 10px;
}

 dhavan
  ”

Затем круглое изображение и этот quote-jail поместил в блок, которому задал flex-direction: row. Но мне кажется, такой подход неверный. Очень настораживают отрицательные top/left. Все ли я правильно сделал и есть ли другой, альтернативный способ наверстать это?

A: При увеличении размера шрифта увеличивается и line-height, отсюда эти ненужные отступы. Попробуйте уменьшить line-height вплоть до 0.
Если не поможет, просто вставьте кавычки в вёрстку как png-картинку и не заморачивайтесь :)


text:
Q: Help identify this component (probably some sort of thermal fuse) This is a part taken from an old steam cooker. It has two terminals at the top. The first terminal is connected to the phase wire (230 V AC) as it enters the device and from the second terminal it is routed further into the device. For this reason I think it is probably some sort of a fuse.

The two terminals on top are bridged by a two thin metal sheets. There is a vertical ceramic rod that goes through the part, pushing on those metals from downwards. When the rod is pushed up, the metal sheets are disconnected. In the base there is what I guess may be some bimetallic sheet that would push the rod up when the device overheats.
I would like to know if it is indeed a fuse and how is this component called exactly. I tried to find some pictures of fuses but they looked very different from what I have.
As a new member on this site I cannot post that many (that is 4) pictures, so I have to give a link to a HTML page where additional photos are.

A: It is a thermostat as Dave Tweed and Kaz noticed.
I got a similar one and it has the temerature written on it:


text:
Q: Mars Curiosity Power System Curiosity's power source comes from a radioisotope thermoelectric generator (RTG) rather than from solar panels like the two Mars Rovers. 2,000 watts of thermal power from alpha particle emission in 4.8 kg of Pu-238 (half-life 87.8 years) yields about 120 watts of electric power via the Seebeck effect (thermocouples). This source slowly declines in power output (~1%/year), and is expected to provide a reliable power source for years.

It appears that the efficiency of Curiosity's RTG is only 120/2000 = 6%. Why is the RTG efficiency so small? Is there a problem maintaining greater hot/cold junction delta temperatures or are there other issues?

A: Most of the loss is the simple thermal conductivity from the hot (radioactive source) to the cold (atmosphere).
If you have a pretty much infinite cold sink you are going to lose all the heat eventually so getting 6% of it as electricity is pretty good.
Don't know what the internal temperature of the source is, but guessing it's around 300-500C (any higher and the metalurgy gets challenging). And a martian atmosphere of -50C
So the maximum Eff = 1 - (273-50)/(273+300) = 60%, 70% at 500C
I suspect you could get closer to this with a Stirling engine but a thermo-electric generator has no moving parts.

A: Here is a schematic outline of Curiosity's MMRTG which has 4.8 kg of Pu-238 dioxide and provides 110 Watts of power (twice the maximum power of Apple Mac-book Pro)
The MMRTG from Idaho National Laboratories also provides heat to maintain a proper operating temperature of all the instruments and systems in the rover. It weighs 45 kg and is capable to produce power for almost 14 years. But, A great advantage of these thermoelectric generators is that there are no moving parts associated with them. It produces power by directly converting the heat generated by the decay into electrical energy using thermocouples at an operational efficiency of 6 to 7 % which seems too low.
The generator is fueled with a ceramic form of plutonium dioxide encased in multiple layers of protective materials including iridium capsules and high-strength graphite blocks. As the plutonium naturally decays, it gives off heat, which is circulated through the rover by heat transfer fluid plumbed throughout the system. Electric voltage is produced by using thermocouples, which exploit the temperature difference between the heat source and the cold exterior (i.e. Martian atmosphere).
As @Beckett says, Most of this efficiency loss is due to thermal conductivity with Martian atmosphere.
A nuclear power source is chosen because solar panels did not meet the full range of the mission's requirements. Only the radioisotope power system allows full-time communication with the rover during its atmospheric entry, descent and landing regardless of the landing site. Also, the nuclear-powered rover can go farther, travel to more places, last longer, and also power & heat a larger (size of a car) and more capable scientific payload compared to the solar power alternative. The radioisotope power system gives Curiosity the potential to be the longest-operating, farthest-traveling, most productive Mars surface mission in history.


text:
Q: Error when trying to use ggmap::get_map ( JPEG decompression error: Not a JPEG file: starts with 0x89 0x50) I am trying to set up a map from ggmap.I have borrowed this line from another script but it is not working for me. I want to specify the boundary of the map.
myLocation <- c( -133.50734,   26.07781,  -60.49268,   47.77387)
myMap <- ggmap::get_map(location=myLocation, source="stamen", maptype="terrain", crop=TRUE)

The map should show the US boundary, but it throws the following error when trying to run it:
Map from URL : http://tile.stamen.com/terrain/5/4/11.jpg
Error in readJPEG(tmp) :
 JPEG decompression error: Not a JPEG file: starts with 0x89 0x50

Any comment on how to fix the issue?


text:
Q: Spring Boot Thymeleaf variables blocking login page I'm making a webshop in Spring Boot 2.1.1, with ThymeLeaf 3.0.11
My login page does not appear in every cases, everytime it wants to load it gives a "TemplateInputException" and fails to show up.
I figured it out, if I delete thymeleaf variables from the body or div tags (I mean th:with attributes), then it works until it reaches the next html tag with TL variables, after that, the html page just stops to render. What could be the problem? There is no scenario  where i dont use those variables, I need them in the container tag. What is the relation between the Spring Boot login page and template variables?
I copy some code, if you need any more, please let me know.
Any help would be appreciated!
Here is my Webconfig:
@Configuration
public class WebConfig implements WebMvcConfigurer{

@Override
public void addViewControllers(ViewControllerRegistry registry){

    registry.addViewController("/login").setViewName("auth/login");

    registry.setOrder(Ordered.HIGHEST_PRECEDENCE);

}

My security config's configure method:
@Override
public void configure (HttpSecurity httpSec)throws Exception {
    httpSec
        .authorizeRequests()

        .antMatchers("/", "/reg", "/login", "/css/**","/images/**",
        "/js/**", "/register", "/error",
        "/records", "/search", "/record", "/altercart",
        "/showcart", "/category", "/viewchange",
        "/images").permitAll()

        .antMatchers("/admin").hasRole("ADMIN")

        .anyRequest().authenticated()

       .and()

        .formLogin()
        .loginPage("/login")
        .permitAll()
       .and()
        .logout()
        .logoutSuccessUrl("/login?logout")
        .permitAll();

}

My login page(using layout dialect):

            <form method="post" th:action="@{login}">
                <input type="text" name="username" th:placeholder="#{login.ph.username}" required class="col-12"/>

                <input type="password" name="password" th:placeholder="#{login.ph.password}" required class="col-12"/>

                <input type="submit" th:value="#{loginSubmitButton}" class="col-12"/>

            </form>

            Registration

Beggining of stack trace:
org.thymeleaf.exceptions.TemplateInputException: An error happened during
template parsing (template: "class path resource
[templates/auth/login.html]"


text:
Q: Where to download the defaultss.xsl or the official URL (not res://msxml.dll/defaultss.xsl) When I am actually interacting with IE through a .aspx file. I can refer to the defautl xslt as res://msxml.dll/defaultss.xsl.
Dim objDefaultXSL As New System.Xml.XmlDocument
objDefaultXSL.load("res://msxml.dll/defaultss.xsl")

But if I am not using IE which url should i use to to accomplish the same?
Thanks

A:
When i am actually interacting with IE through a .aspx file

I have no idea what you mean with this. ASPX is used server-side to dynamcially create HTML or other pages and serve them with a web server to the client side. The client side can be Internet Explorer, but the ASPX code does not "interact" with the client.

but if I am not using IE which url should i use to to accomplish the same? Thanks

res://msxml.dll/defaultss.xsl is a location in a resource inside a DLL, in this case msxml.dll. This is a Microsoft-specific DLL, used when people in Internet Explorer use XML or XSLT technologies.
When you are not targeting IE, this DLL will not be loaded and so you cannot access that file. But if, for some reason, you want that resource, simply load and save it to disk once and reuse it in your other code. Whether this makes any sense, I doubt it, because that file is specifically meant for IE.


text:
Q: Given a field extension E/F, $f(x)\in E[x]$, and $f(\alpha )\in F, \forall \alpha \in F$. Does $f(x)\in F[x]$? Given a field extension E/F, $f(x)\in E[x]$, and $f(\alpha )\in F, \forall \alpha \in F$. Does $f(x)\in F[x]$ ?
I have tried the thought that to lower its degree as below.
Let $f(x)=\alpha_n x^n+...+\alpha_1x+\alpha_0$. Since $0\in F$, $f(0)=\alpha_0 \in F$.
$(f(x)-\alpha_0)/x\in F$ when $x\neq 0$. Hence, $\alpha_n x^{n-1}+...+\alpha_1\in F$ when $x\neq 0$.
I want to say that $\alpha_1\in F$ in a similar way. However, the restriction that $x\neq 0$ does not allow me to claim it.
I believe that this proposition is correct but I cannot prove it. I need some help or a simple hint to get myself out. Thanks.
Edit. $\alpha_n=1$ in $f(x)$


text:
Q: String formatting options: pros and cons These are two very popular ways of formatting a string in Python. One is using a dict:
>>> 'I will be %(years)i on %(month)s %(day)i' % {'years': 21, 'month': 'January', 'day': 23}
'I will be 21 on January 23'

And the other one using a simple tuple:
>>> 'I will be %i on %s %i' % (21, 'January', 23)
'I will be 21 on January 23'

The first one is way more readable, but the second one is faster to write. I actually use them indistinctly.
What are the pros and cons of each one? regarding performance, readability, code optimization (is one of them transformed to the other?) and anything else you would think is useful to share.

A: Why format() is more flexible than % string operations
I think you should really stick to format() method of str, because it is the preferred way to format strings and will probably replace string formatting operation in the future.
Furthermore, it has some really good features, that can also combine position-based formatting with keyword-based one:
>>> string = 'I will be {} years and {} months on {month} {day}'
>>> some_date = {'month': 'January', 'day': '1st'}
>>> diff = [3, 11] # years, months
>>> string.format(*diff, **some_date)
'I will be 3 years and 11 months on January 1st'

even the following will work:
>>> string = 'On {month} {day} it will be {1} months, {0} years'
>>> string.format(*diff, **some_date)
'On January 1st it will be 11 months, 3 years'

There is also one other reason in favor of format(). Because it is a method, it can be passed as a callback like in the following example:
>>> data = [(1, 2), ('a', 'b'), (5, 'ABC')]
>>> formatter = 'First is "{0[0]}", then comes "{0[1]}"'.format
>>> for item in map(formatter, data):
    print item

First is "1", then comes "2"
First is "a", then comes "b"
First is "5", then comes "ABC"

Isn't it a lot more flexible than string formatting operation?
See more examples on documentation page for comparison between % operations and .format() method.
Comparing tuple-based % string formatting with dictionary-based
Generally there are three ways of invoking % string operations (yes, three, not two) like that:
base_string % values

and they differ by the type of values (which is a consequence of what is the content of base_string):

*

*it can be a tuple, then they are replaced one by one, in the order they are appearing in tuple,
>>> 'Three first values are: %f, %f and %f' % (3.14, 2.71, 1)
'Three first values are: 3.140000, 2.710000 and 1.000000'

*it can be a dict (dictionary), then they are replaced based on the keywords,
>>> 'My name is %(name)s, I am %(age)s years old' % {'name':'John','age':98}
'My name is John, I am 98 years old'

*it can be a single value, if the base_string contains single place where the value should be inserted:
>>> 'This is a string: %s' % 'abc'
'This is a string: abc'

There are obvious differences between them and these ways cannot be combined (in contrary to format() method which is able to combine some features, as mentioned above).
But there is something that is specific only to dictionary-based string formatting operation and is rather unavailable in remaining three formatting operations' types. This is ability to replace specificators with actual variable names in a simple manner:
>>> name = 'John'
>>> surname = 'Smith'
>>> age = 87
# some code goes here
>>> 'My name is %(surname)s, %(name)s %(surname)s. I am %(age)i.' % locals()
'My name is Smith, John Smith. I am 87.'

Just for the record: of course the above could be easily replaced by using format() by unpacking the dictionary like that:
>>> 'My name is {surname}, {name} {surname}. I am {age}.'.format(**locals())
'My name is Smith, John Smith. I am 87.'

Does anyone else have an idea what could be a feature specific to one type of string formatting operation, but not to the other? It could be quite interesting to hear about it.

A: I'm not exactly answering your question, but just thought it'd be nice to throw format into your mix.
I personally prefer the syntax of format to both:
'I will be {years} on {month} {day}'.format(years=19, month='January', day=23)

If I want something compact, I just write:
'I will be {} on {} {}'.format(19, 'January', 23)

And format plays nicely with objects:
class Birthday:
  def __init__(self, age, month, day):
    self.age = age
    self.month = month
    self.day = day

print 'I will be {b.age} on {b.month} {b.day}'.format(b = Birthday(19, 'January', 23))

A: I am not answering the question but just explaining the idea I came up in my TIScript.
I've introduced so called "stringizer" functions: any function with name starting from '$' is a stringizer. Compiler treats '$name(' and ')' as quotes of string literal combined with function call.
Example, this:
$print(I will be {b.age} on {b.month} {b.day});

is actually compiled into
$print("I will be ", b.age, " on ",b.month," ",b.day);

where even arguments are always literal strings and odd ones are expressions. This way it is possible to define custom stringizers that use different formatting/argument processing.
For example Element.$html(Hello <b>{who}</b>); will apply HTML escape on expressions. And this Element.$(option[value={12}]); will do select in jQuery style.
Pretty convenient and flexible.
I am not sure is it possible to do something like this in Python without changing its compiler. Consider just as an idea.


text:
Q: How to read array of array in Objective c I'm trying to read this but unable to get proper value.
NSString *arr = [self.myArray valueForKey:@"description"];
NSLog(@"%@",arr);

I'm getting this output :
(
        (
        050,
        051
    )
)

And also it should remove first 0 i.e 050->50
But I want it as single array, like this [50, 51]
I'm newbie, please help me out.

A: Use this code
NSArray * NewArray = [[self.myArray valueForKey:@"description"]objectAtIndex: 0];
NSLog(@"New Array is %@", NewArray);

A: Try the below code:
NSArray *arr = [[self.myArray valueForKey:@"description"]objectAtIndex: 0];
NSLog(@"%@",arr);

Also to remove the first 0 from string, You can try stringByReplacingCharactersInRange providing the place of 0.
This link can help you

A: Use Below code
 [myArray setObject:arr2 forKey:@"description"];
    for (NSString *st in [[myArray valueForKey:@"description"] objectAtIndex:0]) {
        NSLog(@"%@",st);
        NSString *firstChar = [st substringToIndex:1];
        if ([firstChar  isEqual: @"0"]) {
            NSString *newStr = [st substringWithRange:NSMakeRange(1, [st length]-1)];
            NSLog(@"%@",newStr);
        }
    }

OutPut:
050
50
051
51


text:
Q: How can I unit test controller together with a filter (ASP.NET MVC with autofac) so I am writing a high-level unit test in ASP.NET MVC 4 using autofac.
So I have a sample controller:
    public class SomeController
    {
        [SomeFilter]
        public ActionResult SomeAction()
        {
            SomeCode();
        }
    }

And I can write a sample test:
    [Test]
    public void Test()
    {
        var controller = new SomeController();
        var result = controller.SomeAction();
        // Asserts go here
    }

That all works great, provided I fake out all external dependencies.
However, there is also some code that is attached via filter attribute that I would like to run (it is important to this test, and I do not want to just test it in isolation).
This code would be executed when run within the application, but it would not be executed if run within the test. It does not matter if I new up controller manually, or retrieve it using DependencyResolver as:
var someController = DependencyResolver.Current.GetService<SomeController>();

This is obviously because during normal run-time the framework creates and attaches those filters properly.
So the question is - how could I duplicate this behavior in the test and have those action filters executed?

A: Good Morning Sebastian,
For reasons beyond posting here I had to write unit tests to utilize the action filter along with the web api controller end point.
Of course as you observed and I found out as well the action filters do not fire during a unit test.
I hacked my way to this solution but am definitely open to further education.
In my unit test I am using a fluent builder pattern but in short spin up your controller. (BTW if you want more info on a fluent builder pattern just post a comment and I'll pass along links...that or Google it.)
//we need to setup some context stuff that you'll notice is passed
//in to the builder WithControllerContext...and then the controller is
//used to get the ActionFilter primed

//0. Setup WebApi Context
var config = new HttpConfiguration();
var route = config.Routes.MapHttpRoute("DefaultSlot", "cars/_services/addPickup");
var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "AddPickup" } });

var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:24244/cars/_services/addPickup");
request.RequestUri = new Uri("http://localhost:24244/cars/_services/addPickup");
List<string> x = new List<string>() { MediaType.CarsV2.GetDescription() };
request.Headers.Add("Accept", x);

 ....obviously 1 & 2 I skipped as they aren't relevant

//3. controller
PickupController controller = new PickupControllerBuilder()
//.MoqReqHlpr_IsAny_CreateResp(HttpStatusCode.OK) //3a. setup return message
.MoqCarRepoAny_ReturnsSampleDataCar(new Guid("000...0011")) //3b. car object
.MoqFulfillRepoAnyCar_IsAny_IsQuickShop(true) //3c. fulfillment repository
.MoqCartRepoAnyCar_IsAny_UpdateCar(true) //3d. car repository
.WithControllerContext(config, routeData, request)
.WithHttpPropertyKey(lsd);

//HttpActionContextFilter is the name of my ActionFilter so as you can
//see we actually instantiate the ActionFilter then hook it to the
//controller instance
var filter = new HttpActionContextFilter();
filter.OnActionExecuting(controller.ActionContext);

Two things to note that bit me.

*

*make sure you have the correct namespace. I let VS import it via Ctrl-. and of course it imported System.Web.Mvc and I needed System.Web.Http.

*You need to hook the overrides you want to fire. So if your action filter
has four overrides then you need to hook four times. If you have multiple ActionFilters then you need to instantiate each and hook its overrides.

I included the screenshot thinking a picture would be helpful here.


text:
Q: proxy.conf.js not working in ASP.NET Core app with Angular I am trying to setup an ASP.NET Core app with Angular frontend by following this tutorial. I was already able to successfully create the projects and I am also able to run and debug them flawlessly. The problem is that for some reason I cannot get proxying the backend calls to the ASP.NET Core backend to work. When I try to call an action inside a controller from the angular app, I get a 404 error.
Here is my proxy.conf.js file:
const PROXY_CONFIG = [
  {
    context: [
      "/api/*",
    ],
    target: "https://localhost:7139",
    secure: false
  }
]

module.exports = PROXY_CONFIG;

This is my TestController which I created for testing purposes:
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class TestController : ControllerBase
{
    private readonly ILogger<TestController> _logger;

    public TestController(ILogger<TestController> logger)
    {
        _logger = logger;
    }

    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "Test response";
    }
}

Here is how I am trying to call it from within the Angular app:
this.http.get<string>(`api/test/1`).subscribe((value) => {
  alert(value);
},
(error) => {
  alert(`Error: ${error.error}`);
});

This is how the proxy.conf.js is added in the serve section of my angular.json:
"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "configurations": {
    "production": {
      "browserTarget": "angularproject1.Client:build:production"
    },
    "development": {
      "browserTarget": "angularproject1.Client:build:development"
    }
  },
  "defaultConfiguration": "development",
  "options": {
    "proxyConfig": "src/proxy.conf.js"
  }
},

I already checked the port and in the proxy.conf.json and it does indeed match the port specified in the applicationUrl entry of the launchSettings.json file in the ASP.NET Core project. Here is the content of the launchSettings.json file:
{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:30959",
      "sslPort": 44345
    }
  },
  "profiles": {
    "WebApplication1": {
      "commandName": "Project",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "https://localhost:7139;http://localhost:5139",
      "dotnetRunMessages": true
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

What could be the reason why this is still not working? Could it be related to the fact that I am trying to get this to work with Windows Authentication, or what am I doing wrong here?

A: I ran into the same problem. After an hour I remembered that Angular uses ** as a catch all and not *.
const PROXY_CONFIG = [
  {
    context: [
      "/api/**",
    ],
    target: "https://localhost:7139",
    secure: false
  }
]

module.exports = PROXY_CONFIG;

I think that you can use a single * if the proxy.conf.js file is formatted the same as a json file. Like so:
{
  "/api/*": {
    "target": "https://localhost:7139",
    "secure": false
  }
}

A: Try adding your [Controller][Action] explicitly into proxy.config.js
Like this:
const PROXY_CONFIG = [
{
   context: [
   "/api/Test/Get",
  ],
  target: "https://localhost:7139",
  secure: false
 }
 ]

 module.exports = PROXY_CONFIG;

A: I had the same problem using VS Code on Ubuntu. All I needed to do was update my PROXY_CONFIG's context entry to  ["/api/**"] then I could change all my controllers to route with the /api/ prefix.
The reason for the proxy is that your dotnet application runs on one port while your angular app on another. When you press F5 VS Code will start both apps, and load the UI through the angular port.
If you look at the fetch-data-component from the default project you'll see it injects a BASE_URL. This base url uses the port the angular app listens on. It is suggested to use this BASE_URL in your service and allow the proxy to do its job.
So for example a request such [angular app]+/api/customers needs to be resolved to the dotnet app, this is the purpose of proxy.conf.js.
To differentiate between an agular route and a dotnet api route the context value in PROXY_CONFIG is used to trigger the redirect to the dotnet app. This is where /api/** comes in as angular uses the **-wildcard to catch all incoming urls starting with the api-prefix, then redirects them to whatever the target value is.

A: I had the same problem (ASP.NET Core 6 / Angular), I fixed it simply using "/api/".
const PROXY_CONFIG = [
  {
    context: [
      "/api/" // <---
    ],
    target: target,
    secure: false
  }
]

Don't forget to change your Controller's routes accordingly.


text:
Q: Building App with Config File (White Label) not working with Null Safety I added the config file like this. But when I try to build iOS there is the error "my config don't support null safety" what can I do ?
class FlavorStrings {
static const String APP_HEADING_COPY = "BASE APP HEADING";
static const int COLORCODE = 2312312;
}

/var/folders/mk/xvjbsrs56fn17mh2_60n28d40000gn/T/flutter_tools.Kc07aJ/flutter_ios_build_temp_diryUd6y9/temporary_xcresult_bundle


text:
Q: IVPort raspberry pi camera module Im trying to design multiplex camera system for my raspberry pi something like this https://www.tindie.com/products/canerdurmusoglu/ivport-dual-v2-raspberry-pi-camera-multiplexer/#product-description
Does anyone knows, what kind of chip is on a board like this, something like 14bit bus 2:1 mux. But I cant find something like that

A:
..something like 14bit bus 2:1 mux

Unlikely. The Raspberry-Pi camera interfaces are MIPI CSI ports. You can't use a normal multiplexer.

what kind of chip is on a board like this?

Look for a MIPI multiplexer.


text:
Q: Finding the derivative of sinus and cosinus. Trigonometric identities How can we see that $$\sin(x+h)-\sin(x)=2\sin\left(\frac h2\right)\cos\left(x+\frac h2\right)$$
How can we see that $$\cos(x+h)-\cos(x)=-2\sin\left(\frac h2\right)\sin\left(x+\frac h2\right)$$
Do these identities have a name?

A: For any $a,b$, we have the well known "addition theorems"
$$ \sin(a+b) = \sin a \cos b + \sin b \cos a$$
and $$ \sin(a-b) = \sin a \cos b - \sin b \cos a $$
Subtracting these two equations, we get
$$ \sin(a+b) - \sin(a-b) = 2\sin b \cos a $$
For the cosine, we have
$$ \cos(a+b) = \cos a \cos b - \sin a \sin b $$
and $$ \cos(a-b) = \cos a \cos b + \sin a \sin b $$
Subtraction again
$$ \cos(a+b) - \cos(a-b) =  -2\sin a\sin b$$
Now let $b = \frac h2$, $a = x+\frac h2$.

A: You asked for a name: Looks like an application of the reverse of the Prosthaphaeresis identities, or sum-to-product identities.
$$
\sin a − \sin b = 2 \cos\frac{a + b}{2} \sin\frac{a − b}{2} \\
\cos a − \cos b = −2 \sin\frac{a + b}{2} \sin\frac{a − b}{2}
$$
using $a = x + h$ and $b = x$.
Another link here.
I usually use the complex definitions of $\sin$ and $\cos$ to proof, but you probably want an elementary one.
Note there are four identities in total.
$$
\sin a + \sin b = 2 \sin\frac{a + b}{2} \cos\frac{a − b}{2} \\
\cos a + \cos b = 2 \cos\frac{a + b}{2} \cos\frac{a − b}{2}
$$
which would yield
$$
\sin(x+h) + \sin(x) =
2 \sin\left(x+\frac{h}{2}\right) \cos\left(\frac{h}{2}\right) \\
\cos(x+h) + \cos(x) =
2 \cos\left(x+\frac{h}{2}\right) \cos\left(\frac{h}{2}\right)
$$


text:
Q: Cannot upload CSV to SFTP Server by Using RCurl I am trying to upload a .csv (Advertising data) file by using R and SFTP on a Google Server.
user = "userinfo"
password = "password"
host = "partnerupload.google.com"
port = "19321"

url = str_c("sftp://", user, ":", password, "@", host)

upload_to_ftp("test.csv",
              url = url,
              basename = FALSE,
              verbose = FALSE)

Here is the error message that I get:
Error in function (type, msg, asError = TRUE)  :
Failed to connect to partnerupload.google.com port 22: Connection timed out

I also tried to run the following function:
ftpUpload(what = "test.csv", to = str_c("sftp://partnerupload.google.com", user,":",password)

Which produced the exact same mistake as above.
When I try to specify the port as shown below:
url = str_c("sftp://", user, ":", password, "@", host, ":", port)

upload_to_ftp("test.csv",
              url = url,
              basename = FALSE,
              verbose = FALSE)

I get the following error, even though the message is truncated:
Error in function (type, msg, asError = TRUE)  :

I also went into the terminal and manually changed the port number by going inside the following file:
nano /etc/ssh/sshd_config

Port changed in terminal

I would really appreciate your help, I have been working on this for more than 4 hours, unsuccessfully.

A: If I try to run it with the curl package: https://github.com/jeroen/curl
I get the following error: SSL peer certificate or SSH remote key was not O


text:
Q: Export scraped tables to CSV I´ve scraped these tables in one single table in python using BeautifulSoup. The code is the following :
import urllib2
from bs4 import BeautifulSoup
for i in range(0,39):
    first=urllib2.urlopen("http://www.admision.unmsm.edu.pe/res20130914/A/011/"+str(i)+".html").read()
    soup=BeautifulSoup(first)
    for tr in soup.find_all('tr')[2:]:
      tds = tr.find_all('td')
      print tds[0].text, tds[1].text, tds[2].text, tds[3].text

The result is something like this :
494560 ABAD SAAVEDRA, GERSON HORACIO 011 1116.8750
455314 ABAD VALVERDE, MARIA ISABEL 011 1482.7500
491005 ABREGU HUAMAN, MERCEDES LILIANA 011 503.4000
457929 ACOSTA ABAD, ALEJANDRO FRANCISCO 011 413.0500

So, how can I export this table to CSV?

A: Use csv module:
import csv
import urllib2
from bs4 import BeautifulSoup

with open('listing.csv', 'wb') as f:
    writer = csv.writer(f)
    for i in range(39):
        url = "http://www.admision.unmsm.edu.pe/res20130914/A/011/{}.html".format(i)
        u = urllib2.urlopen(url)
        try:
            html = u.read()
        finally:
            u.close()
        soup=BeautifulSoup(html)
        for tr in soup.find_all('tr')[2:]:
            tds = tr.find_all('td')
            row = [elem.text.encode('utf-8') for elem in tds[:4]]
            writer.writerow(row)


text:
Q: What is the best way to add a parent group to user groups in userfrosting? I'm new here and this is my first question.
First of all I apologize for my poor English.
I would like to create an application using userfrosting 0.3.0 where:

*

*Anyone not registered can create a super group (eg a company)

*At that time an administrator user is created, other than root, but can only read information from the supergroup (administrators can not see other companies)

*Administrators can organize your users inside user-groups, but only root can create groups and modify permissions

I thank you very much for your time.

A: UserFrosting, as of version 0.3.1, does not have built-in support for group hierarchies.  However, it should be pretty easy to implement.  Here is how I would do it:

*

*Create two groups, "Administrators" and "Members".  Set it up so that "Administrator" is the default primary group for new users.

*Create two tables, company and company_user.  The company table will store information about the companies, with a primary key id.  The company_user table will associate companies with users, and have four columns:

*

*id (int)

*company_id (int)

*user_id (int)

*flag_admin (bool)

Change the register() method in AccountController.php so that when someone registers, it creates a new company and then associates them with this company, marking them as the Administrator of this company by setting flag_admin to '1'.
Any members that get added to a specific company should also be added to this table, but with flag_admin set to '0'.

*Create a new AccessCondition called manages(user_id_1, user_id_2) which returns true if user_id_1 and user_id_2 belong to the same company and user_id_1 has flag_admin set to '1', false otherwise.

*Grant appropriate permissions to users in group "Administrators" so that they can create/update/delete/view users, but only users in group "Members" and only if the Administrator manages them (so if "Members" has a group_id of "4", condition=in_group(user.id,4)&&manages(self.id,user.id).

*You will also want to modify the various user create/update/delete methods so that when an Administrator creates a user, it adds them to group "Member" and associates them with the appropriate company.

That should get you started, let me know if you need further clarification.


text:
Q: cache_size effect on SVC processing time I've done a cross-validated SVC analysis. Reading the scikit-learn docs for svc, I see this:
"Kernel cache size: For SVC, SVR, nuSVC and NuSVR, the size of the kernel cache has a strong impact on run times for larger problems. If you have enough RAM available, it is recommended to set cache_size to a higher value than the default of 200(MB), such as 500(MB) or 1000(MB)."
http://scikit-learn.org/stable/modules/svm.html
So I re-ran my analysis several times and timed the results using several different values for cache_size (50, 100, 200, 800, 1200, 2000, 4000, 8000).
My full analysis takes about 11.2 seconds when the cache_size is below 2000, and the time jumps to 40 seconds when the cache_size is greater than 2000.
The analysis takes place on a modern computer with 16 gigabytes of ram.
I'm wondering if anybody knows possible reasons why the processing time wouldn't change at all for any cache value below 2000, and why the processing time would get longer with higher values. Again, the computer has 16 gigs of ram and no signs of otherwise slowing occurs at any value of cache_size.
Thank you for anybody's thoughts.

A: The slow-down you noticed for cache > 2000 MB may be the consequence of this bug: https://github.com/scikit-learn/scikit-learn/issues/8012 (signed 32-bit integer overflow).


text:
Q: How can I detect when a pdf file is not available via a link I am developing a website with an archive of (hundreds) of old 'magazines' existing as pdf files. I can link to them with a normal 'a' tag but there are missing files, which are being slowly/gradually replaced as available. What I want to do is to have page links to all the files but automatically disable all links where the file is missing (maybe even with an explanatory popup). I could do this by hand of course but I'm looking for a coding approach (maybe js ajax?) which handles all page links. I have tried this with jQuery:
$('a').on('click', function (e) {
        e.preventDefault();
        let href = $(this).attr('href');
        console.log(href);
        $.get(href)
            .done(function () {
                console.log('File present');
            }).fail(function () {
                console.log('File missing');
            });
    });

I realize that 'preventDefault' stops the link working normally anyway but this is testing. However I get 'File present' even when the file is missing. Is this because pdf files respond differently and is there a perhaps simpler approach altogether?


text:
Q: Assign Int value to sprite node In my game, I have the same node added many times repeatedly to move across the screen. This node has a SKLabelNode child with text either "1" or "2". I want to be able to assign a number value of either 1 or 2 depending on the text of the label. Using the code below I set a value for a key but I didn't know how to relate this with my node to be able to check for it. Does anyone have a simpler way of doing this or have anyway to fix my existing code?
 if theLabel.text == "1" {

            var userDefaults = NSUserDefaults.standardUserDefaults()

            number = userDefaults.integerForKey("number")

            userDefaults.setValue(1, forKey: "number")

        }

        if theLabel.text == "2" {

            var userDefaults = NSUserDefaults.standardUserDefaults()

            number = userDefaults.integerForKey("number")

            userDefaults.setValue(2, forKey: "number")

        }

A: If inside didBeginContact you wanted to check what text was inside of a child labelNode, you should first specify a name for the labelNodes when you initialize them:
theLabel.name = "labelNode"

this will suffice. Now, inside of your didBeginContact method you probably already have something like this in order to check for contact:
var firstBody: SKPhysicsBody
var secondBody: SKPhysicsBody

firstBody = contact.BodyA
secondBody = contact.BodyB

And you probably already know that to access the sprite node associated with each body you just specify for example contact.BodyA.node. So, all thats left is to find the child node of contact.BodyA.node with the name "labelNode". You can do that like this:
var labelNode: SKLabelNode = contact.bodyA.node.childNodeWithName("labelNode") as SKLabelNode

Ok now that you have your label node you can easily check its text and do whatever you want:
println(labelNode.text)

Now you just do the same thing with bodyB. Hope this helps!


text:
Q: If $\lim_{n \rightarrow +\infty} \frac{|T'_n|}{|T_n|} = 1$, then $\lim_{n \rightarrow +\infty} \frac{|T_n \Delta T'_n|}{|T_n|} = 0$ Let $\{T_n\}_{n \in \mathbb{N}}$ be a Folner sequence and $\{T'_n\}_{n \in \mathbb{N}}$ be any sequences of subsets of $\mathbb{Z}^d$ such that $\lim_{n \rightarrow +\infty} \frac{|T'_n|}{|T_n|} = 1$. Then, $\lim_{n \rightarrow +\infty} \frac{|T_n \Delta T'_n|}{|T_n|} = 0$, where $\Delta$ means the symmetric difference.
$\{T_n\}$ being a Folner sequence means that for any $v \in \mathbb{Z}^d$, $\lim_{n \rightarrow +\infty} \frac{1}{|T_n|}|vT_n \Delta T_n| = 0$, where $vT_n = \{vt^{(n)} : t^{(n)} \in T_n\}$.
Using the fact that $A \Delta C = (A \Delta B) \Delta (B \Delta C)$, we can write, for any $v \in \mathbb{Z}^d$ and any $n \in \mathbb{N}$
\begin{equation*}
T'_n \Delta T_n = (T'_n \Delta vT_n) \Delta (vT_n \Delta T_n).
\end{equation*}
Then,
$$\lim_{n \rightarrow +\infty} \frac{|T_n \Delta T'_n|}{|T_n|} = \lim_{n \rightarrow +\infty} \frac{|(T'_n \Delta vT_n) \Delta (vT_n \Delta T_n)|}{|T_n|} $$.
As $\{T_n\}_{n \in \mathbb{N}}$ is Folner, we know that $\lim_{n \rightarrow +\infty} \frac{1}{|T_n|}|vT_n \Delta T_n| = 0$, for any $v \in \mathbb{Z}^d$.
I guess I need to find a suitable $v$ such that $\lim_{n \rightarrow +\infty} \frac{|T'_n \Delta vT_n|}{T_n} = 0$ and I guess the existence of this $v$ is guaranteed by the hypothesis that $\lim_{n \rightarrow +\infty} \frac{|T'_n|}{|T_n|} = 1$, but I am not sure if this is right and how I can justify that.
Could someone help me?


text:
Q: python csv two columns with same name Is there a way to use the python csv module to save a csv which has two columns of the same name?
This is my function
def DictListToCsv(Data, FileName, FieldNames):
    with open(FileName, 'w') as f:
        writer = csv.DictWriter(f, fieldnames = FieldNames, dialect = 'excel', delimiter=',', lineterminator='\n')
        writer.writeheader()
        writer.writerows(Data)

Every approach i try would involve at some point having a dictionary with two headers named the same, which is of course not possible

A: Have you tried using pandas module ?
Convert your data into pandas dataframe ("df") and then use :
df.columns=['x','x']

and finally, save it to a csv file :
 df.to_csv(r'/home/ishan/Desktop/a.csv',header=True, index=False)

it will work.

A: Will this work for you?
[update] setting now the delimiter and line terminator
def DictListToCsv(Data, FileName, FieldNames):
    with open(FileName, 'w') as f:
        writer = csv.writer(f, dialect = 'excel', delimiter=',', lineterminator='\n')
        writer.writerow(FieldNames)
        writer.writerows(Data)

FieldNames = ['Spam','Spam','Spam','Spam','more Spam']
Data = [[11,12,13,14,15],[21,22,23,24,25]]

DictListToCsv(Data, 'eggs.csv', FieldNames)


text:
Q: Client and server in C how to keep communication I have a simple tcp based client and server written in c, but once I establish a connection after the server sends a message back to the client, the connection stops working. Could you help me fix this - I would like the server to continue receiving/ sending messages to the client.
Code:
Server.c
#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <resolv.h>
#include <arpa/inet.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <unistd.h>

#define port    5000
#define buf     512

void answer(int);

int main(int argc, char *argv[]){
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    int portid;
    int backlog = 10;
    struct sockaddr_in addr;
    char BUFF[buf];
    int n;
    int received = 0;
    int connfd;

    if(sock == -1){
        perror("socket error");
        exit(errno);
    }

    memset(&addr,0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_ANY;

    if(bind(sock, (struct sockaddr*) &addr, sizeof(addr)) == -1){
            perror("bind error");
            exit(errno);
    }

    if(listen(sock, backlog) == -1){
            perror("listen error");
            exit(errno);
    }

    listen(sock, 5);
    struct sockaddr_in cliaddr;
    //struct sockaddr_in addr;
    int cliaddr_len = sizeof(cliaddr);

    while(1){

        connfd = accept(sock, (struct sockaddr*)&cliaddr,&cliaddr_len);
        if(connfd == -1){
            perror("error connfd");
            exit(errno);
        }
        portid = fork();
        if(portid<0)
            perror("error on fork");
        if(portid ==0){
            close(sock);
            answer(connfd);
            exit(0);
        }

        //close(sock);
    }

    close(connfd);
    return 0;

    //close(sock);
    //return 0;
}

void answer(int connfd){
    int n;
    char BUFF[buf];
    memset(BUFF,buf,buf);
    n = read(connfd,BUFF,buf);
    printf("connected: %s",BUFF);
    //received = 1;
    //memset(BUFF,0,buf);
    printf("please enter your message: ");
    memset(BUFF,0,buf);
    fgets(BUFF,buf, stdin);
    n = write(connfd, BUFF,strlen(BUFF));
    if(n<0) err("writing to socket problem");
}

A: Your server is calling fork, then if(portid ==0){...get and send message...}, then it loops back to the top of the loop where it tries to accept() --- not the job of the child, but the child is trying to do that anyway.
Refactor your code to do what you want. Break it into smaller parts that are simple for you to inspect so you can see things like this.

A: This is because you recv() data just one time. Use a loop to receive until the client disconnects.
    while ((n = read(connfd,BUFF,buf))
    {
       printf("connected: %s",BUFF);
       //received = 1;
       //memset(BUFF,0,buf);
       printf("please enter your message: ");
       memset(BUFF,0,buf);
       fgets(BUFF,buf, stdin);
       n = write(connfd, BUFF,strlen(BUFF));
       if(n<0) err("writing to socket problem");
    }

A: You are reading the data in your child, so once the child is done the program exits, so try to read in the parent and send the data along to the child.


text:
Q: How to chain a promise that calls another promise in node js I'm new to node js, I'm trying to create a rest method that returns a list of objects, all was fine until I wanted to send the response, the logic does something like this:

*

*find objects

*init the objects

*push the object into a list

*send the list with the objects

what happens is that the point 3 is happening after the point 4 and I got an empty list, after research I found that is due to the async nature of node, I tried to rewrite the code using promises but I could not find an example of a promise that calls another promise
first version
app.get('/initDevices', (req, res) => {
    console.log('init devices.');
    cameras = [];
    onvif.startProbe().then((device_info_list) => {
        let requests = device_info_list.map((info) => {
            processDevice(info)
        });
        Promise.all(requests).then(() => {
            console.log('all done ');
            res.json(cameras);
        });
    }).catch((error) => {
        res.json('nothing');
    });
});

function processDevice(info) {
    return new Promise((resolve, reject) => {
        console.log("step 1");
        let device = new onvif.OnvifDevice();
        console.log("step 2");
        device.init().then((devinfo) => {
            console.log("step 3");
            cameras.push(devinfo);
            console.log("cameras: " + cameras.length);
            resolve("done");
        }).catch((error) => {
            reject("It broke");
        });
    });
}

output
 init devices.
 step 1
 step 2
 //response goes to the user with empty array []
 step 3 //push happens

second try (with promises)
function processDevice(info) {
    return new Promise((resolve) => {
        console.log("step 1");
        let device = new onvif.OnvifDevice();
        console.log("step 2");
        resolve(device);
    }).then((device) => {
       console.log("step 3");
        return device.init();
    }).then((device) => {
       console.log("step 4");
        return cameras.push(device);
    });
}

output
init devices.
step 1
step 2
step 3
//response goes to the user with empty array []
step 4 //push happens

I think this line return device.init(); makes the promise to finish but I do not know why.
Can someone help me to understand why the chain doesn't work as expected?
what did I do wrong?
by the way, the examples that I followed are here but the operations are just some additions that do not invoke other promises
Edit: I found a better way to achieve this
function processDevice(info) {
    let device = new onvif.OnvifDevice();
    return device.init().then(() => {
        console.log("init done");
        cameras.push(camObj);
    });
}

since a promise was already being used, it was not necessary to wrap it around another

A: Your requests variable is undefined - you have to return the processDevice(info) inside the map like this:
let requests = device_info_list.map((info) => {
            return processDevice(info)
        });


text:
Q: How to play a particular item from media play list? I am using windows media player in windows forms application. I have 10 media items in my playlist. foo, foo1,foo2,foo3 ....
Now my playlist is playing lets say foo1. Now on button click I want to play item foo6. How do I play this ? i.e. how do I change my current playing item too foo6 ?
If this is not clear please comment, I will add more information.
Edit: Following is the code for creating a new playlist.
WindowsMediaPlayerClass wmp = new WindowsMediaPlayerClass();
playlist = WMPLeft.playlistCollection.newPlaylist("myplaylist1");
for (int i = 0; i < FOO.Length; i++)
{
    media = WMPLeft.newMedia(FOO[i]);
    playlist.appendItem(media);
}

What I want is something like this
WMPLeft.playlist.Item(3).play();

This is wrong. But this is the kind of code I want.

A: After much research I have found this msdn link which shows how to do what I wanted.
// Declare a variable to hold the position of the media item
// in the current playlist. An arbitrary value is supplied here.
int index = 3;

// Get the media item at the fourth position in the current playlist.
WMPLib.IWMPMedia media = player.currentPlaylist.get_Item(index);

// Play the media item.
player.Ctlcontrols.playItem(media);

LINK to MSDN


text:
Q: OL missing numbers This is going to seem like a stupid question and is basic html but I'm going to ask it anyway. I've seen a few posts that ask this similar question and its not helping fix my issue. I'm working off my local server for testing. I have this for my syntax.

Kid Wonder

Kid Wonder

Kid Wonder

Kid Wonder

Kid Wonder

However it is not putting the numbers for the ordered list and just seeing if anyone can see my problem. This is what I have applied to the rendered page in my css:
li.top5rankings {
color: red;
display: block;
text-align: center;
}

styles.css (line 103)
* {
    margin: 0;
    padding: 0;
    }

styles.css (line 4) Inherited from ol
ol {
    list-style-position: inside;
    list-style-type: decimal;
}

A: If you're using any kind of css-reset stylesheet, it's likely that the list-style-type has been removed, or the margin has been set to 0. Try:
ol {
    margin-left: 2em;
}

ol li {
    list-style-type: decimal-leading-zero;
    list-style-position: outside;
}

JS Fiddle demo
It's also worth noting, as @Fredrik does in his answer, that the display property might be causing problems. For list-elements the default is:
display: list-item;

A: Try removing display: block; so that your css becomes like this instead:
li.top5rankings {
  color: red;
  text-align: center;
}