Programs & Examples On #Cwrsync

Why is this rsync connection unexpectedly closed on Windows?

I had this error coming up between 2 Linux boxes. Easily solved by installing RSYNC on the remote box as well as the local one.

Moving items around in an ArrayList

A simple swap is far better for "moving something up" in an ArrayList:

if(i > 0) {
    Item toMove = arrayList.get(i);
    arrayList.set(i, arrayList.get(i-1));
    arrayList.set(i-1, toMove);
}

Because an ArrayList uses an array, if you remove an item from an ArrayList, it has to "shift" all the elements after that item upward to fill in the gap in the array. If you insert an item, it has to shift all the elements after that item to make room to insert it. These shifts can get very expensive if your array is very big. Since you know that you want to end up with the same number of elements in the list, doing a swap like this allows you to "move" an element to another location in the list very efficiently.

As Chris Buckler and Michal Kreuzman point out, there is even a handy method in the Collections class to reduce these three lines of code to one:

Collections.swap(arrayList, i, i-1);

How to copy to clipboard in Vim?

I had issue because my vim was not supporting clipboard:

vim --version | grep clip
-clipboard       +insert_expand   +path_extra      +user_commands
+emacs_tags      -mouseshape      +startuptime     -xterm_clipboard

I installed vim-gnome (which support clipboard) and then checked again:

vim --version | grep clipboard
+clipboard       +insert_expand   +path_extra      +user_commands
+emacs_tags      +mouseshape      +startuptime     +xterm_clipboard

Now I am able to copy and paste using "+y and "+p respectively.

What is the difference between 'java', 'javaw', and 'javaws'?

See Java tools documentation for:

  1. The java tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method.
  2. The javaw command is identical to java, except that with javaw there is no associated console window. Use javaw when you don't want a command prompt window to appear.

The javaws command launches Java Web Start, which is the reference implementation of the Java Network Launching Protocol (JNLP). Java Web Start launches Java applications/applets hosted on a network.

If a JNLP file is specified, javaws will launch the Java application/applet specified in the JNLP file.

The javaws launcher has a set of options that are supported in the current release. However, the options may be removed in a future release.

See also JDK 9 Release Notes Deprecated APIs, Features, and Options:

Java Deployment Technologies are deprecated and will be removed in a future release
Java Applet and WebStart functionality, including the Applet API, the Java plug-in, the Java Applet Viewer, JNLP and Java Web Start, including the javaws tool, are all deprecated in JDK 9 and will be removed in a future release.

How to reset a timer in C#?

For System.Timers.Timer, according to MSDN documentation, http://msdn.microsoft.com/en-us/library/system.timers.timer.enabled.aspx:

If the interval is set after the Timer has started, the count is reset. For example, if you set the interval to 5 seconds and then set the Enabled property to true, the count starts at the time Enabled is set. If you reset the interval to 10 seconds when count is 3 seconds, the Elapsed event is raised for the first time 13 seconds after Enabled was set to true.

So,

    const double TIMEOUT = 5000; // milliseconds

    aTimer = new System.Timers.Timer(TIMEOUT);
    aTimer.Start();     // timer start running

    :
    :

    aTimer.Interval = TIMEOUT;  // restart the timer

How to resolve "gpg: command not found" error during RVM installation?

GnuPG (with binary name gpg) is an application used for public key encryption using the OpenPGP protocol, but also verification of signatures (cryptographic signatures, that also can validate the publisher if used correctly). To some extend, you could say it's for OpenPGP what OpenSSL is for X.509 and TLS.

Unlike most Linux distributions (which make heavy use of GnuPG for ensuring untampered software within their package repositories), Mac OS X does not bring GnuPG with the operating system, so you have to install it on your own.

Possible sources are:

  • Package manager Homebrew: brew install gnupg gnupg2
  • Package manager MacPorts: sudo port install gnupg gnupg2
  • Install from GPGTools, which also brings GUI applications and integration in Apple Mail

How to get htaccess to work on MAMP

If you have MAMP PRO you can set up a host like mysite.local, then add some options from the 'Advanced' panel in the main window. Just switch on the options 'Indexes' and 'MultiViews'. 'Includes' and 'FollowSymLinks' should already be checked.

Rollback a Git merge

If you merged the branch, then reverted the merge using a pull request and merged that pull request to revert.

The easiest way I felt was to:

  1. Take out a new branch from develop/master (where you merged)
  2. Revert the "revert" using git revert -m 1 xxxxxx (if the revert was merged using a branch) or using git revert xxxxxx if it was a simple revert
  3. The new branch should now have the changes you want to merge again.
  4. Make changes or merge this branch to develop/master

Usage of MySQL's "IF EXISTS"

You cannot use IF control block OUTSIDE of functions. So that affects both of your queries.

Turn the EXISTS clause into a subquery instead within an IF function

SELECT IF( EXISTS(
             SELECT *
             FROM gdata_calendars
             WHERE `group` =  ? AND id = ?), 1, 0)

In fact, booleans are returned as 1 or 0

SELECT EXISTS(
         SELECT *
         FROM gdata_calendars
         WHERE `group` =  ? AND id = ?)

How to get the current working directory using python 3?

Using pathlib you can get the folder in which the current file is located. __file__ is the pathname of the file from which the module was loaded. Ref: docs

import pathlib

current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)

Doc ref: link

Printing out a linked list using toString

When the JVM tries to run your application, it calls your main method statically; something like this:

LinkedList.main();

That means there is no instance of your LinkedList class. In order to call your toString() method, you can create a new instance of your LinkedList class.

So the body of your main method should be like this:

public static void main(String[] args){
    // creating an instance of LinkedList class
    LinkedList ll = new LinkedList();

    // adding some data to the list
    ll.insertFront(1);
    ll.insertFront(2);
    ll.insertFront(3);
    ll.insertBack(4);

    System.out.println(ll.toString());
}

Access the css ":after" selector with jQuery

If you use jQuery built-in after() with empty value it will create a dynamic object that will match your :after CSS selector.

$('.active').after().click(function () {
    alert('clickable!');
});

See the jQuery documentation.

How can I concatenate a string within a loop in JSTL/JSP?

Perhaps this will work?

<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
  <c:set var="myVar" value="${stat.first ? '' : myVar} ${currentItem}" />
</c:forEach>

Remove all occurrences of a value from a list?

Functional approach:

Python 3.x

>>> x = [1,2,3,2,2,2,3,4]
>>> list(filter((2).__ne__, x))
[1, 3, 3, 4]

or

>>> x = [1,2,3,2,2,2,3,4]
>>> list(filter(lambda a: a != 2, x))
[1, 3, 3, 4]

Python 2.x

>>> x = [1,2,3,2,2,2,3,4]
>>> filter(lambda a: a != 2, x)
[1, 3, 3, 4]

How to check string length with JavaScript

That's the function I wrote to get string in Unicode characters:

function nbUnicodeLength(string){
    var stringIndex = 0;
    var unicodeIndex = 0;
    var length = string.length;
    var second;
    var first;
    while (stringIndex < length) {

        first = string.charCodeAt(stringIndex);  // returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.
        if (first >= 0xD800 && first <= 0xDBFF && string.length > stringIndex + 1) {
            second = string.charCodeAt(stringIndex + 1);
            if (second >= 0xDC00 && second <= 0xDFFF) {
                stringIndex += 2;
            } else {
                stringIndex += 1;
            }
        } else {
            stringIndex += 1;
        }

        unicodeIndex += 1;
    }
    return unicodeIndex;
}

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

How to create custom exceptions in Java?

For a checked exception:

public class MyCustomException extends Exception { }

Technically, anything that extends Throwable can be an thrown, but exceptions are generally extensions of the Exception class so that they're checked exceptions (except RuntimeException or classes based on it, which are not checked), as opposed to the other common type of throwable, Errors which usually are not something designed to be gracefully handled beyond the JVM internals.

You can also make exceptions non-public, but then you can only use them in the package that defines them, as opposed to across packages.

As far as throwing/catching custom exceptions, it works just like the built-in ones - throw via

throw new MyCustomException()

and catch via

catch (MyCustomException e) { }

XAMPP - Apache could not start - Attempting to start Apache service

For me it wasn't a port or service issue; I had to re-run the XAMPP setup script. Although this didn't directly fix the issue for me, the script was much more verbose than the XAMPP log, pointing me in the right direction to actually solve the problem.

From the XAMPP GUI, click on Shell, type set, press Tab to autocomplete to the setup_xampp.bat file, and then press Enter to run it.

In my case I got the following output:

[ERROR]: Test php.exe failed !!!
[ERROR]: Perhaps the Microsoft C++ 2008 runtime package is not installed.
[ERROR]: Please try to install the MS VC++ 2008 Redistributable Package from the Mircrosoft page first
[ERROR]: http://www.microsoft.com/en-us/download/details.aspx?id=5582

This particular error is misleading. Although it specifies the Visual C++ 2008 Redistributable Package, PHP 7.4.x requires the Visual C++ 2019 Redistributable Package.

After installing that and following the prompt to restart, sure enough I'm now able to start Apache as normal.

How to link home brew python version and set it as default

If you used

brew install python

before 'unlink' you got

brew info python
/usr/local/Cellar/python/2.7.11

python -V
Python 2.7.10

so do

brew unlink python && brew link python

and open a new terminal shell

python -V
Python 2.7.11

Abstract class in Java

Solution - base class (abstract)

public abstract class Place {

String Name;
String Postcode;
String County;
String Area;

Place () {

        }

public static Place make(String Incoming) {
        if (Incoming.length() < 61) return (null);

        String Name = (Incoming.substring(4,26)).trim();
        String County = (Incoming.substring(27,48)).trim();
        String Postcode = (Incoming.substring(48,61)).trim();
        String Area = (Incoming.substring(61)).trim();

        Place created;
        if (Name.equalsIgnoreCase(Area)) {
                created = new Area(Area,County,Postcode);
        } else {
                created = new District(Name,County,Postcode,Area);
        }
        return (created);
        }

public String getName() {
        return (Name);
        }

public String getPostcode() {
        return (Postcode);
        }

public String getCounty() {
        return (County);
        }

public abstract String getArea();

}

How to print a string in C++

You need to access the underlying buffer:

printf("%s\n", someString.c_str());

Or better use cout << someString << endl; (you need to #include <iostream> to use cout)

Additionally you might want to import the std namespace using using namespace std; or prefix both string and cout with std::.

How to get a substring of text?

Since you tagged it Rails, you can use truncate:

http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-truncate

Example:

 truncate(@text, :length => 17)

Excerpt is nice to know too, it lets you display an excerpt of a text Like so:

 excerpt('This is an example', 'an', :radius => 5)
 # => ...s is an exam...

http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-excerpt

Detect if user is scrolling

If you want detect when user scroll over certain div, you can do something like this:

window.onscroll = function() {
    var distanceScrolled = document.documentElement.scrollTop;
    console.log('Scrolled: ' + distanceScrolled);
}

For example, if your div appear after scroll until the position 112:

window.onscroll = function() {
    var distanceScrolled = document.documentElement.scrollTop;
    if (distanceScrolled > 112) {
      do something...
    }
}

But as you can see you don't need a div, just the offset distance you want something to happen.

How to get param from url in angular 4?

Routes

export const MyRoutes: Routes = [
    { path: '/items/:id', component: MyComponent }
]

Component

import { ActivatedRoute } from '@angular/router';
public id: string;

constructor(private route: ActivatedRoute) {}

ngOnInit() {
   this.id = this.route.snapshot.paramMap.get('id');
}

Excel data validation with suggestions/autocomplete

If you don't want to go down the VBA path, there is this trick from a previous question.

Excel 2010: how to use autocomplete in validation list

It does add some annoying bulk to the top of your sheets, and potential maintenance (should you need more options, adding names of people from a staff list, new projects etc.) but works all the same.

How to do a HTTP HEAD request from the windows command line?

There is a Win32 port of wget that works decently.

PowerShell's Invoke-WebRequest -Method Head would work as well.

Find and replace strings in vim on multiple lines

VI search and replace command examples

Let us say you would like to find a word called “foo” and replace with “bar”.

First hit [Esc] key

Type : (colon) followed by %s/foo/bar/ and hit [Enter] key

:%s/foo/bar/

JavaScript adding decimal numbers issue

Testing this Javascript:

var arr = [1234563995.721, 12345691212.718, 1234568421.5891, 12345677093.49284];

var sum = 0;
for( var i = 0; i < arr.length; i++ ) {
    sum += arr[i];
}

alert( "fMath(sum) = " + Math.round( sum * 1e12 ) / 1e12 );
alert( "fFixed(sum) = " + sum.toFixed( 5 ) );

Conclusion

Dont use Math.round( (## + ## + ... + ##) * 1e12) / 1e12

Instead, use ( ## + ## + ... + ##).toFixed(5) )

In IE 9, toFixed works very well.

Spark specify multiple column conditions for dataframe join

In Pyspark you can simply specify each condition separately:

val Lead_all = Leads.join(Utm_Master,  
    (Leaddetails.LeadSource == Utm_Master.LeadSource) &
    (Leaddetails.Utm_Source == Utm_Master.Utm_Source) &
    (Leaddetails.Utm_Medium == Utm_Master.Utm_Medium) &
    (Leaddetails.Utm_Campaign == Utm_Master.Utm_Campaign))

Just be sure to use operators and parenthesis correctly.

Two HTML tables side by side, centered on the page

Unfortunately, all of these solutions rely on specifying a fixed width. Since the tables are generated dynamically (statistical results pulled from a database), the width can not be known in advance.

The desired result can be achieved by wrapping the two tables within another table:

<table align="center"><tr><td>
//code for table on the left
</td><td>
//code for table on the right
</td></tr></table>

and the result is a perfectly centered pair of tables that responds fluidly to arbitrary widths and page (re)sizes (and the align="center" table attribute could be hoisted out into an outer div with margin autos).

I conclude that there are some layouts that can only be achieved with tables.

ActionLink htmlAttributes

The problem is that your anonymous object property data-icon has an invalid name. C# properties cannot have dashes in their names. There are two ways you can get around that:

Use an underscore instead of dash (MVC will automatically replace the underscore with a dash in the emitted HTML):

@Html.ActionLink("Edit", "edit", "markets",
      new { id = 1 },
      new {@class="ui-btn-right", data_icon="gear"})

Use the overload that takes in a dictionary:

@Html.ActionLink("Edit", "edit", "markets",
      new { id = 1 },
      new Dictionary<string, object> { { "class", "ui-btn-right" }, { "data-icon", "gear" } });

Extension exists but uuid_generate_v4 fails

This worked for me.

create extension IF NOT EXISTS "uuid-ossp" schema pg_catalog version "1.1"; 

make sure the extension should by on pg_catalog and not in your schema...

Create a new txt file using VB.NET

You could just use this

FileOpen(1, "C:\my files\2010\SomeFileName.txt", OpenMode.Output)
FileClose(1)

This opens the file replaces whatever is in it and closes the file.

What's the difference between JPA and Hibernate?

JPA is a specification to standardize ORM-APIs. Hibernate is a vendor of a JPA implementation. So if you use JPA with hibernate, you can use the standard JPA API, hibernate will be under the hood, offering some more non standard functions. See http://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html_single/ and http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/

Convert a character digit to the corresponding integer in C

Subtract '0' like this:

int i = c - '0';

The C Standard guarantees each digit in the range '0'..'9' is one greater than its previous digit (in section 5.2.1/3 of the C99 draft). The same counts for C++.

Convert String to SecureString

no fancy linq, not adding all the chars by hand, just plain and simple:

var str = "foo";
var sc = new SecureString();
foreach(char c in str) sc.appendChar(c);

UICollectionView Self Sizing Cells with Auto Layout

For anyone who tried everything without luck, this is the only thing that got it working for me. For the multiline labels inside cell, try adding this magic line:

label.preferredMaxLayoutWidth = 200

More info: here

Cheers!

Upload folder with subfolders using S3 and the AWS console

You can upload files by dragging and dropping or by pointing and clicking. To upload folders, you must drag and drop them. Drag and drop functionality is supported only for the Chrome and Firefox browsers

Best Practices: working with long, multiline strings in PHP?

Adding \n and/or \r in the middle of the string, and having a very long line of code, like in second example, doesn't feel right : when you read the code, you don't see the result, and you have to scroll.

In this kind of situations, I always use Heredoc (Or Nowdoc, if using PHP >= 5.3) : easy to write, easy to read, no need for super-long lines, ...

For instance :

$var = 'World';
$str = <<<MARKER
this is a very
long string that
doesn't require
horizontal scrolling, 
and interpolates variables :
Hello, $var!
MARKER;

Just one thing : the end marker (and the ';' after it) must be the only thing on its line : no space/tab before or after !

window.location.href not working

if anyone faced problem even after using return false; . then use the below.

setTimeout(function(){document.location.href = "index.php"},500);

sed fails with "unknown option to `s'" error

The problem is with slashes: your variable contains them and the final command will be something like sed "s/string/path/to/something/g", containing way too many slashes.

Since sed can take any char as delimiter (without having to declare the new delimiter), you can try using another one that doesn't appear in your replacement string:

replacement="/my/path"
sed --expression "s@pattern@$replacement@"

Note that this is not bullet proof: if the replacement string later contains @ it will break for the same reason, and any backslash sequences like \1 will still be interpreted according to sed rules. Using | as a delimiter is also a nice option as it is similar in readability to /.

Why can't I push to this bare repository?

Yes, the problem is that there are no commits in "bare". This is a problem with the first commit only, if you create the repos in the order (bare,alice). Try doing:

git push --set-upstream origin master

This would only be required the first time. Afterwards it should work normally.

As Chris Johnsen pointed out, you would not have this problem if your push.default was customized. I like upstream/tracking.

How to detect Esc Key Press in React and how to handle it

If you're looking for a document-level key event handling, then binding it during componentDidMount is the best way (as shown by Brad Colthurst's codepen example):

class ActionPanel extends React.Component {
  constructor(props){
    super(props);
    this.escFunction = this.escFunction.bind(this);
  }
  escFunction(event){
    if(event.keyCode === 27) {
      //Do whatever when esc is pressed
    }
  }
  componentDidMount(){
    document.addEventListener("keydown", this.escFunction, false);
  }
  componentWillUnmount(){
    document.removeEventListener("keydown", this.escFunction, false);
  }
  render(){
    return (   
      <input/>
    )
  }
}

Note that you should make sure to remove the key event listener on unmount to prevent potential errors and memory leaks.

EDIT: If you are using hooks, you can use this useEffect structure to produce a similar effect:

const ActionPanel = (props) => {
  const escFunction = useCallback((event) => {
    if(event.keyCode === 27) {
      //Do whatever when esc is pressed
    }
  }, []);

  useEffect(() => {
    document.addEventListener("keydown", escFunction, false);

    return () => {
      document.removeEventListener("keydown", escFunction, false);
    };
  }, []);

  return (   
    <input />
  )
};

Console.WriteLine and generic List

public static void WriteLine(this List<int> theList)
{
  foreach (int i in list)
  {
    Console.Write("{0}\t", t.ToString());
  }
  Console.WriteLine();
}

Then, later...

list.WriteLine();

How do I write a Python dictionary to a csv file?

Your code was very close to working.

Try using a regular csv.writer rather than a DictWriter. The latter is mainly used for writing a list of dictionaries.

Here's some code that writes each key/value pair on a separate row:

import csv

somedict = dict(raymond='red', rachel='blue', matthew='green')
with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)
    w.writerows(somedict.items())

If instead you want all the keys on one row and all the values on the next, that is also easy:

with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)
    w.writerow(somedict.keys())
    w.writerow(somedict.values())

Pro tip: When developing code like this, set the writer to w = csv.writer(sys.stderr) so you can more easily see what is being generated. When the logic is perfected, switch back to w = csv.writer(f).

Giving multiple conditions in for loop in Java

If you prefer a code with a pretty look, you can do a break:

for(int j = 0; ; j++){
    if(j < 6
    && j < ( (int) abc[j] & 0xff)){
        break;
    }

    // Put your code here
}

What is the difference between Nexus and Maven?

Sonatype Nexus and Apache Maven are two pieces of software that often work together but they do very different parts of the job. Nexus provides a repository while Maven uses a repository to build software.

Here's a quote from "What is Nexus?":

Nexus manages software "artifacts" required for development. If you develop software, your builds can download dependencies from Nexus and can publish artifacts to Nexus creating a new way to share artifacts within an organization. While Central repository has always served as a great convenience for developers you shouldn't be hitting it directly. You should be proxying Central with Nexus and maintaining your own repositories to ensure stability within your organization. With Nexus you can completely control access to, and deployment of, every artifact in your organization from a single location.

And here is a quote from "Maven and Nexus Pro, Made for Each Other" explaining how Maven uses repositories:

Maven leverages the concept of a repository by retrieving the artifacts necessary to build an application and deploying the result of the build process into a repository. Maven uses the concept of structured repositories so components can be retrieved to support the build. These components or dependencies include libraries, frameworks, containers, etc. Maven can identify components in repositories, understand their dependencies, retrieve all that are needed for a successful build, and deploy its output back to repositories when the build is complete.

So, when you want to use both you will have a repository managed by Nexus and Maven will access this repository.

Html: Difference between cell spacing and cell padding

CellSpacing as the name suggests it is the Space between the Adjacent cells and CellPadding on the other hand means the padding around the cell content.

How can I simulate a print statement in MySQL?

This is an old post, but thanks to this post I have found this:

\! echo 'some text';

Tested with MySQL 8 and working correctly. Cool right? :)

Extracting substrings in Go

To avoid a panic on a zero length input, wrap the truncate operation in an if

input, _ := src.ReadString('\n')
var inputFmt string
if len(input) > 0 {
    inputFmt = input[:len(input)-1]
}
// Do something with inputFmt

Multi-line bash commands in makefile

What's wrong with just invoking the commands?

foo:
       echo line1
       echo line2
       ....

And for your second question, you need to escape the $ by using $$ instead, i.e. bash -c '... echo $$a ...'.

EDIT: Your example could be rewritten to a single line script like this:

gcc $(for i in `find`; do echo $i; done)

What is the purpose of a plus symbol before a variable?

It is a unary "+" operator which yields a numeric expression. It would be the same as d*1, I believe.

Display current time in 12 hour format with AM/PM

tl;dr

Let the modern java.time classes of JSR 310 automatically generate localized text, rather than hard-coding 12-hour clock and AM/PM.

LocalTime                                     // Represent a time-of-day, without date, without time zone or offset-from-UTC.
.now(                                         // Capture the current time-of-day as seen in a particular time zone.
    ZoneId.of( "Africa/Casablanca" )          
)                                             // Returns a `LocalTime` object.
.format(                                      // Generate text representing the value in our `LocalTime` object.
    DateTimeFormatter                         // Class responsible for generating text representing the value of a java.time object.
    .ofLocalizedTime(                         // Automatically localize the text being generated.
        FormatStyle.SHORT                     // Specify how long or abbreviated the generated text should be.
    )                                         // Returns a `DateTimeFormatter` object.
    .withLocale( Locale.US )                  // Specifies a particular locale for the `DateTimeFormatter` rather than rely on the JVM’s current default locale. Returns another separate `DateTimeFormatter` object rather than altering the first, per immutable objects pattern.
)                                             // Returns a `String` object.

10:31 AM

Automatically localize

Rather than insisting on 12-hour clock with AM/PM, you may want to let java.time automatically localize for you. Call DateTimeFormatter.ofLocalizedTime.

To localize, specify:

  • FormatStyle to determine how long or abbreviated should the string be.
  • Locale to determine:
    • The human language for translation of name of day, name of month, and such.
    • The cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.

Here we get the current time-of-day as seen in a particular time zone. Then we generate text to represent that time. We localize to French language in Canada culture, then English language in US culture.

ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
LocalTime localTime = LocalTime.now( z ) ;

// Québec
Locale locale_fr_CA = Locale.CANADA_FRENCH ;  // Or `Locale.US`, and so on.
DateTimeFormatter formatterQuébec = DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT ).withLocale( locale_fr_CA ) ;
String outputQuébec = localTime.format( formatterQuébec ) ;

System.out.println( outputQuébec ) ;

// US
Locale locale_en_US = Locale.US ;  
DateTimeFormatter formatterUS = DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT ).withLocale( locale_en_US ) ;
String outputUS = localTime.format( formatterUS ) ;

System.out.println( outputUS ) ;

See this code run live at IdeOne.com.

10 h 31

10:31 AM

How to easily get network path to the file you are working on?

I found a way to display the Document Location module in Office 2010.

File -> Options -> Quick Access Toolbar

From the Choose commands list select All Commands find "Document Location" press the "Add>>" button.

press OK.

Viola, the file path is at the top of your 2010 office document.

How to verify static void method has been called with power mockito

If you are mocking the behavior (with something like doNothing()) there should really be no need to call to verify*(). That said, here's my stab at re-writing your test method:

@PrepareForTest({InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest { //Note the renaming of the test class.
   public void testProcessOrder() {
        //Variables
        InternalService is = new InternalService();
        Order order = mock(Order.class);

        //Mock Behavior
        when(order.isSuccessful()).thenReturn(true);
        mockStatic(Internalutils.class);
        doNothing().when(InternalUtils.class); //This is the preferred way
                                               //to mock static void methods.
        InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());

        //Execute
        is.processOrder(order);            

        //Verify
        verifyStatic(InternalUtils.class); //Similar to how you mock static methods
                                           //this is how you verify them.
        InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());
   }
}

I grouped into four sections to better highlight what is going on:

1. Variables

I choose to declare any instance variables / method arguments / mock collaborators here. If it is something used in multiple tests, consider making it an instance variable of the test class.

2. Mock Behavior

This is where you define the behavior of all of your mocks. You're setting up return values and expectations here, prior to executing the code under test. Generally speaking, if you set the mock behavior here you wouldn't need to verify the behavior later.

3. Execute

Nothing fancy here; this just kicks off the code being tested. I like to give it its own section to call attention to it.

4. Verify

This is when you call any method starting with verify or assert. After the test is over, you check that the things you wanted to have happen actually did happen. That is the biggest mistake I see with your test method; you attempted to verify the method call before it was ever given a chance to run. Second to that is you never specified which static method you wanted to verify.

Additional Notes

This is mostly personal preference on my part. There is a certain order you need to do things in but within each grouping there is a little wiggle room. This helps me quickly separate out what is happening where.

I also highly recommend going through the examples at the following sites as they are very robust and can help with the majority of the cases you'll need:

Calling another different view from the controller using ASP.NET MVC 4

Also, you can just set the ViewName:

return View("ViewName");

Full controller example:

public ActionResult SomeAction() {
    if (condition)
    {
        return View("CustomView");
    }else{
        return View();
    }
}

This works on MVC 5.

Convert ASCII TO UTF-8 Encoding

"ASCII is a subset of UTF-8, so..." - so UTF-8 is a set? :)

In other words: any string build with code points from x00 to x7F has indistinguishable representations (byte sequences) in ASCII and UTF-8. Converting such string is pointless.

Markdown and including multiple files

Another HTML-based, client-side solution using markdown-it and jQuery. Below is a small HTML wrapper as a master document, that supports unlimited includes of markdown files, but not nested includes. Explanation is provided in the JS comments. Error handling is omitted.

<script src="/markdown-it.min.js"></script>
<script src="/jquery-3.5.1.min.js"></script>

<script> 
  $(function() {
    var mdit = window.markdownit();
    mdit.options.html=true;
    // Process all div elements of class include.  Follow up with custom callback
    $('div.include').each( function() {
      var inc = $(this);
      // Use contents between div tag as the file to be included from server
      var filename = inc.html();
      // Unable to intercept load() contents.  post-process markdown rendering with callback
      inc.load(filename, function () {
        inc.html( mdit.render(this.innerHTML) );
      });
  });
})
</script>
</head>

<body>
<h1>Master Document </h1>

<h1>Section 1</h1>
<div class="include">sec_1.md</div>
<hr/>
<h1>Section 2</h1>
<div class="include">sec_2.md</div>

Installation error: INSTALL_FAILED_OLDER_SDK

Ionic Android emulator error INSTALL_FAILED_OLDER_SDK

So, basically it means that the installation has failed due to having an older SDK version than the targetSdkVersion specified in your app (it's a Gradle issue). Just edit the AndroidManifest.xml file and add the following code:

_x000D_
_x000D_
<uses-sdk android:minSdkVersion="19" android:targetSdkVersion="14"/>
_x000D_
_x000D_
_x000D_

After days looking for the solution, that's it.

Works fine for me!

Change the background color in a twitter bootstrap modal?

For Bootstrap 4 you may have to use .modal-backdrop.show and play around with !important flag on both background-color and opacity.

E.g.

.modal-backdrop.show {
   background-color: #f00;
   opacity: 0.75;
}

How can I open a popup window with a fixed size using the HREF tag?

I can't comment on Esben Skov Pedersen's answer directly, but using the following notation for links:

<a href="javascript:window.open('http://www.websiteofyourchoice.com');">Click here</a>

In Internet Explorer, the new browser window appears, but the current window navigates to a page which says "[Object]". To avoid this, simple put a "void(0)" behind the JavaScript function.

Source: https://support.microsoft.com/en-us/kb/257321

Properly escape a double quote in CSV

If a value contains a comma, a newline character or a double quote, then the string must be enclosed in double quotes. E.g: "Newline char in this field \n".

You can use below online tool to escape "" and , operators. https://www.freeformatter.com/csv-escape.html#ad-output

MySQL Query - Records between Today and Last 30 Days

For the current date activity and complete activity for previous 30 days use this, since the SYSDATE is variable in a day the previous 30th day will not have the whole data for that day.

SELECT  DATE_FORMAT(create_date, '%m/%d/%Y')
FROM mytable
WHERE create_date BETWEEN CURDATE() - INTERVAL 30 DAY AND SYSDATE()

How to parse a string in JavaScript?

as amber and sinan have noted above, the javascritp '.split' method will work just fine. Just pass it the string separator(-) and the string that you intend to split('123-abc-itchy-knee') and it will do the rest.

    var coolVar = '123-abc-itchy-knee';
    var coolVarParts = coolVar.split('-'); // this is an array containing the items

    var1=coolVarParts[0]; //this will retrieve 123

To access each item from the array just use the respective index(indices start at zero).

Python 3 sort a dict by its values

itemgetter (see other answers) is (as I know) more efficient for large dictionaries but for the common case, I believe that d.get wins. And it does not require an extra import.

>>> d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
>>> for k in sorted(d, key=d.get, reverse=True):
...     k, d[k]
...
('bb', 4)
('aa', 3)
('cc', 2)
('dd', 1)

Note that alternatively you can set d.__getitem__ as key function which may provide a small performance boost over d.get.

How to get main div container to align to centre?

The basic principle of centering a page is to have a body CSS and main_container CSS. It should look something like this:

body {
     margin: 0;
     padding: 0;
     text-align: center;
}
#main_container {
     margin: 0 auto;
     text-align: left;
}

How do I compile with -Xlint:unchecked?

A cleaner way to specify the Gradle compiler arguments follow:

compileJava.options.compilerArgs = ['-Xlint:unchecked','-Xlint:deprecation']

No module named pkg_resources

sudo apt-get install --reinstall python-pkg-resources

fixed it for me in Debian. Seems like uninstalling some .deb packages (twisted set in my case) has broken the path python uses to find packages

Pandas DataFrame concat vs append

So what are you doing is with append and concat is almost equivalent. The difference is the empty DataFrame. For some reason this causes a big slowdown, not sure exactly why, will have to look at some point. Below is a recreation of basically what you did.

I almost always use concat (though in this case they are equivalent, except for the empty frame); if you don't use the empty frame they will be the same speed.

In [17]: df1 = pd.DataFrame(dict(A = range(10000)),index=pd.date_range('20130101',periods=10000,freq='s'))

In [18]: df1
Out[18]: 
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 10000 entries, 2013-01-01 00:00:00 to 2013-01-01 02:46:39
Freq: S
Data columns (total 1 columns):
A    10000  non-null values
dtypes: int64(1)

In [19]: df4 = pd.DataFrame()

The concat

In [20]: %timeit pd.concat([df1,df2,df3])
1000 loops, best of 3: 270 us per loop

This is equavalent of your append

In [21]: %timeit pd.concat([df4,df1,df2,df3])
10 loops, best of 

 3: 56.8 ms per loop

error: RPC failed; curl transfer closed with outstanding read data remaining

After few days, today I just resolved this problem. Generate ssh key, follow this article:

https://help.github.com/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent/

Declare it to

  1. Git provider (GitLab what I am using, GitHub).
  2. Add this to local identity.

Then clone by command:

git clone [email protected]:my_group/my_repository.git

And no error happen.

The above problem

error: RPC failed; curl 18 transfer closed with outstanding read data remaining

because have error when clone by HTTP protocol (curl command).

And, you should increment buffer size:

git config --global http.postBuffer 524288000

Web scraping with Python

Use urllib2 in combination with the brilliant BeautifulSoup library:

import urllib2
from BeautifulSoup import BeautifulSoup
# or if you're using BeautifulSoup4:
# from bs4 import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen('http://example.com').read())

for row in soup('table', {'class': 'spad'})[0].tbody('tr'):
    tds = row('td')
    print tds[0].string, tds[1].string
    # will print date and sunrise

Java8: HashMap<X, Y> to HashMap<X, Z> using Stream / Map-Reduce / Collector

A generic solution like so

public static <X, Y, Z> Map<X, Z> transform(Map<X, Y> input,
        Function<Y, Z> function) {
    return input
            .entrySet()
            .stream()
            .collect(
                    Collectors.toMap((entry) -> entry.getKey(),
                            (entry) -> function.apply(entry.getValue())));
}

Example

Map<String, String> input = new HashMap<String, String>();
input.put("string1", "42");
input.put("string2", "41");
Map<String, Integer> output = transform(input,
            (val) -> Integer.parseInt(val));

Remove a data connection from an Excel 2010 spreadsheet in compatibility mode

I had the same problem. Get the warning. Went to Data connections and deleted connection. Save, close reopen. Still get the warning. I use a xp/vista menu plugin for classic menus. I found under data, get external data, properties, uncheck the save query definition. Save close and reopen. That seemed to get rid of the warning. Just removing the connection does not work. You have to get rid of the query.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 23: ordinal not in range(128)

When you get a UnicodeEncodeError, it means that somewhere in your code you convert directly a byte string to a unicode one. By default in Python 2 it uses ascii encoding, and utf8 encoding in Python3 (both may fail because not every byte is valid in either encoding)

To avoid that, you must use explicit decoding.

If you may have 2 different encoding in your input file, one of them accepts any byte (say UTF8 and Latin1), you can try to first convert a string with first and use the second one if a UnicodeDecodeError occurs.

def robust_decode(bs):
    '''Takes a byte string as param and convert it into a unicode one.
First tries UTF8, and fallback to Latin1 if it fails'''
    cr = None
    try:
        cr = bs.decode('utf8')
    except UnicodeDecodeError:
        cr = bs.decode('latin1')
    return cr

If you do not know original encoding and do not care for non ascii character, you can set the optional errors parameter of the decode method to replace. Any offending byte will be replaced (from the standard library documentation):

Replace with a suitable replacement character; Python will use the official U+FFFD REPLACEMENT CHARACTER for the built-in Unicode codecs on decoding and ‘?’ on encoding.

bs.decode(errors='replace')

Changing the color of an hr element

As a general rule, you can’t just set the color of a horizontal line with CSS like you would anything else. First of all, Internet Explorer needs the color in your CSS to read like this:

“color: #123455”

But Opera and Mozilla needs the color in your CSS to read like this:

“background-color: #123455”

So, you will need to add both options to your CSS.

Next, you will need to give the horizontal line some dimensions or it will default to the standard height, width and color set by your browser. Here is a sample code of what your CSS should look like to get the blue horizontal line.

hr {
border: 0;
width: 100%;
color: #123455;
background-color: #123455;
height: 5px;
}

Or you could just add the style to your HTML page directly when you insert a horizontal line, like this:

<hr style="background:#123455" />

Hope this helps.

how to delete all cookies of my website in php

Use the function to clear cookies:

function clearCookies($clearSession = false)
{
    $past = time() - 3600;
    if ($clearSession === false)
        $sessionId = session_id();
    foreach ($_COOKIE as $key => $value)
    {
        if ($clearSession !== false || $value !== $sessionId)
            setcookie($key, $value, $past, '/');
    }
}

If you pass true then it clears session data, otherwise session data is preserved.

Assign a login to a user created without login (SQL Server)

Through trial and error, it seems if the user was originally created "without login" then this query

select * from sys.database_principals

will show authentication_type = 0 (NONE).

Apparently these users cannot be re-linked to any login (pre-existing or new, SQL or Windows) since this command:

alter user [TempUser] with login [TempLogin]

responds with the Remap Error "Msg 33016" shown in the question.

Also these users do not show up in classic (deprecating) SP report:

exec sp_change_users_login 'Report'

If anyone knows a way around this or how to change authentication_type, please comment.

PHP Fatal error: Call to undefined function json_decode()

CENTOS

Scene

I installed PHP in Centos Docker, this is my DockerFile:

FROM centos:7.6.1810

LABEL maintainer="[email protected]"

RUN yum install httpd-2.4.6-88.el7.centos -y
RUN rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
RUN rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
RUN yum install php72w -y
ENTRYPOINT ["/usr/sbin/httpd", "-D", "FOREGROUND"]

The app returned the same error with json_decode and json_encode

Resolution

Install PHP Common that has json_encode and json_decode

yum install -y php72w-common-7.2.14-1.w7.x86_64

How to find the resolution?

I have another Docker File what build the container for the API and it has the order to install php-mysql client:

yum install php72w-mysql.x86_64 -y

If i use these image to mount the app, the json_encode and json_decode works!! Ok..... What dependencies does this have?

[root@c023b46b720c etc]# yum install php72w-mysql.x86_64
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
 * base: mirror.gtdinternet.com
 * epel: mirror.globo.com
 * extras: linorg.usp.br
 * updates: mirror.gtdinternet.com
 * webtatic: us-east.repo.webtatic.com
Resolving Dependencies
--> Running transaction check
---> Package php72w-mysql.x86_64 0:7.2.14-1.w7 will be installed
--> Processing Dependency: php72w-pdo(x86-64) for package: php72w-mysql-7.2.14-1.w7.x86_64
--> Processing Dependency: libmysqlclient.so.18(libmysqlclient_18)(64bit) for package: php72w-mysql-7.2.14-1.w7.x86_64
--> Processing Dependency: libmysqlclient.so.18()(64bit) for package: php72w-mysql-7.2.14-1.w7.x86_64
--> Running transaction check
---> Package mariadb-libs.x86_64 1:5.5.60-1.el7_5 will be installed
---> Package php72w-pdo.x86_64 0:7.2.14-1.w7 will be installed
--> Processing Dependency: php72w-common(x86-64) = 7.2.14-1.w7 for package: php72w-pdo-7.2.14-1.w7.x86_64
--> Running transaction check
---> Package php72w-common.x86_64 0:7.2.14-1.w7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

========================================================================================================
 Package                   Arch               Version                        Repository            Size
========================================================================================================
Installing:
 php72w-mysql              x86_64             7.2.14-1.w7                    webtatic              82 k
Installing for dependencies:
 mariadb-libs              x86_64             1:5.5.60-1.el7_5               base                 758 k
 php72w-common             x86_64             7.2.14-1.w7                    webtatic             1.3 M
 php72w-pdo                x86_64             7.2.14-1.w7                    webtatic              89 k

Transaction Summary
========================================================================================================
Install  1 Package (+3 Dependent packages)

Total download size: 2.2 M
Installed size: 17 M
Is this ok [y/d/N]: y
Downloading packages:
(1/4): mariadb-libs-5.5.60-1.el7_5.x86_64.rpm                                    | 758 kB  00:00:00     
(2/4): php72w-mysql-7.2.14-1.w7.x86_64.rpm                                       |  82 kB  00:00:01     
(3/4): php72w-pdo-7.2.14-1.w7.x86_64.rpm                                         |  89 kB  00:00:01     
(4/4): php72w-common-7.2.14-1.w7.x86_64.rpm                                      | 1.3 MB  00:00:06     
--------------------------------------------------------------------------------------------------------
Total                                                                   336 kB/s | 2.2 MB  00:00:06     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : 1:mariadb-libs-5.5.60-1.el7_5.x86_64                                                 1/4 
  Installing : php72w-common-7.2.14-1.w7.x86_64                                                     2/4 
  Installing : php72w-pdo-7.2.14-1.w7.x86_64                                                        3/4 
  Installing : php72w-mysql-7.2.14-1.w7.x86_64                                                      4/4 
  Verifying  : php72w-common-7.2.14-1.w7.x86_64                                                     1/4 
  Verifying  : 1:mariadb-libs-5.5.60-1.el7_5.x86_64                                                 2/4 
  Verifying  : php72w-pdo-7.2.14-1.w7.x86_64                                                        3/4 
  Verifying  : php72w-mysql-7.2.14-1.w7.x86_64                                                      4/4 

Installed:
  php72w-mysql.x86_64 0:7.2.14-1.w7                                                                     

Dependency Installed:
  mariadb-libs.x86_64 1:5.5.60-1.el7_5                php72w-common.x86_64 0:7.2.14-1.w7               
  php72w-pdo.x86_64 0:7.2.14-1.w7                    

Complete!

Yes! Inside the dependences is the common packages. I Installed it into my other container and it works! After, i put de directive into DockerFile, Git commit!! Git Tag!!!! Git Push!!!! Ready!

Differences between action and actionListener

As BalusC indicated, the actionListener by default swallows exceptions, but in JSF 2.0 there is a little more to this. Namely, it doesn't just swallows and logs, but actually publishes the exception.

This happens through a call like this:

context.getApplication().publishEvent(context, ExceptionQueuedEvent.class,                                                          
    new ExceptionQueuedEventContext(context, exception, source, phaseId)
);

The default listener for this event is the ExceptionHandler which for Mojarra is set to com.sun.faces.context.ExceptionHandlerImpl. This implementation will basically rethrow any exception, except when it concerns an AbortProcessingException, which is logged. ActionListeners wrap the exception that is thrown by the client code in such an AbortProcessingException which explains why these are always logged.

This ExceptionHandler can be replaced however in faces-config.xml with a custom implementation:

<exception-handlerfactory>
   com.foo.myExceptionHandler
</exception-handlerfactory>

Instead of listening globally, a single bean can also listen to these events. The following is a proof of concept of this:

@ManagedBean
@RequestScoped
public class MyBean {

    public void actionMethod(ActionEvent event) {

        FacesContext.getCurrentInstance().getApplication().subscribeToEvent(ExceptionQueuedEvent.class, new SystemEventListener() {

        @Override
        public void processEvent(SystemEvent event) throws AbortProcessingException {
            ExceptionQueuedEventContext content = (ExceptionQueuedEventContext)event.getSource();
            throw new RuntimeException(content.getException());
        }

        @Override
        public boolean isListenerForSource(Object source) {
            return true;
        }
        });

        throw new RuntimeException("test");
    }

}

(note, this is not how one should normally code listeners, this is only for demonstration purposes!)

Calling this from a Facelet like this:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">
    <h:body>
        <h:form>
            <h:commandButton value="test" actionListener="#{myBean.actionMethod}"/>
        </h:form>
    </h:body>
</html>

Will result in an error page being displayed.

numbers not allowed (0-9) - Regex Expression in javascript

You could try something like this in javascript:
var regex = /[^a-zA-Z]/g;

and have a keyup event.
$("#nameofInputbox").value.replace(regex, "");

How to get records randomly from the oracle database?

SELECT * FROM table SAMPLE(10) WHERE ROWNUM <= 20;

This is more efficient as it doesn't need to sort the Table.

What is .Net Framework 4 extended?

Got this from Bing. Seems Microsoft has removed some features from the core framework and added it to a separate optional(?) framework component.

To quote from MSDN (http://msdn.microsoft.com/en-us/library/cc656912.aspx)

The .NET Framework 4 Client Profile does not include the following features. You must install the .NET Framework 4 to use these features in your application:

* ASP.NET
* Advanced Windows Communication Foundation (WCF) functionality
* .NET Framework Data Provider for Oracle
* MSBuild for compiling

case in sql stored procedure on SQL Server

(SELECT CASE WHEN (SELECT  Salary FROM tbl_Salary WHERE Code=102 AND Month=1 AND Year=2020 )=0 THEN 'Pending'
WHEN (SELECT  Salary FROM tbl_Salary WHERE Code=102 AND Month=1 AND Year=2020 AND )<>0 THEN (SELECT CASE  WHEN ISNULL(ChequeNo,0) IS NOT NULL   THEN 'Deposit' ELSE 'Pending' END AS Deposite FROM tbl_EEsi WHERE  AND (Month= 1) AND (Year = 2020) AND )END AS Stat)

TERM environment variable not set

SOLVED: On Debian 10 by adding "EXPORT TERM=xterm" on the Script executed by CRONTAB (root) but executed as www-data.

$ crontab -e

*/15 * * * * /bin/su - www-data -s /bin/bash -c '/usr/local/bin/todos.sh'

FILE=/usr/local/bin/todos.sh

#!/bin/bash -p
export TERM=xterm && cd /var/www/dokuwiki/data/pages && clear && grep -r -h '|(TO-DO)' > /var/www/todos.txt && chmod 664 /var/www/todos.txt && chown www-data:www-data /var/www/todos.txt

How to set Oracle's Java as the default Java in Ubuntu?

If you're doing any sort of development you need to point to the JDK (Java Development Kit). Otherwise, you can point to the JRE (Java Runtime Environment).

The JDK contains everything the JRE has and more. If you're just executing Java programs, you can point to either the JRE or the JDK.

You should set JAVA_HOME based on current Java you are using. readlink will print value of a symbolic link for current Java and sed will adjust it to JRE directory:

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")

If you want to set up JAVA_HOME to JDK you should go up one folder more:

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:jre/bin/java::")

Getting path of captured image in Android using camera intent

Try this method to get path of original image captured by camera.

public String getOriginalImagePath() {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getActivity().managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection, null, null, null);
        int column_index_data = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToLast();

        return cursor.getString(column_index_data);
    }

This method will return path of the last image captured by camera. So this path would be of original image not of thumbnail bitmap.

Printing all global variables/local variables?

In case you want to see the local variables of a calling function use select-frame before info locals

E.g.:

(gdb) bt
#0  0xfec3c0b5 in _lwp_kill () from /lib/libc.so.1
#1  0xfec36f39 in thr_kill () from /lib/libc.so.1
#2  0xfebe3603 in raise () from /lib/libc.so.1
#3  0xfebc2961 in abort () from /lib/libc.so.1
#4  0xfebc2bef in _assert_c99 () from /lib/libc.so.1
#5  0x08053260 in main (argc=1, argv=0x8047958) at ber.c:480
(gdb) info locals
No symbol table info available.
(gdb) select-frame 5
(gdb) info locals
i = 28
(gdb) 

Understanding .get() method in Python

If d is a dictionary, then d.get(k, v) means, give me the value of k in d, unless k isn't there, in which case give me v. It's being used here to get the current count of the character, which should start at 0 if the character hasn't been encountered before.

How to find the kafka version in linux

Not sure if there's a convenient way, but you can just inspect your kafka/libs folder. You should see files like kafka_2.10-0.8.2-beta.jar, where 2.10 is Scala version and 0.8.2-beta is Kafka version.

Is background-color:none valid CSS?

.class {
    background-color:none;
}

This is not a valid property. W3C validator will display following error:

Value Error : background-color none is not a background-color value : none

transparent may have been selected as better term instead of 0 or none values during the development of specification of CSS.

Passing Objects By Reference or Value in C#

When you pass the the System.Drawing.Image type object to a method you are actually passing a copy of reference to that object.

So if inside that method you are loading a new image you are loading using new/copied reference. You are not making change in original.

YourMethod(System.Drawing.Image image)
{
    //now this image is a new reference
    //if you load a new image 
    image = new Image()..
    //you are not changing the original reference you are just changing the copy of original reference
}

How to do fade-in and fade-out with JavaScript and CSS

The following javascript will fade in an element from opacity 0 to whatever the opacity value was at the time of calling fade in. You can also set the duration of the animation which is nice:

    function fadeIn(element) {
        var duration = 0.5;
        var interval = 10;//ms
        var op = 0.0;
        var iop = element.style.opacity;
        var timer = setInterval(function () {
            if (op >= iop) {
                op = iop;
                clearInterval(timer);
            }
            element.style.opacity = op;
            op += iop/((1000/interval)*duration);
        }, interval);
    }

*Based on IBUs answer but modified to account for previous opacity value and ability to set duration, also removed irrelevant CSS changes it was making

Converting List<Integer> to List<String>

This is such a basic thing to do I wouldn't use an external library (it will cause a dependency in your project that you probably don't need).

We have a class of static methods specifically crafted to do these sort of jobs. Because the code for this is so simple we let Hotspot do the optimization for us. This seems to be a theme in my code recently: write very simple (straightforward) code and let Hotspot do its magic. We rarely have performance issues around code like this - when a new VM version comes along you get all the extra speed benefits etc.

As much as I love Jakarta collections, they don't support Generics and use 1.4 as the LCD. I am wary of Google Collections because they are listed as Alpha support level!

Firefox and SSL: sec_error_unknown_issuer

June 2014:

This is the configuration I used and it working fine after banging my head on the wall for some days. I use Express 3.4 (I think is the same for Express 4.0)

var privateKey  = fs.readFileSync('helpers/sslcert/key.pem', 'utf8');
var certificate = fs.readFileSync('helpers/sslcert/csr.pem', 'utf8');

files = ["COMODORSADomainValidationSecureServerCA.crt",
         "COMODORSAAddTrustCA.crt",
         "AddTrustExternalCARoot.crt"
        ];

ca = (function() {
  var _i, _len, _results;

  _results = [];
  for (_i = 0, _len = files.length; _i < _len; _i++) {
    file = files[_i];
    _results.push(fs.readFileSync("helpers/sslcert/" + file));
  }
  return _results;
})();

var credentials = {ca:ca, key: privateKey, cert: certificate};

// process.env.PORT : Heroku Config environment
var port = process.env.PORT || 4000;

var app = express();
var server = http.createServer(app).listen(port, function() {
        console.log('Express HTTP server listening on port ' + server.address().port);
});
https.createServer(credentials, app).listen(3000, function() {
        console.log('Express HTTPS server listening on port ' + server.address().port);
});

// redirect all http requests to https
app.use(function(req, res, next) {
  if(!req.secure) {
    return res.redirect(['https://mydomain.com', req.url].join(''));
  }
  next();
});

Then I redirected the 80 and 443 ports:

sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 4000
sudo iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-ports 3000

As you can see after checking my certifications I have 4 [0,1,2,3]:

openssl s_client -connect mydomain.com:443 -showcerts | grep "^ "

ubuntu@ip-172-31-5-134:~$ openssl s_client -connect mydomain.com:443 -showcerts | grep "^ "
depth=3 C = SE, O = AddTrust AB, OU = AddTrust External TTP Network, CN = AddTrust External CA Root
verify error:num=19:self signed certificate in certificate chain
verify return:0
 0 s:/OU=Domain Control Validated/OU=PositiveSSL/CN=mydomain.com
   i:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Domain Validation Secure Server CA
 1 s:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Domain Validation Secure Server CA
   i:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Certification Authority
 2 s:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Certification Authority
   i:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root
 3 s:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root
   i:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root
    Protocol  : TLSv1.1
    Cipher    : AES256-SHA
    Session-ID: 8FDEAEE92ED20742.....3E7D80F93226142DD
    Session-ID-ctx:
    Master-Key: C9E4AB966E41A85EEB7....4D73C67088E1503C52A9353C8584E94
    Key-Arg   : None
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    TLS session ticket lifetime hint: 300 (seconds)
    TLS session ticket:
    0000 - 7c c8 36 80 95 4d 4c 47-d8 e3 ca 2e 70 a5 8f ac   |.6..MLG....p...
    0010 - 90 bd 4a 26 ef f7 d6 bc-4a b3 dd 8f f6 13 53 e9   ..J&..........S.
    0020 - f7 49 c6 48 44 26 8d ab-a8 72 29 c8 15 73 f5 79   .I.HD&.......s.y
    0030 - ca 79 6a ed f6 b1 7f 8a-d2 68 0a 52 03 c5 84 32   .yj........R...2
    0040 - be c5 c8 12 d8 f4 36 fa-28 4f 0e 00 eb d1 04 ce   ........(.......
    0050 - a7 2b d2 73 df a1 8b 83-23 a6 f7 ef 6e 9e c4 4c   .+.s...........L
    0060 - 50 22 60 e8 93 cc d8 ee-42 22 56 a7 10 7b db 1e   P"`.....B.V..{..
    0070 - 0a ad 4a 91 a4 68 7a b0-9e 34 01 ec b8 7b b2 2f   ..J......4...{./
    0080 - e8 33 f5 a9 48 11 36 f8-69 a6 7a a6 22 52 b1 da   .3..H...i....R..
    0090 - 51 18 ed c4 d9 3d c4 cc-5b d7 ff 92 4e 91 02 9e   .....=......N...
    Start Time: 140...549
    Timeout   : 300 (sec)
    Verify return code: 19 (self signed certificate in certificate chain)

Good luck! PD: if u want more answers please check: http://www.benjiegillam.com/2012/06/node-dot-js-ssl-certificate-chain/

How to align input forms in HTML

For this, I prefer to keep a correct HTML semantic, and to use a CSS simple as possible.

Something like this would do the job :

label{
  display: block;
  float: left;
  width : 120px;    
}

One drawback however : you might have to pick the right label width for each form, and this is not easy if your labels can be dynamic (I18N labels for instance).

How to predict input image using trained model in Keras?

keras predict_classes (docs) outputs A numpy array of class predictions. Which in your model case, the index of neuron of highest activation from your last(softmax) layer. [[0]] means that your model predicted that your test data is class 0. (usually you will be passing multiple image, and the result will look like [[0], [1], [1], [0]] )

You must convert your actual label (e.g. 'cancer', 'not cancer') into binary encoding (0 for 'cancer', 1 for 'not cancer') for binary classification. Then you will interpret your sequence output of [[0]] as having class label 'cancer'

How to get all columns' names for all the tables in MySQL?

I wrote this silly thing a long time ago and still actually use it now and then:

https://gist.github.com/kphretiq/e2f924416a326895233d

Basically, it does a "SHOW TABLES", then a "DESCRIBE " on each table, then spits it out as markdown.

Just edit below the "if name" and go. You'll need to have pymysql installed.

jQuery Mobile: Stick footer to bottom of page

You can add this in your css file:

[data-role=page]{height: 100% !important; position:relative !important;}
[data-role=footer]{bottom:0; position:absolute !important; top: auto !important; width:100%;}  

So the page data-role now have 100% height, and footer is in absolute position.

Also Yappo have wrote an excellent plugin that you can find here: jQuery Mobile in a iScroll plugin http://yappo.github.com/projects/jquery.mobile.iscroll/livedemo.html

hope you found the answer!

An answer update

You can now use the data-position="fixed" attribute to keep your footer element on the bottom.
Docs and demos: http://view.jquerymobile.com/master/demos/toolbar-fixed/

When to use async false and async true in ajax function in jquery

It is best practice to go asynchronous if you can do several things in parallel (no inter-dependencies). If you need it to complete to continue loading the next thing you could use synchronous, but note that this option is deprecated to avoid abuse of sync:

jQuery.ajax() method's async option deprecated, what now?

Unicode character for "X" cancel / close?

I prefer Font Awesome: http://fortawesome.github.io/Font-Awesome/icons/

The icon you would be looking for is fa-times. It's as simple as this to use:

<button><i class="fa fa-times"></i> Close</button>

Fiddle here

Java Generate Random Number Between Two Given Values

Use Random.nextInt(int).

In your case it would look something like this:

a[i][j] = r.nextInt(101);

What is the use of WPFFontCache Service in WPF? WPFFontCache_v0400.exe taking 100 % CPU all the time this exe is running, why?

for win xp

Steps

  1. [windows key] + R, type services.msc, search for the running instance of "Windows Presentation Foundation (WPF) Font Cache". For my case its 4.0. Stop the service.
  2. [windows key] + R, type C:\Documents and Settings\LocalService\Local Settings\Application Data\, delete all font cache files.
  3. Start the "Windows Presentation Foundation (WPF) Font Cache" service.

Generate random numbers with a given (numerical) distribution

Make a list of items, based on their weights:

items = [1, 2, 3, 4, 5, 6]
probabilities= [0.1, 0.05, 0.05, 0.2, 0.4, 0.2]
# if the list of probs is normalized (sum(probs) == 1), omit this part
prob = sum(probabilities) # find sum of probs, to normalize them
c = (1.0)/prob # a multiplier to make a list of normalized probs
probabilities = map(lambda x: c*x, probabilities)
print probabilities

ml = max(probabilities, key=lambda x: len(str(x)) - str(x).find('.'))
ml = len(str(ml)) - str(ml).find('.') -1
amounts = [ int(x*(10**ml)) for x in probabilities]
itemsList = list()
for i in range(0, len(items)): # iterate through original items
  itemsList += items[i:i+1]*amounts[i]

# choose from itemsList randomly
print itemsList

An optimization may be to normalize amounts by the greatest common divisor, to make the target list smaller.

Also, this might be interesting.

What is external linkage and internal linkage?

  • A global variable has external linkage by default. Its scope can be extended to files other than containing it by giving a matching extern declaration in the other file.
  • The scope of a global variable can be restricted to the file containing its declaration by prefixing the declaration with the keyword static. Such variables are said to have internal linkage.

Consider following example:

1.cpp

void f(int i);
extern const int max = 10;
int n = 0;
int main()
{
    int a;
    //...
    f(a);
    //...
    f(a);
    //...
}
  1. The signature of function f declares f as a function with external linkage (default). Its definition must be provided later in this file or in other translation unit (given below).
  2. max is defined as an integer constant. The default linkage for constants is internal. Its linkage is changed to external with the keyword extern. So now max can be accessed in other files.
  3. n is defined as an integer variable. The default linkage for variables defined outside function bodies is external.

2.cpp

#include <iostream>
using namespace std;

extern const int max;
extern int n;
static float z = 0.0;

void f(int i)
{
    static int nCall = 0;
    int a;
    //...
    nCall++;
    n++;
    //...
    a = max * z;
    //...
    cout << "f() called " << nCall << " times." << endl;
}
  1. max is declared to have external linkage. A matching definition for max (with external linkage) must appear in some file. (As in 1.cpp)
  2. n is declared to have external linkage.
  3. z is defined as a global variable with internal linkage.
  4. The definition of nCall specifies nCall to be a variable that retains its value across calls to function f(). Unlike local variables with the default auto storage class, nCall will be initialized only once at the start of the program and not once for each invocation of f(). The storage class specifier static affects the lifetime of the local variable and not its scope.

NB: The keyword static plays a double role. When used in the definitions of global variables, it specifies internal linkage. When used in the definitions of the local variables, it specifies that the lifetime of the variable is going to be the duration of the program instead of being the duration of the function.

Hope that helps!

Rails find_or_create_by more than one attribute?

Multiple attributes can be connected with an and:

GroupMember.find_or_create_by_member_id_and_group_id(4, 7)

(use find_or_initialize_by if you don't want to save the record right away)

Edit: The above method is deprecated in Rails 4. The new way to do it will be:

GroupMember.where(:member_id => 4, :group_id => 7).first_or_create

and

GroupMember.where(:member_id => 4, :group_id => 7).first_or_initialize

Edit 2: Not all of these were factored out of rails just the attribute specific ones.

https://github.com/rails/rails/blob/4-2-stable/guides/source/active_record_querying.md

Example

GroupMember.find_or_create_by_member_id_and_group_id(4, 7)

became

GroupMember.find_or_create_by(member_id: 4, group_id: 7)

How to open warning/information/error dialog in Swing?

JOptionPane.showOptionDialog
JOptionPane.showMessageDialog
....

Have a look on this tutorial on how to make dialogs.

Printing 2D array in matrix format

Your can do it like this in short hands.

        int[,] values=new int[2,3]{{2,4,5},{4,5,2}};

        for (int i = 0; i < values.GetLength(0); i++)
        {
            for (int k = 0; k < values.GetLength(1); k++) {
                Console.Write(values[i,k]);
            }

            Console.WriteLine();
        }

Volley JsonObjectRequest Post request not working

try to use this helper class

import java.io.UnsupportedEncodingException;
import java.util.Map;    
import org.json.JSONException;
import org.json.JSONObject;    
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

public class CustomRequest extends Request<JSONObject> {

    private Listener<JSONObject> listener;
    private Map<String, String> params;

    public CustomRequest(String url, Map<String, String> params,
            Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    public CustomRequest(int method, String url, Map<String, String> params,
            Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    protected Map<String, String> getParams()
            throws com.android.volley.AuthFailureError {
        return params;
    };

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        // TODO Auto-generated method stub
        listener.onResponse(response);
    }
}

In activity/fragment do use this

RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
CustomRequest jsObjRequest = new CustomRequest(Method.POST, url, params, this.createRequestSuccessListener(), this.createRequestErrorListener());

requestQueue.add(jsObjRequest);

OnClick Send To Ajax

Tried and working. you are using,

<textarea name='Status'> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>

I am using javascript , (don't know about php), use id ="status" in textarea like

<textarea name='Status' id="status"> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>

then make a call to servlet sending the status to backend for updating using whatever strutucre(like MVC in java or anyother) you like, like this in your UI in script tag

<srcipt>
function UpdateStatus(){

//make an ajax call and get status value using the same 'id'
var var1= document.getElementById("status").value;
$.ajax({

        type:"GET",//or POST
        url:'http://localhost:7080/ajaxforjson/Testajax',
                           //  (or whatever your url is)
        data:{data1:var1},
        //can send multipledata like {data1:var1,data2:var2,data3:var3
        //can use dataType:'text/html' or 'json' if response type expected 
        success:function(responsedata){
               // process on data
               alert("got response as "+"'"+responsedata+"'");

        }
     })

}
</script>

and jsp is like

the servlet will look like:   //webservlet("/zcvdzv") is just for url annotation
@WebServlet("/Testajax")

public class Testajax extends HttpServlet {
private static final long serialVersionUID = 1L;
public Testajax() {
    super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String data1=request.getParameter("data1");
    //do processing on datas pass in other java class to add to DB
    // i am adding or concatenate
    String data="i Got : "+"'"+data1+"' ";
    System.out.println(" data1 : "+data1+"\n data "+data);
    response.getWriter().write(data);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
}

}

Select row and element in awk

To print the columns with a specific string, you use the // search pattern. For example, if you are looking for second columns that contains abc:

awk '$2 ~ /abc/'

... and if you want to print only a particular column:

awk '$2 ~ /abc/ { print $3 }'

... and for a particular line number:

awk '$2 ~ /abc/ && FNR == 5 { print $3 }'

virtualenvwrapper and Python 3

You can make virtualenvwrapper use a custom Python binary instead of the one virtualenvwrapper is run with. To do that you need to use VIRTUALENV_PYTHON variable which is utilized by virtualenv:

$ export VIRTUALENV_PYTHON=/usr/bin/python3
$ mkvirtualenv -a myproject myenv
Running virtualenv with interpreter /usr/bin/python3
New python executable in myenv/bin/python3
Also creating executable in myenv/bin/python
(myenv)$ python
Python 3.2.3 (default, Oct 19 2012, 19:53:16) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.

Makefiles with source files in different directories

The traditional way is to have a Makefile in each of the subdirectories (part1, part2, etc.) allowing you to build them independently. Further, have a Makefile in the root directory of the project which builds everything. The "root" Makefile would look something like the following:

all:
    +$(MAKE) -C part1
    +$(MAKE) -C part2
    +$(MAKE) -C part3

Since each line in a make target is run in its own shell, there is no need to worry about traversing back up the directory tree or to other directories.

I suggest taking a look at the GNU make manual section 5.7; it is very helpful.

What jsf component can render a div tag?

In JSF 2.2 it's possible to use passthrough elements:

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:jsf="http://xmlns.jcp.org/jsf">
    ...
    <div jsf:id="id1" />
    ...
</html>

The requirement is to have at least one attribute in the element using jsf namespace.

Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?

hello to everyone just wanted to share my experience with phpMailer , that was working locally (XAMPP) but wasn't working on my hosting provider.

I turned on phpMailer error reporting

 $mail->SMTPDebug=2

i got 'Connection refused Error'

I email my host provider for the issue , and he said that he would open the SMTP PORTS and he opened the ports 25,465,587 .

Then i got the following error response "SMTP ERROR: Password command failed:"...."Please log in via your web browser and then try again"...."SMTP Error: Could not authenticate."

So google checks if your are logged in to your account (i was when i ran the script locally through my browser) and then allows you to send mail through the phpMailer script.

To fix that 1:go to your google account -> security 2:Scroll to the Key Icon and choose "2 way verification" and follow the procedure 3:When done go back to the key icon from google account -> security and choose the second option "create app passwords" and follow the procedure to get the password.

Now go to your phpMailer object and change your google password with the password given from the above procedure

you are done .

The code

require_once('class.phpmailer.php');

$phpMailerObj= new PHPMailer();

                $phpMailerObj->isSMTP();                    
                $phpMailerObj->SMTPDebug = 0;
                $phpMailerObj->Debugoutput = 'html';                    
                $phpMailerObj->Host = 'smtp.gmail.com';                     
                $phpMailerObj->Port = 587;
                $phpMailerObj->SMTPSecure = 'tls';
                $phpMailerObj->SMTPAuth = true;                 
                $phpMailerObj->Username = "YOUR EMAIL";                 
                $phpMailerObj->Password = "THE NEW PASSWORD FROM GOOGLE ";
                $phpMailerObj->setFrom('YOUR EMAIL ADDRESS', 'THE NAME OF THE SENDER',0);
                $phpMailerObj->addAddress('RECEIVER EMAIL ADDRESS', 'RECEIVER NAME');

                $phpMailerObj->Subject = 'SUBJECT';
                $phpMailerObj->Body ='MESSAGE';

                if (!phpMailerObj->send()) {
                    echo "phpMailerObjer Error: " . $phpMailerObj->ErrorInfo;
                    return 0;
                } else {
                    echo "Message sent!";
                    return 1;
                } 

Difference between webdriver.Dispose(), .Close() and .Quit()

driver.close and driver.quit are two different methods for closing the browser session in Selenium WebDriver. Understanding both of them and knowing when to use each method is important in your test execution. Therefore, I have tried to shed some light on both of these methods.

driver.close - This method closes the browser window on which the focus is set. Despite the familiar name for this method, WebDriver does not implement the AutoCloseable interface.

driver.quit – This method basically calls driver.dispose a now internal method which in turn closes all of the browser windows and ends the WebDriver session gracefully.

driver.dispose - As mentioned previously, is an internal method of WebDriver which has been silently dropped according to another answer - Verification needed. This method really doesn't have a use-case in a normal test workflow as either of the previous methods should work for most use cases.

Explanation use case: You should use driver.quit whenever you want to end the program. It will close all opened browser windows and terminates the WebDriver session. If you do not use driver.quit at the end of the program, the WebDriver session will not close properly and files would not be cleared from memory. This may result in memory leak errors.

The above explanation should explain the difference between driver.close and driver.quit methods in WebDriver. I hope you find it useful.

The following website has some good tips on selenium testing : Link

jQuery set checkbox checked

Set the check box after loading the modal window. I think you are setting the check box before loading the page.

$('#fModal').modal('show');
$("#estado_cat").attr("checked","checked");

Like Operator in Entity Framework?

I don't know anything about EF really, but in LINQ to SQL you usually express a LIKE clause using String.Contains:

where entity.Name.Contains("xyz")

translates to

WHERE Name LIKE '%xyz%'

(Use StartsWith and EndsWith for other behaviour.)

I'm not entirely sure whether that's helpful, because I don't understand what you mean when you say you're trying to implement LIKE. If I've misunderstood completely, let me know and I'll delete this answer :)

How can I stop python.exe from closing immediately after I get an output?

In windows, if Python is installed into the default directory (For me it is):

cd C:\Python27

You then proceed to type

"python.exe "[FULLPATH]\[name].py" 

to run your Python script in Command Prompt

dropping a global temporary table

-- First Truncate temporary table
SQL> TRUNCATE TABLE test_temp1;

-- Then Drop temporary table
SQL> DROP TABLE test_temp1;

val() vs. text() for textarea

The best way to set/get the value of a textarea is the .val(), .value method.

.text() internally uses the .textContent (or .innerText for IE) method to get the contents of a <textarea>. The following test cases illustrate how text() and .val() relate to each other:

var t = '<textarea>';
console.log($(t).text('test').val());             // Prints test
console.log($(t).val('too').text('test').val());  // Prints too
console.log($(t).val('too').text());              // Prints nothing
console.log($(t).text('test').val('too').val());  // Prints too

console.log($(t).text('test').val('too').text()); // Prints test

The value property, used by .val() always shows the current visible value, whereas text()'s return value can be wrong.

SQL Call Stored Procedure for each Row without using a cursor

This is a variation on the answers already provided, but should be better performing because it doesn't require ORDER BY, COUNT or MIN/MAX. The only disadvantage with this approach is that you have to create a temp table to hold all the Ids (the assumption is that you have gaps in your list of CustomerIDs).

That said, I agree with @Mark Powell though that, generally speaking, a set based approach should still be better.

DECLARE @tmp table (Id INT IDENTITY(1,1) PRIMARY KEY NOT NULL, CustomerID INT NOT NULL)
DECLARE @CustomerId INT 
DECLARE @Id INT = 0

INSERT INTO @tmp SELECT CustomerId FROM Sales.Customer

WHILE (1=1)
BEGIN
    SELECT @CustomerId = CustomerId, @Id = Id
    FROM @tmp
    WHERE Id = @Id + 1

    IF @@rowcount = 0 BREAK;

    -- call your sproc
    EXEC dbo.YOURSPROC @CustomerId;
END

MySQL check if a table exists without throwing an exception

Here is the my solution that I prefer when using stored procedures. Custom mysql function for check the table exists in current database.

delimiter $$

CREATE FUNCTION TABLE_EXISTS(_table_name VARCHAR(45))
RETURNS BOOLEAN
DETERMINISTIC READS SQL DATA
BEGIN
    DECLARE _exists  TINYINT(1) DEFAULT 0;

    SELECT COUNT(*) INTO _exists
    FROM information_schema.tables 
    WHERE table_schema =  DATABASE()
    AND table_name =  _table_name;

    RETURN _exists;

END$$

SELECT TABLE_EXISTS('you_table_name') as _exists

failed to lazily initialize a collection of role

Try swich fetchType from LAZY to EAGER

...
@OneToMany(fetch=FetchType.EAGER)
private Set<NodeValue> nodeValues;
...

But in this case your app will fetch data from DB anyway. If this query very hard - this may impact on performance. More here: https://docs.oracle.com/javaee/6/api/javax/persistence/FetchType.html

==> 73

Multiprocessing vs Threading Python

Other answers have focused more on the multithreading vs multiprocessing aspect, but in python Global Interpreter Lock (GIL) has to be taken into account. When more number (say k) of threads are created, generally they will not increase the performance by k times, as it will still be running as a single threaded application. GIL is a global lock which locks everything out and allows only single thread execution utilizing only a single core. The performance does increase in places where C extensions like numpy, Network, I/O are being used, where a lot of background work is done and GIL is released.
So when threading is used, there is only a single operating system level thread while python creates pseudo-threads which are completely managed by threading itself but are essentially running as a single process. Preemption takes place between these pseudo threads. If the CPU runs at maximum capacity, you may want to switch to multiprocessing.
Now in case of self-contained instances of execution, you can instead opt for pool. But in case of overlapping data, where you may want processes communicating you should use multiprocessing.Process.

Android: TextView: Remove spacing and padding on top and bottom

See this:

Align ImageView with EditText horizontally

It seems that the background image of EditText has some transparent pixels which also add padding.

A solution is to change the default background of EditText to something else (or nothing, but no background for a EditText is probably not acceptable). That's can be made setting android:background XML attribute.

android:background="@drawable/myEditBackground"

Outputting data from unit test in Python

We use the logging module for this.

For example:

import logging
class SomeTest( unittest.TestCase ):
    def testSomething( self ):
        log= logging.getLogger( "SomeTest.testSomething" )
        log.debug( "this= %r", self.this )
        log.debug( "that= %r", self.that )
        # etc.
        self.assertEquals( 3.14, pi )

if __name__ == "__main__":
    logging.basicConfig( stream=sys.stderr )
    logging.getLogger( "SomeTest.testSomething" ).setLevel( logging.DEBUG )
    unittest.main()

That allows us to turn on debugging for specific tests which we know are failing and for which we want additional debugging information.

My preferred method, however, isn't to spend a lot of time on debugging, but spend it writing more fine-grained tests to expose the problem.

Query EC2 tags from within instance

I have pieced together the following that is hopefully simpler and cleaner than some of the existing answers and uses only the AWS CLI and no additional tools.

This code example shows how to get the value of tag 'myTag' for the current EC2 instance:

Using describe-tags:

export AWS_DEFAULT_REGION=us-east-1
instance_id=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
aws ec2 describe-tags \
  --filters "Name=resource-id,Values=$instance_id" 'Name=key,Values=myTag' \
  --query 'Tags[].Value' --output text

Or, alternatively, using describe-instances:

aws ec2 describe-instances --instance-id $instance_id \
  --query 'Reservations[].Instances[].Tags[?Key==`myTag`].Value' --output text

How to get year/month/day from a date object?

Why not using the method toISOString() with slice or simply toLocaleDateString()?

Check here:

_x000D_
_x000D_
const d = new Date() // today, now

console.log(d.toISOString().slice(0, 10)) // YYYY-MM-DD

console.log(d.toLocaleDateString('en-US')) // M/D/YYYY
console.log(d.toLocaleDateString('de-DE')) // D.M.YYYY
console.log(d.toLocaleDateString('pt-PT')) // DD/MM/YYYY
_x000D_
_x000D_
_x000D_

Google Maps: how to get country, state/province/region, city given a lat/long value?

Just try this code this code work with me

var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
 //console.log(lat +"          "+long);
$http.get('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + long + '&key=your key here').success(function (output) {
//console.log( JSON.stringify(output.results[0]));
//console.log( JSON.stringify(output.results[0].address_components[4].short_name));
var results = output.results;
if (results[0]) {
//console.log("results.length= "+results.length);
//console.log("hi "+JSON.stringify(results[0],null,4));
for (var j = 0; j < results.length; j++){
 //console.log("j= "+j);
//console.log(JSON.stringify(results[j],null,4));
for (var i = 0; i < results[j].address_components.length; i++){
 if(results[j].address_components[i].types[0] == "country") {
 //this is the object you are looking for
  country = results[j].address_components[i];
 }
 }
 }
 console.log(country.long_name);
 console.log(country.short_name);
 } else {
 alert("No results found");
 console.log("No results found");
 }
 });
 }, function (err) {
 });

Find specific string in a text file with VBS script

Try to change like this ..

firstStr = "<?xml version" 'my file always starts like this

Do until objInputFile.AtEndOfStream  

    strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/DD/Beginning_of_DD_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_DD_TC" & CStr(index) & "</a></td></tr>"  

   substrToFind = "<tr><td><a href=" & chr(34) & "../Test case " & trim(cstr((index)))

   tmpStr = objInputFile.ReadLine

   If InStr(tmpStr, substrToFind) <= 0 Then
       If Instr(tmpStr, firstStr) > 0 Then
          text = tmpStr 'to avoid the first empty line
       Else
          text = text & vbCrLf & tmpStr
       End If
   Else
      text = text & vbCrLf & strToAdd & vbCrLf & tmpStr

   End If
   index = index + 1
Loop

How to Run the Procedure?

In SQL Plus:

VAR rc REFCURSOR
EXEC gokul_proc(1,'GOKUL', :rc);
print rc

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

We also had this problem when upgrading our system to Revive. After turning of GZIP we found the problem still persisted. Upon further investigation we found the file permissions where not correct after the upgrade. A simple recursive chmod did the trick.

How to make a drop down list in yii2?

There are some good solutions above, and mine is just a combination of two (I came here looking for a solution).

@Sarvar Nishonboyev's solution is good because it maintains the creation of the form input label and help-block for error messages.

I went with:

<?php
use yii\helpers\ArrayHelper;
use app\models\Product;
?>
<?=
$form->field($model, 'parent_id')
     ->dropDownList(
            ArrayHelper::map(Product::find()->asArray()->all(), 'parent_id', 'name')
            )
?>

Again, full credit to: @Sarvar Nishonboyev's and @ippi

Copy and Paste a set range in the next empty row

You could also try this

Private Sub CommandButton1_Click()

Sheets("Sheet1").Range("A3:E3").Copy

Dim lastrow As Long
lastrow = Range("A65536").End(xlUp).Row

Sheets("Summary Info").Activate
Cells(lastrow + 1, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

End Sub

How to fix "ImportError: No module named ..." error in Python?

Example solution for adding the library to your PYTHONPATH.

  1. Add the following line into your ~/.bashrc or just run it directly:

    export PYTHONPATH="$PYTHONPATH:$HOME/.python"
    
  2. Then link your required library into your ~/.python folder, e.g.

    ln -s /home/user/work/project/foo ~/.python/
    

automatically execute an Excel macro on a cell change

Handle the Worksheet_Change event or the Workbook_SheetChange event.

The event handlers take an argument "Target As Range", so you can check if the range that's changing includes the cell you're interested in.

How To Check If A Key in **kwargs Exists?

DSM's and Tadeck's answers answer your question directly.

In my scripts I often use the convenient dict.pop() to deal with optional, and additional arguments. Here's an example of a simple print() wrapper:

def my_print(*args, **kwargs):
    prefix = kwargs.pop('prefix', '')
    print(prefix, *args, **kwargs)

Then:

>>> my_print('eggs')
 eggs
>>> my_print('eggs', prefix='spam')
spam eggs

As you can see, if prefix is not contained in kwargs, then the default '' (empty string) is being stored in the local prefix variable. If it is given, then its value is being used.

This is generally a compact and readable recipe for writing wrappers for any kind of function: Always just pass-through arguments you don't understand, and don't even know if they exist. If you always pass through *args and **kwargs you make your code slower, and requires a bit more typing, but if interfaces of the called function (in this case print) changes, you don't need to change your code. This approach reduces development time while supporting all interface changes.

How to properly use unit-testing's assertRaises() with NoneType objects?

The usual way to use assertRaises is to call a function:

self.assertRaises(TypeError, test_function, args)

to test that the function call test_function(args) raises a TypeError.

The problem with self.testListNone[:1] is that Python evaluates the expression immediately, before the assertRaises method is called. The whole reason why test_function and args is passed as separate arguments to self.assertRaises is to allow assertRaises to call test_function(args) from within a try...except block, allowing assertRaises to catch the exception.

Since you've defined self.testListNone = None, and you need a function to call, you might use operator.itemgetter like this:

import operator
self.assertRaises(TypeError, operator.itemgetter, (self.testListNone,slice(None,1)))

since

operator.itemgetter(self.testListNone,slice(None,1))

is a long-winded way of saying self.testListNone[:1], but which separates the function (operator.itemgetter) from the arguments.

What is the most efficient way to deep clone an object in JavaScript?

Lodash has a nice _.cloneDeep(value) method:

var objects = [{ 'a': 1 }, { 'b': 2 }];

var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);
// => false

Javascript onHover event

I don't think you need/want the timeout.

onhover (hover) would be defined as the time period while "over" something. IMHO

onmouseover = start...

onmouseout = ...end

For the record I've done some stuff with this to "fake" the hover event in IE6. It was rather expensive and in the end I ditched it in favor of performance.

Register 32 bit COM DLL to 64 bit Windows 7

Try to run it at Framework64.

Example:

  • 32 bit

    C:\Windows\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe D:\DemoIconOverlaySln\Demo\bin\Debug\HandleOverlayWarning\AsmOverlayIconWarning.dll /codebase 
    
  • 64 bit

    C:\Windows\Microsoft.NET\Framework64\v2.0.50727\RegAsm.exe D:\DemoIconOverlaySln\Demo\bin\Debug\HandleOverlayWarning\AsmOverlayIconWarning.dll /codebase
    

Why do I get a C malloc assertion failure?

99.9% likely that you have corrupted memory (over- or under-flowed a buffer, wrote to a pointer after it was freed, called free twice on the same pointer, etc.)

Run your code under Valgrind to see where your program did something incorrect.

Reading Email using Pop3 in C#

I just tried SMTPop and it worked.

  1. I downloaded this.
  2. Added smtpop.dll reference to my C# .NET project

Wrote the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;    
using SmtPop;

namespace SMT_POP3 {

    class Program {
        static void Main(string[] args) {
            SmtPop.POP3Client pop = new SmtPop.POP3Client();
            pop.Open("<hostURL>", 110, "<username>", "<password>");

            // Get message list from POP server
            SmtPop.POPMessageId[] messages = pop.GetMailList();
            if (messages != null) {

                // Walk attachment list
                foreach(SmtPop.POPMessageId id in messages) {
                    SmtPop.POPReader reader= pop.GetMailReader(id);
                    SmtPop.MimeMessage msg = new SmtPop.MimeMessage();

                    // Read message
                    msg.Read(reader);
                    if (msg.AddressFrom != null) {
                        String from= msg.AddressFrom[0].Name;
                        Console.WriteLine("from: " + from);
                    }
                    if (msg.Subject != null) {
                        String subject = msg.Subject;
                        Console.WriteLine("subject: "+ subject);
                    }
                    if (msg.Body != null) {
                        String body = msg.Body;
                        Console.WriteLine("body: " + body);
                    }
                    if (msg.Attachments != null && false) {
                        // Do something with first attachment
                        SmtPop.MimeAttachment attach = msg.Attachments[0];

                        if (attach.Filename == "data") {
                           // Read data from attachment
                           Byte[] b = Convert.FromBase64String(attach.Body);
                           System.IO.MemoryStream mem = new System.IO.MemoryStream(b, false);

                           //BinaryFormatter f = new BinaryFormatter();
                           // DataClass data= (DataClass)f.Deserialize(mem); 
                           mem.Close();
                        }                     

                        // Delete message
                        // pop.Dele(id.Id);
                    }
               }
           }    
           pop.Quit();
        }
    }
}

What is the simplest C# function to parse a JSON string into an object?

I think this is what you want:

JavaScriptSerializer JSS = new JavaScriptSerializer();
T obj = JSS.Deserialize<T>(String);

How to un-commit last un-pushed git commit without losing the changes

With me mostly it happens when I push changes to the wrong branch and realize later. And following works in most of the time.

git revert commit-hash
git push

git checkout my-other-branch
git revert revert-commit-hash
git push
  1. revert the commit
  2. (create and) checkout other branch
  3. revert the revert

Powershell remoting with ip-address as target

Try doing this:

Set-Item WSMan:\localhost\Client\TrustedHosts -Value "*" -Force

Select distinct values from a list using LINQ in C#

You can use GroupBy with anonymous type, and then get First:

list.GroupBy(e => new { 
                          empLoc = e.empLoc, 
                          empPL = e.empPL, 
                          empShift = e.empShift 
                       })

    .Select(g => g.First());

Check whether specific radio button is checked

Your selector won't select the input field, and if it did it would return a jQuery object. Try this:

$('#test2').is(':checked'); 

Using Math.round to round to one decimal place?

Double toBeTruncated = new Double("2.25");

Double truncatedDouble = new BigDecimal(toBeTruncated).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();

it will return 2.3

How might I find the largest number contained in a JavaScript array?

Find Max and Min value using Bubble Sort

_x000D_
_x000D_
    var arr = [267, 306, 108];_x000D_
_x000D_
    for(i=0, k=0; i<arr.length; i++) {_x000D_
      for(j=0; j<i; j++) {_x000D_
        if(arr[i]>arr[j]) {_x000D_
          k = arr[i];_x000D_
          arr[i] = arr[j];_x000D_
          arr[j] = k;_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
    console.log('largest Number: '+ arr[0]);_x000D_
    console.log('Smallest Number: '+ arr[arr.length-1]);
_x000D_
_x000D_
_x000D_

PHP json_decode() returns NULL with valid JSON?

If you are getting json from database, put

mysqli_set_charset($con, "utf8");

after defining connection link $con

String Pattern Matching In Java

You can do it using string.indexOf("{item}"). If the result is greater than -1 {item} is in the string

Make .gitignore ignore everything except a few files

To ignore some files in a directory, you have to do this in the correct order:

For example, ignore everything in folder "application" except index.php and folder "config" pay attention to the order.

You must negate want you want first.

FAILS

application/*

!application/config/*

!application/index.php

WORKS

!application/config/*

!application/index.php

application/*

How to change font in ipython notebook

In addition to the suggestion by Konrad here, I'd like to suggest jupyter themes, which seems to have more options, such as line-height, font size, cell width etc.

Command line usage:

jt  [-h] [-l] [-t THEME] [-f MONOFONT] [-fs MONOSIZE] [-nf NBFONT]
[-nfs NBFONTSIZE] [-tf TCFONT] [-tfs TCFONTSIZE] [-dfs DFFONTSIZE]
[-m MARGINS] [-cursw CURSORWIDTH] [-cursc CURSORCOLOR] [-vim]
[-cellw CELLWIDTH] [-lineh LINEHEIGHT] [-altp] [-P] [-T] [-N]
[-r] [-dfonts]

What is the difference between Java RMI and RPC?

1. Approach:

RMI uses an object-oriented paradigm where the user needs to know the object and the method of the object he needs to invoke.

RPC doesn't deal with objects. Rather, it calls specific subroutines that are already established.

2. Working:

With RPC, you get a procedure call that looks pretty much like a local call. RPC handles the complexities involved with passing the call from local to the remote computer.

RMI does the very same thing, but RMI passes a reference to the object and the method that is being called.

RMI = RPC + Object-orientation

3. Better one:

RMI is a better approach compared to RPC, especially with larger programs as it provides a cleaner code that is easier to identify if something goes wrong.

4. System Examples:

RPC Systems: SUN RPC, DCE RPC

RMI Systems: Java RMI, CORBA, Microsoft DCOM/COM+, SOAP(Simple Object Access Protocol)

Making Enter key on an HTML form submit instead of activating button

Try this, if enter key was pressed you can capture it like this for example, I developed an answer the other day html button specify selected, see if this helps.

Specify the forms name as for example yourFormName then you should be able to submit the form without having focus on the form.

document.onkeypress = keyPress;

function keyPress(e){
  var x = e || window.event;
  var key = (x.keyCode || x.which);
  if(key == 13 || key == 3){
   //  myFunc1();
   document.yourFormName.submit();
  }
}

How do I check/uncheck all checkboxes with a button using jQuery?

add this in your code block, or even click of your button

$('input:checkbox').attr('checked',false);

JavaScript array to CSV

The cited answer was wrong. You had to change

csvContent += index < infoArray.length ? dataString+ "\n" : dataString;

to

csvContent += dataString + "\n";

As to why the cited answer was wrong (funny it has been accepted!): index, the second parameter of the forEach callback function, is the index in the looped-upon array, and it makes no sense to compare this to the size of infoArray, which is an item of said array (which happens to be an array too).

EDIT

Six years have passed now since I wrote this answer. Many things have changed, including browsers. The following was part of the answer:

START of aged part

BTW, the cited code is suboptimal. You should avoid to repeatedly append to a string. You should append to an array instead, and do an array.join("\n") at the end. Like this:

var lineArray = [];
data.forEach(function (infoArray, index) {
    var line = infoArray.join(",");
    lineArray.push(index == 0 ? "data:text/csv;charset=utf-8," + line : line);
});
var csvContent = lineArray.join("\n");

END of aged part

(Keep in mind that the CSV case is a bit different from generic string concatenation, since for every string you also have to add the separator.)

Anyway, the above seems not to be true anymore, at least not for Chrome and Firefox (it seems to still be true for Safari, though).

To put an end to uncertainty, I wrote a jsPerf test that tests whether, in order to concatenate strings in a comma-separated way, it's faster to push them onto an array and join the array, or to concatenate them first with the comma, and then directly with the result string using the += operator.

Please follow the link and run the test, so that we have enough data to be able to talk about facts instead of opinions.

Running PowerShell as another user, and launching a script

You can open a new powershell window under a specified user credential like this:

start powershell -credential ""

enter image description here

Pandas aggregate count distinct

Just adding to the answers already given, the solution using the string "nunique" seems much faster, tested here on ~21M rows dataframe, then grouped to ~2M

%time _=g.agg({"id": lambda x: x.nunique()})
CPU times: user 3min 3s, sys: 2.94 s, total: 3min 6s
Wall time: 3min 20s

%time _=g.agg({"id": pd.Series.nunique})
CPU times: user 3min 2s, sys: 2.44 s, total: 3min 4s
Wall time: 3min 18s

%time _=g.agg({"id": "nunique"})
CPU times: user 14 s, sys: 4.76 s, total: 18.8 s
Wall time: 24.4 s

ASP.NET MVC DropDownListFor with model of type List<string>

To make a dropdown list you need two properties:

  1. a property to which you will bind to (usually a scalar property of type integer or string)
  2. a list of items containing two properties (one for the values and one for the text)

In your case you only have a list of string which cannot be exploited to create a usable drop down list.

While for number 2. you could have the value and the text be the same you need a property to bind to. You could use a weakly typed version of the helper:

@model List<string>
@Html.DropDownList(
    "Foo", 
    new SelectList(
        Model.Select(x => new { Value = x, Text = x }),
        "Value",
        "Text"
    )
)

where Foo will be the name of the ddl and used by the default model binder. So the generated markup might look something like this:

<select name="Foo" id="Foo">
    <option value="item 1">item 1</option>
    <option value="item 2">item 2</option>
    <option value="item 3">item 3</option>
    ...
</select>

This being said a far better view model for a drop down list is the following:

public class MyListModel
{
    public string SelectedItemId { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
}

and then:

@model MyListModel
@Html.DropDownListFor(
    x => x.SelectedItemId,
    new SelectList(Model.Items, "Value", "Text")
)

and if you wanted to preselect some option in this list all you need to do is to set the SelectedItemId property of this view model to the corresponding Value of some element in the Items collection.

Inserting values into tables Oracle SQL

You can expend the following function in order to pull out more parameters from the DB before the insert:

--
-- insert_employee  (Function) 
--
CREATE OR REPLACE FUNCTION insert_employee(p_emp_id in number, p_emp_name in varchar2, p_emp_address in varchar2, p_emp_state in varchar2, p_emp_position in varchar2, p_emp_manager in varchar2) 
RETURN VARCHAR2 AS

   p_state_id varchar2(30) := '';
 BEGIN    
      select state_id 
      into   p_state_id
      from states where lower(emp_state) = state_name;

      INSERT INTO Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager) VALUES 
                (p_emp_id, p_emp_name, p_emp_address, p_state_id, p_emp_position, p_emp_manager);

    return 'SUCCESS';

 EXCEPTION 
   WHEN others THEN
    RETURN 'FAIL';
 END;
/

How can I change the Bootstrap default font family using font from Google?

I think the best and cleanest way would be to get a custom download of bootstrap.

http://getbootstrap.com/customize/

You can then change the font-defaults in the Typography (in that link). This then gives you a .Less file that you can make further changes to defaults with later.

Find out how much memory is being used by an object in Python

There's no easy way to find out the memory size of a python object. One of the problems you may find is that Python objects - like lists and dicts - may have references to other python objects (in this case, what would your size be? The size containing the size of each object or not?). There are some pointers overhead and internal structures related to object types and garbage collection. Finally, some python objects have non-obvious behaviors. For instance, lists reserve space for more objects than they have, most of the time; dicts are even more complicated since they can operate in different ways (they have a different implementation for small number of keys and sometimes they over allocate entries).

There is a big chunk of code (and an updated big chunk of code) out there to try to best approximate the size of a python object in memory.

You may also want to check some old description about PyObject (the internal C struct that represents virtually all python objects).

for-in statement

edit 2018: This is outdated, js and typescript now have for..of loops.
http://www.typescriptlang.org/docs/handbook/iterators-and-generators.html


The book "TypeScript Revealed" says

"You can iterate through the items in an array by using either for or for..in loops as demonstrated here:

// standard for loop
for (var i = 0; i < actors.length; i++)
{
  console.log(actors[i]);
}

// for..in loop
for (var actor in actors)
{
  console.log(actor);
}

"

Turns out, the second loop does not pass the actors in the loop. So would say this is plain wrong. Sadly it is as above, loops are untouched by typescript.

map and forEach often help me and are due to typescripts enhancements on function definitions more approachable, lke at the very moment:

this.notes = arr.map(state => new Note(state));

My wish list to TypeScript;

  1. Generic collections
  2. Iterators (IEnumerable, IEnumerator interfaces would be best)

how to refresh page in angular 2

window.location.reload() or just location.reload()

How to run Maven from another directory (without cd to project dir)?

You can try this:

pushd ../
maven install [...]
popd

What's the best way to loop through a set of elements in JavaScript?

I know that you don't want to hear that, but: I consider the best practice is the most readable in this case. As long as the loop is not counting from here to the moon, the performance-gain will not be uhge enough.

Retrieving the text of the selected <option> in <select> element

Under HTML5 you are be able to do this:

document.getElementById('test').selectedOptions[0].text

MDN's documentation at https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedOptions indicates full cross-browser support (as of at least December 2017), including Chrome, Firefox, Edge and mobile browsers, but excluding Internet Explorer.

Javascript/jQuery detect if input is focused

Using jQuery's .is( ":focus" )

$(".status").on("click","textarea",function(){
        if ($(this).is( ":focus" )) {
            // fire this step
        }else{
                    $(this).focus();
            // fire this step
    }

How do I hide javascript code in a webpage?

'Is not possible!'

Oh yes it is ....

//------------------------------
function unloadJS(scriptName) {
  var head = document.getElementsByTagName('head').item(0);
  var js = document.getElementById(scriptName);
  js.parentNode.removeChild(js);
}


//----------------------
function unloadAllJS() {
  var jsArray = new Array();
  jsArray = document.getElementsByTagName('script');
  for (i = 0; i < jsArray.length; i++){
    if (jsArray[i].id){
      unloadJS(jsArray[i].id)
    }else{
      jsArray[i].parentNode.removeChild(jsArray[i]);
    }
  }      
}

What's the difference between integer class and numeric class in R

There are multiple classes that are grouped together as "numeric" classes, the 2 most common of which are double (for double precision floating point numbers) and integer. R will automatically convert between the numeric classes when needed, so for the most part it does not matter to the casual user whether the number 3 is currently stored as an integer or as a double. Most math is done using double precision, so that is often the default storage.

Sometimes you may want to specifically store a vector as integers if you know that they will never be converted to doubles (used as ID values or indexing) since integers require less storage space. But if they are going to be used in any math that will convert them to double, then it will probably be quickest to just store them as doubles to begin with.

Fail during installation of Pillow (Python module) in Linux

I had the ValueError: zlib is required unless explicitly disabled using --disable-zlib but upgrading pip from 7.x to 8.y resolved the problem.

So I would try to update tools before anything else.

That can be done using:

pip install --upgrade pip

Get skin path in Magento?

To use it in phtml apply :

echo $this->getSkinUrl('your_image_folder_under_skin/image_name.png');

To use skin path in cms page :

<img style="width: 715px; height: 266px;" src="{{skin url=images/banner1.jpg}}" alt="title" />

This part====> {{skin url=images/banner1.jpg}}

I hope this will help you.

Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

function Time_Function() {
var date = new Date()
var time =""
var x= "AM"
if(date.getHours() >12){
    x= "PM"
}
time= date.getHours()%12 + x +":"+ date.getMinutes() +":"+ date.getSeconds()
}

API vs. Webservice

another example: google map api vs google direction api web service, while the former serves (delivers) javascript file to the site (which can then be used as an api to make new functions) , the later is a Rest web service delivering data (in json or xml format), which can be processed (but not used in an api sense).

Mixing C# & VB In The Same Project

You need one project per language. I'm quite confident I saw a tool that merged assemblies, if you find that tool you should be good to go. If you need to use both languages in the same class, you should be able to write half of it in say VB.net and then write the rest in C# by inheriting the VB.net class.

How do I detect what .NET Framework versions and service packs are installed?

Using the Signum.Utilities library from SignumFramework (which you can use stand-alone), you can get it nicely and without dealing with the registry by yourself:

AboutTools.FrameworkVersions().ToConsole();
//Writes in my machine:
//v2.0.50727 SP2
//v3.0 SP2
//v3.5 SP1

Listing only directories using ls in Bash?

I partially solved it with:

cd "/path/to/pricipal/folder"

for i in $(ls -d .*/); do sudo ln -s "$PWD"/${i%%/} /home/inukaze/${i%%/}; done

 

    ln: «/home/inukaze/./.»: can't overwrite a directory
    ln: «/home/inukaze/../..»: can't overwrite a directory
    ln: accesing to «/home/inukaze/.config»: too much symbolics links levels
    ln: accesing to «/home/inukaze/.disruptive»: too much symbolics links levels
    ln: accesing to «/home/inukaze/innovations»: too much symbolics links levels
    ln: accesing to «/home/inukaze/sarl»: too much symbolics links levels
    ln: accesing to «/home/inukaze/.e_old»: too much symbolics links levels
    ln: accesing to «/home/inukaze/.gnome2_private»: too much symbolics links levels
    ln: accesing to «/home/inukaze/.gvfs»: too much symbolics links levels
    ln: accesing to «/home/inukaze/.kde»: too much symbolics links levels
    ln: accesing to «/home/inukaze/.local»: too much symbolics links levels
    ln: accesing to «/home/inukaze/.xVideoServiceThief»: too much symbolics links levels

Well, this reduce to me, the major part :)

jQuery, simple polling example

Here's a helpful article on long polling (long-held HTTP request) using jQuery. A code snippet derived from this article:

(function poll() {
    setTimeout(function() {
        $.ajax({
            url: "/server/api/function",
            type: "GET",
            success: function(data) {
                console.log("polling");
            },
            dataType: "json",
            complete: poll,
            timeout: 2000
        })
    }, 5000);
})();

This will make the next request only after the ajax request has completed.

A variation on the above that will execute immediately the first time it is called before honouring the wait/timeout interval.

(function poll() {
    $.ajax({
        url: "/server/api/function",
        type: "GET",
        success: function(data) {
            console.log("polling");
        },
        dataType: "json",
        complete: setTimeout(function() {poll()}, 5000),
        timeout: 2000
    })
})();

How to escape indicator characters (i.e. : or - ) in YAML

Another way that works with the YAML parser used in Jekyll:

title: My Life&#58; A Memoir

Colons not followed by spaces don't seem to bother Jekyll's YAML parser, on the other hand. Neither do dashes.

Auto highlight text in a textbox control

It is very easy to achieve with built in method SelectAll

Simply cou can write this:

txtTextBox.Focus();
txtTextBox.SelectAll();

And everything in textBox will be selected :)

Convert date yyyyMMdd to system.datetime format

have at look at the static methods DateTime.Parse() and DateTime.TryParse(). They will allow you to pass in your date string and a format string, and get a DateTime object in return.

http://msdn.microsoft.com/en-us/library/6fw7727c.aspx

Linux c++ error: undefined reference to 'dlopen'

you can try to add this

LIBS=-ldl CFLAGS=-fno-strict-aliasing

to the configure options

Change Schema Name Of Table In SQL

CREATE SCHEMA exe AUTHORIZATION [dbo]
GO

ALTER SCHEMA exe
TRANSFER dbo.Employees
GO

How to detect scroll direction

Here is a sample showing an easy way to do it. The script is:

$(function() {
  var _t = $("#container").scrollTop();
  $("#container").scroll(function() {
    var _n = $("#container").scrollTop();
    if (_n > _t) {
      $("#target").text("Down");
    } else {
      $("#target").text("Up");
    }
    _t = _n;
  });
});

The #container is your div id. The #target is just to see it working. Change to what you want when up or when down.

EDIT

The OP didn't say before, but since he's using a div with overflow: hidden, scrolling doesn't occur, then the script to detect the scroll is the least of it. Well, how to detect something that does not happen?!

So, the OP himself posted the link with what he wants, so why not use that library? http://cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js.

The call is just:

$(function() {
    $(".scrollable").scrollable({ vertical: true, mousewheel: true });
});

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

If you add this to your web.config transformation file, you can also set certain publish options to have debugging enabled or disabled:

<system.web>
    <customErrors mode="Off" defaultRedirect="~/Error.aspx" xdt:Transform="Replace"/>
</system.web>

initialize a vector to zeros C++/C++11

Initializing a vector having struct, class or Union can be done this way

std::vector<SomeStruct> someStructVect(length);
memset(someStructVect.data(), 0, sizeof(SomeStruct)*length);

Linq code to select one item

These are the preferred methods:

var item = Items.SingleOrDefault(x => x.Id == 123);

Or

var item = Items.Single(x => x.Id == 123);

Oracle find a constraint

maybe this can help..

SELECT constraint_name, constraint_type, column_name
from user_constraints natural join user_cons_columns
where table_name = "my_table_name";

Finding three elements in an array whose sum is closest to a given number

Here is the Python3 code

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        result = set()
        nums.sort()
        L = len(nums)     
        for i in range(L):
            if i > 0 and nums[i] == nums[i-1]:
                continue
            for j in range(i+1,L):
                if j > i + 1 and nums[j] == nums[j-1]:
                    continue  
                l = j+1
                r = L -1
                while l <= r:
                    sum = nums[i] + nums[j] + nums[l]
                    result.add(sum)
                    l = l + 1
                    while l<=r and nums[l] == nums[l-1]:
                        l = l + 1
        result = list(result)
        min = result[0]
        for i in range(1,len(result)):
            if abs(target - result[i]) < abs(target - min):
                min = result[i]
        return min

Does Python have “private” variables in classes?

As mentioned earlier, you can indicate that a variable or method is private by prefixing it with an underscore. If you don't feel like this is enough, you can always use the property decorator. Here's an example:

class Foo:

    def __init__(self, bar):
        self._bar = bar

    @property
    def bar(self):
        """Getter for '_bar'."""
        return self._bar

This way, someone or something that references bar is actually referencing the return value of the bar function rather than the variable itself, and therefore it can be accessed but not changed. However, if someone really wanted to, they could simply use _bar and assign a new value to it. There is no surefire way to prevent someone from accessing variables and methods that you wish to hide, as has been said repeatedly. However, using property is the clearest message you can send that a variable is not to be edited. property can also be used for more complex getter/setter/deleter access paths, as explained here: https://docs.python.org/3/library/functions.html#property

Using a dictionary to count the items in a list

Simply use list property count\

i = ['apple','red','apple','red','red','pear']
d = {x:i.count(x) for x in i}
print d

output :

{'pear': 1, 'apple': 2, 'red': 3}

When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

Define Principal as a dependency in your controller method and spring will inject the current authenticated user in your method at invocation.

Instance member cannot be used on type

For anyone else who stumbles on this make sure you're not attempting to modify the class rather than the instance! (unless you've declared the variable as static)

eg.

MyClass.variable = 'Foo' // WRONG! - Instance member 'variable' cannot be used on type 'MyClass'

instanceOfMyClass.variable = 'Foo' // Right!

How can we stop a running java process through Windows cmd?

In case you want to kill not all java processes but specif jars running. It will work for multiple jars as well.

wmic Path win32_process Where "CommandLine Like '%YourJarName.jar%'" Call Terminate

Else taskkill /im java.exe will work to kill all java processes