Programs & Examples On #Git filter branch

git filter-branch is a native Git tool used to extensively rewrite branches, and is often used to remove unwanted large or secret files from Git repository history.

How do you fix a bad merge, and replay your good commits onto a fixed merge?

Rewriting Git history demands changing all the affected commit ids, and so everyone who's working on the project will need to delete their old copies of the repo, and do a fresh clone after you've cleaned the history. The more people it inconveniences, the more you need a good reason to do it - your superfluous file isn't really causing a problem, but if only you are working on the project, you might as well clean up the Git history if you want to!

To make it as easy as possible, I'd recommend using the BFG Repo-Cleaner, a simpler, faster alternative to git-filter-branch specifically designed for removing files from Git history. One way in which it makes your life easier here is that it actually handles all refs by default (all tags, branches, etc) but it's also 10 - 50x faster.

You should carefully follow the steps here: http://rtyley.github.com/bfg-repo-cleaner/#usage - but the core bit is just this: download the BFG jar (requires Java 6 or above) and run this command:

$ java -jar bfg.jar --delete-files filename.orig my-repo.git

Your entire repository history will be scanned, and any file named filename.orig (that's not in your latest commit) will be removed. This is considerably easier than using git-filter-branch to do the same thing!

Full disclosure: I'm the author of the BFG Repo-Cleaner.

git rm - fatal: pathspec did not match any files

To remove the tracked and old committed file from git you can use the below command. Here in my case, I want to untrack and remove all the file from dist directory.

git filter-branch --force --index-filter 'git rm -r --cached --ignore-unmatch dist' --tag-name-filter cat -- --all

Then, you need to add it into your .gitignore so it won't be tracked further.

Detach (move) subdirectory into separate Git repository

This is no longer so complex you can just use the git filter-branch command on a clone of you repo to cull the subdirectories you don't want and then push to the new remote.

git filter-branch --prune-empty --subdirectory-filter <YOUR_SUBDIR_TO_KEEP> master
git push <MY_NEW_REMOTE_URL> -f .

How do I remove the old history from a git repository?

I needed to read several answers and some other info to understand what I was doing.

1. Ignore everything older than a certain commit

The file .git/info/grafts can define fake parents for a commit. A line with just a commit id, says that the commit doesn't have a parent. If we wanted to say that we care only about the last 2000 commits, we can type:

git rev-parse HEAD~2000 > .git/info/grafts

git rev-parse gives us the commit id of the 2000th parent of the current commit. The above command will overwrite the grafts file if present. Check if it's there first.

2. Rewrite the Git history (optional)

If you want to make this grafted fake parent a real one, then run:

git filter-branch -- --all

It will change all commit ids. Every copy of this repository needs to be updated forcefully.

3. Clean up disk space

I didn't done step 2, because I wanted my copy to stay compatible with the upstream. I just wanted to save some disk space. In order to forget all the old commits:

git prune
git gc

Alternative: shallow copies

If you have a shallow copy of another repository and just want to save some disk space, you can update .git/shallow. But be careful that nothing is pointing at a commit from before. So you could run something like this:

git fetch --prune
git rev-parse HEAD~2000 > .git/shallow
git prune
git gc

The entry in shallow works like a graft. But be careful not to use grafts and shallow at the same time. At least, don't have the same entries in there, it will fail.

If you still have some old references (tags, branches, remote heads) that point to older commits, they won't be cleaned up and you won't save more disk space.

How to change the author and committer name and e-mail of multiple commits in Git?

I want to add my Example too. I want to create a bash_function with given parameter.

this works in mint-linux-17.3

# $1 => email to change, $2 => new_name, $3 => new E-Mail

function git_change_user_config_for_commit {

 # defaults
 WRONG_EMAIL=${1:-"[email protected]"}
 NEW_NAME=${2:-"your name"}
 NEW_EMAIL=${3:-"[email protected]"}

 git filter-branch -f --env-filter "
  if [ \$GIT_COMMITTER_EMAIL = '$WRONG_EMAIL' ]; then
    export GIT_COMMITTER_NAME='$NEW_NAME'
    export GIT_COMMITTER_EMAIL='$NEW_EMAIL'
  fi
  if [ \$GIT_AUTHOR_EMAIL = '$WRONG_EMAIL' ]; then
    export GIT_AUTHOR_NAME='$NEW_NAME'
    export GIT_AUTHOR_EMAIL='$NEW_EMAIL'
  fi
 " --tag-name-filter cat -- --branches --tags;
}

Change first commit of project with Git?

If you want to modify only the first commit, you may try git rebase and amend the commit, which is similar to this post: How to modify a specified commit in git?

And if you want to modify all the commits which contain the raw email, filter-branch is the best choice. There is an example of how to change email address globally on the book Pro Git, and you may find this link useful http://git-scm.com/book/en/Git-Tools-Rewriting-History

Remove sensitive files and their commits from Git history

I've had to do this a few times to-date. Note that this only works on 1 file at a time.

  1. Get a list of all commits that modified a file. The one at the bottom will the the first commit:

    git log --pretty=oneline --branches -- pathToFile

  2. To remove the file from history use the first commit sha1 and the path to file from the previous command, and fill them into this command:

    git filter-branch --index-filter 'git rm --cached --ignore-unmatch <path-to-file>' -- <sha1-where-the-file-was-first-added>..

Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:

you have to be aware that when using interface builder and creating a Xib (nib) containing one cell that there is also a placeholder created that points to the class that will be used. Meaning, when you place two UITableViewCell in one Xib file you possibly run into the exact same trouble causing an *** Assertion failure .... The placeholder mechanism doesn't work adn will be confused then. Instead placing different placeholders in one Xib read on..

The most easy solution (even if that seems a bit to simple) is to place one Cell at a time in one Xib. IB will create a placeholder for you and all works as expected then. But this then leads directly to one extra line of code, because then you need to load the correct nib/xib asking for the reuseIdentified Cell where it resides in. So the following example code focuses the use of multiple Cell Indentifiers in one tableview where an Assertion Failure is very common.

// possibly above class implementation
static NSString *firstCellIdentifier = @"firstCellIdentifier";
static NSString *secondCellIdentifier = @"secondCellIdentifier";

// possibly in -(instancetype)init 
UINib *firstNib = [UINib nibWithNibName:@"FirstCell" bundle:nil];
[self.tableView registerNib:firstNib forCellReuseIdentifier:firstCellIdentifier];
UINib *secondNib = [UINib nibWithNibName:@"SecondCell" bundle:nil];
[self.tableView registerNib:secondNib forCellReuseIdentifier:secondCellIdentifier];

Another trouble with the use of two CellIdentifier's in one UITableView is that row height and/or section height have to be taken care of. Two cells can have different heights of course.

When registering classes for reuse the code should look different.

The "simple solution" looks also much different when your cells reside inside a Storyboard instead of Xib's. Watch out for the placeholders.

Keep also in mind that interface builder files have version wise variations and need to be set to a version that your targeted OS version supports. Even if you may be lucky that the particular feature you placed in your Xib is not changed since the last IB version and does not throw errors yet. So a Xib made with IB set to be compatible to iOS 13+ but used in a target that is compiled on an earlier version iOS 12.4 will cause also trouble and can end up with Assertion failure.

How can I replace text with CSS?

This worked for me with inline text. It was tested in Firefox, Safari, Chrome, and Opera.

<p>Lorem ipsum dolor sit amet, consectetur <span>Some Text</span> adipiscing elit.</p>

span {
    visibility: hidden;
    word-spacing: -999px;
    letter-spacing: -999px;
}

span:after {
    content: "goodbye";
    visibility: visible;
    word-spacing: normal;
    letter-spacing: normal;
}

Sharing link on WhatsApp from mobile website (not application) for Android

use it like "whatsapp://send?text=" + encodeURIComponent(your text goes here), it will definitely work.

getting the difference between date in days in java

Use JodaTime for this. It is much better than the standard Java DateTime Apis. Here is the code in JodaTime for calculating difference in days:

private static void dateDiff() {

    System.out.println("Calculate difference between two dates");
    System.out.println("=================================================================");

    DateTime startDate = new DateTime(2000, 1, 19, 0, 0, 0, 0);
    DateTime endDate = new DateTime();

    Days d = Days.daysBetween(startDate, endDate);
    int days = d.getDays();

    System.out.println("  Difference between " + endDate);
    System.out.println("  and " + startDate + " is " + days + " days.");

  }

Why can't I call a public method in another class?

For example 1 and 2 you need to create static methods:

public static string InstanceMethod() {return "Hello World";}

Then for example 3 you need an instance of your object to invoke the method:

object o = new object();
string s = o.InstanceMethod();

Refer to a cell in another worksheet by referencing the current worksheet's name?

Still using indirect. Say your A1 cell is your variable that will contain the name of the referenced sheet (Jan). If you go by:

=INDIRECT(CONCATENATE("'",A1," Item'", "!J3"))

Then you will have the 'Jan Item'!J3 value.

Splitting string with pipe character ("|")

split takes regex as a parameter.| has special meaning in regex.. use \\| instead of | to escape it.

Could not load file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies

I had this same problem - some users could pull from git and everything ran fine. Some would pull and get a very similar exception:

Could not load file or assembly '..., Version=..., Culture=neutral, PublicKeyToken=...' or one of its dependencies. The system cannot find the file specified.

In my particular case it was AjaxMin, so the actual error looked like this but the details don't matter:

Could not load file or assembly 'AjaxMin, Version=4.95.4924.12383, Culture=neutral, PublicKeyToken=21ef50ce11b5d80f' or one of its dependencies. The system cannot find the file specified.

It turned out to be a result of the following actions on a Solution:

  1. NuGet Package Restore was turned on for the Solution.

  2. A Project was added, and a Nuget package was installed into it (AjaxMin in this case).

  3. The Project was moved to different folder in the Solution.

  4. The Nuget package was updated to a newer version.

And slowly but surely this bug started showing up for some users.

The reason was the Solution-level packages/respositories.config kept the old Project reference, and now had a new, second entry for the moved Project. In other words it had this before the reorg:

  <repository path="..\Old\packages.config" />

And this after the reorg:

  <repository path="..\Old\packages.config" />
  <repository path="..\New\packages.config" />

So the first line now refers to a Project that, while on disk, is no longer part of my Solution.

With Nuget Package Restore on, both packages.config files were being read, which each pointed to their own list of Nuget packages and package versions. Until a Nuget package was updated to a newer version however, there weren't any conflicts.

Once a Nuget package was updated, however, only active Projects had their repositories listings updated. NuGet Package Restore chose to download just one version of the library - the first one it encountered in repositories.config, which was the older one. The compiler and IDE proceeded as though it chose the newer one. The result was a run-time exception saying the DLL was missing.

The answer obviously is to delete any lines from this file that referenced Projects that aren't in your Solution.

Value cannot be null. Parameter name: source

It could be as silly as in my case where savechanges was erroring bcoz the db did not have foreign keys and associations were added to EDM tables. I added foreign keys in the db and regenerated EDM for a fix.

The errors I was seeing are as follows: Case 1 -> when using DBContext for EDM Message=Value cannot be null. Parameter name: source at System.Linq.Enumerable.Any[TSource](IEnumerable1 source, Func2 predicate)

Case 2 -> when using ObjectContext for EDM Message=Unable to update the EntitySet 'Contact' because it has a DefiningQuery and no element exists in the element to support the current operation.

(Just wanted to throw it in there in case it helps someone).

Instagram API to fetch pictures with specific hashtags

Firstly, the Instagram API endpoint "tags" required OAuth authentication.

You can query results for a particular hashtag (snowy in this case) using the following url

It is rate limited to 5000 (X-Ratelimit-Limit:5000) per hour

https://api.instagram.com/v1/tags/snowy/media/recent

Sample response

{
  "pagination":  {
    "next_max_tag_id": "1370433362010",
    "deprecation_warning": "next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
    "next_max_id": "1370433362010",
    "next_min_id": "1370443976800",
    "min_tag_id": "1370443976800",
    "next_url": "https://api.instagram.com/v1/tags/snowy/media/recent?access_token=40480112.1fb234f.4866541998fd4656a2e2e2beaa5c4bb1&max_tag_id=1370433362010"
  },
  "meta":  {
    "code": 200
  },
  "data":  [
     {
      "attribution": null,
      "tags":  [
        "snowy"
      ],
      "type": "image",
      "location": null,
      "comments":  {
        "count": 0,
        "data":  []
      },
      "filter": null,
      "created_time": "1370418343",
      "link": "http://instagram.com/p/aK1yrGRi3l/",
      "likes":  {
        "count": 1,
        "data":  [
           {
            "username": "iri92lol",
            "profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
            "id": "404174490",
            "full_name": "Iri"
          }
        ]
      },
      "images":  {
        "low_resolution":  {
          "url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_6.jpg",
          "width": 306,
          "height": 306
        },
        "thumbnail":  {
          "url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_5.jpg",
          "width": 150,
          "height": 150
        },
        "standard_resolution":  {
          "url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_7.jpg",
          "width": 612,
          "height": 612
        }
      },
      "users_in_photo":  [],
      "caption":  {
        "created_time": "1370418353",
        "text": "#snowy",
        "from":  {
          "username": "iri92lol",
          "profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
          "id": "404174490",
          "full_name": "Iri"
        },
        "id": "471425773832908504"
      },
      "user_has_liked": false,
      "id": "471425689728724453_404174490",
      "user":  {
        "username": "iri92lol",
        "website": "",
        "profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
        "full_name": "Iri",
        "bio": "",
        "id": "404174490"
      }
    }
}

You can play around here :

https://apigee.com/console/instagram?req=%7B%22resource%22%3A%22get_tags_media_recent%22%2C%22params%22%3A%7B%22query%22%3A%7B%7D%2C%22template%22%3A%7B%22tag-name%22%3A%22snowy%22%7D%2C%22headers%22%3A%7B%7D%2C%22body%22%3A%7B%22attachmentFormat%22%3A%22mime%22%2C%22attachmentContentDisposition%22%3A%22form-data%22%7D%7D%2C%22verb%22%3A%22get%22%7D

You need to use "Authentication" as OAuth 2 and will be prompted to signin via Instagram. Post that you might have to reneter the "tag-name" in "Template" section.

All the pagination related data is available in the "pagination" parameter in the response and use it's "next_url" to query for the next set of result.

Waiting for Target Device to Come Online

Go to terminal and type android avd. Select your AVD and select "Edit". Make sure you do not see No CPU/ABI system image available for this target - it will show in red font at the bottom. Change the target to the one that is available or download the ABI image. Sometimes, if you create an AVD from inside Android Studio, it does not ensure this requirement.

AVD error

How to insert programmatically a new line in an Excel cell in C#?

You can use Chr(13). Then just wrap the whole thing in Chr(34). Chr(34) is double quotes.

  • VB.Net Example:
  • TheContactInfo = ""
  • TheContactInfo = Trim(TheEmail) & chr(13)
  • TheContactInfo = TheContactInfo & Trim(ThePhone) & chr(13)
  • TheContactInfo = Chr(34) & TheContactInfo & Chr(34)

Swift: Sort array of objects alphabetically

Sorted array Swift 4.2

arrayOfRaces = arrayOfItems.sorted(by: { ($0["raceName"] as! String) < ($1["raceName"] as! String) })

Concatenate a vector of strings/character

Try using an empty collapse argument within the paste function:

paste(sdata, collapse = '')

Thanks to http://twitter.com/onelinetips/status/7491806343

Last executed queries for a specific database

This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):

SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC

This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.

In Angular, how to add Validator to FormControl after control is created?

In addition to Eduard Void answer here's the addValidators method:

declare module '@angular/forms' {
  interface FormControl {
    addValidators(validators: ValidatorFn[]): void;
  }
}

FormControl.prototype.addValidators = function(this: FormControl, validators: ValidatorFn[]) {
  if (!validators || !validators.length) {
    return;
  }

  this.clearValidators();
  this.setValidators( this.validator ? [ this.validator, ...validators ] : validators );
};

Using it you can set validators dynamically:

some_form_control.addValidators([ first_validator, second_validator ]);
some_form_control.addValidators([ third_validator ]);

Write values in app.config file

Try the following:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);            
config.AppSettings.Settings[key].Value = value;
config.Save();
ConfigurationManager.RefreshSection("appSettings");

Is it possible to view RabbitMQ message contents directly from the command line?

You should enable the management plugin.

rabbitmq-plugins enable rabbitmq_management

See here:

http://www.rabbitmq.com/plugins.html

And here for the specifics of management.

http://www.rabbitmq.com/management.html

Finally once set up you will need to follow the instructions below to install and use the rabbitmqadmin tool. Which can be used to fully interact with the system. http://www.rabbitmq.com/management-cli.html

For example:

rabbitmqadmin get queue=<QueueName> requeue=false

will give you the first message off the queue.

Select unique values with 'select' function in 'dplyr' library

In dplyr 0.3 this can be easily achieved using the distinct() method.

Here is an example:

distinct_df = df %>% distinct(field1)

You can get a vector of the distinct values with:

distinct_vector = distinct_df$field1

You can also select a subset of columns at the same time as you perform the distinct() call, which can be cleaner to look at if you examine the data frame using head/tail/glimpse.:

distinct_df = df %>% distinct(field1) %>% select(field1) distinct_vector = distinct_df$field1

Why is the use of alloca() not considered good practice?

As noted in this newsgroup posting, there are a few reasons why using alloca can be considered difficult and dangerous:

  • Not all compilers support alloca.
  • Some compilers interpret the intended behaviour of alloca differently, so portability is not guaranteed even between compilers that support it.
  • Some implementations are buggy.

how to delete a specific row in codeigniter?

My controller

public function delete_category()   //Created a controller class //
    {      
         $this->load->model('Managecat'); //Load model Managecat here 
         $id=$this->input->get('id');     //  get the requested in a variable
         $sql_del=$this->Managecat->deleteRecord($id); //send the parameter $id in Managecat  there I have created a function name deleteRecord

         if($sql_del){

               $data['success'] = "Category Have been deleted Successfully!!";  //success message goes here 

         }

    }

My Model

public function deleteRecord($id) {

    $this->db->where('cat_id', $id);
    $del=$this->db->delete('category');   
    return $del;

}

Nesting optgroups in a dropdownlist/select

I think if you have something that structured and complex, you might consider something other than a single drop-down box.

Pandas: how to change all the values of a column?

Or if one want to use lambda function in the apply function:

data['Revenue']=data['Revenue'].apply(lambda x:float(x.replace("$","").replace(",", "").replace(" ", "")))

Convert datetime object to a String of date only in Python

You can convert datetime to string.

published_at = "{}".format(self.published_at)

Add centered text to the middle of a <hr/>-like line

Woohoo my first post even though this is a year old. To avoid the background-coloring issues with wrappers, you could use inline-block with hr (nobody said that explicitly). Text-align should center correctly since they are inline elements.

<div style="text-align:center">
    <hr style="display:inline-block; position:relative; top:4px; width:45%" />
       &nbsp;New Section&nbsp;
    <hr style="display:inline-block; position:relative; top:4px; width:45%" />
</div>

How to change href attribute using JavaScript after opening the link in a new window?

Your onclick fires before the href so it will change before the page is opened, you need to make the function handle the window opening like so:

function changeLink() {
    var link = document.getElementById("mylink");

    window.open(
      link.href,
      '_blank'
    );

    link.innerHTML = "facebook";
    link.setAttribute('href', "http://facebook.com");

    return false;
}

How to get raw text from pdf file using java

For the newer versions of Apache pdfbox. Here is the example from the original source

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.pdfbox.examples.util;

import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.text.PDFTextStripper;

/**
 * This is a simple text extraction example to get started. For more advance usage, see the
 * ExtractTextByArea and the DrawPrintTextLocations examples in this subproject, as well as the
 * ExtractText tool in the tools subproject.
 *
 * @author Tilman Hausherr
 */
public class ExtractTextSimple
{
    private ExtractTextSimple()
    {
        // example class should not be instantiated
    }

    /**
     * This will print the documents text page by page.
     *
     * @param args The command line arguments.
     *
     * @throws IOException If there is an error parsing or extracting the document.
     */
    public static void main(String[] args) throws IOException
    {
        if (args.length != 1)
        {
            usage();
        }

        try (PDDocument document = PDDocument.load(new File(args[0])))
        {
            AccessPermission ap = document.getCurrentAccessPermission();
            if (!ap.canExtractContent())
            {
                throw new IOException("You do not have permission to extract text");
            }

            PDFTextStripper stripper = new PDFTextStripper();

            // This example uses sorting, but in some cases it is more useful to switch it off,
            // e.g. in some files with columns where the PDF content stream respects the
            // column order.
            stripper.setSortByPosition(true);

            for (int p = 1; p <= document.getNumberOfPages(); ++p)
            {
                // Set the page interval to extract. If you don't, then all pages would be extracted.
                stripper.setStartPage(p);
                stripper.setEndPage(p);

                // let the magic happen
                String text = stripper.getText(document);

                // do some nice output with a header
                String pageStr = String.format("page %d:", p);
                System.out.println(pageStr);
                for (int i = 0; i < pageStr.length(); ++i)
                {
                    System.out.print("-");
                }
                System.out.println();
                System.out.println(text.trim());
                System.out.println();

                // If the extracted text is empty or gibberish, please try extracting text
                // with Adobe Reader first before asking for help. Also read the FAQ
                // on the website: 
                // https://pdfbox.apache.org/2.0/faq.html#text-extraction
            }
        }
    }

    /**
     * This will print the usage for this document.
     */
    private static void usage()
    {
        System.err.println("Usage: java " + ExtractTextSimple.class.getName() + " <input-pdf>");
        System.exit(-1);
    }
}

java.time.format.DateTimeParseException: Text could not be parsed at index 21

The default parser can parse your input. So you don't need a custom formatter and

String dateTime = "2012-02-22T02:06:58.147Z";
ZonedDateTime d = ZonedDateTime.parse(dateTime);

works as expected.

Breaking up long strings on multiple lines in Ruby without stripping newlines

Three years later, there is now a solution in Ruby 2.3: The squiggly heredoc.

class Subscription
  def warning_message
    <<~HEREDOC
      Subscription expiring soon!
      Your free trial will expire in #{days_until_expiration} days.
      Please update your billing information.
    HEREDOC
  end
end

Blog post link: https://infinum.co/the-capsized-eight/articles/multiline-strings-ruby-2-3-0-the-squiggly-heredoc

The indentation of the least-indented line will be removed from each line of the content.

What is the difference between And and AndAlso in VB.NET?

In addition to the answers above, AndAlso provides a conditioning process known as short circuiting. Many programming languages have this functionality built in like vb.net does, and can provide substantial performance increases in long condition statements by cutting out evaluations that are unneccessary.

Another similar condition is the OrElse condition which would only check the right condition if the left condition is false, thus cutting out unneccessary condition checks after a true condition is found.

I would advise you to always use short circuiting processes and structure your conditional statements in ways that can benefit the most by this. For example, test your most efficient and fastest conditions first so that you only run your long conditions when you absolutely have to and short circuit the other times.

Launch Failed. Binary not found. CDT on Eclipse Helios

I had this problem for a long while and I couldn't figure out the answer. I had added all the paths, built everything and pretty much followed what everyone on here had suggested, but no luck.

Finally I read the comments and saw that there were some compilation errors that were aborting the procedure before the binaries and exe file was generated.

Bottom line: Do a code review and make sure that there are no errors in your code because sometimes eclipse will not always catch everything.

If you can run a basic hello world but not your code then obviously something is wrong with your code. I learned the hard way.

How to write macro for Notepad++?

Posting more than 10 years after the OP, but I think that this is still a relevant question (it is for me, at least). Today, there is quite some information in the Notepad++ User Manual, relating to the OP's question:

Here is a block of macro code: replace SEARCHTEXT by REPLACETEXT, using regular expressions, "." finds /r and /n, in every file matching the filter GLOBFILEFILTER in a folder PATH (no subfolders, not sure where this flag is defined/set).

<Macro name="REPLACE_IN_FILES_REGEX_DOT_FINDS_CR_AND_LF" Ctrl="no" Alt="no" Shift="no" Key="0">
    <Action type="3" message="1700" wParam="0" lParam="0" sParam="" />
    <Action type="3" message="1601" wParam="0" lParam="0" sParam="SEARCHTEXT" />
    <Action type="3" message="1625" wParam="0" lParam="2" sParam="" />
    <Action type="3" message="1602" wParam="0" lParam="0" sParam="REPLACETEXT" />
    <Action type="3" message="1653" wParam="0" lParam="0" sParam="PATH" />
    <Action type="3" message="1652" wParam="0" lParam="0" sParam="GLOBFILEFILTER" />
    <Action type="3" message="1702" wParam="0" lParam="1024" sParam="" /> 
        <!-- #COMMENT: "1024" seems to be the flag ". finds /n and /r". This is not in the documentation. -->
    <Action type="3" message="1701" wParam="0" lParam="1660" sParam="" />
</Macro>

Remarks about this code:

  • The path to the folder needs to end with a backslash.
  • Characters like <, >, & need to be escaped in the xml. Rather create your search and replace strings by recording a macro.

Find maximum value of a column and return the corresponding row values using Pandas

I'd recommend using nlargest for better performance and shorter code. import pandas

df[col_name].value_counts().nlargest(n=1)

Concept behind putting wait(),notify() methods in Object class

In simple terms, the reasons are as follows.

  1. Object has monitors.
  2. Multiple threads can access one Object. Only one thread can hold object monitor at a time for synchronized methods/blocks.
  3. wait(), notify() and notifyAll() method being in Object class allows all the threads created on that object to communicate with other
  4. Locking ( using synchronized or Lock API) and Communication (wait() and notify()) are two different concepts.

If Thread class contains wait(), notify() and notifyAll() methods, then it will create below problems:

  1. Thread communication problem
  2. Synchronization on object won’t be possible. If each thread will have monitor, we won’t have any way of achieving synchronization
  3. Inconsistency in state of object

Refer to this article for more details.

How can I color Python logging output?

The following solution works with python 3 only, but for me it looks most clear.

The idea is to use log record factory to add 'colored' attributes to log record objects and than use these 'colored' attributes in log format.

import logging
logger = logging.getLogger(__name__)

def configure_logging(level):

    # add 'levelname_c' attribute to log resords
    orig_record_factory = logging.getLogRecordFactory()
    log_colors = {
        logging.DEBUG:     "\033[1;34m",  # blue
        logging.INFO:      "\033[1;32m",  # green
        logging.WARNING:   "\033[1;35m",  # magenta
        logging.ERROR:     "\033[1;31m",  # red
        logging.CRITICAL:  "\033[1;41m",  # red reverted
    }
    def record_factory(*args, **kwargs):
        record = orig_record_factory(*args, **kwargs)
        record.levelname_c = "{}{}{}".format(
            log_colors[record.levelno], record.levelname, "\033[0m")
        return record

    logging.setLogRecordFactory(record_factory)

    # now each log record object would contain 'levelname_c' attribute
    # and you can use this attribute when configuring logging using your favorite
    # method.
    # for demo purposes I configure stderr log right here

    formatter_c = logging.Formatter("[%(asctime)s] %(levelname_c)s:%(name)s:%(message)s")

    stderr_handler = logging.StreamHandler()
    stderr_handler.setLevel(level)
    stderr_handler.setFormatter(formatter_c)

    root_logger = logging.getLogger('')
    root_logger.setLevel(logging.DEBUG)
    root_logger.addHandler(stderr_handler)


def main():
    configure_logging(logging.DEBUG)

    logger.debug("debug message")
    logger.info("info message")
    logger.critical("something unusual happened")


if __name__ == '__main__':
    main()

You can easily modify this example to create other colored attributes (f.e. message_c) and then use these attributes to get colored text (only) where you want.

(handy trick I discovered recently: I have a file with colored debug logs and whenever I want temporary increase the log level of my application I just tail -f the log file in different terminal and see debug logs on screen w/o changing any configuration and restarting application)

CAST DECIMAL to INT

The CAST() function does not support the "official" data type "INT" in MySQL, it's not in the list of supported types. With MySQL, "SIGNED" (or "UNSIGNED") could be used instead:

CAST(columnName AS SIGNED)

However, this seems to be MySQL-specific (not standardized), so it may not work with other databases. At least this document (Second Informal Review Draft) ISO/IEC 9075:1992, Database does not list "SIGNED"/"UNSIGNED" in section 4.4 Numbers.

But DECIMAL is both standardized and supported by MySQL, so the following should work for MySQL (tested) and other databases:

CAST(columnName AS DECIMAL(0))

According to the MySQL docs:

If the scale is 0, DECIMAL values contain no decimal point or fractional part.

HTML/CSS font color vs span style

Use style. The font tag is deprecated (W3C Wiki).

What column type/length should I use for storing a Bcrypt hashed password in a Database?

I don't think that there are any neat tricks you can do storing this as you can do for example with an MD5 hash.

I think your best bet is to store it as a CHAR(60) as it is always 60 chars long

Can you nest html forms?

Even if you could get it to work in one browser, there's no guarantee that it would work the same in all browsers. So while you might be able to get it to work some of the time, you certainly wouldn't be able to get it to work all of the time.

When using a Settings.settings file in .NET, where is the config actually stored?

While browsing around to figure out about the hash in the folder name, I came across (via this answer):

http://blogs.msdn.com/b/rprabhu/archive/2005/06/29/433979.aspx

(edit: Wayback Machine link: https://web.archive.org/web/20160307233557/http://blogs.msdn.com:80/b/rprabhu/archive/2005/06/29/433979.aspx)

The exact path of the user.config files looks something like this:

<Profile Directory>\<Company Name>\<App Name>_<Evidence Type>_<Evidence Hash>\<Version>\user.config

where

<Profile Directory> - is either the roaming profile directory or the local one. Settings are stored by default in the local user.config file. To store a setting in the roaming user.config file, you need to mark the setting with the SettingsManageabilityAttribute with SettingsManageability set to Roaming.

<Company Name> - is typically the string specified by the AssemblyCompanyAttribute (with the caveat that the string is escaped and truncated as necessary, and if not specified on the assembly, we have a fallback procedure).

<App Name> - is typically the string specified by the AssemblyProductAttribute (same caveats as for company name).

<Evidence Type> and <Evidence Hash> - information derived from the app domain evidence to provide proper app domain and assembly isolation.

<Version> - typically the version specified in the AssemblyVersionAttribute. This is required to isolate different versions of the app deployed side by side.

The file name is always simply 'user.config'.

Using the Jersey client to do a POST operation

Not done this yet myself, but a quick bit of Google-Fu reveals a tech tip on blogs.oracle.com with examples of exactly what you ask for.

Example taken from the blog post:

MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");
ClientResponse response = webResource
    .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
    .post(ClientResponse.class, formData);

That any help?

Check if cookie exists else set cookie to Expire in 10 days

You need to read and write document.cookie

if (document.cookie.indexOf("visited=") >= 0) {
  // They've been here before.
  alert("hello again");
}
else {
  // set a new cookie
  expiry = new Date();
  expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes

  // Date()'s toGMTSting() method will format the date correctly for a cookie
  document.cookie = "visited=yes; expires=" + expiry.toGMTString();
  alert("this is your first time");
}

Java null check why use == instead of .equals()

if you invoke .equals() on null you will get NullPointerException

So it is always advisble to check nullity before invoking method where ever it applies

if(str!=null && str.equals("hi")){
 //str contains hi
}  

Also See

Android Studio Emulator and "Process finished with exit code 0"

You can try to delete the emulator and reinstall it this usually does the trick for me. Sometimes you also run into hiccups on your computer so try restarting your computer. Your computer may not be able to handle android studio if so there is nothing you can do. Consequently, you may not have the right ram requirements. Finally, If all else fails you can try to delete then reinstall android studio.

Appending a byte[] to the end of another byte[]

The other provided solutions are great when you want to add only 2 byte arrays, but if you want to keep appending several byte[] chunks to make a single:

byte[] readBytes ; // Your byte array .... //for eg. readBytes = "TestBytes".getBytes();

ByteArrayBuffer mReadBuffer = new ByteArrayBuffer(0 ) ; // Instead of 0, if you know the count of expected number of bytes, nice to input here

mReadBuffer.append(readBytes, 0, readBytes.length); // this copies all bytes from readBytes byte array into mReadBuffer
// Any new entry of readBytes, you can just append here by repeating the same call.

// Finally, if you want the result into byte[] form:
byte[] result = mReadBuffer.buffer();

What tool can decompile a DLL into C++ source code?

There really isn't any way of doing this as most of the useful information is discarded in the compilation process. However, you may want to take a look at this site to see if you can find some way of extracting something from the DLL.

how to remove pagination in datatable

It's working

Try below code

$('#example').dataTable({
    "bProcessing": true,
    "sAutoWidth": false,
    "bDestroy":true,
    "sPaginationType": "bootstrap", // full_numbers
    "iDisplayStart ": 10,
    "iDisplayLength": 10,
    "bPaginate": false, //hide pagination
    "bFilter": false, //hide Search bar
    "bInfo": false, // hide showing entries
})

Disable activity slide-in animation when launching new activity?

The FLAG_ACTIVITY_NO_ANIMATION flag works fine for disabling the animation when starting activities.

To disable the similar animation that is triggered when calling finish() on an Activity, i.e the animation slides from right to left instead, you can call overridePendingTransition(0, 0) after calling finish() and the next animation will be excluded.

This also works on the in-animation if you call overridePendingTransition(0, 0) after calling startActivity(...).

Pointer to incomplete class type is not allowed

You get this error when declaring a forward reference inside the wrong namespace thus declaring a new type without defining it. For example:

namespace X
{
  namespace Y
  {
    class A;

    void func(A* a) { ... } // incomplete type here!
  }
}

...but, in class A was defined like this:

namespace X
{
  class A { ... };
}

Thus, A was defined as X::A, but I was using it as X::Y::A.

The fix obviously is to move the forward reference to its proper place like so:

namespace X
{
  class A;
  namespace Y
  {
    void func(X::A* a) { ... } // Now accurately referencing the class`enter code here`
  }
}

How to delete all data from solr and hbase

Post json data (e.g. with curl)

curl -X POST -H 'Content-Type: application/json' \
    'http://<host>:<port>/solr/<core>/update?commit=true' \
    -d '{ "delete": {"query":"*:*"} }'

svn over HTTP proxy

Okay, this topic is somewhat outdated, but as I found it on google and have a solution this might be interesting for someone:

Basically (of course) this is not possible on every http proxy but works on proxies allowing http connect on port 3690. This method is used by http proxies on port 443 to provide a way for secure https connections. If your administrator configures the proxy to open port 3690 for http connect you can setup your local machine to establish a tunnel through the proxy.

I just was in the need to check out some files from svn.openwrt.org within our companies network. An easy solution to create a tunnel is adding the following line to your /etc/hosts

127.0.0.1 svn.openwrt.org

Afterwards, you can use socat to create a tcp tunnel to a local port:

while true; do socat tcp-listen:3690 proxy:proxy.at.your.company:svn.openwrt.org:3690; done

You should execute the command as root. It opens the local port 3690 and on connection creates a tunnel to svn.openwrt.org on the same port.

Just replace the port and server addresses on your own needs.

Maven "build path specifies execution environment J2SE-1.5", even though I changed it to 1.7

I was facing the same issue. In pom.xml I have specified maven compiler plugin to pick 1.7 as source and target. Even then when I would import the git project in eclipse it would pick 1.5 as compile version for the project. To be noted that the eclipse has installed runtime set to JDK 1.8

I also checked that none of the .classpath .impl or .project file is checked in git repository.

Solution that worked for me: I simply deleted .classpath files and did a 'maven-update project'. .classpath file was regenerated and it picked up 1.7 as compile version from pom file.

Subscripts in plots in R

Another example, expression works for negative superscripts without the need for quotes around the negative number:

title(xlab=expression("Nitrate Loading in kg ha"^-1*"yr"^-1))

and you only need the * to separate sections as mentioned above (when you write a superscript or subscript and need to add more text to the expression after).

Where can I download Eclipse Android bundle?

The Android Developer pages still state how you can download and use the ADT plugin for Eclipse:

  1. Start Eclipse, then select Help > Install New Software.
  2. Click Add, in the top-right corner.
  3. In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following URL for the Location: https://dl-ssl.google.com/android/eclipse/
  4. Click OK.
  5. In the Available Software dialog, select the checkbox next to Developer Tools and click Next.
  6. In the next window, you'll see a list of the tools to be downloaded. Click Next.
  7. Read and accept the license agreements, then click Finish. If you get a security warning saying that the authenticity or validity of the software can't be established, click OK
  8. When the installation completes, restart Eclipse.

Links for the Eclipse ADT Bundle (found using Archive.org's WayBackMachine) I don't know how future-proof these links are. They all worked on February 27th, 2017.


Update (2015-06-29): Google will end development and official support for ADT in Eclipse at the end of this year and recommends switching to Android Studio.

Storing data into list with class

And if you want to create the list with some elements to start with:

var emailList = new List<EmailData>
{
   new EmailData { FirstName = "John", LastName = "Doe", Location = "Moscow" },
   new EmailData {.......}
};

How to use bootstrap datepicker

You should include bootstrap-datepicker.js after bootstrap.js and you should bind the datepicker to your control.

$(function(){
   $('.datepicker').datepicker({
      format: 'mm-dd-yyyy'
    });
});

Java 8 Iterable.forEach() vs foreach loop

The advantage comes into account when the operations can be executed in parallel. (See http://java.dzone.com/articles/devoxx-2012-java-8-lambda-and - the section about internal and external iteration)

  • The main advantage from my point of view is that the implementation of what is to be done within the loop can be defined without having to decide if it will be executed in parallel or sequential

  • If you want your loop to be executed in parallel you could simply write

     joins.parallelStream().forEach(join -> mIrc.join(mSession, join));
    

    You will have to write some extra code for thread handling etc.

Note: For my answer I assumed joins implementing the java.util.Stream interface. If joins implements only the java.util.Iterable interface this is no longer true.

What is a wrapper class?

Wrapper classes came in to existence to fulfill a basic need of programmers - i.e. to use primitive values wherever only Objects are allowed. As their name suggests wrapper classes wrap around a primitive value and hold the value in an Object. So, all those places where primitives were not allowed - such as generics, hashmap-keys, Arraylists etc - programmers now have an option of providing these primitive values as their corresponding wrapper types.

In addition these wrapper types have a number of utility methods for converting from primitive type to corresponding wrapper types and back, and also from Strings to wrapper types and back.

I have written a detailed article on wrapper classes in a my blog which explains the concept of wrapper types in depth - http://www.javabrahman.com/corejava/java-wrapper-classes-tutorial-with-examples/ (Disclosure - This blog is owned by me)

how to access iFrame parent page using jquery?

To find in the parent of the iFrame use:

$('#parentPrice', window.parent.document).html();

The second parameter for the $() wrapper is the context in which to search. This defaults to document.

How to enable CORS in ASP.net Core WebAPI

try adding jQuery.support.cors = true; before the Ajax call

It could also be that the data your sending to the API is wonky,

try adding the following JSON function

        var JSON = JSON || {};

    // implement JSON.stringify serialization
    JSON.stringify = JSON.stringify || function (obj) {

        var t = typeof (obj);
        if (t != "object" || obj === null) {

            // simple data type
            if (t == "string") obj = '"' + obj + '"';
            return String(obj);

        }
        else {

            // recurse array or object
            var n, v, json = [], arr = (obj && obj.constructor == Array);

            for (n in obj) {
                v = obj[n]; t = typeof (v);

                if (t == "string") v = '"' + v + '"';
                else if (t == "object" && v !== null) v = JSON.stringify(v);

                json.push((arr ? "" : '"' + n + '":') + String(v));
            }

            return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
        }
    };

    // implement JSON.parse de-serialization
    JSON.parse = JSON.parse || function (str) {
        if (str === "") str = '""';
        eval("var p=" + str + ";");
        return p;
    };

then in your data: object change it to

    data: JSON.stringify({
        username: username,
        password: password
    }),

How to use table variable in a dynamic sql statement?

On SQL Server 2008+ it is possible to use Table Valued Parameters to pass in a table variable to a dynamic SQL statement as long as you don't need to update the values in the table itself.

So from the code you posted you could use this approach for @TSku but not for @RelPro

Example syntax below.

CREATE TYPE MyTable AS TABLE 
( 
Foo int,
Bar int
);
GO


DECLARE @T AS MyTable;

INSERT INTO @T VALUES (1,2), (2,3)

SELECT *,
        sys.fn_PhysLocFormatter(%%physloc%%) AS [physloc]
FROM @T

EXEC sp_executesql
  N'SELECT *,
        sys.fn_PhysLocFormatter(%%physloc%%) AS [physloc]
    FROM @T',
  N'@T MyTable READONLY',
  @T=@T 

The physloc column is included just to demonstrate that the table variable referenced in the child scope is definitely the same one as the outer scope rather than a copy.

How can I access the MySQL command line with XAMPP for Windows?

Go to /xampp/mysql/bin and find for mysql. exe

open cmd, change the directory to mysq after write in cmd

mysql -h localhost -u root

How to change root logging level programmatically for logback

I think you can use MDC to change logging level programmatically. The code below is an example to change logging level on current thread. This approach does not create dependency to logback implementation (SLF4J API contains MDC).

<configuration>
  <turboFilter class="ch.qos.logback.classic.turbo.DynamicThresholdFilter">
    <Key>LOG_LEVEL</Key>
    <DefaultThreshold>DEBUG</DefaultThreshold>
    <MDCValueLevelPair>
      <value>TRACE</value>
      <level>TRACE</level>
    </MDCValueLevelPair>
    <MDCValueLevelPair>
      <value>DEBUG</value>
      <level>DEBUG</level>
    </MDCValueLevelPair>
    <MDCValueLevelPair>
      <value>INFO</value>
      <level>INFO</level>
    </MDCValueLevelPair>
    <MDCValueLevelPair>
      <value>WARN</value>
      <level>WARN</level>
    </MDCValueLevelPair>
    <MDCValueLevelPair>
      <value>ERROR</value>
      <level>ERROR</level>
    </MDCValueLevelPair>
  </turboFilter>
  ......
</configuration>
MDC.put("LOG_LEVEL", "INFO");

Can a JSON value contain a multiline string

Per the specification, the JSON grammar's char production can take the following values:

  • any-Unicode-character-except-"-or-\-or-control-character
  • \"
  • \\
  • \/
  • \b
  • \f
  • \n
  • \r
  • \t
  • \u four-hex-digits

Newlines are "control characters", so no, you may not have a literal newline within your string. However, you may encode it using whatever combination of \n and \r you require.

The JSONLint tool confirms that your JSON is invalid.


And, if you want to write newlines inside your JSON syntax without actually including newlines in the data, then you're doubly out of luck. While JSON is intended to be human-friendly to a degree, it is still data and you're trying to apply arbitrary formatting to that data. That is absolutely not what JSON is about.

What's a good hex editor/viewer for the Mac?

The one that I like is HexEdit Quick and easy to use

How do I set the default Java installation/runtime (Windows)?

I have several JDK (1.4, 1.5, 1.6) installed in C:\Java with their JREs. Then I let Sun update the public JRE in C:\Program Files\Java.
Lately there is an improvement, installing in jre6. Previously, there was a different folder per new version (1.5.0_4, 1.5.0_5, etc.), which was taking lot of space

How can you print a variable name in python?

Rather than ask for details to a specific solution, I recommend describing the problem you face; I think you'll get better answers. I say this since there's almost certainly a better way to do whatever it is you're trying to do. Accessing variable names in this way is not commonly needed to solve problems in any language.

That said, all of your variable names are already in dictionaries which are accessible through the built-in functions locals and globals. Use the correct one for the scope you are inspecting.

One of the few common idioms for inspecting these dictionaries is for easy string interpolation:

>>> first = 'John'
>>> last = 'Doe'
>>> print '%(first)s %(last)s' % globals()
John Doe

This sort of thing tends to be a bit more readable than the alternatives even though it requires inspecting variables by name.

Get first and last day of month using threeten, LocalDate

Just use withDayOfMonth, and lengthOfMonth():

LocalDate initial = LocalDate.of(2014, 2, 13);
LocalDate start = initial.withDayOfMonth(1);
LocalDate end = initial.withDayOfMonth(initial.lengthOfMonth());

How to perform a LEFT JOIN in SQL Server between two SELECT statements?

SELECT [UserID] FROM [User] u LEFT JOIN (
SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043) t on t.TailUser=u.USerID

Passing an array as an argument to a function in C

If you want to pass a single-dimension array as an argument in a function, you would have to declare a formal parameter in one of following three ways and all three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received.

int func(int arr[], ...){
    .
    .
    .
}

int func(int arr[SIZE], ...){
    .
    .
    .
}

int func(int* arr, ...){
    .
    .
    .
}

So, you are modifying the original values.

Thanks !!!

Changing capitalization of filenames in Git

Working example:

git mv ./src/images/poster_video.PNG ./src/images/poster_video.png

what is the use of Eval() in asp.net

IrishChieftain didn't really address the question, so here's my take:

eval() is supposed to be used for data that is not known at run time. Whether that be user input (dangerous) or other sources.

What is deserialize and serialize in JSON?

In the context of data storage, serialization (or serialisation) is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer) or transmitted (for example, across a network connection link) and reconstructed later. [...]
The opposite operation, extracting a data structure from a series of bytes, is deserialization. From Wikipedia

In Python "serialization" does nothing else than just converting the given data structure (e.g. a dict) into its valid JSON pendant (object).

  • Python's True will be converted to JSONs true and the dictionary itself will then be encapsulated in quotes.
  • You can easily spot the difference between a Python dictionary and JSON by their Boolean values:
    • Python: True / False,
    • JSON: true / false
  • Python builtin module json is the standard way to do serialization:

Code example:

data = {
    "president": {
        "name": "Zaphod Beeblebrox",
        "species": "Betelgeusian",
        "male": True,
    }
}

import json
json_data = json.dumps(data, indent=2) # serialize
restored_data = json.loads(json_data) # deserialize

# serialized json_data now looks like:
# {
#   "president": {
#     "name": "Zaphod Beeblebrox",
#     "species": "Betelgeusian",
#     "male": true
#   }
# }

Source: realpython.com

100% width background image with an 'auto' height

Just use a two color background image:

<div style="width:100%; background:url('images/bkgmid.png');
       background-size: cover;">
content
</div>

How to develop or migrate apps for iPhone 5 screen resolution?

Rather than using a set of conditionals you can resize your view automatically using the screen size.

int h = [[UIScreen mainScreen] bounds].size.height;
int w = [[UIScreen mainScreen] bounds].size.width;
self.imageView.frame = CGRectMake(20, 80, (h-200), (w-100));

In my case I want a view that fills the space between some input fields at the top and some buttons at the bottom, so fixed top left corner and variable bottom right based on screen size. My app fills the image view with the photo taken by the camera so I want all the space I can get.

Java "user.dir" property - what exactly does it mean?

It's the directory where java was run from, where you started the JVM. Does not have to be within the user's home directory. It can be anywhere where the user has permission to run java.

So if you cd into /somedir, then run your program, user.dir will be /somedir.

A different property, user.home, refers to the user directory. As in /Users/myuser or /home/myuser or C:\Users\myuser.

See here for a list of system properties and their descriptions.

How to enable C++17 compiling in Visual Studio?

If bringing existing Visual Studio 2015 solution into Visual Studio 2017 and you want to build it with c++17 native compiler, you should first Retarget the solution/projects to v141 , THEN the dropdown will appear as described above ( Configuration Properties -> C/C++ -> Language -> Language Standard)

CentOS: Enabling GD Support in PHP Installation

For PHP7 on CentOS or EC2 Linux AMI:

sudo yum install php70-gd

Initializing a struct to 0

If the data is a static or global variable, it is zero-filled by default, so just declare it myStruct _m;

If the data is a local variable or a heap-allocated zone, clear it with memset like:

memset(&m, 0, sizeof(myStruct));

Current compilers (e.g. recent versions of gcc) optimize that quite well in practice. This works only if all zero values (include null pointers and floating point zero) are represented as all zero bits, which is true on all platforms I know about (but the C standard permits implementations where this is false; I know no such implementation).

You could perhaps code myStruct m = {}; or myStruct m = {0}; (even if the first member of myStruct is not a scalar).

My feeling is that using memset for local structures is the best, and it conveys better the fact that at runtime, something has to be done (while usually, global and static data can be understood as initialized at compile time, without any cost at runtime).

How to detect when WIFI Connection has been established in Android?

To detect WIFI connection state, I have used CONNECTIVITY_ACTION from ConnectivityManager class so:

    IntentFilter filter=new IntentFilter();
    filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(receiver, filter);

and from your BroadCastReceiver:

    if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
        int networkType = intent.getIntExtra(
                android.net.ConnectivityManager.EXTRA_NETWORK_TYPE, -1);
        if (ConnectivityManager.TYPE_WIFI == networkType) {
            NetworkInfo networkInfo = (NetworkInfo) intent
                    .getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            if (networkInfo != null) {
                if (networkInfo.isConnected()) {

                    // TODO: wifi is connected
                } else {
                    // TODO: wifi is not connected
                }
            }
        }

    }

ps:works fine for me:)

how to get the value of css style using jquery

I doubt css understands left by itself. You need to use it specifying position. You are using .css() correctly

position: relative/absolute/whatever;
left: 900px;

heres a fiddle of it working

http://jsfiddle.net/gFLZe/

and without the position here's what you get

http://jsfiddle.net/gkkm5/

Change your if statement to be like this - with quotes around -900px

var n = $("items").css("left");

if(n == '-900px'){
    $(".items span").fadeOut("slow");
}

http://jsfiddle.net/gFLZe/1/

In MySQL, how to copy the content of one table to another table within the same database?

This worked for me. You can make the SELECT statement more complex, with WHERE and LIMIT clauses.

First duplicate your large table (without the data), run the following query, and then truncate the larger table.

INSERT INTO table_small (SELECT * FROM table_large WHERE column = 'value' LIMIT 100)

Super simple. :-)

How to debug a stored procedure in Toad?

Open a PL/SQL object in the Editor.

Click on the main toolbar or select Session | Toggle Compiling with Debug. This enables debugging.

Compile the object on the database.

Select one of the following options on the Execute toolbar to begin debugging: Execute PL/SQL with debugger () Step over Step into Run to cursor

How to convert JSON string to array

There is a problem with the string you are calling a json. I have made some changes to it below. If you properly format the string to a correct json, the code below works.

$str = '{
        "action" : "create",
        "record": {
            "type": "n$product",
            "fields": {
                "nname": "Bread",
                "nprice": 2.11
            },
            "namespaces": { "my.demo": "n" }
        }
    }';

    $response = json_decode($str, TRUE);
    echo '<br> action' . $response["action"] . '<br><br>';

How to present a simple alert message in java?

If you don't like "verbosity" you can always wrap your code in a short method:

private void msgbox(String s){
   JOptionPane.showMessageDialog(null, s);
}

and the usage:

msgbox("don't touch that!");

DTO and DAO concepts and MVC

DTO is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.

  • DTO should only contain private fields for your data, getters, setters, and constructors.
  • DTO is not recommended to add business logic methods to such classes, but it is OK to add some util methods.

DAO is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).

Here is an example of how the DAO and DTO interfaces would look like:

interface PersonDTO {
    String getName();
    void setName(String name);
    //.....
}

interface PersonDAO {
    PersonDTO findById(long id);
    void save(PersonDTO person);
    //.....
}

The MVC is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.

As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.

git-diff to ignore ^M

Why do you get these ^M in your git diff?

In my case I was working on a project which was developed in Windows and I used OS X. When I changed some code, I saw ^M at the end of the lines I added in git diff. I think the ^M were showing up because they were different line endings than the rest of the file. Because the rest of the file was developed in Windows it used CR line endings, and in OS X it uses LF line endings.

Apparently, the Windows developer didn't use the option "Checkout Windows-style, commit Unix-style line endings" during the installation of Git.

So what should we do about this?

You can have the Windows users reinstall git and use the "Checkout Windows-style, commit Unix-style line endings" option. This is what I would prefer, because I see Windows as an exception in its line ending characters and Windows fixes its own issue this way.

If you go for this option, you should however fix the current files (because they're still using the CR line endings). I did this by following these steps:

  1. Remove all files from the repository, but not from your filesystem.

    git rm --cached -r .
    
  2. Add a .gitattributes file that enforces certain files to use a LF as line endings. Put this in the file:

    *.ext text eol=crlf
    

    Replace .ext with the file extensions you want to match.

  3. Add all the files again.

    git add .
    

    This will show messages like this:

    warning: CRLF will be replaced by LF in <filename>.
    The file will have its original line endings in your working directory.
    
  4. You could remove the .gitattributes file unless you have stubborn Windows users that don't want to use the "Checkout Windows-style, commit Unix-style line endings" option.

  5. Commit and push it all.

  6. Remove and checkout the applicable files on all the systems where they're used. On the Windows systems, make sure they now use the "Checkout Windows-style, commit Unix-style line endings" option. You should also do this on the system where you executed these tasks because when you added the files git said:

    The file will have its original line endings in your working directory.
    

    You can do something like this to remove the files:

    git ls | grep ".ext$" | xargs rm -f
    

    And then this to get them back with the correct line endings:

    git ls | grep ".ext$" | xargs git checkout
    

    Of course replacing .ext with the extension you want.

Now your project only uses LF characters for the line endings, and the nasty CR characters won't ever come back :).

The other option is to enforce windows style line endings. You can also use the .gitattributes file for this.

More info: https://help.github.com/articles/dealing-with-line-endings/#platform-all

Can a background image be larger than the div itself?

Not really - the background image is bounded by the element it's applied to, and the overflow properties only apply to the content (i.e. markup) within an element.

You can add another div into your footer div and apply the background image to that, though, and have that overflow instead.

Custom events in jQuery?

Take a look at this:

(reprinted from the expired blog page http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/ based on the archived version at http://web.archive.org/web/20130120010146/http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/)


Publish / Subscribe With jQuery

June 17th, 2008

With a view to writing a jQuery UI integrated with the offline functionality of Google Gears i’ve been toying with some code to poll for network connection status using jQuery.

The Network Detection Object

The basic premise is very simple. We create an instance of a network detection object which will poll a URL at regular intervals. Should these HTTP requests fail we can assume that network connectivity has been lost, or the server is simply unreachable at the current time.

$.networkDetection = function(url,interval){
    var url = url;
    var interval = interval;
    online = false;
    this.StartPolling = function(){
        this.StopPolling();
        this.timer = setInterval(poll, interval);
    };
    this.StopPolling = function(){
        clearInterval(this.timer);
    };
    this.setPollInterval= function(i) {
        interval = i;
    };
    this.getOnlineStatus = function(){
        return online;
    };
    function poll() {
        $.ajax({
            type: "POST",
            url: url,
            dataType: "text",
            error: function(){
                online = false;
                $(document).trigger('status.networkDetection',[false]);
            },
            success: function(){
                online = true;
                $(document).trigger('status.networkDetection',[true]);
            }
        });
    };
};

You can view the demo here. Set your browser to work offline and see what happens…. no, it’s not very exciting.

Trigger and Bind

What is exciting though (or at least what is exciting me) is the method by which the status gets relayed through the application. I’ve stumbled upon a largely un-discussed method of implementing a pub/sub system using jQuery’s trigger and bind methods.

The demo code is more obtuse than it need to be. The network detection object publishes ’status ‘events to the document which actively listens for them and in turn publishes ‘notify’ events to all subscribers (more on those later). The reasoning behind this is that in a real world application there would probably be some more logic controlling when and how the ‘notify’ events are published.

$(document).bind("status.networkDetection", function(e, status){
    // subscribers can be namespaced with multiple classes
    subscribers = $('.subscriber.networkDetection');
    // publish notify.networkDetection even to subscribers
    subscribers.trigger("notify.networkDetection", [status])
    /*
    other logic based on network connectivity could go here
    use google gears offline storage etc
    maybe trigger some other events
    */
});

Because of jQuery’s DOM centric approach events are published to (triggered on) DOM elements. This can be the window or document object for general events or you can generate a jQuery object using a selector. The approach i’ve taken with the demo is to create an almost namespaced approach to defining subscribers.

DOM elements which are to be subscribers are classed simply with “subscriber” and “networkDetection”. We can then publish events only to these elements (of which there is only one in the demo) by triggering a notify event on $(“.subscriber.networkDetection”)

The #notifier div which is part of the .subscriber.networkDetection group of subscribers then has an anonymous function bound to it, effectively acting as a listener.

$('#notifier').bind("notify.networkDetection",function(e, online){
    // the following simply demonstrates
    notifier = $(this);
    if(online){
        if (!notifier.hasClass("online")){
            $(this)
                .addClass("online")
                .removeClass("offline")
                .text("ONLINE");
        }
    }else{
        if (!notifier.hasClass("offline")){
            $(this)
                .addClass("offline")
                .removeClass("online")
                .text("OFFLINE");
        }
    };
});

So, there you go. It’s all pretty verbose and my example isn’t at all exciting. It also doesn’t showcase anything interesting you could do with these methods, but if anyone’s at all interested to dig through the source feel free. All the code is inline in the head of the demo page

jQuery DataTable overflow and text-wrapping issues

You can try setting the word-wrap however it doesn't work in all browsers yet.

Another method would be to add an element around your cell data like this:

<td><span>...</span></td>

Then add some css like this:

.datatable td span{
    max-width: 400px;
    display: block;
    overflow: hidden;
}

Display Yes and No buttons instead of OK and Cancel in Confirm box?

As far as I know, it's not possible to change the content of the buttons, at least not easily. It's fairly easy to have your own custom alert box using JQuery UI though

Difference between Convert.ToString() and .ToString()

The methods are "basically" the same, except handling null.

Pen pen = null; 
Convert.ToString(pen); // No exception thrown
pen.ToString(); // Throws NullReferenceException

From MSDN :
Convert.ToString Method

Converts the specified value to its equivalent string representation.

Object.ToString

Returns a string that represents the current object.

How to select top n rows from a datatable/dataview in ASP.NET

I just used Midhat's answer but appended CopyToDataTable() on the end.

The code below is an extension to the answer that I used to quickly enable some paging.

int pageNum = 1;
int pageSize = 25;

DataTable dtPage = dt.Rows.Cast<System.Data.DataRow>().Skip((pageNum - 1) * pageSize).Take(pageSize).CopyToDataTable();

Bug? #1146 - Table 'xxx.xxxxx' doesn't exist

I had the same issue. It happened after windows start up error, it seems some files got corrupted due to this. I did import the DB again from the saved script and it works fine.

Connect Android to WiFi Enterprise network EAP(PEAP)

Finally, I've defeated my CiSCO EAP-FAST corporate wifi network, and all our Android devices are now able to connect to it.

The walk-around I've performed in order to gain access to this kind of networks from an Android device are easiest than you can imagine.

There's a Wifi Config Editor in the Google Play Store you can use to "activate" the secondary CISCO Protocols when you are setting up a EAP wifi connection.

Its name is Wifi Config Advanced Editor.

  • First, you have to setup your wireless network manually as close as you can to your "official" corporate wifi parameters.

  • Save it.

  • Go to the WCE and edit the parameters of the network you have created in the previous step.

  • There are 3 or 4 series of settings you should activate in order to force the Android device to use them as a way to connect (the main site I think you want to visit is Enterprise Configuration, but don't forget to check all the parameters to change them if needed.
    As a suggestion, even if you have a WPA2 EAP-FAST Cipher, try LEAP in your setup. It worked for me as a charm.

  • When you finished to edit the config, go to the main Android wifi controller, and force to connect to this network.

  • Do not Edit the network again with the Android wifi interface.

I have tested it on Samsung Galaxy 1 and 2, Note mobile devices, and on a Lenovo Thinkpad Tablet.

filename and line number of Python script

Just to contribute,

there is a linecache module in python, here is two links that can help.

linecache module documentation
linecache source code

In a sense, you can "dump" a whole file into its cache , and read it with linecache.cache data from class.

import linecache as allLines
## have in mind that fileName in linecache behaves as any other open statement, you will need a path to a file if file is not in the same directory as script
linesList = allLines.updatechache( fileName ,None)
for i,x in enumerate(lineslist): print(i,x) #prints the line number and content
#or for more info
print(line.cache)
#or you need a specific line
specLine = allLines.getline(fileName,numbOfLine)
#returns a textual line from that number of line

For additional info, for error handling, you can simply use

from sys import exc_info
try:
     raise YourError # or some other error
except Exception:
     print(exc_info() )

Automatically plot different colored lines

You could use a colormap such as HSV to generate a set of colors. For example:

cc=hsv(12);
figure; 
hold on;
for i=1:12
    plot([0 1],[0 i],'color',cc(i,:));
end

MATLAB has 13 different named colormaps ('doc colormap' lists them all).

Another option for plotting lines in different colors is to use the LineStyleOrder property; see Defining the Color of Lines for Plotting in the MATLAB documentation for more information.

how to get param in method post spring mvc?

It also works if you change the content type

    <form method="POST"
    action="http://localhost:8080/cms/customer/create_customer"
    id="frmRegister" name="frmRegister"
    enctype="application/x-www-form-urlencoded">

In the controller also add the header value as follows:

    @RequestMapping(value = "/create_customer", method = RequestMethod.POST, headers = "Content-Type=application/x-www-form-urlencoded")

Htaccess: add/remove trailing slash from URL

This is what I've used for my latest app.

# redirect the main page to landing
##RedirectMatch 302 ^/$ /landing

# remove php ext from url
# https://stackoverflow.com/questions/4026021/remove-php-extension-with-htaccess
RewriteEngine on 

# File exists but has a trailing slash
# https://stackoverflow.com/questions/21417263/htaccess-add-remove-trailing-slash-from-url
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?(.*)/+$ /$1 [R=302,L,QSA]

# ok. It will still find the file but relative assets won't load
# e.g. page: /landing/  -> assets/js/main.js/main
# that's we have the rules above.
RewriteCond %{REQUEST_FILENAME} !\.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^/?(.*?)/?$ $1.php

Asp.net - <customErrors mode="Off"/> error when trying to access working webpage

For example in my case I accidentaly changed role of some users to incorrect, and my application got error during starting (NullReferenceException). When I fixed it - the app starts fine.

Imported a csv-dataset to R but the values becomes factors

This only worked right for me when including strip.white = TRUE in the read.csv command.

(I found the solution here.)

Comparing two maps

Quick Answer

You should use the equals method since this is implemented to perform the comparison you want. toString() itself uses an iterator just like equals but it is a more inefficient approach. Additionally, as @Teepeemm pointed out, toString is affected by order of elements (basically iterator return order) hence is not guaranteed to provide the same output for 2 different maps (especially if we compare two different maps).

Note/Warning: Your question and my answer assume that classes implementing the map interface respect expected toString and equals behavior. The default java classes do so, but a custom map class needs to be examined to verify expected behavior.

See: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

boolean equals(Object o)

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.

Implementation in Java Source (java.util.AbstractMap)

Additionally, java itself takes care of iterating through all elements and making the comparison so you don't have to. Have a look at the implementation of AbstractMap which is used by classes such as HashMap:

 // Comparison and hashing

    /**
     * Compares the specified object with this map for equality.  Returns
     * <tt>true</tt> if the given object is also a map and the two maps
     * represent the same mappings.  More formally, two maps <tt>m1</tt> and
     * <tt>m2</tt> represent the same mappings if
     * <tt>m1.entrySet().equals(m2.entrySet())</tt>.  This ensures that the
     * <tt>equals</tt> method works properly across different implementations
     * of the <tt>Map</tt> interface.
     *
     * <p>This implementation first checks if the specified object is this map;
     * if so it returns <tt>true</tt>.  Then, it checks if the specified
     * object is a map whose size is identical to the size of this map; if
     * not, it returns <tt>false</tt>.  If so, it iterates over this map's
     * <tt>entrySet</tt> collection, and checks that the specified map
     * contains each mapping that this map contains.  If the specified map
     * fails to contain such a mapping, <tt>false</tt> is returned.  If the
     * iteration completes, <tt>true</tt> is returned.
     *
     * @param o object to be compared for equality with this map
     * @return <tt>true</tt> if the specified object is equal to this map
     */
    public boolean equals(Object o) {
        if (o == this)
            return true;

        if (!(o instanceof Map))
            return false;
        Map<K,V> m = (Map<K,V>) o;
        if (m.size() != size())
            return false;

        try {
            Iterator<Entry<K,V>> i = entrySet().iterator();
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                K key = e.getKey();
                V value = e.getValue();
                if (value == null) {
                    if (!(m.get(key)==null && m.containsKey(key)))
                        return false;
                } else {
                    if (!value.equals(m.get(key)))
                        return false;
                }
            }
        } catch (ClassCastException unused) {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }

        return true;
    }

Comparing two different types of Maps

toString fails miserably when comparing a TreeMap and HashMap though equals does compare contents correctly.

Code:

public static void main(String args[]) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("2", "whatever2");
map.put("1", "whatever1");
TreeMap<String, Object> map2 = new TreeMap<String, Object>();
map2.put("2", "whatever2");
map2.put("1", "whatever1");

System.out.println("Are maps equal (using equals):" + map.equals(map2));
System.out.println("Are maps equal (using toString().equals()):"
        + map.toString().equals(map2.toString()));

System.out.println("Map1:"+map.toString());
System.out.println("Map2:"+map2.toString());
}

Output:

Are maps equal (using equals):true
Are maps equal (using toString().equals()):false
Map1:{2=whatever2, 1=whatever1}
Map2:{1=whatever1, 2=whatever2}

How can I add NSAppTransportSecurity to my info.plist file?

Xcode 8.2, iOS 10

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

How to open maximized window with Javascript?

The best solution I could find at present time to open a window maximized is (Internet Explorer 11, Chrome 49, Firefox 45):

  var popup = window.open("your_url", "popup", "fullscreen");
  if (popup.outerWidth < screen.availWidth || popup.outerHeight < screen.availHeight)
  {
    popup.moveTo(0,0);
    popup.resizeTo(screen.availWidth, screen.availHeight);
  }

see https://jsfiddle.net/8xwocrp6/7/

Note 1: It does not work on Edge (13.1058686). Not sure whether it's a bug or if it's as designed (I've filled a bug report, we'll see what they have to say about it). Here is a workaround:

if (navigator.userAgent.match(/Edge\/\d+/g))
{
    return window.open("your_url", "popup", "width=" + screen.width + ",height=" + screen.height);
}

Note 2: moveTo or resizeTo will not work (Access denied) if the window you are opening is on another domain.

How can query string parameters be forwarded through a proxy_pass with nginx?

github gist https://gist.github.com/anjia0532/da4a17f848468de5a374c860b17607e7

#set $token "?"; # deprecated

set $token ""; # declar token is ""(empty str) for original request without args,because $is_args concat any var will be `?`

if ($is_args) { # if the request has args update token to "&"
    set $token "&";
}

location /test {
    set $args "${args}${token}k1=v1&k2=v2"; # update original append custom params with $token
    # if no args $is_args is empty str,else it's "?"
    # http is scheme
    # service is upstream server
    #proxy_pass http://service/$uri$is_args$args; # deprecated remove `/`
    proxy_pass http://service$uri$is_args$args; # proxy pass
}

#http://localhost/test?foo=bar ==> http://service/test?foo=bar&k1=v1&k2=v2

#http://localhost/test/ ==> http://service/test?k1=v1&k2=v2

How to correctly set the ORACLE_HOME variable on Ubuntu 9.x?

Had the same problem,

All i had to do whas set the oracle shell variable:

. /u01/app/oracle/product/11.2.0/xe/bin/oracle_env.sh

Sorterd!

Mysql command not found in OS X 10.7

Add the following lines in bash_profile:

alias startmysql='sudo /usr/local/mysql/support-files/mysql.server start'
alias stopmysql='sudo /usr/local/mysql/support-files/mysql.server stop'

and save the bash_profile.

Now, in the terminal start and stop the mysql server using the following commands:

startmysql //to start mysql server

and

stopmysql //to stop mysql server

Change text from "Submit" on input tag

<input name="submitBnt" type="submit" value="like"/>

name is useful when using $_POST in php and also in javascript as document.getElementByName('submitBnt'). Also you can use name as a CS selector like input[name="submitBnt"]; Hope this helps

How Do I Make Glyphicons Bigger? (Change Size?)

Fontawesome has a perfect solution to this.

I implemented the same. just on your main .css file add this

.gi-2x{font-size: 2em;}
.gi-3x{font-size: 3em;}
.gi-4x{font-size: 4em;}
.gi-5x{font-size: 5em;}

In your example you just have to do this.

<div class = "jumbotron">
    <span class="glyphicon glyphicon-globe gi-5x"></span>
</div>  

Should I learn C before learning C++?

I'm going to disagree with the majority here. I think you should learn C before learning C++. It's definitely not necessary, but I think it makes learning C++ a lot easier. C is at the heart of C++. Anything you learn about C is applicable to C++, but C is a lot smaller and easier to learn.

Pick up K&R and read through that. It is short and will give you a sufficient sense of the language. Once you have the basics of pointers and function calls down, you can move on to C++ a little easier.

Ruby: kind_of? vs. instance_of? vs. is_a?

It is more Ruby-like to ask objects whether they respond to a method you need or not, using respond_to?. This allows both minimal interface and implementation unaware programming.

It is not always applicable of course, thus there is still a possibility to ask about more conservative understanding of "type", which is class or a base class, using the methods you're asking about.

POST JSON fails with 415 Unsupported media type, Spring 3 mvc

A small side note - stumbled upon this same error while developing a web application. The mistake we found, by toying with the service with Firefox Poster, was that both fields and values in the Json should be surrounded by double quotes. For instance..

[ {"idProductCategory" : "1" , "description":"Descrizione1"}, 
  {"idProductCategory" : "2" , "description":"Descrizione2"} ]

In our case we filled the json via javascript, which can be a little confusing when it comes with dealing with single/double quotes, from what I've heard.

What's been said before in this and other posts, like including the 'Accept' and 'Content-Type' headers, applies too.

Hope t'helps.

Send multipart/form-data files with angular using $http

Take a look at the FormData object: https://developer.mozilla.org/en/docs/Web/API/FormData

this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(){
        })
        .error(function(){
        });
    }

Android studio Gradle build speed up

There is a newer version of gradle (ver 2.4).

You can set this for your project(s) by opening up 'Project Structure' dialog from File menu,

Project Structure -> Project -> Gradle version

and set it to '2.4'.
You can read more about boosting performance at this link.

how to cancel/abort ajax request in axios

Typically you want to cancel the previous ajax request and ignore it's coming response, only when a new ajax request of that instance is started, for this purpose, do the following:

Example: getting some comments from API:

// declare an ajax request's cancelToken (globally)
let ajaxRequest = null; 

function getComments() {

    // cancel  previous ajax if exists
    if (ajaxRequest ) {
        ajaxRequest.cancel(); 
    }

    // creates a new token for upcomming ajax (overwrite the previous one)
    ajaxRequest = axios.CancelToken.source();  

    return axios.get('/api/get-comments', { cancelToken: ajaxRequest.token }).then((response) => {
        console.log(response.data)
    }).catch(function(err) {
        if (axios.isCancel(err)) {
           console.log('Previous request canceled, new request is send', err.message);
        } else {
               // handle error
        }
    });
}

What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

Vava's answer is on the mark. If you use jQuery, then the $.each() function takes care of this, hence it is safer to use.

$.each(evtListeners, function(index, elem) {
    // your code
});

Validate IPv4 address in Java

the lib of apache-httpcomponents

// ipv4 is true
assertTrue(InetAddressUtils.isIPv4Address("127.0.0.1"));
// not detect the ipv6
assertFalse(InetAddressUtils.isIPv4Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334"));

maven lib (update Sep, 2019)

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.10</version>
</dependency>

Error: "The sandbox is not in sync with the Podfile.lock..." after installing RestKit with cocoapods

I was able to fix that by updating CocoaPods.

I. Project Cleanup

  1. In the project navigator, select your project
  2. Select your target
  3. Remove all libPods*.a in Build Phases > Link Binary With Libraries

II. Update CocoaPods

  1. Launch Terminal and go to your project directory.
  2. Update CocoaPods using the command pod install

Playing MP4 files in Firefox using HTML5 video

I can confirm that mp4 just will not work in the video tag. No matter how much you try to mess with the type tag and the codec and the mime types from the server.

Crazy, because for the same exact video, on the same test page, the old embed tag for an mp4 works just fine in firefox. I spent all yesterday messing with this. Firefox is like IE all of a sudden, hours and hours of time, not billable. Yay.

Speaking of IE, it fails FAR MORE gracefully on this. When it can't match up the format it falls to the content between the tags, so it is possible to just put video around object around embed and everything works great. Firefox, nope, despite failing, it puts up the poster image (greyed out so that isn't even useful as a fallback) with an error message smack in the middle. So now the options are put in browser recognition code (meaning we've gained nothing on embedding videos in the last ten years) or ditch html5.

Difference between $(this) and event.target?

Within an event handler function or object method, one way to access the properties of "the containing element" is to use the special this keyword. The this keyword represents the owner of the function or method currently being processed. So:

  • For a global function, this represents the window.

  • For an object method, this represents the object instance.

  • And in an event handler, this represents the element that received the event.

For example:

<!DOCTYPE html>
<html>
    <head>
        <script>
        function mouseDown() {
            alert(this);
        }
        </script>
    </head>
    <body>
        <p onmouseup="mouseDown();alert(this);">Hi</p>
    </body>
</html>

The content of alert windows after rendering this html respectively are:

object Window
object HTMLParagraphElement

An Event object is associated with all events. It has properties that provide information "about the event", such as the location of a mouse click in the web page.

For example:

<!DOCTYPE html>
<html>
    <head>
        <script>
        function mouseDown(event) {
            var theEvent = event ? event : window.event;
            var locString = "X = " + theEvent.screenX + " Y = " + theEvent.screenY;
            alert(event);
                    alert(locString);
        }
        </script>
    </head>
    <body>
        <p onmouseup="mouseDown(event);">Hi</p>
    </body>
</html>

The content of alert windows after rendering this html respectively are:

object MouseEvent
X = 982 Y = 329

Determine the data types of a data frame's columns

I would suggest

sapply(foo, typeof)

if you need the actual types of the vectors in the data frame. class() is somewhat of a different beast.

If you don't need to get this information as a vector (i.e. you don't need it to do something else programmatically later), just use str(foo).

In both cases foo would be replaced with the name of your data frame.

Indent List in HTML and CSS

_x000D_
_x000D_
li {
  padding-left: 30px;
}
_x000D_
<p>Some text to show left edge of container.<p>
<ul>
  <li>List item</li>
</ul>
_x000D_
_x000D_
_x000D_ The above will add 30px of space between the bullet or number and your text.

_x000D_
_x000D_
li {
  margin-left: 30px;
}
_x000D_
<p>Some text to show left edge of container.<p>
<ul>
  <li>List item</li>
</ul>
_x000D_
_x000D_
_x000D_ The above will add 30px of space between the bullet or number and the left edge of the container.

Javascript to stop HTML5 video playback on modal window close

Have a try:

_x000D_
_x000D_
function stop(){_x000D_
    var video = document.getElementById("video");_x000D_
    video.load();_x000D_
}
_x000D_
_x000D_
_x000D_

Setting default values to null fields when mapping with Jackson

Make the member private and add a setter/getter pair. In your setter, if null, then set default value instead. Additionally, I have shown the snippet with the getter also returning a default when internal value is null.

class JavaObject {
    private static final String DEFAULT="Default Value";

    public JavaObject() {
    }

    @NotNull
    private String notNullMember;
    public void setNotNullMember(String value){
            if (value==null) { notNullMember=DEFAULT; return; }
            notNullMember=value;
            return;
    }

    public String getNotNullMember(){
            if (notNullMember==null) { return DEFAULT;}
            return notNullMember;
    }

    public String optionalMember;
}

How to square or raise to a power (elementwise) a 2D numpy array?

The fastest way is to do a*a or a**2 or np.square(a) whereas np.power(a, 2) showed to be considerably slower.

np.power() allows you to use different exponents for each element if instead of 2 you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2 or a*a, which become important in cases where you have small tolerances.

I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:

In [29]: a = np.random.random((1000, 1000))

In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop

In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop

In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop

How to make a page redirect using JavaScript?

Use:

document.location.href = "http://yoursite.com" + document.getElementById('somefield');

That would get the value of some text field or hidden field, and add it to your site URL to get a new URL (href). You can modify this to suit your needs.

What does the ELIFECYCLE Node.js error mean?

When running Webpack build I was getting similar error because node doesn't understand async await keywords on older versions. I added webpack babel-plugin-transform-async-to-generator and it was solved. This replaces them with promises.

How to easily map c++ enums to strings

MSalters solution is a good one but basically re-implements boost::assign::map_list_of. If you have boost, you can use it directly:

#include <boost/assign/list_of.hpp>
#include <boost/unordered_map.hpp>
#include <iostream>

using boost::assign::map_list_of;

enum eee { AA,BB,CC };

const boost::unordered_map<eee,const char*> eeeToString = map_list_of
    (AA, "AA")
    (BB, "BB")
    (CC, "CC");

int main()
{
    std::cout << " enum AA = " << eeeToString.at(AA) << std::endl;
    return 0;
}

Reflection generic get field value

 Integer typeValue = 0;
 try {
     Class<Types> types = Types.class;
     java.lang.reflect.Field field = types.getDeclaredField("Type");
     field.setAccessible(true);
     Object value = field.get(types);
     typeValue = (Integer) value;
 } catch (Exception e) {
     e.printStackTrace();
 }

Java File - Open A File And Write To It

Suggestions:

  • Create a File object that refers to the already existing file on disk.
  • Use a FileWriter object, and use the constructor that takes the File object and a boolean, the latter if true would allow appending text into the File if it exists.
  • Then initialize a PrintWriter passing in the FileWriter into its constructor.
  • Then call println(...) on your PrintWriter, writing your new text into the file.
  • As always, close your resources (the PrintWriter) when you are done with it.
  • As always, don't ignore exceptions but rather catch and handle them.
  • The close() of the PrintWriter should be in the try's finally block.

e.g.,

  PrintWriter pw = null;

  try {
     File file = new File("fubars.txt");
     FileWriter fw = new FileWriter(file, true);
     pw = new PrintWriter(fw);
     pw.println("Fubars rule!");
  } catch (IOException e) {
     e.printStackTrace();
  } finally {
     if (pw != null) {
        pw.close();
     }
  }

Easy, no?

Vertical Alignment of text in a table cell

I had the same issue but solved it by using !important. I forgot about the inheritance in CSS. Just a tip to check first.

How to connect to a remote Windows machine to execute commands using python?

I don't know WMI but if you want a simple Server/Client, You can use this simple code from tutorialspoint

Server:

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                # Close the connection 

Client

#!/usr/bin/python           # This is client.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close                     # Close the socket when done

it also have all the needed information for simple client/server applications.

Just convert the server and use some simple protocol to call a function from python.

P.S: i'm sure there are a lot of better options, it's just a simple one if you want...

PyCharm error: 'No Module' when trying to import own module (python script)

This can be caused when Python interpreter can't find your code. You have to mention explicitly to Python to find your code in this location.

To do so:

  • Go to your python console
  • Add sys.path.extend(['your module location']) to Python console.

In your case:

  • Go to your python console,
  • On the start, write the following code:

    import sys
    sys.path.extend([my module URI location])
    
  • Once you have written this statement you can run following command:

    from mymodule import functions
    

What is the meaning of 'No bundle URL present' in react-native?

Just run in Terminal react-native start:

cd your react native app directory/ react-native start 

It will start up the packager, now don't close this terminal window, in another terminal window run your project. This is the only want that I found to get it working properly.

Remove an item from a dictionary when its key is unknown

c is the new dictionary, and a is your original dictionary, {'z','w'} are the keys you want to remove from a

c = {key:a[key] for key in a.keys() - {'z', 'w'}}

Also check: https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch01.html

How do I properly set the Datetimeindex for a Pandas datetime object in a dataframe?

To simplify Kirubaharan's answer a bit:

df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])
df = df.set_index('Datetime')

And to get rid of unwanted columns (as OP did but did not specify per se in the question):

df = df.drop(['date','time'], axis=1)

Scroll to the top of the page using JavaScript?

You can use javascript's built in function scrollTo:

_x000D_
_x000D_
function scroll() {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
}
_x000D_
<button onclick="scroll">Scroll</button>
_x000D_
_x000D_
_x000D_

Nuget connection attempt failed "Unable to load the service index for source"

I have resolved this issue using below steps

  1. Click on run search this %APPDATA%\NuGet\NuGet.config.

  2. Open the setting and add this http_proxy keyin NuGet.config.

  3. Then you will able install the BouncyCastle.Crypto.dll in your application.

Thank you! Responses are welcome if you help this answer.

Calling C++ class methods via a function pointer

Read this for detail :

// 1 define a function pointer and initialize to NULL

int (TMyClass::*pt2ConstMember)(float, char, char) const = NULL;

// C++

class TMyClass
{
public:
   int DoIt(float a, char b, char c){ cout << "TMyClass::DoIt"<< endl; return a+b+c;};
   int DoMore(float a, char b, char c) const
         { cout << "TMyClass::DoMore" << endl; return a-b+c; };

   /* more of TMyClass */
};
pt2ConstMember = &TMyClass::DoIt; // note: <pt2Member> may also legally point to &DoMore

// Calling Function using Function Pointer

(*this.*pt2ConstMember)(12, 'a', 'b');

compareTo() vs. equals()

equals() checks whether two strings are equal or not.It gives boolean value. compareTo() checks whether string object is equal to,greater or smaller to the other string object.It gives result as : 1 if string object is greater 0 if both are equal -1 if string is smaller than other string

eq:

String a = "Amit";
String b = "Sumit";
String c = new String("Amit");
System.out.println(a.equals(c));//true
System.out.println(a.compareTo(c)); //0
System.out.println(a.compareTo(b)); //1

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

Here is what I have found:

Use RenderAction when you do not have a model to send to the view and have a lot of html to bring back that doesn't need to be stored in a variable.

Use Action when you do not have a model to send to the view and have a little bit of text to bring back that needs to be stored in a variable.

Use RenderPartial when you have a model to send to the view and there will be a lot of html that doesn't need to be stored in a variable.

Use Partial when you have a model to send to the view and there will be a little bit of text that needs to be stored in a variable.

RenderAction and RenderPartial are faster.

Getting a list of all subdirectories in the current directory

Thanks for the tips, guys. I ran into an issue with softlinks (infinite recursion) being returned as dirs. Softlinks? We don't want no stinkin' soft links! So...

This rendered just the dirs, not softlinks:

>>> import os
>>> inf = os.walk('.')
>>> [x[0] for x in inf]
['.', './iamadir']

Return in Scala

Use case match for early return purpose. It will force you to declare all return branches explicitly, preventing the careless mistake of forgetting to write return somewhere.

Python creating a dictionary of lists

You can build it with list comprehension like this:

>>> dict((i, range(int(i), int(i) + 2)) for i in ['1', '2'])
{'1': [1, 2], '2': [2, 3]}

And for the second part of your question use defaultdict

>>> from collections import defaultdict
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
        d[k].append(v)

>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

Sum function in VBA

Function is not a property/method from range.

If you want to sum values then use the following:

Range("A1").Value = Application.Sum(Range(Cells(2, 1), Cells(3, 2)))

EDIT:

if you want the formula then use as follows:

Range("A1").Formula = "=SUM(" & Range(Cells(2, 1), Cells(3, 2)).Address(False, False) & ")"

'The two false after Adress is to define the address as relative (A2:B3).
'If you omit the parenthesis clause or write True instead, you can set the address
'as absolute ($A$2:$B$3).

In case you are allways going to use the same range address then you can use as Rory sugested:

Range("A1").Formula ="=Sum(A2:B3)"

How to hide a div with jQuery?

$('#myDiv').hide(); hide function is used to edit content and show function is used to show again.

For more please click on this link.

How to stop/kill a query in postgresql?

What I did is first check what are the running processes by

SELECT * FROM pg_stat_activity WHERE state = 'active';

Find the process you want to kill, then type:

SELECT pg_cancel_backend(<pid of the process>)

This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.

If the process cannot be killed, try:

SELECT pg_terminate_backend(<pid of the process>)

javascript onclick increment number

jQuery Example

_x000D_
_x000D_
var $button = $('.increment-btn');
var $counter = $('.counter');

$button.click(function(){
  $counter.val( parseInt($counter.val()) + 1 ); // `parseInt` converts the `value` from a string to a number
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" value="1" class="counter"/>
<button type="button" class="increment-btn">Increment</button>
_x000D_
_x000D_
_x000D_

'Plain' JavaScript Example

_x000D_
_x000D_
var $button = document.querySelector('.increment-btn');
var $counter = document.querySelector('.counter');

$button.addEventListener('click', function(){
  $counter.value = parseInt($counter.value) + 1; // `parseInt` converts the `value` from a string to a number
}, false);
_x000D_
<input type="text" class="counter" value="1"/>
<button type="button" class="increment-btn">Increment</button>
_x000D_
_x000D_
_x000D_

Find size of object instance in bytes in c#

I have created benchmark test for different collections in .NET: https://github.com/scholtz/TestDotNetCollectionsMemoryAllocation

Results are as follows for .NET Core 2.2 with 1,000,000 of objects with 3 properties allocated:

Testing with string: 1234567
Hashtable<TestObject>:                                     184 672 704 B
Hashtable<TestObjectRef>:                                  136 668 560 B
Dictionary<int, TestObject>:                               171 448 160 B
Dictionary<int, TestObjectRef>:                            123 445 472 B
ConcurrentDictionary<int, TestObject>:                     200 020 440 B
ConcurrentDictionary<int, TestObjectRef>:                  152 026 208 B
HashSet<TestObject>:                                       149 893 216 B
HashSet<TestObjectRef>:                                    101 894 384 B
ConcurrentBag<TestObject>:                                 112 783 256 B
ConcurrentBag<TestObjectRef>:                               64 777 632 B
Queue<TestObject>:                                         112 777 736 B
Queue<TestObjectRef>:                                       64 780 680 B
ConcurrentQueue<TestObject>:                               112 784 136 B
ConcurrentQueue<TestObjectRef>:                             64 783 536 B
ConcurrentStack<TestObject>:                               128 005 072 B
ConcurrentStack<TestObjectRef>:                             80 004 632 B

For memory test I found the best to be used

GC.GetAllocatedBytesForCurrentThread()

Need to navigate to a folder in command prompt

Navigate to the folder in Windows Explorer, highlight the complete folder path in the top pane and type "cmd" - voila!

How to extract the hostname portion of a URL in JavaScript

I know this is a bit late, but I made a clean little function with a little ES6 syntax

function getHost(href){
  return Object.assign(document.createElement('a'), { href }).host;
}

It could also be writen in ES5 like

function getHost(href){
  return Object.assign(document.createElement('a'), { href: href }).host;
}

Of course IE doesn't support Object.assign, but in my line of work, that doesn't matter.

How do I disable TextBox using JavaScript?

With the help of jquery it can be done as follows.

$("#color").prop('disabled', true);

Which version of Python do I have installed?

If you are already in a REPL window and don't see the welcome message with the version number, you can use help() to see the major and minor version:

>>>help()
Welcome to Python 3.6's help utility!
...

Getting a File's MD5 Checksum in Java

Here is a handy variation that makes use of InputStream.transferTo() from Java 9, and OutputStream.nullOutputStream() from Java 11. It requires no external libraries and does not need to load the entire file into memory.

public static String hashFile(String algorithm, File f) throws IOException, NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance(algorithm);

    try(BufferedInputStream in = new BufferedInputStream((new FileInputStream(f)));
        DigestOutputStream out = new DigestOutputStream(OutputStream.nullOutputStream(), md)) {
        in.transferTo(out);
    }

    String fx = "%0" + (md.getDigestLength()*2) + "x";
    return String.format(fx, new BigInteger(1, md.digest()));
}

and

hashFile("SHA-512", Path.of("src", "test", "resources", "some.txt").toFile());

returns

"e30fa2784ba15be37833d569280e2163c6f106506dfb9b07dde67a24bfb90da65c661110cf2c5c6f71185754ee5ae3fd83a5465c92f72abd888b03187229da29"

OAuth: how to test with local URLs?

Set your local domain to mywebsite.example.com (and redirect it to localhost) -- even though the usual is to use mywebsite.dev. This will allow robust automatic testing.

Although authorizing .test and .dev is not allowed, authorizing example.com is allowed in google oauth2.

(You can redirect any domain to localhost in your hosts file (unix/linux: /etc/hosts))

Why mywebsite.example.com?
Because example.com is a reserved domain name. So

  1. there would be no naming conflicts on your machine.
  2. no data-risk if your test system exposes data to not-redirected-by-mistake.example.com.

Object spread vs. Object.assign

I'd like to summarize status of the "spread object merge" ES feature, in browsers, and in the ecosystem via tools.

Spec

Browsers: in Chrome, in SF, Firefox soon (ver 60, IIUC)

  • Browser support for "spread properties" shipped in Chrome 60, including this scenario.
  • Support for this scenario does NOT work in current Firefox (59), but DOES work in my Firefox Developer Edition. So I believe it will ship in Firefox 60.
  • Safari: not tested, but Kangax says it works in Desktop Safari 11.1, but not SF 11
  • iOS Safari: not teseted, but Kangax says it works in iOS 11.3, but not in iOS 11
  • not in Edge yet

Tools: Node 8.7, TS 2.1

Links

Code Sample (doubles as compatibility test)

var x = { a: 1, b: 2 };
var y = { c: 3, d: 4, a: 5 };
var z = {...x, ...y};
console.log(z); // { a: 5, b: 2, c: 3, d: 4 }

Again: At time of writing this sample works without transpilation in Chrome (60+), Firefox Developer Edition (preview of Firefox 60), and Node (8.7+).

Why Answer?

I'm writing this 2.5 years after the original question. But I had the very same question, and this is where Google sent me. I am a slave to SO's mission to improve the long tail.

Since this is an expansion of "array spread" syntax I found it very hard to google, and difficult to find in compatibility tables. The closest I could find is Kangax "property spread", but that test doesn't have two spreads in the same expression (not a merge). Also, the name in the proposals/drafts/browser status pages all use "property spread", but it looks to me like that was a "first principal" the community arrived at after the proposals to use spread syntax for "object merge". (Which might explain why it is so hard to google.) So I document my finding here so others can view, update, and compile links about this specific feature. I hope it catches on. Please help spread the news of it landing in the spec and in browsers.

Lastly, I would have added this info as a comment, but I couldn't edit them without breaking the authors' original intent. Specifically, I can't edit @ChillyPenguin's comment without it losing his intent to correct @RichardSchulte. But years later Richard turned out to be right (in my opinion). So I write this answer instead, hoping it will gain traction on the old answers eventually (might take years, but that's what the long tail effect is all about, after all).

vba error handling in loop

The problem is probably that you haven't resumed from the first error. You can't throw an error from within an error handler. You should add in a resume statement, something like the following, so VBA no longer thinks you are inside the error handler:

For Each oSheet In ActiveWorkbook.Sheets
    On Error GoTo NextSheet:
     Set qry = oSheet.ListObjects(1).QueryTable
     oCmbBox.AddItem oSheet.Name
NextSheet:
    Resume NextSheet2
NextSheet2:
Next oSheet

How to break/exit from a each() function in JQuery?

if (condition){ // where condition evaluates to true 
    return false
}

see similar question asked 3 days ago.

R Apply() function on specific dataframe columns

lapply is probably a better choice than apply here, as apply first coerces your data.frame to an array which means all the columns must have the same type. Depending on your context, this could have unintended consequences.

The pattern is:

df[cols] <- lapply(df[cols], FUN)

The 'cols' vector can be variable names or indices. I prefer to use names whenever possible (it's robust to column reordering). So in your case this might be:

wifi[4:9] <- lapply(wifi[4:9], A)

An example of using column names:

wifi <- data.frame(A=1:4, B=runif(4), C=5:8)
wifi[c("B", "C")] <- lapply(wifi[c("B", "C")], function(x) -1 * x)

Query to search all packages for table and/or column

By the way, if you need to add other characters such as "(" or ")" because the column may be used as "UPPER(bqr)", then those options can be added to the lists of before and after characters.

(\s|\(|\.|,|^)bqr(\s|,|\)|$)

How to safely open/close files in python 2.4

In the above solution, repeated here:

f = open('file.txt', 'r')

try:
    # do stuff with f
finally:
   f.close()

if something bad happens (you never know ...) after opening the file successfully and before the try, the file will not be closed, so a safer solution is:

f = None
try:
    f = open('file.txt', 'r')

    # do stuff with f

finally:
    if f is not None:
       f.close()

Excel VBA - Sum up a column

I think you are misinterpreting the source of the error; rExternalTotal appears to be equal to a single cell. rReportData.offset(0,0) is equal to rReportData
rReportData.offset(261,0).end(xlUp) is likely also equal to rReportData, as you offset by 261 rows and then use the .end(xlUp) function which selects the top of a contiguous data range.
If you are interested in the sum of just a column, you can just refer to the whole column:

dExternalTotal = Application.WorksheetFunction.Sum(columns("A:A"))

or

dExternalTotal = Application.WorksheetFunction.Sum(columns((rReportData.column))

The worksheet function sum will correctly ignore blank spaces.

Let me know if this helps!

Render a string in HTML and preserve spaces and linebreaks

I was trying the white-space: pre-wrap; technique stated by pete but if the string was continuous and long it just ran out of the container, and didn't warp for whatever reason, didn't have much time to investigate.. but if you too are having the same problem, I ended up using the <pre> tags and the following css and everything was good to go..

pre {
font-size: inherit;
color: inherit;
border: initial;
padding: initial;
font-family: inherit;
}

How to use onSavedInstanceState example please

This is for extra information.

Imagine this scenario

  1. ActivityA launch ActivityB.
  2. ActivityB launch a new ActivityAPrime by

    Intent intent = new Intent(getApplicationContext(), ActivityA.class);
    startActivity(intent);
    
  3. ActivityAPrime has no relationship with ActivityA.
    In this case the Bundle in ActivityAPrime.onCreate() will be null.

If ActivityA and ActivityAPrime should be the same activity instead of different activities, ActivityB should call finish() than using startActivity().

Error: free(): invalid next size (fast):

We need the code, but that usually pops up when you try to free() memory from a pointer that is not allocated. This often happens when you're double-freeing.

How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

Action Filters, jquery stringify, bleh...

Peter, this functionality is native to MVC. That's one of things that makes MVC so great.

$.post('SomeController/Batch', { 'ids': ['1', '2', '3']}, function (r) {
   ...
});

And in the action,

[HttpPost]
public ActionResult Batch(string[] ids)
{
}

Works like a charm:

enter image description here

If you're using jQuery 1.4+, then you want to look into setting traditional mode:

jQuery.ajaxSettings.traditional = true;

As described here: http://www.dovetailsoftware.com/blogs/kmiller/archive/2010/02/24/jquery-1-4-breaks-asp-net-mvc-actions-with-array-parameters

This even works for complex objects. If you're interested, you should look into the MVC documentation about Model Binding: http://msdn.microsoft.com/en-us/library/dd410405.aspx

Laravel Controller Subfolder routing

I am using Laravel 4.2. Here how I do it:
I have a directory structure like this one:
app
--controllers
----admin
------AdminController.php

After I have created the controller I've put in the composer.json the path to the new admin directory:

"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/controllers/admin",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php"
]
}, 

Next I have run

composer dump-autoload

and then

php artisan dump-autoload

Then in the routes.php I have the controller included like this:

Route::controller('admin', 'AdminController');

And everything works fine.

SQL query to find record with ID not in another table

Try this

SELECT ID, Name 
FROM   Table1 
WHERE  ID NOT IN (SELECT ID FROM Table2)

SQL Statement with multiple SETs and WHEREs

No, you need to handle every statement separately..

UPDATE table1
 Statement1;
 UPDATE table 1
 Statement2;

And so on

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

How to make Bootstrap Panel body with fixed height

HTML :

<div class="span4">
  <div class="panel panel-primary">
    <div class="panel-heading">jhdsahfjhdfhs</div>
    <div class="panel-body panel-height">fdoinfds sdofjohisdfj</div>
  </div>
</div>

CSS :

.panel-height {
  height: 100px; / change according to your requirement/
}

NPM: npm-cli.js not found when running npm

I know it is an older post but as I write this the version of Node js is 12.13.1. People face this generally because they might have already installed a previous version of Node js which added the following to the system path.

C:\Program Files\nodejs\node_modules\npm\bin

However, the newer versions need to add the following:-

C:\Program Files\nodejs

I mean to say the path where you installed the Nodejs. The default is

C:\Program Files\nodejs

However, if you gave a different location you should point it to that.

Select last row in MySQL

You can use an OFFSET in a LIMIT command:

SELECT * FROM aTable LIMIT 1 OFFSET 99

in case your table has 100 rows this return the last row without relying on a primary_key

PHP get dropdown value and text

$animals = array('--Select Animal--', 'Cat', 'Dog', 'Cow');
$selected_key = $_POST['animal'];
$selected_val = $animals[$_POST['animal']];

Use your $animals list to generate your dropdown list; you now can get the key & the value of that key.

Print list without brackets in a single row

I don't know if this is efficient as others but simple logic always works:

import sys
name = ["Sam", "Peter", "James", "Julian", "Ann"]
for i in range(0, len(names)):
    sys.stdout.write(names[i])
    if i != len(names)-1:
        sys.stdout.write(", ")

Output:

Sam, Peter, James, Julian, Ann

Values of disabled inputs will not be submitted

Disabled controls cannot be successful, and a successful control is "valid" for submission. This is the reason why disabled controls don't submit with the form.

Append an empty row in dataframe using pandas

Assuming your df.index is sorted you can use:

df.loc[df.index.max() + 1] = None

It handles well different indexes and column types.

[EDIT] it works with pd.DatetimeIndex if there is a constant frequency, otherwise we must specify the new index exactly e.g:

df.loc[df.index.max() + pd.Timedelta(milliseconds=1)] = None

long example:

df = pd.DataFrame([[pd.Timestamp(12432423), 23, 'text_field']], 
                    columns=["timestamp", "speed", "text"],
                    index=pd.DatetimeIndex(start='2111-11-11',freq='ms', periods=1))
df.info()

<class 'pandas.core.frame.DataFrame'> DatetimeIndex: 1 entries, 2111-11-11 to 2111-11-11 Freq: L Data columns (total 3 columns): timestamp 1 non-null datetime64[ns] speed 1 non-null int64 text 1 non-null object dtypes: datetime64[ns](1), int64(1), object(1) memory usage: 32.0+ bytes

df.loc[df.index.max() + 1] = None
df.info()

<class 'pandas.core.frame.DataFrame'> DatetimeIndex: 2 entries, 2111-11-11 00:00:00 to 2111-11-11 00:00:00.001000 Data columns (total 3 columns): timestamp 1 non-null datetime64[ns] speed 1 non-null float64 text 1 non-null object dtypes: datetime64[ns](1), float64(1), object(1) memory usage: 64.0+ bytes

df.head()

                            timestamp                   speed      text
2111-11-11 00:00:00.000 1970-01-01 00:00:00.012432423   23.0    text_field
2111-11-11 00:00:00.001 NaT NaN NaN

Combining INSERT INTO and WITH/CTE

You need to put the CTE first and then combine the INSERT INTO with your select statement. Also, the "AS" keyword following the CTE's name is not optional:

WITH tab AS (
    bla bla
)
INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos (
BatchID,
AccountNo,
APartyNo,
SourceRowID
)  
SELECT * FROM tab

Please note that the code assumes that the CTE will return exactly four fields and that those fields are matching in order and type with those specified in the INSERT statement. If that is not the case, just replace the "SELECT *" with a specific select of the fields that you require.

As for your question on using a function, I would say "it depends". If you are putting the data in a table just because of performance reasons, and the speed is acceptable when using it through a function, then I'd consider function to be an option. On the other hand, if you need to use the result of the CTE in several different queries, and speed is already an issue, I'd go for a table (either regular, or temp).

WITH common_table_expression (Transact-SQL)

How to convert characters to HTML entities using plain JavaScript

Demo on JSFiddle

here's a tiny stand alone method that:

  • attempts to consolidate the answers on this page, without using a library
  • works in older browsers
  • supports surrogate pairs (like emojis)
  • applies character overrides (what's that? not sure exactly)

i don't know too much about unicode, but it seems to be working well.

// escape a string for display in html
// see also: 
// polyfill for String.prototype.codePointAt
//   https://raw.githubusercontent.com/mathiasbynens/String.prototype.codePointAt/master/codepointat.js
// how to convert characters to html entities
//     http://stackoverflow.com/a/1354491/347508
// html overrides from 
//   https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides / http://stackoverflow.com/questions/1354064/how-to-convert-characters-to-html-entities-using-plain-javascript/23831239#comment36668052_1354098

var _escape_overrides = { 0x00:'\uFFFD',0x80:'\u20AC',0x82:'\u201A',0x83:'\u0192',0x84:'\u201E',0x85:'\u2026',0x86:'\u2020',0x87:'\u2021',0x88:'\u02C6',0x89:'\u2030',0x8A:'\u0160',0x8B:'\u2039',0x8C:'\u0152',0x8E:'\u017D',0x91:'\u2018',0x92:'\u2019',0x93:'\u201C',0x94:'\u201D',0x95:'\u2022',0x96:'\u2013',0x97:'\u2014',0x98:'\u02DC',0x99:'\u2122',0x9A:'\u0161',0x9B:'\u203A',0x9C:'\u0153',0x9E:'\u017E',0x9F:'\u0178' }; 

function escapeHtml(str){
    return str.replace(/([\u0000-\uD799]|[\uD800-\uDBFF][\uDC00-\uFFFF])/g, function(c) {
        var c1 = c.charCodeAt(0);
        // ascii character, use override or escape
        if( c1 <= 0xFF ) return (c1=_escape_overrides[c1])?c1:escape(c).replace(/%(..)/g,"&#x$1;");
        // utf8/16 character
        else if( c.length == 1 ) return "&#" + c1 + ";"; 
        // surrogate pair
        else if( c.length == 2 && c1 >= 0xD800 && c1 <= 0xDBFF ) return "&#" + ((c1-0xD800)*0x400 + c.charCodeAt(1) - 0xDC00 + 0x10000) + ";"
        // no clue .. 
        else return "";
    });
}

How can I add new item to the String array?

From arrays

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.

enter image description here

So in the case of a String array, once you create it with some length, you can't modify it, but you can add elements until you fill it.

String[] arr = new String[10]; // 10 is the length of the array.
arr[0] = "kk";
arr[1] = "pp";
...

So if your requirement is to add many objects, it's recommended that you use Lists like:

List<String> a = new ArrayList<String>();
a.add("kk");
a.add("pp"); 

Access images inside public folder in laravel

I have created an Asset helper of my own.

First I defined the asset types and path in app/config/assets.php:

return array(

    /*
    |--------------------------------------------------------------------------
    | Assets paths
    |--------------------------------------------------------------------------
    |
    | Location of all application assets, relative to the public folder,
    | may be used together with absolute paths or with URLs.
    |
    */

    'images' => '/storage/images',
    'css' => '/assets/css',
    'img' => '/assets/img',
    'js' => '/assets/js'
);

Then the actual Asset class:

class Asset
{
    private static function getUrl($type, $file)
    {
        return URL::to(Config::get('assets.' . $type) . '/' . $file);
    }

    public static function css($file)
    {
        return self::getUrl('css', $file);
    }

    public static function img($file)
    {
        return self::getUrl('img', $file);
    }

    public static function js($file)
    {
        return self::getUrl('js', $file);
    }

}

So in my view I can do this to show an image:

{{ HTML::image(Asset::img('logo.png'), "My logo")) }}

Or like this to implement a Java script:

{{ HTML::script(Asset::js('my_script.js')) }}

python pandas extract year from datetime: df['year'] = df['date'].year is not working

What worked for me was upgrading pandas to latest version:

From Command Line do:

conda update pandas

MySQL Insert with While Loop

drop procedure if exists doWhile;
DELIMITER //  
CREATE PROCEDURE doWhile()   
BEGIN
DECLARE i INT DEFAULT 2376921001; 
WHILE (i <= 237692200) DO
    INSERT INTO `mytable` (code, active, total) values (i, 1, 1);
    SET i = i+1;
END WHILE;
END;
//  

CALL doWhile(); 

Linux command to check if a shell script is running or not

pgrep -f aa.sh 

To do something with the id, you pipe it. Here I kill all its child tasks.

pgrep aa.sh | xargs pgrep -P ${} | xargs kill

If you want to execute a command if the process is running do this

pgrep aa.sh && echo Running

How to enable scrolling of content inside a modal?

Set height for modal-body and not for the whole modal to get a perfect scroll on modal overlay. I get it work like this:

.MyModal {
    height: 450px;
    overflow-y: auto;
}

Here you can set height as per your requirements.

Can I have an IF block in DOS batch file?

Instead of this goto mess, try using the ampersand & or double ampersand && (conditional to errorlevel 0) as command separators.

I fixed a script snippet with this trick, to summarize, I have three batch files, one which calls the other two after having found which letters the external backup drives have been assigned. I leave the first file on the primary external drive so the calls to its backup routine worked fine, but the calls to the second one required an active drive change. The code below shows how I fixed it:

for %%b in (d e f g h i j k l m n o p q r s t u v w x y z) DO (
if exist "%%b:\Backup.cmd" %%b: & CALL "%%b:\Backup.cmd"
)

IOCTL Linux device driver

An ioctl, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.

An alternative is the sysfs interface, where you set up a file under /sys/ and read/write that to get information from and to the driver. An example of how to set this up:

static ssize_t mydrvr_version_show(struct device *dev,
        struct device_attribute *attr, char *buf)
{
    return sprintf(buf, "%s\n", DRIVER_RELEASE);
}

static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);

And during driver setup:

device_create_file(dev, &dev_attr_version);

You would then have a file for your device in /sys/, for example, /sys/block/myblk/version for a block driver.

Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl or libnl3 libraries.

How can you dynamically create variables via a while loop?

NOTE: This should be considered a discussion rather than an actual answer.

An approximate approach is to operate __main__ in the module you want to create variables. For example there's a b.py:

#!/usr/bin/env python
# coding: utf-8


def set_vars():
    import __main__
    print '__main__', __main__
    __main__.B = 1

try:
    print B
except NameError as e:
    print e

set_vars()

print 'B: %s' % B

Running it would output

$ python b.py
name 'B' is not defined
__main__ <module '__main__' from 'b.py'>
B: 1

But this approach only works in a single module script, because the __main__ it import will always represent the module of the entry script being executed by python, this means that if b.py is involved by other code, the B variable will be created in the scope of the entry script instead of in b.py itself. Assume there is a script a.py:

#!/usr/bin/env python
# coding: utf-8

try:
    import b
except NameError as e:
    print e

print 'in a.py: B', B

Running it would output

$ python a.py
name 'B' is not defined
__main__ <module '__main__' from 'a.py'>
name 'B' is not defined
in a.py: B 1

Note that the __main__ is changed to 'a.py'.

How many spaces will Java String.trim() remove?

One very important thing is that a string made entirely of "white spaces" will return a empty string.

if a string sSomething = "xxxxx", where x stand for white spaces, sSomething.trim() will return an empty string.

if a string sSomething = "xxAxx", where x stand for white spaces, sSomething.trim() will return A.

if sSomething ="xxSomethingxxxxAndSomethingxElsexxx", sSomething.trim() will return SomethingxxxxAndSomethingxElse, notice that the number of x between words is not altered.

If you want a neat packeted string combine trim() with regex as shown in this post: How to remove duplicate white spaces in string using Java?.

Order is meaningless for the result but trim() first would be more efficient. Hope it helps.

PowerShell : retrieve JSON object by field value

David Brabant's answer led me to what I needed, with this addition:

x.Stuffs | where { $_.Name -eq "Darts" } | Select -ExpandProperty Type

How do I download a file from the internet to my linux server with Bash

You can use the command wget to download from command line. Specifically, you could use

wget http://download.oracle.com/otn-pub/java/jdk/7u10-b18/jdk-7u10-linux-x64.tar.gz

However because Oracle requires you to accept a license agreement this may not work (and I am currently unable to test it).

jQuery get the location of an element relative to window

This sounds more like you want a tooltip for the link selected. There are many jQuery tooltips, try out jQuery qTip. It has a lot of options and is easy to change the styles.

Otherwise if you want to do this yourself you can use the jQuery .position(). More info about .position() is on http://api.jquery.com/position/

$("#element").position(); will return the current position of an element relative to the offset parent.

There is also the jQuery .offset(); which will return the position relative to the document.

How can I disable all views inside the layout?

Actully what work for me is:

getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);

and to undo it:

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);

How do you run your own code alongside Tkinter's event loop?

Use the after method on the Tk object:

from tkinter import *

root = Tk()

def task():
    print("hello")
    root.after(2000, task)  # reschedule event in 2 seconds

root.after(2000, task)
root.mainloop()

Here's the declaration and documentation for the after method:

def after(self, ms, func=None, *args):
    """Call function once after given time.

    MS specifies the time in milliseconds. FUNC gives the
    function which shall be called. Additional parameters
    are given as parameters to the function call.  Return
    identifier to cancel scheduling with after_cancel."""

JavaScript DOM remove element

Using Node.removeChild() does the job for you, simply use something like this:

var leftSection = document.getElementById('left-section');
leftSection.parentNode.removeChild(leftSection);

In DOM 4, the remove method applied, but there is a poor browser support according to W3C:

The method node.remove() is implemented in the DOM 4 specification. But because of poor browser support, you should not use it.

But you can use remove method if you using jQuery...

$('#left-section').remove(); //using remove method in jQuery

Also in new frameworks like you can use conditions to remove an element, for example *ngIf in Angular and in React, rendering different views, depends on the conditions...

Difference between Inheritance and Composition

Inheritances Vs Composition.

Inheritances and composition both are used to re-usability and extension of class behavior.

Inheritances mainly use in a family algorithm programming model such as IS-A relation type means similar kind of object. Example.

  1. Duster is a Car
  2. Safari is a Car

These are belongs to Car family.

Composition represents HAS-A relationship Type.It shows the ability of an object such as Duster has Five Gears , Safari has four Gears etc. Whenever we need to extend the ability of an existing class then use composition.Example we need to add one more gear in Duster object then we have to create one more gear object and compose it to the duster object.

We should not make the changes in base class until/unless all the derived classes needed those functionality.For this scenario we should use Composition.Such as

class A Derived by Class B

Class A Derived by Class C

Class A Derived by Class D.

When we add any functionality in class A then it is available to all sub classes even when Class C and D don't required those functionality.For this scenario we need to create a separate class for those functionality and compose it to the required class(here is class B).

Below is the example:

          // This is a base class
                 public abstract class Car
                    {
                       //Define prototype
                       public abstract void color();
                       public void Gear() {
                           Console.WriteLine("Car has a four Gear");
                       }
                    }


           // Here is the use of inheritence
           // This Desire class have four gears.
          //  But we need to add one more gear that is Neutral gear.

          public class Desire : Car
                   {
                       Neutral obj = null;
                       public Desire()
                       {
     // Here we are incorporating neutral gear(It is the use of composition). 
     // Now this class would have five gear. 

                           obj = new Neutral();
                           obj.NeutralGear();
                       }

                       public override void color()
                       {
                           Console.WriteLine("This is a white color car");
                       }

                   }


             // This Safari class have four gears and it is not required the neutral
             //  gear and hence we don't need to compose here.

                   public class Safari :Car{
                       public Safari()
                       { }

                       public override void color()
                       {
                           Console.WriteLine("This is a red color car");
                       }


                   }

   // This class represents the neutral gear and it would be used as a composition.

   public class Neutral {
                      public void NeutralGear() {
                           Console.WriteLine("This is a Neutral Gear");
                       }
                   }