Programs & Examples On #Fstream

fstream provides an iostream interface for file I/O in C++.

How to read line by line or a whole text file at once?

You can use std::getline :

#include <fstream>
#include <string>

int main() 
{ 
    std::ifstream file("Read.txt");
    std::string str; 
    while (std::getline(file, str))
    {
        // Process str
    }
}

Also note that it's better you just construct the file stream with the file names in it's constructor rather than explicitly opening (same goes for closing, just let the destructor do the work).

Further documentation about std::string::getline() can be read at CPP Reference.

Probably the easiest way to read a whole text file is just to concatenate those retrieved lines.

std::ifstream file("Read.txt");
std::string str;
std::string file_contents;
while (std::getline(file, str))
{
  file_contents += str;
  file_contents.push_back('\n');
}  

clear data inside text file in c++

As far as I am aware, simply opening the file in write mode without append mode will erase the contents of the file.

ofstream file("filename.txt"); // Without append
ofstream file("filename.txt", ios::app); // with append

The first one will place the position bit at the beginning erasing all contents while the second version will place the position bit at the end-of-file bit and write from there.

fstream won't create a file

This will do:

#include <fstream>
#include <iostream>
using std::fstream;

int main(int argc, char *argv[]) {
    fstream file;
    file.open("test.txt",std::ios::out);
    file << fflush;
    file.close();
}

Reading from text file until EOF repeats last line

Just follow closely the chain of events.

  • Grab 10
  • Grab 20
  • Grab 30
  • Grab EOF

Look at the second-to-last iteration. You grabbed 30, then carried on to check for EOF. You haven't reached EOF because the EOF mark hasn't been read yet ("binarically" speaking, its conceptual location is just after the 30 line). Therefore you carry on to the next iteration. x is still 30 from previous iteration. Now you read from the stream and you get EOF. x remains 30 and the ios::eofbit is raised. You output to stderr x (which is 30, just like in the previous iteration). Next you check for EOF in the loop condition, and this time you're out of the loop.

Try this:

while (true) {
    int x;
    iFile >> x;
    if( iFile.eof() ) break;
    cerr << x << endl;
}

By the way, there is another bug in your code. Did you ever try to run it on an empty file? The behaviour you get is for the exact same reason.

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

Using C++ filestreams (fstream), how can you determine the size of a file?

Like this:

long begin, end;
ifstream myfile ("example.txt");
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size: " << (end-begin) << " bytes." << endl;

Confirmation dialog on ng-click - AngularJS

An angular-only solution that works alongside ng-click is possible by using compile to wrap the ng-click expression.

Directive:

.directive('confirmClick', function ($window) {
  var i = 0;
  return {
    restrict: 'A',
    priority:  1,
    compile: function (tElem, tAttrs) {
      var fn = '$$confirmClick' + i++,
          _ngClick = tAttrs.ngClick;
      tAttrs.ngClick = fn + '($event)';

      return function (scope, elem, attrs) {
        var confirmMsg = attrs.confirmClick || 'Are you sure?';

        scope[fn] = function (event) {
          if($window.confirm(confirmMsg)) {
            scope.$eval(_ngClick, {$event: event});
          }
        };
      };
    }
  };
});

HTML:

<a ng-click="doSomething()" confirm-click="Are you sure you wish to proceed?"></a>

jQuery - Redirect with post data

There is a JQuery plug-in that accomplishes pretty much what you're trying to do: https://github.com/mgalante/jquery.redirect/blob/master/jquery.redirect.js.

After including JQuery and the jquery.redirect.min.js plug-in, you can simply do something like this:

$().redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});

Use the following code on newer JQuery versions instead:

$.redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});

Hope this helps!

Pandas merge two dataframes with different columns

I had this problem today using any of concat, append or merge, and I got around it by adding a helper column sequentially numbered and then doing an outer join

helper=1
for i in df1.index:
    df1.loc[i,'helper']=helper
    helper=helper+1
for i in df2.index:
    df2.loc[i,'helper']=helper
    helper=helper+1
df1.merge(df2,on='helper',how='outer')

Removing all non-numeric characters from string in Python

@Ned Batchelder and @newacct provided the right answer, but ...

Just in case if you have comma(,) decimal(.) in your string:

import re
re.sub("[^\d\.]", "", "$1,999,888.77")
'1999888.77'

Unable to install pyodbc on Linux

On Ubuntu, you'll need to install unixodbc-dev:

sudo apt-get install unixodbc-dev

Install pip by using this command:

sudo apt-get install python-pip

once that is installed, you should be able to install pyodbc successfully:

pip install pyodbc

How to revert uncommitted changes including files and folders?

git clean -fd

didn't help, new files remained. What I did is totally deleting all the working tree and then

git reset --hard

See "How do I clear my local working directory in git?" for advice to add the -x option to clean:

git clean -fdx

Note -x flag will remove all files ignored by Git so be careful (see discussion in the answer I refer to).

Android Google Maps API V2 Zoom to Current Location

Try this coding:

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();

Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
    map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));

    CameraPosition cameraPosition = new CameraPosition.Builder()
        .target(new LatLng(location.getLatitude(), location.getLongitude()))      // Sets the center of the map to location user
        .zoom(17)                   // Sets the zoom
        .bearing(90)                // Sets the orientation of the camera to east
        .tilt(40)                   // Sets the tilt of the camera to 30 degrees
        .build();                   // Creates a CameraPosition from the builder
    map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));       
}

How to scroll to an element inside a div?

browser does scrolling automatically to an element that gets focus, so what you can also do it to wrap the element that you need to be scrolled to into <a>...</a> and then when you need scroll just set the focus on that a

Create a branch in Git from another branch

Git 2.23 introduces git switch and git restore to split the responsibilities of git checkout

Creating a new branch from an existing branch as of git 2.23:

git switch -c my-new-branch

Switched to a new branch 'my-new-branch'

  • -c is short for --create and replaces the well-known git checkout -b

Take a look at this Github blog post explaining the changes in greater detail:

Git 2.23 brings a new pair of experimental commands to the suite of existing ones: git switch and git restore. These two are meant to eventually provide a better interface for the well-known git checkout. The new commands intend to each have a clear separation, neatly divvying up what the many responsibilities of git checkout

jQuery .val change doesn't change input value

<script src="//code.jquery.com/jquery.min.js"></script>
<script>
function changes() {
$('#link').val('new value');
}
</script>
<button onclick="changes()">a</button>
<input type='text' value='http://www.link.com' id='link'>

How to view file history in Git?

git log --all -- path/to/file should work

How to filter array when object key value is in array

In case you have key value pairs in your input array, I used:

.filter(
          this.multi_items[0] != null && store.state.isSearchBox === false
            ? item =>
                _.map(this.multi_items, "value").includes(item["wijknaam"])
            : item => item["wijknaam"].includes("")
        );

where the input array is multi_items as: [{"text": "bla1", "value": "green"}, {"text": etc. etc.}]

_.map is a lodash function.

In CSS what is the difference between "." and "#" when declaring a set of styles?

Like pretty much everyone has stated already:

A period (.) indicates a class, and a hash (#) indicates an ID.

The fundamental difference between is that you can reuse a class on your page over and over, whereas an ID can be used once. That is, of course, if you are sticking to WC3 standards.

A page will still render if you have multiple elements with the same ID, but you will run into problems if/when you try to dynamically update said elements by calling them with their ID, since they are not unique.

It is also useful to note that ID properties will supersede class properties.

Check if an HTML input element is empty or has no value entered by user

getElementById will return false if the element was not found in the DOM.

var el = document.getElementById("customx");
if (el !== null && el.value === "")
{
  //The element was found and the value is empty.
}

How can I pad an integer with zeros on the left?

Found this example... Will test...

import java.text.DecimalFormat;
class TestingAndQualityAssuranceDepartment
{
    public static void main(String [] args)
    {
        int x=1;
        DecimalFormat df = new DecimalFormat("00");
        System.out.println(df.format(x));
    }
}

Tested this and:

String.format("%05d",number);

Both work, for my purposes I think String.Format is better and more succinct.

Remove a fixed prefix/suffix from a string in Bash

Using the =~ operator:

$ string="hello-world"
$ prefix="hell"
$ suffix="ld"
$ [[ "$string" =~ ^$prefix(.*)$suffix$ ]] && echo "${BASH_REMATCH[1]}"
o-wor

Enable VT-x in your BIOS security settings (refer to documentation for your computer)

Check "Virtualization" status under performance option in your task manager. If you already have enabled it in your BIOS and still status is "Disabled", then go to bios, disable it and save & exit. Restart or shut down again. Enable it in BIOS again and save & exit. This time you'll see the status changed to "Enabled", It took me 3 attempts (don't know why it took that much time, but finally it worked).

How to echo or print an array in PHP?

You can use var_dump() function to display structured information about variables/expressions including its type and value, or you can use print_r() to display information about a variable in a way that's readable by humans.

Example: Say we have got the following array and we want to display its contents.

$arr = array ('xyz', false, true, 99, array('50'));

print_r() function - Displays human-readable output

Array
(
    [0] => xyz
    [1] =>
    [2] => 1
    [3] => 99
    [4] => Array
        (
            [0] => 50
        )
)

var_dump() function - Displays values and types

array(5) {
  [0]=>
  string(3) "xyz"
  [1]=>
  bool(false)
  [2]=>
  bool(true)
  [3]=>
  int(100)
  [4]=>
  array(1) {
    [0]=>
    string(2) "50"
  }
}

The functions used in this answer can be found on the PHP.net website var_dump(), print_r()

For more details:

» https://stackhowto.com/how-to-display-php-variable-values-with-echo-print_r-and-var_dump/

» https://stackhowto.com/how-to-echo-an-array-in-php/

What is the difference between 'git pull' and 'git fetch'?

What is the difference between git pull and git fetch?

To understand this, you first need to understand that your local git maintains not only your local repository, but it also maintains a local copy of the remote repository.

git fetch brings your local copy of the remote repository up to date. For example, if your remote repository is GitHub - you may want to fetch any changes made in the remote repository to your local copy of it the remote repository. This will allow you to perform operations such as compare or merge.

git pull on the other hand will bring down the changes in the remote repository to where you keep your own code. Typically, git pull will do a git fetch first to bring the local copy of the remote repository up to date, and then it will merge the changes into your own code repository and possibly your working copy.

Check if an element contains a class in JavaScript?

Tip: Try to remove dependencies of jQuery in your projects as much as you can - VanillaJS.

document.firstElementChild returns <html> tag then the classList attribute returns all classes added to it.

if(document.firstElementChild.classList.contains("your-class")){
    // <html> has 'your-class'
} else {
    // <html> doesn't have 'your-class'
}

How to remove last n characters from every element in the R vector

Although this is mostly the same with the answer by @nfmcclure, I prefer using stringr package as it provdies a set of functions whose names are most consistent and descriptive than those in base R (in fact I always google for "how to get the number of characters in R" as I can't remember the name nchar()).

library(stringr)
str_sub(iris$Species, end=-4)
#or 
str_sub(iris$Species, 1, str_length(iris$Species)-3)

This removes the last 3 characters from each value at Species column.

get user timezone

This will get you the timezone as a PHP variable. I wrote a function using jQuery and PHP. This is tested, and does work!

On the PHP page where you are want to have the timezone as a variable, have this snippet of code somewhere near the top of the page:

<?php    
    session_start();
    $timezone = $_SESSION['time'];
?>

This will read the session variable "time", which we are now about to create.

On the same page, in the <head> section, first of all you need to include jQuery:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

Also in the <head> section, paste this jQuery:

<script type="text/javascript">
    $(document).ready(function() {
        if("<?php echo $timezone; ?>".length==0){
            var visitortime = new Date();
            var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
            $.ajax({
                type: "GET",
                url: "http://example.com/timezone.php",
                data: 'time='+ visitortimezone,
                success: function(){
                    location.reload();
                }
            });
        }
    });
</script>

You may or may not have noticed, but you need to change the url to your actual domain.

One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above url)

<?php
    session_start();
    $_SESSION['time'] = $_GET['time'];
?>

If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.

You can read more about this on my blog

How to `wget` a list of URLs in a text file?

try:

wget -i text_file.txt

(check man wget)

What's the most efficient way to check if a record exists in Oracle?

Simply get a count of the record(s) you're looking for. If count > 0 then record(s) exist.

    DECLARE
    rec_count NUMBER := 0;

    BEGIN

    select count(*) 
    into rec_count  
    from EMPLOYEETABLE  
    WHERE employee_id = inEMPLOYEE_ID  
    AND department_nbr = inDEPARTMENT_NBR;  


    if rec_count > 0 then  
       {UPDATE EMPLOYEETABLE}
    else  
       {INSERT INTO EMPLOYEETABLE}  
    end if;  

    END;

Use own username/password with git and bitbucket

I had to merge some of those good answers here! This works for me:

git remote set-url origin 'https://bitbucket.org/teamName/repo.git'

In the end, it will always prompt anyone who wants to pull from it

Change the Theme in Jupyter Notebook?

To install the Jupyterthemes package directly with conda, use:

conda install -c conda-forge jupyterthemes

Then, as others have pointed out, change the theme with jt -t <theme-name>

Implementing Singleton with an Enum (in Java)

In this Java best practices book by Joshua Bloch, you can find explained why you should enforce the Singleton property with a private constructor or an Enum type. The chapter is quite long, so keeping it summarized:

Making a class a Singleton can make it difficult to test its clients, as it’s impossible to substitute a mock implementation for a singleton unless it implements an interface that serves as its type. Recommended approach is implement Singletons by simply make an enum type with one element:

// Enum singleton - the preferred approach
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}

This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks.

While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

Vertical (rotated) text in HTML table

Here is one that works for plain-text with some server side processing:

public string RotateHtmltext(string innerHtml)
{
   const string TRANSFORMTEXT = "transform: rotate(90deg);";
   const string EXTRASTYLECSS = "<style type='text/css'>.r90 {"
                                 + "-webkit-" + TRANSFORMTEXT
                                 + "-moz-" + TRANSFORMTEXT
                                 + "-o-" + TRANSFORMTEXT
                                 + "-ms-" + TRANSFORMTEXT
                                 + "" + TRANSFORMTEXT
                                 + "width:1em;line-height:1ex}</style>";
   const string WRAPPERDIV = "<div style='display: table-cell; vertical-align: middle;'>";

   var newinnerHtml = string.Join("</div>"+WRAPPERDIV, Regex.Split(innerHtml, @"<br */?>").Reverse());

   newinnerHtml = Regex.Replace(newinnerHtml, @"((?:<[^>]*>)|(?:[^<]+))",
                                 match => match.Groups[1].Value.StartsWith("<")
                                             ? match.Groups[1].Value
                                             : string.Join("", match.Groups[1].Value.ToCharArray().Select(x=>"<div class='r90'>"+x+"</div>")),
                                 RegexOptions.Singleline);
   return EXTRASTYLECSS + WRAPPERDIV + newinnerHtml + "</div>";
}

which gives something like:

<style type="text/css">.r90 {
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
width: 1em;
line-height: 1ex; 
}</style>
<div style="display: table-cell; vertical-align: middle;">
<div class="r90">p</div>
<div class="r90">o</div>
<div class="r90">s</div>
</div><div style="display: table-cell; vertical-align: middle;">
<div class="r90">(</div>
<div class="r90">A</div>
<div class="r90">b</div>
<div class="r90">s</div>
<div class="r90">)</div>
</div>

http://jsfiddle.net/TzzHy/

Should I use `import os.path` or `import os`?

os.path works in a funny way. It looks like os should be a package with a submodule path, but in reality os is a normal module that does magic with sys.modules to inject os.path. Here's what happens:

  • When Python starts up, it loads a bunch of modules into sys.modules. They aren't bound to any names in your script, but you can access the already-created modules when you import them in some way.

    • sys.modules is a dict in which modules are cached. When you import a module, if it already has been imported somewhere, it gets the instance stored in sys.modules.
  • os is among the modules that are loaded when Python starts up. It assigns its path attribute to an os-specific path module.

  • It injects sys.modules['os.path'] = path so that you're able to do "import os.path" as though it was a submodule.

I tend to think of os.path as a module I want to use rather than a thing in the os module, so even though it's not really a submodule of a package called os, I import it sort of like it is one and I always do import os.path. This is consistent with how os.path is documented.


Incidentally, this sort of structure leads to a lot of Python programmers' early confusion about modules and packages and code organization, I think. This is really for two reasons

  1. If you think of os as a package and know that you can do import os and have access to the submodule os.path, you may be surprised later when you can't do import twisted and automatically access twisted.spread without importing it.

  2. It is confusing that os.name is a normal thing, a string, and os.path is a module. I always structure my packages with empty __init__.py files so that at the same level I always have one type of thing: a module/package or other stuff. Several big Python projects take this approach, which tends to make more structured code.

How to clear gradle cache?

The gradle daemon also creates a many large text files of every single build log. They are stored here:

~/.gradle/daemon/X.X/daemon-XXXX.out.log

"X.X" is the gradle version in use, like "4.4", and "XXXX" are just random numbers, like "1234".

The total size can grow to several hundred MB in just a few months. There is no way to disable the logging, and the files are not automatically deleted and they do not really need to be retained.

But you can create a small gradle task to automatically delete them, and free up lots of disk space:

Add this to your app/build.gradle:

android {

    buildTypes {
        ...
    }

    // Delete large build log files from ~/.gradle/daemon/X.X/daemon-XXX.out.log
    // Source: https://discuss.gradle.org/t/gradle-daemon-produces-a-lot-of-logs/9905
    def gradle = project.getGradle()
    new File("${gradle.getGradleUserHomeDir().getAbsolutePath()}/daemon/${gradle.getGradleVersion()}").listFiles().each {
        if (it.getName().endsWith('.out.log')) {
            // println("Deleting gradle log file: $it") // Optional debug output
            it.delete()
        }
    }
}

To see which files are being deleted, you can see the debug output in Android Studio -> View -> Tool Windows -> Build. Then press "Toggle View" button on that window to show the text output.

Note that a Gradle Sync or any Gradle Build will trigger the file deletions.

A better way would be to automatically move the files to the Trash/Recycle Bin, or at least copy them to a Trash folder first. But I don't know how to do that.

JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

- First to me Iterating and Looping are 2 different things.

Eg: Increment a variable till 5 is Looping.

    int count = 0;

    for (int i=0 ; i<5 ; i++){

        count = count + 1;

   }

Eg: Iterate over the Array to print out its values, is about Iteration

    int[] arr = {5,10,15,20,25};

    for (int i=0 ; i<arr.length ; i++){

        System.out.println(arr[i]);

   }

Now about all the Loops:

- Its always better to use For-Loop when you know the exact nos of time you gonna Loop, and if you are not sure of it go for While-Loop. Yes out there many geniuses can say that it can be done gracefully with both of them and i don't deny with them...but these are few things which makes me execute my program flawlessly...

For Loop :

int sum = 0; 

for (int i = 1; i <= 100; i++) {

  sum += i; 

}

 System.out.println("The sum is " + sum);

The Difference between While and Do-While is as Follows :

- While is a Entry Control Loop, Condition is checked in the Beginning before entering the loop.

- Do-While is a Exit Control Loop, Atleast once the block is always executed then the Condition is checked.

While Loop :

int sum = 0; 
int i = 0;       // i is 0 Here

    while (i<100) {

      sum += i; 
      i++;

    }

  System.out.println("The sum is " + sum);

do-While :

int sum = 0; 
int i = 0;      // i is 0 Here

    do{ 

      sum += i; 
       i++
    }while(i < 100; );

     System.out.println("The sum is " + sum);

From Java 5 we also have For-Each Loop to iterate over the Collections, even its handy with Arrays.

ArrayList<String> arr = new ArrayList<String>();

arr.add("Vivek");
arr.add("Is");
arr.add("Good");
arr.add("Boy");

for (String str : arr){         // str represents the value in each index of arr

    System.out.println(str);     

 }

clearing select using jquery

Here is a small jQuery plugin that (among other things) can empty an dropdown list.

Just write:

$('your-select-element').selectUtils('setEmpty');

Clearing NSUserDefaults

All above answers are very relevant, but if someone still unable to reset the userdefaults for deleted app, then you can reset the content settings of you simulator, and it will work.enter image description here

How to build a 2 Column (Fixed - Fluid) Layout with Twitter Bootstrap?

Update 2018

Bootstrap 4

Now that BS4 is flexbox, the fixed-fluid is simple. Just set the width of the fixed column, and use the .col class on the fluid column.

.sidebar {
    width: 180px;
    min-height: 100vh;
}

<div class="row">
    <div class="sidebar p-2">Fixed width</div>
    <div class="col bg-dark text-white pt-2">
        Content
    </div>
</div>

http://www.codeply.com/go/7LzXiPxo6a

Bootstrap 3..

One approach to a fixed-fluid layout is using media queries that align with Bootstrap's breakpoints so that you only use the fixed width columns are larger screens and then let the layout stack responsively on smaller screens...

@media (min-width:768px) {
  #sidebar {
      min-width: 300px;
      max-width: 300px;
  }
  #main {
      width:calc(100% - 300px);
  }
}

Working Bootstrap 3 Fixed-Fluid Demo

Related Q&A:
Fixed width column with a container-fluid in bootstrap
How to left column fixed and right scrollable in Bootstrap 4, responsive?

How to remove files and directories quickly via terminal (bash shell)

rm -rf *

Would remove everything (folders & files) in the current directory.

But be careful! Only execute this command if you are absolutely sure, that you are in the right directory.

Rest-assured. Is it possible to extract value from request json?

I found the answer :)

Use JsonPath or XmlPath (in case you have XML) to get data from the response body.

In my case:

JsonPath jsonPath = new JsonPath(responseBody);
int user_id = jsonPath.getInt("user_id");

"Faceted Project Problem (Java Version Mismatch)" error message

Did you check your Project Properties -> Project Facets panel? (From that post)

A WTP project is composed of multiple units of functionality (known as facets).

The Java facet version needs to always match the java compiler compliance level.
The best way to change java level is to use the Project Facets properties panel as that will update both places at the same time.

WTP

The "Project->Preferences->Project Facets" stores its configuration in this file, "org.eclipse.wst.common.project.facet.core.xml", under the ".settings" directory.

The content might look like this

<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
  <runtime name="WebSphere Application Server v6.1"/>
  <fixed facet="jst.java"/>
  <fixed facet="jst.web"/>
  <installed facet="jst.java" version="5.0"/>
  <installed facet="jst.web" version="2.4"/>
  <installed facet="jsf.ibm" version="7.0"/>
  <installed facet="jsf.base" version="7.0"/>
  <installed facet="web.jstl" version="1.1"/>
</faceted-project>

Check also your Java compliance level:

Java compliance level

Excel cell value as string won't store as string

Use Range("A1").Text instead of .Value

post comment edit:
Why?
Because the .Text property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92 then <- Text will return exactly what it in the cell including any formatting.
The .Value and .Value2 properties return what's stored in the cell under the hood excluding formatting. Specially .Value2 for date types, it will return the decimal representation.

If you want to dig deeper into the meaning and performance, I just found this article which seems like a good guide

another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
Dont Format column A, Format B as TEXT, C as Date, D as Percentage
now,
paste this code in a module

Sub main()

    Dim ws As Worksheet, i&, j&
    Set ws = Sheets(1)
    For i = 3 To 7
        For j = 1 To 4
            Debug.Print _
                    "row " & i & vbTab & vbTab & _
                    Cells(i, j).Text & vbTab & _
                    Cells(i, j).Value & vbTab & _
                    Cells(i, j).Value2
        Next j
    Next i
End Sub

and Analyse the output! Its really easy and there isn't much more i can do to help :)

            .TEXT              .VALUE             .VALUE2
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 4       1                 1                   1
row 4       1                 1                   1
row 4       01/01/1900        31/12/1899          1
row 4       1.00%             0.01                0.01
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 6       63                63                  63
row 6       =7*9              =7*9                =7*9
row 6       03/03/1900        03/03/1900          63
row 6       6300.00%          63                  63
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013        29/05/2013          29/05/2013
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013%       29/05/2013%         29/05/2013%

C++ queue - simple example

Simply declare it as below if you want to us the STL queue container.

std::queue<myclass*> my_queue;

Remove Null Value from String array in java

Quite similar approve as already posted above. However it's easier to read.

/**
 * Remove all empty spaces from array a string array
 * @param arr array
 * @return array without ""
 */
public static String[] removeAllEmpty(String[] arr) {
    if (arr == null)
        return arr;

    String[] result = new String[arr.length];
    int amountOfValidStrings = 0;

    for (int i = 0; i < arr.length; i++) {
        if (!arr[i].equals(""))
            result[amountOfValidStrings++] = arr[i];
    }

    result = Arrays.copyOf(result, amountOfValidStrings);

    return result;
}

git ignore vim temporary files

If You are using source control. vim temp files are quite useless.
So You might want to configure vim not to create them.

Just edit Your ~/.vimrc and add these lines:

set nobackup
set noswapfile

Add button to a layout programmatically

If you just have included a layout file at the beginning of onCreate() inside setContentView and want to get this layout to add new elements programmatically try this:

ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);

then you can create a new Button for example and just add it:

Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 
                                    LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);

Git push error: "origin does not appear to be a git repository"

When you create a repository in bitbucket.org, it gives you instructions on how to set up your local directory. Chances are, you just forgot to run the code:

git remote add origin https://[email protected]/username/reponame.git

How can I keep my branch up to date with master with git?

If your branch is local only and hasn't been pushed to the server, use

git rebase master

Otherwise, use

git merge master

Is it possible to specify a different ssh port when using rsync?

A bit offtopic but might help someone. If you need to pass password and port I suggest using sshpass package. Command line command would look like this: sshpass -p "password" rsync -avzh -e 'ssh -p PORT312' [email protected]:/dir_on_host/

Regex: ignore case sensitivity

Assuming you want the whole regex to ignore case, you should look for the i flag. Nearly all regex engines support it:

/G[a-b].*/i

string.match("G[a-b].*", "i")

Check the documentation for your language/platform/tool to find how the matching modes are specified.

If you want only part of the regex to be case insensitive (as my original answer presumed), then you have two options:

  1. Use the (?i) and [optionally] (?-i) mode modifiers:

    (?i)G[a-b](?-i).*
    
  2. Put all the variations (i.e. lowercase and uppercase) in the regex - useful if mode modifiers are not supported:

    [gG][a-bA-B].*
    

One last note: if you're dealing with Unicode characters besides ASCII, check whether or not your regex engine properly supports them.

Set ANDROID_HOME environment variable in mac

Here are the steps:

  1. Open Terminal
  2. Type touch .bash_profile and press Enter
  3. Now Type open .bash_profile and again press Enter
  4. A textEdit file will be opened
  5. Now type export ANDROID_HOME="Users/Your_User_Name/Library/Android/sdk"
  6. Then in next line type export PATH="${PATH}:/$ANDROID_HOME/platform-tools:/$ANDROID_HOME/tools:/$ANDROID_HOME/tools/bin"
  7. Now save this .bash_profile file
  8. Close the Terminal

To verify if Path is set successfully open terminal again and type adb if adb version and other details are displayed that means path is set properly.

Show DialogFragment with animation growing from a point

Add this code on values anim

 <scale
    android:duration="@android:integer/config_longAnimTime"
    android:fromXScale="0.2"
    android:fromYScale="0.2"
    android:toXScale="1.0"
    android:toYScale="1.0"
    android:pivotX="50%"
    android:pivotY="50%"/>
<alpha
    android:fromAlpha="0.1"
    android:toAlpha="1.0"
    android:duration="@android:integer/config_longAnimTime"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator"/>

call on styles.xml

<style name="DialogScale">
    <item name="android:windowEnterAnimation">@anim/scale_in</item>
    <item name="android:windowExitAnimation">@anim/scale_out</item>
</style>

On java code: set Onclick

public void onClick(View v) {
        fab_onclick(R.style.DialogScale, "Scale" ,(Activity) context,getWindow().getDecorView().getRootView());
      //  Dialogs.fab_onclick(R.style.DialogScale, "Scale");

    }

setup on method:

alertDialog.getWindow().getAttributes().windowAnimations = type;

Array of arrays (Python/NumPy)

It seems strange that you would write arrays without commas (is that a MATLAB syntax?)

Have you tried going through NumPy's documentation on multi-dimensional arrays?

It seems NumPy has a "Python-like" append method to add items to a NumPy n-dimensional array:

>>> p = np.array([[1,2],[3,4]])

>>> p = np.append(p, [[5,6]], 0)

>>> p = np.append(p, [[7],[8],[9]],1)

>>> p
array([[1, 2, 7], [3, 4, 8], [5, 6, 9]])

It has also been answered already...

From the documentation for MATLAB users:

You could use a matrix constructor which takes a string in the form of a matrix MATLAB literal:

mat("1 2 3; 4 5 6")

or

matrix("[1 2 3; 4 5 6]")

Please give it a try and tell me how it goes.

What does "select count(1) from table_name" on any database tables mean?

You can test like this:

create table test1(
 id number,
 name varchar2(20)
);

insert into test1 values (1,'abc');
insert into test1 values (1,'abc');

select * from test1;
select count(*) from test1;
select count(1) from test1;
select count(ALL 1) from test1;
select count(DISTINCT 1) from test1;

Uncaught TypeError: Cannot set property 'onclick' of null

Wrap code in

window.onload = function(){ 
    // your code 
};

Failed to execute removeChild on Node

As others have mentioned, myCoolDiv is a child of markerDiv not playerContainer. If you want to remove myCoolDiv but keep markerDiv for some reason you can do the following

myCoolDiv.parentNode.removeChild(myCoolDiv);

JSFiddle

XCOPY: Overwrite all without prompt in BATCH

The solution is the /Y switch:

xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y

Does Hibernate create tables in the database automatically

Yes, Hibernate can be configured by way of the hibernate.hbm2ddl.auto property in the hibernate.cfg.xml file to automatically create tables in your DB in order to store your entities in them if the table doesn't already exist.

This can be handy during development where a new, in-memory, DB can be used and created a new on every run of the application or during testing.

SQL SERVER: Check if variable is null and then assign statement for Where Clause

Try the following:

if ((select VisitCount from PageImage where PID=@pid and PageNumber=5) is NULL)
begin
    update PageImage
    set VisitCount=1
    where PID=@pid and PageNumber=@pageno
end 
else
begin
    update PageImage 
    set VisitCount=VisitCount+1
    where PID=@pid and PageNumber=@pageno
end

Regex - Should hyphens be escaped?

Typically you would always put the hyphen first in the [] match section. EG, to match any alphanumeric character including hyphens (written the long way), you would use [-a-zA-Z0-9]

Generate Controller and Model

For generate Model , controller with resources and migration best command is:

php artisan make:model ModelName -m -cr 

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

i had the same problem and it seems like i didn't initiate the button used with click listener, in other words id didn't te

Better way to represent array in java properties file

Either define a delimiter that will not be a potential value or learn to use XML.

If you still insist on using properties use one of the methods that will return a list of all keys. Your key appears to have three parts a group identifier (foo, bar) an index (1, 2) and then an element name (filename, expire). Get all the keys break them into their component parts. Create a List for each type of identifier, when processing the list use the identifier to determine which List to add to. Create you paired elements as you said and simply add to the list! If the index order is important either add that as a field to your paired elements or sort the keys before processing.

How to return data from PHP to a jQuery ajax call

based on accepted answer

$output = some_function();
  echo $output;

if it results array then use json_encode it will result json array which is supportable by javascript

$output = some_function();
  echo json_encode($output);

If someone wants to stop execution after you echo some result use exit method of php. It will work like return keyword

$output = some_function();
  echo $output;
exit;

How to ping multiple servers and return IP address and Hostnames using batch script?

This works for spanish operation system.

Script accepts two parameters:

  • a file with the list of IP or domains
  • output file

script.bat listofurls.txt output.txt

@echo off
setlocal enabledelayedexpansion
set OUTPUT_FILE=%2
>nul copy nul %OUTPUT_FILE%
for /f %%i in (%1) do (
    set SERVER_ADDRESS=No se pudo resolver el host
    for /f "tokens=1,2,3,4,5" %%v in ('ping -a -n 1 %%i ^&^& echo SERVER_IS_UP') 
    do (
        if %%v==Haciendo set SERVER_ADDRESS=%%z
        if %%v==Respuesta set SERVER_ADDRESS=%%x
        if %%v==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
    )
    echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE! >>%OUTPUT_FILE%
    echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE!
)

How can I sharpen an image in OpenCV?

You can find a sample code about sharpening image using "unsharp mask" algorithm at OpenCV Documentation.

Changing values of sigma,threshold,amount will give different results.

// sharpen image using "unsharp mask" algorithm
Mat blurred; double sigma = 1, threshold = 5, amount = 1;
GaussianBlur(img, blurred, Size(), sigma, sigma);
Mat lowContrastMask = abs(img - blurred) < threshold;
Mat sharpened = img*(1+amount) + blurred*(-amount);
img.copyTo(sharpened, lowContrastMask);

Setting and getting localStorage with jQuery

The localStorage can only store string content and you are trying to store a jQuery object since html(htmlString) returns a jQuery object.

You need to set the string content instead of an object. And use the setItem method to add data and getItem to get data.

window.localStorage.setItem('content', 'Test');
$('#test').html(window.localStorage.getItem('content'));

How do I schedule a task to run at periodic intervals?

Use timer.scheduleAtFixedRate

public void scheduleAtFixedRate(TimerTask task,
                                long delay,
                                long period)

Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period.
In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time. It is also appropriate for recurring activities where the total time to perform a fixed number of executions is important, such as a countdown timer that ticks once every second for ten seconds. Finally, fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain synchronized with respect to one another.

Parameters:

  • task - task to be scheduled.
  • delay - delay in milliseconds before task is to be executed.
  • period - time in milliseconds between successive task executions.

Throws:

  • IllegalArgumentException - if delay is negative, or delay + System.currentTimeMillis() is negative.
  • IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.

RegEx: How can I match all numbers greater than 49?

I know there is already a good answer posted, but it won't allow leading zeros. And I don't have enough reputation to leave a comment, so... Here's my solution allowing leading zeros:

First I match the numbers 50 through 99 (with possible leading zeros):

0*[5-9]\d

Then match numbers of 100 and above (also with leading zeros):

0*[1-9]\d{2,}

Add them together with an "or" and wrap it up to match the whole sentence:

^0*([1-9]\d{2,}|[5-9]\d)$

That's it!

Store JSON object in data attribute in HTML jQuery

Combine the use of window.btoa and window.atob together with JSON.stringify and JSON.parse.

- This works for strings containing single quotes

Encoding the data:

var encodedObject = window.btoa(JSON.stringify(dataObject));

Decoding the data:

var dataObject = JSON.parse(window.atob(encodedObject));

Here is an example of how the data is constructed and decoded later with the click event.

Construct the html and encode the data:

var encodedObject = window.btoa(JSON.stringify(dataObject));

"<td>" + "<a class='eventClass' href='#' data-topic='" + encodedObject + "'>" 
+ "Edit</a></td>"

Decode the data in the click event handler:

$("#someElementID").on('click', 'eventClass', function(e) {
            event.preventDefault();
            var encodedObject = e.target.attributes["data-topic"].value;
            var dataObject = JSON.parse(window.atob(encodedObject));

            // use the dataObject["keyName"] 
}

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

I also had the same error. I had not added the below dependency in my POM file.

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.1.7.RELEASE</version>
  </dependency>

But My porject used to run even before I had added this dependency. But at one point it stopped and started giving the same above error.

If any one couldn't solve this error they can also solve by this link

Already defined in .obj - no double inclusions

This is one of the method to overcome this issue.

  • Just put the prototype in the header files and include the header files in the .cpp files as shown below.

client.cpp

#ifndef SOCKET_CLIENT_CLASS
#define SOCKET_CLIENT_CLASS
#ifndef BOOST_ASIO_HPP
#include <boost/asio.hpp>
#endif

class SocketClient // Or whatever the name is... {

// ...

    bool read(int, char*); // Or whatever the name is...

//  ... };

#endif

client.h

bool SocketClient::read(int, char*)
{
    // Implementation  goes here...
}

main.cpp

#include <iostream>
#include <string>
#include <sstream>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include "client.h"
//              ^^ Notice this!

main.h

int main()

How to round up a number in Javascript?

Very near to TheEye answer, but I change a little thing to make it work:

_x000D_
_x000D_
var num = 192.16;_x000D_
    _x000D_
console.log(    Math.ceil(num * 10) / 10    );
_x000D_
_x000D_
_x000D_

Index of Currently Selected Row in DataGridView

Use the Index property in your DGV's SelectedRows collection:

int index = yourDGV.SelectedRows[0].Index;

What is the Java equivalent for LINQ?

Now that Java 8 supports lambdas, it's possible to create Java APIs that closely resemble LINQ.

Jinq is one of these new LINQ-style libraries for Java.

I am the developer of this library. It is based on five years of research on using bytecode analysis to translate Java to database queries. Similar to how C#'s D-LINQ is a query layer that sits on top of the Entity Framework, Jinq is able to act as a query layer sitting on top of JPA or jOOQ. It has support for aggregation, groups, and subqueries. Even Erik Meijer (the creator of LINQ) has acknowledged Jinq.

How do you detect/avoid Memory leaks in your (Unmanaged) code?

At least for MS VC++, the C Runtime library has several functions that I've found helpful in the past. Check the MSDN help for the _Crt* functions.

How to check if PHP array is associative or sequential?

function is_array_assoc($foo) {
    if (is_array($foo)) {
        return (count(array_filter(array_keys($foo), 'is_string')) > 0);
    }
    return false;
}

How to set value to form control in Reactive Forms in Angular

Setting or Updating of Reactive Forms Form Control values can be done using both patchValue and setValue. However, it might be better to use patchValue in some instances.

patchValue does not require all controls to be specified within the parameters in order to update/set the value of your Form Controls. On the other hand, setValue requires all Form Control values to be filled in, and it will return an error if any of your controls are not specified within the parameter.

In this scenario, we will want to use patchValue, since we are only updating user and questioning:

this.qService.editQue([params["id"]]).subscribe(res => {
  this.question = res;
  this.editqueForm.patchValue({
    user: this.question.user,
    questioning: this.question.questioning
  });
});

EDIT: If you feel like doing some of ES6's Object Destructuring, you may be interested to do this instead

const { user, questioning } = this.question;

this.editqueForm.patchValue({
  user,
  questioning
});

Ta-dah!

How to set text size of textview dynamically for different screens

You should use the resource folders such as

values-ldpi
values-mdpi
values-hdpi

And write the text size in 'dimensions.xml' file for each range.

And in the java code you can set the text size with

textView.setTextSize(getResources().getDimension(R.dimen.textsize));

Sample dimensions.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="textsize">15sp</dimen>
</resources>

Convert NSDate to String in iOS Swift

After allocating DateFormatter you need to give the formatted string then you can convert as string like this way

var date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date)
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
let updatedString = formatter.string(from: yourDate!)
print(updatedString)

OutPut

01-Mar-2017

RS256 vs HS256: What's the difference?

In cryptography there are two types of algorithms used:

Symmetric algorithms

A single key is used to encrypt data. When encrypted with the key, the data can be decrypted using the same key. If, for example, Mary encrypts a message using the key "my-secret" and sends it to John, he will be able to decrypt the message correctly with the same key "my-secret".

Asymmetric algorithms

Two keys are used to encrypt and decrypt messages. While one key(public) is used to encrypt the message, the other key(private) can only be used to decrypt it. So, John can generate both public and private keys, then send only the public key to Mary to encrypt her message. The message can only be decrypted using the private key.

HS256 and RS256 Scenario

These algorithms are NOT used to encrypt/decryt data. Rather they are used to verify the origin or the authenticity of the data. When Mary needs to send an open message to Jhon and he needs to verify that the message is surely from Mary, HS256 or RS256 can be used.

HS256 can create a signature for a given sample of data using a single key. When the message is transmitted along with the signature, the receiving party can use the same key to verify that the signature matches the message.

RS256 uses pair of keys to do the same. A signature can only be generated using the private key. And the public key has to be used to verify the signature. In this scenario, even if Jack finds the public key, he cannot create a spoof message with a signature to impersonate Mary.

How to emulate GPS location in the Android Emulator?

Just make Alberto Gaona's answer into one line

token=$(cat ~/.emulator_console_auth_token); cat <(echo -e "auth $token \n  geo fix 96.0290791 16.9041016  \n exit") - | nc localhost 5554

5554 is the emulator port number shown in adb devices.

It would have been better if adb emu work.

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

It is possible to enable/disable wifi on pre Android 10 devices using the following code:

WifiManager wifiManager = 
(WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);

wifiManager.setWifiEnabled(status);

But note that it is not possible to do this anymore on Android 10 and probably going ahead as well.
https://issuetracker.google.com/issues/141011684

Where is Java Installed on Mac OS X?

You could use echo $(/usr/libexec/java_home) command in your terminal to know the path where Java being installed.

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

Is this what you are looking for? Otherwise, let me know and I will remove this post.

Try this jQuery plugin: http://archive.plugins.jquery.com/project/client-detect

Demo: http://www.stoimen.com/jquery.client.plugin/

This is based on quirksmode BrowserDetect a wrap for jQuery browser/os detection plugin.

For keen readers:
http://www.stoimen.com/blog/2009/07/16/jquery-browser-and-os-detection-plugin/
http://www.quirksmode.org/js/support.html

And more code around the plugin resides here: http://www.stoimen.com/jquery.client.plugin/jquery.client.js

How to replace list item in best way

i find best for do it fast and simple

  1. find ur item in list

    var d = Details.Where(x => x.ProductID == selectedProduct.ID).SingleOrDefault();
    
  2. make clone from current

    OrderDetail dd = d;
    
  3. Update ur clone

    dd.Quantity++;
    
  4. find index in list

    int idx = Details.IndexOf(d);
    
  5. remove founded item in (1)

      Details.Remove(d);
    
  6. insert

     if (idx > -1)
          Details.Insert(idx, dd);
      else
          Details.Insert(Details.Count, dd);
    

How do I fix MSB3073 error in my post-build event?

Playing around with different project properties, I found that the project build order was the problem. The project that generated the files I wanted to copy was built second, but the project that was running the batch file as a post-build event was built first, so I simply attached the build event to the second project instead, and it works just fine. Thanks for your help, everyone, though.

@selector() in Swift?

Create Refresh control using Selector method.   
    var refreshCntrl : UIRefreshControl!
    refreshCntrl = UIRefreshControl()
    refreshCntrl.tintColor = UIColor.whiteColor()
    refreshCntrl.attributedTitle = NSAttributedString(string: "Please Wait...")
    refreshCntrl.addTarget(self, action:"refreshControlValueChanged", forControlEvents: UIControlEvents.ValueChanged)
    atableView.addSubview(refreshCntrl)

//Refresh Control Method

func refreshControlValueChanged(){
    atableView.reloadData()
    refreshCntrl.endRefreshing()

}

C - function inside struct

This will only work in C++. Functions in structs are not a feature of C.

Same goes for your client.AddClient(); call ... this is a call for a member function, which is object oriented programming, i.e. C++.

Convert your source to a .cpp file and make sure you are compiling accordingly.

If you need to stick to C, the code below is (sort of) the equivalent:

typedef struct client_t client_t, *pno;
struct client_t
{
        pid_t pid;
        char password[TAM_MAX]; // -> 50 chars
        pno next;

};


pno AddClient(pno *pclient) 
{
    /* code */
}


int main()
{

    client_t client;

    //code ..

    AddClient(client);

}

How can I execute Python scripts using Anaconda's version of Python?

I like to run a "bare-bones" version of Python 2 to verify scripts that I create for other people without an advanced python setup. But Anaconda and Python 3 have a lot of nice features. To enjoy both things on the same computer I do this on my Windows computer which allows me to easily switch.

C:\Users>python --version
Python 2.7.11

C:\Users>conda create --name p3 python=3

C:\Users>conda info --envs
Using Anaconda Cloud api site https://api.anaconda.org
# conda environments:
#
p3                       C:\Anaconda3\envs\p3
root                  *  C:\Anaconda3

C:\Users>activate p3
Deactivating environment "C:\Anaconda3"...
Activating environment "C:\Anaconda3\envs\p3"...

[p3] C:\Users>python --version
Python 3.5.1 :: Continuum Analytics, Inc.

For more info: http://conda.pydata.org/docs/test-drive.html

Tool for sending multipart/form-data request

The usual error is one tries to put Content-Type: {multipart/form-data} into the header of the post request. That will fail, it is best to let Postman do it for you. For example:

Suggestion To Load Via Postman Body Part

Fails If In Header Common Error

Works should remove content type from the Header

Python Timezone conversion

Time conversion

To convert a time in one timezone to another timezone in Python, you could use datetime.astimezone():

so, below code is to convert the local time to other time zone.

  • datetime.datetime.today() - return current the local time
  • datetime.astimezone() - convert the time zone, but we have to pass the time zone.
  • pytz.timezone('Asia/Kolkata') -passing the time zone to pytz module
  • Strftime - Convert Datetime to string
# Time conversion from local time
import datetime
import pytz
dt_today = datetime.datetime.today()   # Local time
dt_India = dt_today.astimezone(pytz.timezone('Asia/Kolkata')) 
dt_London = dt_today.astimezone(pytz.timezone('Europe/London'))
India = (dt_India.strftime('%m/%d/%Y %H:%M'))
London = (dt_London.strftime('%m/%d/%Y %H:%M'))
print("Indian standard time: "+India+" IST")
print("British Summer Time: "+London+" BST")

list all the time zone

import pytz
for tz in pytz.all_timezones:
    print(tz)

No module named serial

it may be very old post, but I would like to share my experience. I had the same issue when I used Pycharm and I installed the package from Project Interpreter page in the Project Settings/Preferences... That fixed the issue, please check below link: https://www.jetbrains.com/help/pycharm/installing-uninstalling-and-upgrading-packages.html?_ga=2.41088674.1813230270.1594526819-1842497340.1594080707

Importing lodash into angular2 + typescript application

I am using ng2 with webpack, not system JS. Steps need for me were:

npm install underscore --save
typings install dt~underscore --global --save

and then in the file I wish to import underscore into:

import * as _ from 'underscore';

Where can I view Tomcat log files in Eclipse?

if you're after the catalina.out log and you are using eclispe with tomcat, this works for me:

  • create catelina.out some where in your computer. In my case, I put it in logs directory of my tomcat install directory e.g: /opt/apache-tomcat-7.0.83/logs/catena.out
  • go to your eclipse, in the servers tab, double-click on the Tomcat Server. You will get a screen called Overview.
  • Click on "Open launch configuration". Then click on the "Common" tab.
  • At standard input and output section, check "output file", click on file system and then selected the folder where your create your catelina.out.
  • Finally, restart the Tomcat server.

How to select from subquery using Laravel Query Builder?

I could not made your code to do the desired query, the AS is an alias only for the table abc, not for the derived table. Laravel Query Builder does not implicitly support derived table aliases, DB::raw is most likely needed for this.

The most straight solution I could came up with is almost identical to yours, however produces the query as you asked for:

$sql = Abc::groupBy('col1')->toSql();
$count = DB::table(DB::raw("($sql) AS a"))->count();

The produced query is

select count(*) as aggregate from (select * from `abc` group by `col1`) AS a;

C++ deprecated conversion from string constant to 'char*'

This is an error message you see whenever you have a situation like the following:

char* pointer_to_nonconst = "string literal";

Why? Well, C and C++ differ in the type of the string literal. In C the type is array of char and in C++ it is constant array of char. In any case, you are not allowed to change the characters of the string literal, so the const in C++ is not really a restriction but more of a type safety thing. A conversion from const char* to char* is generally not possible without an explicit cast for safety reasons. But for backwards compatibility with C the language C++ still allows assigning a string literal to a char* and gives you a warning about this conversion being deprecated.

So, somewhere you are missing one or more consts in your program for const correctness. But the code you showed to us is not the problem as it does not do this kind of deprecated conversion. The warning must have come from some other place.

get number of columns of a particular row in given excel using Java

/** Count max number of nonempty cells in sheet rows */
private int getColumnsCount(XSSFSheet xssfSheet) {
    int result = 0;
    Iterator<Row> rowIterator = xssfSheet.iterator();
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();
        List<Cell> cells = new ArrayList<>();
        Iterator<Cell> cellIterator = row.cellIterator();
        while (cellIterator.hasNext()) {
            cells.add(cellIterator.next());
        }
        for (int i = cells.size(); i >= 0; i--) {
            Cell cell = cells.get(i-1);
            if (cell.toString().trim().isEmpty()) {
                cells.remove(i-1);
            } else {
                result = cells.size() > result ? cells.size() : result;
                break;
            }
        }
    }
    return result;
}

Compiler error "archive for required library could not be read" - Spring Tool Suite

In case of VSCode, follow the below steps:

  1. Navigate to the respective folder that contains the corrupted jar
  2. Delete just the jar
  3. mvn clean
  4. mvn compile

That worked for me.

LINQ query to find if items in a list are contained in another list

bool doesL1ContainsL2 = l1.Intersect(l2).Count() == l2.Count;

L1 and L2 are both List<T>

How to get current page URL in MVC 3

My favorite...

Url.Content(Request.Url.PathAndQuery)

or just...

Url.Action()

How to set Java SDK path in AndroidStudio?

C:\Program Files\Android\Android Studio\jre\bin>java -version
openjdk version "1.8.0_76-release"
OpenJDK Runtime Environment (build 1.8.0_76-release-b03)
OpenJDK 64-Bit Server VM (build 25.76-b03, mixed mode)

Somehow the Studio installer would install another version under:

C:\Program Files\Android\Android Studio\jre\jre\bin>java -version
openjdk version "1.8.0_76-release"
OpenJDK Runtime Environment (build 1.8.0_76-release-b03)
OpenJDK 64-Bit Server VM (build 25.76-b03, mixed mode)

where the latest version was installed the Java DevKit installer in:

C:\Program Files\Java\jre1.8.0_121\bin>java -version
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)

Need to clean up the Android Studio so it would use the proper latest 1.8.0 versions.

According to How to set Java SDK path in AndroidStudio? one could override with a specific JDK but when I renamed

C:\Program Files\Android\Android Studio\jre\jre\

to:

C:\Program Files\Android\Android Studio\jre\oldjre\

And restarted Android Studio, it would complain that the jre was invalid. When I tried to aecify an JDK to pick the one in C:\Program Files\Java\jre1.8.0_121\bin or:

C:\Program Files\Java\jre1.8.0_121\

It said that these folders are invalid. So I guess that the embedded version must have some special purpose.

Array of strings in groovy

If you really want to create an array rather than a list use either

String[] names = ["lucas", "Fred", "Mary"]

or

def names = ["lucas", "Fred", "Mary"].toArray()

In PHP how can you clear a WSDL cache?

I recommend using a cache-buster in the wsdl url.

In our apps we use a SVN Revision id in the wsdl url so the client immediately knows of changing structures. This works on our app because, everytime we change the server-side, we also need to adjust the client accordingly.

$client = new SoapClient('http://somewhere.com/?wsdl&rev=$Revision$');

This requires svn to be configured properly. Not on all repositories this is enabled by default.

In case you are not responsible for both components (server,client) or you don't use SVN you may find another indicator which can be utilised as a cache-buster in your wsdl url.

How can I create a blank/hardcoded column in a sql query?

For varchars, you may need to do something like this:

select convert(varchar(25), NULL) as abc_column into xyz_table

If you try

select '' as abc_column into xyz_table

you may get errors related to truncation, or an issue with null values, once you populate.

Get jQuery version from inspecting the jQuery object

For older versions of jQuery

jQuery().jquery  (or)

jQuery().fn.jquery

For newer versions of jQuery

$().jquery  (or)

$().fn.jquery

Image overlay on responsive sized images bootstrap

When you specify position:absolute it positions itself to the next-highest element with position:relative. In this case, that's the .project div.

If you give the image's immediate parent div a style of position:relative, the overlay will key to that instead of the div which includes the text. For example: http://jsfiddle.net/7gYUU/1/

 <div class="parent">
    <img src="http://placehold.it/500x500" class="img-responsive"/>
    <div class="fa fa-plus project-overlay"></div>
 </div>

.parent {
   position: relative;
}

What is your most productive shortcut with Vim?

I recently discovered q:. It opens the "command window" and shows your most recent ex-mode (command-mode) commands. You can move as usual within the window, and pressing <CR> executes the command. You can edit, etc. too. Priceless when you're messing around with some complex command or regex and you don't want to retype the whole thing, or if the complex thing you want to do was 3 commands back. It's almost like bash's set -o vi, but for vim itself (heh!).

See :help q: for more interesting bits for going back and forth.

How can I replace every occurrence of a String in a file with PowerShell?

Small correction for the Set-Content command. If the searched string is not found the Set-Content command will blank (empty) the target file.

You can first verify if the string you are looking for exist or not. If not it will not replace anything.

If (select-string -path "c:\Windows\System32\drivers\etc\hosts" -pattern "String to look for") `
    {(Get-Content c:\Windows\System32\drivers\etc\hosts).replace('String to look for', 'String to replace with') | Set-Content c:\Windows\System32\drivers\etc\hosts}
    Else{"Nothing happened"}

How to declare array of zeros in python (or an array of a certain size)

use numpy

import numpy
zarray = numpy.zeros(100)

And then use the Histogram library function

GROUP BY with MAX(DATE)

I know I'm late to the party, but try this...

SELECT 
    `Train`, 
    `Dest`,
    SUBSTRING_INDEX(GROUP_CONCAT(`Time` ORDER BY `Time` DESC), ",", 1) AS `Time`
FROM TrainTable
GROUP BY Train;

Src: Group Concat Documentation

Edit: fixed sql syntax

Generate list of all possible permutations of a string

Some working Java code based on Sarp's answer:

public class permute {

    static void permute(int level, String permuted,
                    boolean used[], String original) {
        int length = original.length();
        if (level == length) {
            System.out.println(permuted);
        } else {
            for (int i = 0; i < length; i++) {
                if (!used[i]) {
                    used[i] = true;
                    permute(level + 1, permuted + original.charAt(i),
                       used, original);
                    used[i] = false;
                }
            }
        }
    }

    public static void main(String[] args) {
        String s = "hello";
        boolean used[] = {false, false, false, false, false};
        permute(0, "", used, s);
    }
}

Redirect to a page/URL after alert button is pressed

You're missing semi-colons after your javascript lines. Also, window.location should have .href or .replace etc to redirect - See this post for more information.

echo '<script type="text/javascript">'; 
echo 'alert("review your answer");'; 
echo 'window.location.href = "index.php";';
echo '</script>';

For clarity, try leaving PHP tags for this:

?>
<script type="text/javascript">
alert("review your answer");
window.location.href = "index.php";
</script>
<?php

NOTE: semi colons on seperate lines are optional, but encouraged - however as in the comments below, PHP won't break lines in the first example here but will in the second, so semi-colons are required in the first example.

Quickest way to convert XML to JSON in Java

The only problem with JSON in Java is that if your XML has a single child, but is an array, it will convert it to an object instead of an array. This can cause problems if you dynamically always convert from XML to JSON, where if your example XML has only one element, you return an object, but if it has 2+, you return an array, which can cause parsing issues for people using the JSON.

Infoscoop's XML2JSON class has a way of tagging elements that are arrays before doing the conversion, so that arrays can be properly mapped, even if there is only one child in the XML.

Here is an example of using it (in a slightly different language, but you can also see how arrays is used from the nodelist2json() method of the XML2JSON link).

Greater than and less than in one statement

Nowadays you can use lodash:

var x = 1;
var y = 5;
var z = 3;
_.inRange(z,x,y);
//results true

Css height in percent not working

Add height:100% to body

body{height:100%}

What's the easy way to auto create non existing dir in ansible

To ensure success with a full path use recurse=yes

- name: ensure custom facts directory exists
    file: >
      path=/etc/ansible/facts.d
      recurse=yes
      state=directory

version `CXXABI_1.3.8' not found (required by ...)

GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:

export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH

Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).

PDO mysql: How to know if insert was successful

PDOStatement->execute() returns true on success. There is also PDOStatement->errorCode() which you can check for errors.

Node JS Promise.all and forEach

I had through the same situation. I solved using two Promise.All().

I think was really good solution, so I published it on npm: https://www.npmjs.com/package/promise-foreach

I think your code will be something like this

var promiseForeach = require('promise-foreach')
var jsonItems = [];
promiseForeach.each(jsonItems,
    [function (jsonItems){
        return new Promise(function(resolve, reject){
            if(jsonItems.type === 'file'){
                jsonItems.getFile().then(function(file){ //or promise.all?
                    resolve(file.getSize())
                })
            }
        })
    }],
    function (result, current) {
        return {
            type: current.type,
            size: jsonItems.result[0]
        }
    },
    function (err, newList) {
        if (err) {
            console.error(err)
            return;
        }
        console.log('new jsonItems : ', newList)
    })

Adding images to an HTML document with javascript

You need to use document.getElementById() in line 3.

If you try this right now in the console:

_x000D_
_x000D_
var img = document.createElement("img");_x000D_
img.src = "http://www.google.com/intl/en_com/images/logo_plain.png";_x000D_
var src = document.getElementById("header");_x000D_
src.appendChild(img);
_x000D_
<div id="header"></div>
_x000D_
_x000D_
_x000D_

... you'd get this:

enter image description here

Why does using an Underscore character in a LIKE filter give me all the results?

In case people are searching how to do it in BigQuery:

  • An underscore "_" matches a single character or byte.

  • You can escape "\", "_", or "%" using two backslashes. For example, "\%". If you are using raw strings, only a single backslash is required. For example, r"\%".

WHERE mycolumn LIKE '%\\_%'

Source: https://cloud.google.com/bigquery/docs/reference/standard-sql/operators

Sending HTTP POST with System.Net.WebClient

WebClient doesn't have a direct support for form data, but you can send a HTTP post by using the UploadString method:

Using client as new WebClient
    result = client.UploadString(someurl, "param1=somevalue&param2=othervalue")
End Using

JSTL if tag for equal strings

Try:

<c:if test = "${ansokanInfo.PSystem == 'NAT'}">

JSP/Servlet 2.4 (I think that's the version number) doesn't support method calls in EL and only support properties. The latest servlet containers do support method calls (ie Tomcat 7).

PHP refresh window? equivalent to F5 page reload?

Use JavaScript for this. You can do:

echo '
<script type="text/javascript">
   parent.window.location.reload(true);
</script>
';

In PHP and it will refresh the parent's frame page.

PHP Session Destroy on Log Out Button

// logout

if(isset($_GET['logout'])) {
    session_destroy();
    unset($_SESSION['username']);
    header('location:login.php');
}

?>

C# nullable string error

You are making it complicated. string is already nullable. You don't need to make it more nullable. Take out the ? on the property type.

Background images: how to fill whole div if image is small and vice versa

  1. I agree with yossi's example, stretch the image to fit the div but in a slightly different way (without background-image as this is a little inflexible in css 2.1). Show full image:

    <div id="yourdiv">
        <img id="theimage" src="image.jpg" alt="" />
    </div>
    
    #yourdiv img {
        width:100%;
      /*height will be automatic to remain aspect ratio*/
    }
    
  2. Show part of the image using background-position:

    #yourdiv 
    {
        background-image: url(image.jpg);
        background-repeat: no-repeat;
        background-position: 10px 25px;
    }
    
  3. Same as the first part of (1) the image will scale to the div so bigger or smaller will both work

  4. Same as yossi's.

Consider defining a bean of type 'service' in your configuration [Spring boot]

Please make sure that you have added the dependency in pom.xml or gradle file

spring-boot-starter-data-jpa

Ubuntu: OpenJDK 8 - Unable to locate package

After adding the JDK repo, before Installing you might want to run an update first so the repo can be added run apt update

an then continue with your installation sudo apt install adoptopenjdk-8-hotspot

Android: show/hide a view using an animation

Try to use TranslateAnimation class, which creates the animation for position changes. Try reading this for help - http://developer.android.com/reference/android/view/animation/TranslateAnimation.html

Update: Here's the example for this. If you have the height of your view as 50 and in the hide mode you want to show only 10 px. The sample code would be -

TranslateAnimation anim=new TranslateAnimation(0,0,-40,0);
anim.setFillAfter(true);
view.setAnimation(anim);

PS: There are lot's or other methods there to help you use the animation according to your need. Also have a look at the RelativeLayout.LayoutParams if you want to completely customize the code, however using the TranslateAnimation is easier to use.

EDIT:-Complex version using LayoutParams

RelativeLayout relParam=new RelativeLayout.LayoutParam(RelativeLayout.LayoutParam.FILL_PARENT,RelativeLayout.LayoutParam.WRAP_CONTENT); //you can give hard coded width and height here in (width,height) format.
relParam.topMargin=-50; //any number that work.Set it to 0, when you want to show it.
view.setLayoutParams(relparam);

This example code assumes you are putting your view in RelativeLayout, if not change the name of Layout, however other layout might not work. If you want to give an animation effect on them, reduce or increase the topMargin slowly. You can consider using Thread.sleep() there too.

How to uninstall jupyter

For Mac OS, you may use the below command in order to remove files manually.

sudo rm -rf /usr/local/bin/jupyter

MSSQL Select statement with incremental integer column... not from a table

For SQL 2005 and up

SELECT ROW_NUMBER() OVER( ORDER BY SomeColumn ) AS 'rownumber',*
    FROM YourTable

for 2000 you need to do something like this

SELECT IDENTITY(INT, 1,1) AS Rank ,VALUE
INTO #Ranks FROM YourTable WHERE 1=0

INSERT INTO #Ranks
SELECT SomeColumn  FROM YourTable
ORDER BY SomeColumn 

SELECT * FROM #Ranks
Order By Ranks

see also here Row Number

static function in C

Looking at the posts above I would like to give a more clarified answer:

Suppose our main.c file looks like this:

#include "header.h"

int main(void) {
    FunctionInHeader();
}

Now consider three cases:

  • Case 1: Our header.h file looks like this:

     #include <stdio.h>
    
     static void FunctionInHeader();
    
     void FunctionInHeader() {
         printf("Calling function inside header\n");
     }
    

    Then the following command on linux:

     gcc main.c -o main
    

    will succeed! That's because after the main.c file includes the header.h, the static function definition will be in the same main.c file (more precisely, in the same translation unit) to where it's called.

    If one runs ./main, the output will be Calling function inside header, which is what that static function should print.

  • Case 2: Our header header.h looks like this:

      static void FunctionInHeader();     
    

    and we also have one more file header.c, which looks like this:

      #include <stdio.h>
      #include "header.h"
    
      void FunctionInHeader() {
          printf("Calling function inside header\n");
      }
    

    Then the following command

      gcc main.c header.c -o main
    

    will give an error. In this case main.c includes only the declaration of the static function, but the definition is left in another translation unit and the static keyword prevents the code defining a function to be linked

  • Case 3:

    Similar to case 2, except that now our header header.h file is:

      void FunctionInHeader(); // keyword static removed
    

    Then the same command as in case 2 will succeed, and further executing ./main will give the expected result. Here the FunctionInHeader definition is in another translation unit, but the code defining it can be linked.

Thus, to conclude:

static keyword prevents the code defining a function to be linked,
when that function is defined in another translation unit than where it is called.

How to get start and end of previous month in VB

Public Shared Function GetFOMPrev(ByVal tdate As Date) As Date
    Return tdate.AddDays(-(tdate.Day - 1))
End Function

Public Shared Function GetEOMPrev(ByVal tdate As Date) As Date
    Return tdate.AddDays(-tdate.Day)
End Function

Usage:

'Get End of Month of Previous Month - Pass today's date
EOM = GetEOMPrev(Date.Today)

'Get First of Month of Previous Month - Pass date just calculated
FOM = GetFOMPrev(EOM)

Can I simultaneously declare and assign a variable in VBA?

There is no shorthand in VBA unfortunately, The closest you will get is a purely visual thing using the : continuation character if you want it on one line for readability;

Dim clientToTest As String:  clientToTest = clientsToTest(i)
Dim clientString As Variant: clientString = Split(clientToTest)

Hint (summary of other answers/comments): Works with objects too (Excel 2010):

Dim ws  As Worksheet: Set ws = ActiveWorkbook.Worksheets("Sheet1")
Dim ws2 As New Worksheet: ws2.Name = "test"

Display encoded html with razor

You can also simply use the HtmlString class

    @(new HtmlString(Model.Content))

"Proxy server connection failed" in google chrome

I had the same problem with a freshly installed copy of Chrome. If nothing works, and your Use a proxy server your LAN setting is unchecked, check it and then uncheck it . Believe it or not it might work. I don't know if I should consider it a bug or not.

Can I run a 64-bit VMware image on a 32-bit machine?

You can if your processor is 64-bit and Virtualization Technology (VT) extension is enabled (it can be switched off in BIOS). You can't do it on 32-bit processor.

To check this under Linux you just need to look into /proc/cpuinfo file. Just look for the appropriate flag (vmx for Intel processor or svm for AMD processor)

egrep '(vmx|svm)' /proc/cpuinfo

To check this under Windows you need to use a program like CPU-Z which will display your processor architecture and supported extensions.

How to set an image as a background for Frame in Swing GUI of java?

The Background Panel entry shows a couple of different ways depending on your requirements.

Android ListView with different layouts for each row

I know how to create a custom row + custom array adapter to support a custom row for the entire list view. But how can one listview support many different row styles?

You already know the basics. You just need to get your custom adapter to return a different layout/view based on the row/cursor information being provided.

A ListView can support multiple row styles because it derives from AdapterView:

An AdapterView is a view whose children are determined by an Adapter.

If you look at the Adapter, you'll see methods that account for using row-specific views:

abstract int getViewTypeCount()
// Returns the number of types of Views that will be created ...

abstract int getItemViewType(int position)
// Get the type of View that will be created ...

abstract View getView(int position, View convertView, ViewGroup parent)
// Get a View that displays the data ...

The latter two methods provide the position so you can use that to determine the type of view you should use for that row.


Of course, you generally don't use AdapterView and Adapter directly, but rather use or derive from one of their subclasses. The subclasses of Adapter may add additional functionality that change how to get custom layouts for different rows. Since the view used for a given row is driven by the adapter, the trick is to get the adapter to return the desired view for a given row. How to do this differs depending on the specific adapter.

For example, to use ArrayAdapter,

  • override getView() to inflate, populate, and return the desired view for the given position. The getView() method includes an opportunity reuse views via the convertView parameter.

But to use derivatives of CursorAdapter,

  • override newView() to inflate, populate, and return the desired view for the current cursor state (i.e. the current "row") [you also need to override bindView so that widget can reuse views]

However, to use SimpleCursorAdapter,

  • define a SimpleCursorAdapter.ViewBinder with a setViewValue() method to inflate, populate, and return the desired view for a given row (current cursor state) and data "column". The method can define just the "special" views and defer to SimpleCursorAdapter's standard behavior for the "normal" bindings.

Look up the specific examples/tutorials for the kind of adapter you end up using.

JavaScript to get rows count of a HTML table

$('tableName').find('tr').length

Error "initializer element is not constant" when trying to initialize variable with const

It's a limitation of the language. In section 6.7.8/4:

All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

In section 6.6, the spec defines what must considered a constant expression. No where does it state that a const variable must be considered a constant expression. It is legal for a compiler to extend this (6.6/10 - An implementation may accept other forms of constant expressions) but that would limit portability.

If you can change my_foo so it does not have static storage, you would be okay:

int main()
{
    foo_t my_foo = foo_init;
    return 0;
}

Java: How to convert String[] to List or Set

java.util.Arrays.asList(new String[]{"a", "b"})

Query an object array using linq

Add:

using System.Linq;

to the top of your file.

And then:

Car[] carList = ...
var carMake = 
    from item in carList
    where item.Model == "bmw" 
    select item.Make;

or if you prefer the fluent syntax:

var carMake = carList
    .Where(item => item.Model == "bmw")
    .Select(item => item.Make);

Things to pay attention to:

  • The usage of item.Make in the select clause instead if s.Make as in your code.
  • You have a whitespace between item and .Model in your where clause

How to match, but not capture, part of a regex?

Try this:

/\d{3}-(?:(apple|banana)-)?\d{3}/

Make XmlHttpRequest POST using JSON

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));

How to get CRON to call in the correct PATHs

I used /etc/crontab. I used vi and entered in the PATHs I needed into this file and ran it as root. The normal crontab overwrites PATHs that you have set up. A good tutorial on how to do this.

The systemwide cron file looks like this:

This has the username field, as used by /etc/crontab.
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file.
# This file also has a username field, that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user   command
42 6 * * *   root    run-parts --report /etc/cron.daily
47 6 * * 7   root    run-parts --report /etc/cron.weekly
52 6 1 * *   root    run-parts --report /etc/cron.monthly
01 01 * * 1-5 root python /path/to/file.py

Angular.js programmatically setting a form field to dirty

If you have access to the NgModelController (you can only get access to it from a directive) then you can call

ngModel.$setViewValue("your new view value");
// or to keep the view value the same and just change it to dirty
ngModel.$setViewValue(ngModel.$viewValue);

getResourceAsStream returns null

Don't use absolute paths, make them relative to the 'resources' directory in your project. Quick and dirty code that displays the contents of MyTest.txt from the directory 'resources'.

@Test
public void testDefaultResource() {
    // can we see default resources
    BufferedInputStream result = (BufferedInputStream) 
         Config.class.getClassLoader().getResourceAsStream("MyTest.txt");
    byte [] b = new byte[256];
    int val = 0;
    String txt = null;
    do {
        try {
            val = result.read(b);
            if (val > 0) {
                txt += new String(b, 0, val);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } 
    } while (val > -1);
    System.out.println(txt);
}

Easy way to turn JavaScript array into comma-separated list?

Simple Array

_x000D_
_x000D_
let simpleArray = [1,2,3,4]
let commaSeperated = simpleArray.join(",");
console.log(commaSeperated);
_x000D_
_x000D_
_x000D_

Array of Objects with a particular attributes as comma separated.

_x000D_
_x000D_
let arrayOfObjects = [
{
id : 1,
name : "Name 1",
address : "Address 1"
},
{
id : 2,
name : "Name 2",
address : "Address 2"
},
{
id : 3,
name : "Name 3",
address : "Address 3"
}]
let names = arrayOfObjects.map(x => x.name).join(", ");
console.log(names);
_x000D_
_x000D_
_x000D_

Make scrollbars only visible when a Div is hovered over?

_x000D_
_x000D_
div {_x000D_
  height: 100px;_x000D_
  width: 50%;_x000D_
  margin: 0 auto;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
div:hover {_x000D_
  overflow-y: scroll;_x000D_
}
_x000D_
<div>_x000D_
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It_x000D_
    has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop_x000D_
    publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
  </p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Would something like that work?

How to get duplicate items from a list using LINQ?

I know it's not the answer to the original question, but you may find yourself here with this problem.

If you want all of the duplicate items in your results, the following works.

var duplicates = list
    .GroupBy( x => x )               // group matching items
    .Where( g => g.Skip(1).Any() )   // where the group contains more than one item
    .SelectMany( g => g );           // re-expand the groups with more than one item

In my situation I need all duplicates so that I can mark them in the UI as being errors.

Can I convert a C# string value to an escaped string literal

Here is a little improvement for Smilediver's answer, it will not escape all no-ASCII chars but only these are really needed.

using System;
using System.Globalization;
using System.Text;

public static class CodeHelper
{
    public static string ToLiteral(this string input)
    {
        var literal = new StringBuilder(input.Length + 2);
        literal.Append("\"");
        foreach (var c in input)
        {
            switch (c)
            {
                case '\'': literal.Append(@"\'"); break;
                case '\"': literal.Append("\\\""); break;
                case '\\': literal.Append(@"\\"); break;
                case '\0': literal.Append(@"\0"); break;
                case '\a': literal.Append(@"\a"); break;
                case '\b': literal.Append(@"\b"); break;
                case '\f': literal.Append(@"\f"); break;
                case '\n': literal.Append(@"\n"); break;
                case '\r': literal.Append(@"\r"); break;
                case '\t': literal.Append(@"\t"); break;
                case '\v': literal.Append(@"\v"); break;
                default:
                    if (Char.GetUnicodeCategory(c) != UnicodeCategory.Control)
                    {
                        literal.Append(c);
                    }
                    else
                    {
                        literal.Append(@"\u");
                        literal.Append(((ushort)c).ToString("x4"));
                    }
                    break;
            }
        }
        literal.Append("\"");
        return literal.ToString();
    }
}

Possible heap pollution via varargs parameter

It's rather safe to add @SafeVarargs annotation to the method when you can control the way it's called (e.g. a private method of a class). You must make sure that only the instances of the declared generic type are passed to the method.

If the method exposed externally as a library, it becomes hard to catch such mistakes. In this case it's best to avoid this annotation and rewrite the solution with a collection type (e.g. Collection<Type1<Type2>>) input instead of varargs (Type1<Type2>...).

As for the naming, the term heap pollution phenomenon is quite misleading in my opinion. In the documentation the actual JVM heap is not event mentioned. There is a question at Software Engineering that contains some interesting thoughts on the naming of this phenomenon.

Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss

Gooye if it's possible to use Joda Time in your project then this code works for me:

String dateStr = "2012-10-01T09:45:00.000+02:00";
String customFormat = "yyyy-MM-dd HH:mm:ss";

DateTimeFormatter dtf = ISODateTimeFormat.dateTime();
LocalDateTime parsedDate = dtf.parseLocalDateTime(dateStr);

String dateWithCustomFormat = parsedDate.toString(DateTimeFormat.forPattern(customFormat));
System.out.println(dateWithCustomFormat);

How can I install pip on Windows?

Working as of Feb 04 2014 :):

If you have tried installing pip through the Windows installer file from http://www.lfd.uci.edu/~gohlke/pythonlibs/#pip as suggested by @Colonel Panic, you might have installed the pip package manager successfully, but you might be unable to install any packages with pip. You might also have got the same SSL error as I got when I tried to install Beautiful Soup 4 if you look in the pip.log file:

Downloading/unpacking beautifulsoup4
  Getting page https://pypi.python.org/simple/beautifulsoup4/
  Could not fetch URL https://pypi.python.org/simple/beautifulsoup4/: **connection error: [Errno 1] _ssl.c:504: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed**
  Will skip URL https://pypi.python.org/simple/beautifulsoup4/ when looking for download links for beautifulsoup4

The problem is an issue with an old version of OpenSSL being incompatible with pip 1.3.1 and above versions. The easy workaround for now, is to install pip 1.2.1, which does not require SSL:

Installing Pip on Windows:

  1. Download pip 1.2.1 from https://pypi.python.org/packages/source/p/pip/pip-1.2.1.tar.gz
  2. Extract the pip-1.2.1.tar.gz file
  3. Change directory to the extracted folder: cd <path to extracted folder>/pip-1.2.1
  4. Run python setup.py install
  5. Now make sure C:\Python27\Scripts is in PATH because pip is installed in the C:\Python27\Scripts directory unlike C:\Python27\Lib\site-packages where Python packages are normally installed

Now try to install any package using pip.

For example, to install the requests package using pip, run this from cmd:

pip install requests

Whola! requests will be successfully installed and you will get a success message.

How to run a JAR file

I have this folder structure:

D:\JavaProjects\OlivePressApp\com\lynda\olivepress\Main.class D:\JavaProjects\OlivePressApp\com\lynda\olivepress\press\OlivePress.class D:\JavaProjects\OlivePressApp\com\lynda\olivepress\olives\Kalamata.class D:\JavaProjects\OlivePressApp\com\lynda\olivepress\olives\Ligurian.class D:\JavaProjects\OlivePressApp\com\lynda\olivepress\olives\Olive.class

Main.class is in package com.lynda.olivepress

There are two other packages:

com.lynda.olivepress.press

com.lynda.olivepress.olive

1) Create a file named "Manifest.txt" with Two Lines, First with Main-Class and a Second Empty Line.

Main-Class: com.lynda.olivepress.Main

D:\JavaProjects\OlivePressApp\ Manifest.txt

2) Create JAR with Manifest and Main-Class Entry Point

D:\JavaProjects\OlivePressApp>jar cfm OlivePressApp.jar Manifest.txt com/lynda/olivepress/Main.class com/lynda/olivepress/*

3) Run JAR

java -jar OlivePressApp.jar

Note: com/lynda/olivepress/* means including the other two packages mentioned above, before point 1)

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

mysql_fetch_array() expects parameter 1 to be resource boolean given in php error on server if you get this error : please select all privileges on your server. u will get the answer..

Print a div content using Jquery

Without using any plugin you can opt this logic.

$("#btn").click(function () {
    //Hide all other elements other than printarea.
    $("#printarea").show();
    window.print();
});

Hide vertical scrollbar in <select> element

Change padding-bottom , i.e may be the simplest possible way .

Moving up one directory in Python

Well.. I'm not sure how portable os.chdir('..') would actually be. Under Unix those are real filenames. I would prefer the following:

import os
os.chdir(os.path.dirname(os.getcwd()))

That gets the current working directory, steps up one directory, and then changes to that directory.

Set NOW() as Default Value for datetime datatype?

`ALTER TABLE  `table_name` CHANGE `column_name` 
    timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP 
    ON UPDATE CURRENT_TIMESTAMP

Can be used to update the timestamp on update.

Adding click event listener to elements with the same class

A short and sweet solution, using ES6:

document.querySelectorAll('.input')
      .forEach(input => input.addEventListener('focus', this.onInputFocus));

How do I style appcompat-v7 Toolbar like Theme.AppCompat.Light.DarkActionBar?

The recommended way to style the Toolbar for a Light.DarkActionBar clone would be to use Theme.AppCompat.Light.DarkActionbar as parent/app theme and add the following attributes to the style to hide the default ActionBar:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

Then use the following as your Toolbar:

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.AppBarLayout>

For further modifications, you would create styles extending ThemeOverlay.AppCompat.Dark.ActionBar and ThemeOverlay.AppCompat.Light replacing the ones within AppBarLayout->android:theme and Toolbar->app:popupTheme. Also note that this will pick up your ?attr/colorPrimary if you have set it in your main style so you might get a different background color.

You will find a good example of this is in the current project template with an Empty Activity of Android Studio (1.4+).

Export to xls using angularjs

You can try Alasql JavaScript library which can work together with XLSX.js library for easy export of Angular.js data. This is an example of controller with exportData() function:

function myCtrl($scope) {
  $scope.exportData = function () {
    alasql('SELECT * INTO XLSX("john.xlsx",{headers:true}) FROM ?',[$scope.items]);
  };

  $scope.items = [{
    name: "John Smith",
    email: "[email protected]",
    dob: "1985-10-10"
  }, {
    name: "Jane Smith",
    email: "[email protected]",
    dob: "1988-12-22"
  }];
}

See full HTML and JavaScript code for this example in jsFiddle.

UPDATED Another example with coloring cells.

Also you need to include two libraries:

How to use variables in a command in sed?

Say:

sed "s|\$ROOT|${HOME}|" abc.sh

Note:

  • Use double quotes so that the shell would expand variables.
  • Use a separator different than / since the replacement contains /
  • Escape the $ in the pattern since you don't want to expand it.

EDIT: In order to replace all occurrences of $ROOT, say

sed "s|\$ROOT|${HOME}|g" abc.sh

Quick way to list all files in Amazon S3 bucket?

Alternatively you can use Minio Client aka mc. Its Open Source and compatible with AWS S3. It is available for Linux, Windows, Mac, FreeBSD.

All you have do do is to run mc ls command for listing the contents.

$ mc ls s3/kline/
[2016-04-30 13:20:47 IST] 1.1MiB 1.jpg
[2016-04-30 16:03:55 IST] 7.5KiB docker.png
[2016-04-30 15:16:17 IST]  50KiB pi.png
[2016-05-10 14:34:39 IST] 365KiB upton.pdf

Note:

  • s3: Alias for Amazon S3
  • kline: AWS S3 bucket name

Installing Minio Client Linux Download mc for:

$ chmod 755 mc
$ ./mc --help

Setting up AWS credentials with Minio Client

$ mc config host add mys3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12

Note: Please replace mys3 with alias you would like for this account and ,BKIKJAA5BMMU2RHO6IBB, V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 with your AWS ACCESS-KEY and SECRET-KEY

Hope it helps.

Disclaimer: I work for Minio

MySQL Error 1215: Cannot add foreign key constraint

I'm guessing that Clients.Case_Number and/or Staff.Emp_ID are not exactly the same data type as Clients_has_Staff.Clients_Case_Number and Clients_has_Staff.Staff_Emp_ID.

Perhaps the columns in the parent tables are INT UNSIGNED?

They need to be exactly the same data type in both tables.

How do I run a program with commandline arguments using GDB within a Bash script?

gdb -ex=r --args myprogram arg1 arg2

-ex=r is short for -ex=run and tells gdb to run your program immediately, rather than wait for you to type "run" at the prompt. Then --args says that everything that follows is the command and arguments, just as you'd normally type them at the commandline prompt.

Read data from SqlDataReader

string col1Value = rdr["ColumnOneName"].ToString();

or

string col1Value = rdr[0].ToString();

These are objects, so you need to either cast them or .ToString().

Illegal Escape Character "\"

You can use:

\\

That's ok, for example:

if (invName.substring(j,k).equals("\\")) {
    copyf=invName.substring(0,j);
}

jquery - fastest way to remove all rows from a very large table

Two issues I can see here:

  1. The empty() and remove() methods of jQuery actually do quite a bit of work. See John Resig's JavaScript Function Call Profiling for why.

  2. The other thing is that for large amounts of tabular data you might consider a datagrid library such as the excellent DataTables to load your data on the fly from the server, increasing the number of network calls, but decreasing the size of those calls. I had a very complicated table with 1500 rows that got quite slow, changing to the new AJAX based table made this same data seem rather fast.

slf4j: how to log formatted message, object array, exception

As of SLF4J 1.6.0, in the presence of multiple parameters and if the last argument in a logging statement is an exception, then SLF4J will presume that the user wants the last argument to be treated as an exception and not a simple parameter. See also the relevant FAQ entry.

So, writing (in SLF4J version 1.7.x and later)

 logger.error("one two three: {} {} {}", "a", "b", 
              "c", new Exception("something went wrong"));

or writing (in SLF4J version 1.6.x)

 logger.error("one two three: {} {} {}", new Object[] {"a", "b", 
              "c", new Exception("something went wrong")});

will yield

one two three: a b c
java.lang.Exception: something went wrong
    at Example.main(Example.java:13)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at ...

The exact output will depend on the underlying framework (e.g. logback, log4j, etc) as well on how the underlying framework is configured. However, if the last parameter is an exception it will be interpreted as such regardless of the underlying framework.

Open mvc view in new window from controller

I assigned the javascript in my Controller:

model.linkCode = "window.open('https://www.yahoo.com', '_blank')";

And in my view:

@section Scripts{
    <script @Html.CspScriptNonce()>

    $(function () {

        @if (!String.IsNullOrEmpty(Model.linkCode))
        {
            WriteLiteral(Model.linkCode);
        }
    });

That opened a new tab with the link, and went to it.

Interestingly, run locally it engaged a popup blocker, but seemed to work fine on the servers.

How to represent a DateTime in Excel

dd-mm-yyyy hh:mm:ss.000 Universal sortable date/time pattern

Concatenate in jQuery Selector

There is nothing wrong with syntax of

$('#part' + number).html(text);

jQuery accepts a String (usually a CSS Selector) or a DOM Node as parameter to create a jQuery Object.

In your case you should pass a String to $() that is

$(<a string>)

Make sure you have access to the variables number and text.

To test do:

function(){
    alert(number + ":" + text);//or use console.log(number + ":" + text)
    $('#part' + number).html(text);
}); 

If you see you dont have access, pass them as parameters to the function, you have to include the uual parameters for $.get and pass the custom parameters after them.

What is default session timeout in ASP.NET?

It depends on either the configuration or programmatic change.
Therefore the most reliable way to check the current value is at runtime via code.

See the HttpSessionState.Timeout property; default value is 20 minutes.

You can access this propery in ASP.NET via HttpContext:

this.HttpContext.Session.Timeout // ASP.NET MVC controller
Page.Session.Timeout // ASP.NET Web Forms code-behind
HttpContext.Current.Session.Timeout // Elsewhere

What's the difference between equal?, eql?, ===, and ==?

=== #---case equality

== #--- generic equality

both works similar but "===" even do case statements

"test" == "test"  #=> true
"test" === "test" #=> true

here the difference

String === "test"   #=> true
String == "test"  #=> false

Terminating idle mysql connections

Manual cleanup:

You can KILL the processid.

mysql> show full processlist;
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| Id      | User       | Host              | db   | Command | Time  | State | Info                  |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| 1193777 | TestUser12 | 192.168.1.11:3775 | www  | Sleep   | 25946 |       | NULL                  |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+

mysql> kill 1193777;

But:

  • the php application might report errors (or the webserver, check the error logs)
  • don't fix what is not broken - if you're not short on connections, just leave them be.

Automatic cleaner service ;)

Or you configure your mysql-server by setting a shorter timeout on wait_timeout and interactive_timeout

mysql> show variables like "%timeout%";
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| connect_timeout          | 5     |
| delayed_insert_timeout   | 300   |
| innodb_lock_wait_timeout | 50    |
| interactive_timeout      | 28800 |
| net_read_timeout         | 30    |
| net_write_timeout        | 60    |
| slave_net_timeout        | 3600  |
| table_lock_wait_timeout  | 50    |
| wait_timeout             | 28800 |
+--------------------------+-------+
9 rows in set (0.00 sec)

Set with:

set global wait_timeout=3;
set global interactive_timeout=3;

(and also set in your configuration file, for when your server restarts)

But you're treating the symptoms instead of the underlying cause - why are the connections open? If the PHP script finished, shouldn't they close? Make sure your webserver is not using connection pooling...

How do I get a list of all subdomains of a domain?

If you can't get this information from DNS (e.g. you aren't authorized) then one alternative is to use Wolfram Alpha.

  1. Enter the domain into the search box and run the search. (E.g. stackexchange.com)

Wolfram - Homepage

  1. In the 3rd section from the top (named "Web statistics for all of stackexchange.com") click Subdomains

Wolfram - Subdomains button

  1. In the Subdomains section click More

Wolfram - More subdomains button

You will be able to see a list of sub-domains there. Although I suspect it does not show ALL sub-domains.

How to sync with a remote Git repository?

Assuming their updates are on master, and you are on the branch you want to merge the changes into.

git remote add origin https://github.com/<github-username>/<repo-name>.git
git pull origin master

Also note that you will then want to push the merge back to your copy of the repository:

git push origin master

How do I check if the user is pressing a key?

Try this:

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main {

    public static void main(String[] argv) throws Exception {

    JTextField textField = new JTextField();

    textField.addKeyListener(new Keychecker());

    JFrame jframe = new JFrame();

    jframe.add(textField);

    jframe.setSize(400, 350);

    jframe.setVisible(true);

}

class Keychecker extends KeyAdapter {

    @Override
    public void keyPressed(KeyEvent event) {

        char ch = event.getKeyChar();

        System.out.println(event.getKeyChar());

    }

}

How do I set the background color of my main screen in Flutter?

you should return Scaffold widget and add your widget inside Scaffold

suck as this code :

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return Scaffold(
          backgroundColor: Colors.white,
          body: Center(child: new Text("Hello, World!"));
    );
  }
}

When to use 'raise NotImplementedError'?

You might want to you use the @property decorator,

>>> class Foo():
...     @property
...     def todo(self):
...             raise NotImplementedError("To be implemented")
... 
>>> f = Foo()
>>> f.todo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in todo
NotImplementedError: To be implemented

What are the safe characters for making URLs?

I found it very useful to encode my URL to a safe one when I was returning a value through Ajax/PHP to a URL which was then read by the page again.

PHP output with URL encoder for the special character &:

// PHP returning the success information of an Ajax request
echo "".str_replace('&', '%26', $_POST['name']) . " category was changed";

// JavaScript sending the value to the URL
window.location.href = 'time.php?return=updated&val=' + msg;

// JavaScript/PHP executing the function printing the value of the URL,
// now with the text normally lost in space because of the reserved & character.

setTimeout("infoApp('updated','<?php echo $_GET['val'];?>');", 360);

How do I compile with -Xlint:unchecked?

For IntelliJ 13.1, go to File -> Settings -> Project Settings -> Compiler -> Java Compiler, and on the right-hand side, for Additional command line parameters enter "-Xlint:unchecked".

The difference between "require(x)" and "import x"

The major difference between require and import, is that require will automatically scan node_modules to find modules, but import, which comes from ES6, won't.

Most people use babel to compile import and export, which makes import act the same as require.

The future version of Node.js might support import itself (actually, the experimental version already does), and judging by Node.js' notes, import won't support node_modules, it base on ES6, and must specify the path of the module.

So I would suggest you not use import with babel, but this feature is not yet confirmed, it might support node_modules in the future, who would know?


For reference, below is an example of how babel can convert ES6's import syntax to CommonJS's require syntax.

Say the fileapp_es6.js contains this import:

import format from 'date-fns/format';

This is a directive to import the format function from the node package date-fns.

The related package.json file could contain something like this:

"scripts": {
    "start": "node app.js",
    "build-server-file": "babel app_es6.js --out-file app.js",
    "webpack": "webpack"
}

The related .babelrc file could be something like this:

{
    "presets": [
        [
            "env",
            {
                "targets":
                {
                    "node": "current"
                }
            }
        ]
    ]
}

This build-server-file script defined in the package.json file is a directive for babel to parse the app_es6.js file and output the file app.js.

After running the build-server-file script, if you open app.js and look for the date-fns import, you will see it has been converted into this:

var _format = require("date-fns/format");

var _format2 = _interopRequireDefault(_format);

Most of that file is gobbledygook to most humans, however computers understand it.


Also for reference, as an example of how a module can be created and imported into your project, if you install date-fns and then open node_modules/date-fns/get_year/index.js you can see it contains:

var parse = require('../parse/index.js')

function getYear (dirtyDate) {
  var date = parse(dirtyDate)
  var year = date.getFullYear()
  return year
}

module.exports = getYear

Using the babel process above, your app_es6.js file could then contain:

import getYear from 'date-fns/get_year';

// Which year is 2 July 2014?
var result = getYear(new Date(2014, 6, 2))
//=> 2014

And babel would convert the imports to:

var _get_year = require("date-fns/get_year");

var _get_year2 = _interopRequireDefault(_get_year);

And handle all references to the function accordingly.

Get ASCII value at input word

simply do

int a = ch

(also this has nothing to do with android)

accessing a variable from another class

I had the same problem. In order to modify variables from different classes, I made them extend the class they were to modify. I also made the super class's variables static so they can be changed by anything that inherits them. I also made them protected for more flexibility.

Source: Bad experiences. Good lessons.

What is the difference between background, backgroundTint, backgroundTintMode attributes in android layout xml?

I won't stress much on the difference as it is already covered, but notice the below:

  • android:backgroundTint android:backgroundTintMode are only available at API 21
  • If you have a widget that has a png/vector drawable background set by android:background, and you want to change its default color, then you can use android:backgroundTint to add a shade to it.

example

<Button
    android:layout_width="50dp"
    android:layout_height="wrap_content"
    android:background="@android:drawable/ic_dialog_email" />

enter image description here

<Button
    android:layout_width="50dp"
    android:layout_height="wrap_content"
    android:background="@android:drawable/ic_dialog_email"
    android:backgroundTint="@color/colorAccent" />

enter image description here

Another example

If you try to change the accent color of the FloatingActionButton using android:background you won't notice a change, that is because it's already utilizes app:srcCompat, so in order to do that you can use android:backgroundTint instead

Configuring ObjectMapper in Spring

In Spring Boot 2.2.x you need to configure it like this:

@Bean
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
    return builder.build()
}

Kotlin:

@Bean
fun objectMapper(builder: Jackson2ObjectMapperBuilder) = builder.build()

How do I pass along variables with XMLHTTPRequest

Following is correct way:

xmlhttp.open("GET","getuser.php?fname="+abc ,true);

Input type for HTML form for integer

Prior to HTML5, input type="text" simply means a field to insert free text, regardless of what you want it be. that is the job of validations you would have to do in order to guarantee the user enters a valid number

If you're using HTML5, you can use the new input types, one of which is number that automatically validates the text input, and forces it to be a number

keep in mind though, that if you're building a server side app (php for example) you will still have to validate the input on that side (make sure it is really a number) since it's pretty easy to hack the html and change the input type, removing the browser validation

How can I give access to a private GitHub repository?

Struggled to find this as well.

Heres a screenshot of how to do it:

enter image description here

Passing variables in remote ssh command

If you use

ssh [email protected] "~/tools/run_pvt.pl $BUILD_NUMBER"

instead of

ssh [email protected] '~/tools/run_pvt.pl $BUILD_NUMBER'

your shell will interpolate the $BUILD_NUMBER before sending the command string to the remote host.

How can I create a correlation matrix in R?

There are other ways to achieve this here: (Plot correlation matrix into a graph), but I like your version with the correlations in the boxes. Is there a way to add the variable names to the x and y column instead of just those index numbers? For me, that would make this a perfect solution. Thanks!

edit: I was trying to comment on the post by [Marc in the box], but I clearly don't know what I'm doing. However, I did manage to answer this question for myself.

if d is the matrix (or the original data frame) and the column names are what you want, then the following works:

axis(1, 1:dim(d)[2], colnames(d), las=2)
axis(2, 1:dim(d)[2], colnames(d), las=2)

las=0 would flip the names back to their normal position, mine were long, so I used las=2 to make them perpendicular to the axis.

edit2: to suppress the image() function printing numbers on the grid (otherwise they overlap your variable labels), add xaxt='n', e.g.:

image(x=seq(dim(x)[2]), y=seq(dim(y)[2]), z=COR, col=rev(heat.colors(20)), xlab="x column", ylab="y column", xaxt='n')

how to get value of selected item in autocomplete

I wanted something pretty close to this - the moment a user picks an item, even by just hitting the arrow keys to one (focus), I want that data item attached to the tag in question. When they type again without picking another item, I want that data cleared.

(function() {
    var lastText = '';

    $('#MyTextBox'), {
        source: MyData
    })
    .on('autocompleteselect autocompletefocus', function(ev, ui) {
        lastText = ui.item.label;
        jqTag.data('autocomplete-item', ui.item);
    })
    .keyup(function(ev) {
        if (lastText != jqTag.val()) {
            // Clear when they stop typing
            jqTag.data('autocomplete-item', null);

            // Pass the event on as autocompleteclear so callers can listen for select/clear
            var clearEv = $.extend({}, ev, { type: 'autocompleteclear' });
            return jqTag.trigger(clearEv);
    });
})();

With this in place, 'autocompleteselect' and 'autocompletefocus' still fire right when you expect, but the full data item that was selected is always available right on the tag as a result. 'autocompleteclear' now fires when that selection is cleared, generally by typing something else.

How to remove a build from itunes connect?

Dang this is hard. Here is what I did to reject/delete/replace my ios build before it was released. The app was approved how ever I found found a bug I wanted to fix before releasing

  1. I set release to "manual" and saved
  2. I tried to create and app release
  3. got an error message something like "you can only have one release at a time"
  4. where the save button was there was not an option to cancel release
  5. the version of the app is not marked "developer rejected" with a red dot

To replace the bad build I did the following

  1. if you click on the "+ version or platform" to create a new version you will not be be able to create a new iOS version
  2. you need to upload a new build
  3. in your rejected app, select the new build
  4. save
  5. submit for review

How can I run a directive after the dom has finished rendering?

I had the a similar problem and want to share my solution here.

I have the following HTML:

<div data-my-directive>
  <div id='sub' ng-include='includedFile.htm'></div>
</div>

Problem: In the link-function of directive of the parent div I wanted to jquery'ing the child div#sub. But it just gave me an empty object because ng-include hadn't finished when link function of directive ran. So first I made a dirty workaround with $timeout, which worked but the delay-parameter depended on client speed (nobody likes that).

Works but dirty:

app.directive('myDirective', [function () {
    var directive = {};
    directive.link = function (scope, element, attrs) {
        $timeout(function() {
            //very dirty cause of client-depending varying delay time 
            $('#sub').css(/*whatever*/);
        }, 350);
    };
    return directive;
}]);

Here's the clean solution:

app.directive('myDirective', [function () {
    var directive = {};
    directive.link = function (scope, element, attrs) {
        scope.$on('$includeContentLoaded', function() {
            //just happens in the moment when ng-included finished
            $('#sub').css(/*whatever*/);
        };
    };
    return directive;
}]);

Maybe it helps somebody.

Git: add vs push vs commit

I was confused about what 'add' really does. I just read a very enlightening paragraph from the book Git Pro that I'd like to add here, because it clarifies things

“It turns out that Git stages a file exactly as it is when you run the git add command. If you commit now, the version of benchmarks.rb as it was when you last ran the git add command is how it will go into the commit, not the version of the file as it looks in your working directory when you run git commit. If you modify a file after you run git add, you have to run git add again to stage the latest version of the file:”

Excerpt From: Chacon, Scott. “Pro Git.” Springer, 2009-08-19T00:00:00+00:00. iBooks. This material may be protected by copyright.