Programs & Examples On #Tarantino

The Tarantino project is a collection of libraries and tools to facilitate change management and development.

regex match any whitespace

The reason I used a + instead of a '*' is because a plus is defined as one or more of the preceding element, where an asterisk is zero or more. In this case we want a delimiter that's a little more concrete, so "one or more" spaces.

word[Aa]\s+word[Bb]\s+word[Cc]

will match:

wordA wordB     wordC
worda wordb wordc
wordA   wordb   wordC

The words, in this expression, will have to be specific, and also in order (a, b, then c)

PHP - cannot use a scalar as an array warning

You need to set$final[$id] to an array before adding elements to it. Intiialize it with either

$final[$id] = array();
$final[$id][0] = 3;
$final[$id]['link'] = "/".$row['permalink'];
$final[$id]['title'] = $row['title'];

or

$final[$id] = array(0 => 3);
$final[$id]['link'] = "/".$row['permalink'];
$final[$id]['title'] = $row['title'];

cv2.imshow command doesn't work properly in opencv-python

If you have not made this working, you better put

import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('Window',img)
cv2.waitKey(0)

into one file and run it.

Single-threaded apartment - cannot instantiate ActiveX control

Go ahead and add [STAThread] to the main entry of your application, this indicates the COM threading model is single-threaded apartment (STA)

example:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new WebBrowser());
    }
}

Programmatically generate video or animated GIF in Python?

I was looking for a single line code and found the following to work for my application. Here is what I did:

First Step: Install ImageMagick from the link below

https://www.imagemagick.org/script/download.php

enter image description here

Second Step: Point the cmd line to the folder where the images (in my case .png format) are placed

enter image description here

Third Step: Type the following command

magick -quality 100 *.png outvideo.mpeg

enter image description here

Thanks FogleBird for the idea!

How to get your Netbeans project into Eclipse

Sharing my experience, how to import simple Netbeans java project into Eclipse workspace. Please follow the following steps:

  1. Copy the Netbeans project folder into Eclipse workspace.
  2. Create .project file, inside the project folder at root level. Below code is the sample reference. Change your project name appropriately.

    <?xml version="1.0" encoding="UTF-8"?>
    <projectDescription>
        <name>PROJECT_NAME</name>
        <comment></comment>
        <projects>
        </projects>
        <buildSpec>
            <buildCommand>
                <name>org.eclipse.jdt.core.javabuilder</name>
                <arguments>
                </arguments>
            </buildCommand>
        </buildSpec>
        <natures>
            <nature>org.eclipse.jdt.core.javanature</nature>
        </natures>
    </projectDescription>
    
  3. Now open Eclipse and follow the steps,

    File > import > Existing Projects into Workspace > Select root directory > Finish

  4. Now we need to correct the build path for proper compilation of src, by following these steps:

    Right Click on project folder > Properties > Java Build Path > Click Source tab > Add Folder

(Add the correct src path from project and remove the incorrect ones). Find the image ref link how it looks.

  1. You are done. Let me know for any queries. Thanks.

C++, How to determine if a Windows Process is running?

JaredPar is right in that you can't know if the process is running. You can only know if the process was running at the moment you checked. It might have died in the mean time.

You also have to be aware the PIDs can be recycled pretty quickly. So just because there's a process out there with your PID, it doesn't mean that it's your process.

Have the processes share a GUID. (Process 1 could generate the GUID and pass it to Process 2 on the command line.) Process 2 should create a named mutex with that GUID. When Process 1 wants to check, it can do a WaitForSingleObject on the mutex with a 0 timeout. If Process 2 is gone, the return code will tell you that the mutex was abandoned, otherwise you'll get a timeout.

Add 2 hours to current time in MySQL?

This will also work

SELECT NAME 
FROM GEO_LOCATION
WHERE MODIFY_ON BETWEEN SYSDATE() - INTERVAL 2 HOUR AND SYSDATE()

Is it possible to insert HTML content in XML document?

The purpose of BASE64 encoding is to take binary data and be able to persist that to a string. That benefit comes at a cost, an increase in the size of the result (I think it's a 4 to 3 ratio). There are two solutions. If you know the data will be well formed XML, include it directly. The other, an better option, is to include the HTML in a CDATA section within an element within the XML.

BigDecimal to string

The BigDecimal can not be a double. you can use Int number. if you want to display exactly own number, you can use the String constructor of BigDecimal .

like this:

BigDecimal bd1 = new BigDecimal("10.0001");

now, you can display bd1 as 10.0001

So simple. GOOD LUCK.

BitBucket - download source as ZIP

To Download Specific Branch - Go To Downloads from Left panel, Select Branches on Downloads page. It will list all Branches available. Download your desired branch in zip, gz, or bz2 format.

enter image description here

jquery onclick change css background image

I think this should be:

$('.home').click(function() {
     $(this).css('background', 'url(images/tabs3.png)');
 });

and remove this:

<div class="home" onclick="function()">
     //-----------^^^^^^^^^^^^^^^^^^^^---------no need for this

You have to make sure you have a correct path to your image.

Converting Java file:// URL to File(...) path, platform independent, including UNC paths

Building on @SotiriosDelimanolis's comment, here is a method to deal with URLs (such as file:...) and non-URLs (such as C:...), using Spring's FileSystemResource:

public FileSystemResource get(String file) {
    try {
        // First try to resolve as URL (file:...)
        Path path = Paths.get(new URL(file).toURI());
        FileSystemResource resource = new FileSystemResource(path.toFile());
        return resource;
    } catch (URISyntaxException | MalformedURLException e) {
        // If given file string isn't an URL, fall back to using a normal file 
        return new FileSystemResource(file);
    }
}

Eclipse compilation error: The hierarchy of the type 'Class name' is inconsistent

I was having this problem too... I found out that the hierarchy of the class that was throwing this exception, cannot be traced all way back to its root class by eclipse... I Explain:

In my case, I have 3 java project: A, B and C... where A and B are maven projects and C a regular java eclipse project...

In the project A, i have the interface "interfaceA" ... In the project B, i have the interface "interfaceB" that extends "interfaceA" In the project C, i have the concrete class "classC" that implements "interfaceB"

The "project C" was including the "project B" in its build path but not "project A" (so that was the cause of the error).... After including "project A" inside the build path of "C", everything went back to normal...

Failed to start mongod.service: Unit mongod.service not found

It worked for me on ubuntu 20.04: In my case, mongod.service file was locked so it was giving me the same error. To resolve the issue:- Step 1: Use following command to check if the mongod.service is present there

cd /usr/bin/systemd/system
ls

Step 2: If the file is present there then Run the following command to unlock the file mongod.service

sudo chmod 777 /usr/bin/systemd/system/mongod.service -R

Step 3: Now run the following commands:

sudo systemctl daemon-reload
sudo systemctl start mongod
sudo systemctl enable mongod

Is either GET or POST more secure than the other?

This isn't security related but... browsers doesn't cache POST requests.

Setting the zoom level for a MKMapView

Based on the fact that longitude lines are spaced apart equally at any point of the map, there is a very simple implementation to set the centerCoordinate and zoomLevel:

@interface MKMapView (ZoomLevel)

@property (assign, nonatomic) NSUInteger zoomLevel;

- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
                  zoomLevel:(NSUInteger)zoomLevel
                   animated:(BOOL)animated;

@end


@implementation MKMapView (ZoomLevel)

- (void)setZoomLevel:(NSUInteger)zoomLevel {
    [self setCenterCoordinate:self.centerCoordinate zoomLevel:zoomLevel animated:NO];
}

- (NSUInteger)zoomLevel {
    return log2(360 * ((self.frame.size.width/256) / self.region.span.longitudeDelta)) + 1;
}

- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
zoomLevel:(NSUInteger)zoomLevel animated:(BOOL)animated {
    MKCoordinateSpan span = MKCoordinateSpanMake(0, 360/pow(2, zoomLevel)*self.frame.size.width/256);
    [self setRegion:MKCoordinateRegionMake(centerCoordinate, span) animated:animated];
}

@end

How can I check that JButton is pressed? If the isEnable() is not work?

The method you are trying to use checks if the button is active:

btnAdd.isEnabled()

When enabled, any component associated with this object is active and able to fire this object's actionPerformed method.

This method does not check if the button is pressed.

If i understand your question correctly, you want to disable your "Add" button after the user clicks "Check out".

Try disabling your button at start: btnAdd.setEnabled(false) or after the user presses "Check out"

SQL 'like' vs '=' performance

You are asking the wrong question. In databases is not the operator performance that matters, is always the SARGability of the expression, and the coverability of the overall query. Performance of the operator itself is largely irrelevant.

So, how do LIKE and = compare in terms of SARGability? LIKE, when used with an expression that does not start with a constant (eg. when used LIKE '%something') is by definition non-SARGabale. But does that make = or LIKE 'something%' SARGable? No. As with any question about SQL performance the answer does not lie with the query of the text, but with the schema deployed. These expression may be SARGable if an index exists to satisfy them.

So, truth be told, there are small differences between = and LIKE. But asking whether one operator or other operator is 'faster' in SQL is like asking 'What goes faster, a red car or a blue car?'. You should eb asking questions about the engine size and vechicle weight, not about the color... To approach questions about optimizing relational tables, the place to look is your indexes and your expressions in the WHERE clause (and other clauses, but it usually starts with the WHERE).

Java: Most efficient method to iterate over all elements in a org.w3c.dom.Document?

for (int i = 0; i < nodeList.getLength(); i++)

change to

for (int i = 0, len = nodeList.getLength(); i < len; i++)

to be more efficient.

The second way of javanna answer may be the best as it tends to use a flatter, predictable memory model.

Fastest way to count exact number of rows in a very large table?

With SQL Server 2019, you can use APPROX_COUNT_DISTINCT, which:

returns the approximate number of unique non-null values in a group

and from the docs:

APPROX_COUNT_DISTINCT is designed for use in big data scenarios and is optimized for the following conditions:

  • Access of data sets that are millions of rows or higher and
  • Aggregation of a column or columns that have many distinct values

Also, the function

  • implementation guarantees up to a 2% error rate within a 97% probability
  • requires less memory than an exhaustive COUNT DISTINCT operation
  • given the smaller memory footprint is less likely to spill memory to disk compared to a precise COUNT DISTINCT operation.

The algorithm behind the implementation its HyperLogLog.

How do I use a regex in a shell script?

the problem is you're trying to use regex features not supported by grep. namely, your \d won't work. use this instead:

REGEX_DATE="^[[:digit:]]{2}[-/][[:digit:]]{2}[-/][[:digit:]]{4}$"
echo "$1" | grep -qE "${REGEX_DATE}"
echo $?

you need the -E flag to get ERE in order to use {#} style.

Tomcat Server not starting with in 45 seconds

I also had the issue of the Eclipse Tomcat Server timing out and tried every suggestion including:

  • increasing timeout seconds
  • deleting various .metadata files in workspace directory
  • deleting the server instance in Eclipse along with the Run Config

Nothing worked until I read a comment on a related issue and realized that I had added a breakpoint in an interceptor class after a big code change and had forgotten to toggle it off. I removed it and all other breakpoints and Tomcat started right up as it usually did.

What is the difference between ManualResetEvent and AutoResetEvent in .NET?

Just imagine that the AutoResetEvent executes WaitOne() and Reset() as a single atomic operation.

Remove Project from Android Studio

In the "Welcome to Android Studio" opening dialog you can highlight the app you want to remove from Android Studio and hit delete on your keyboard.

ExpressJS How to structure an application?

It's been quite a while since the last answer to this question and Express has also recently released version 4, which added a few useful things for organising your app structure.

Below is a long up to date blog post about best practices on how to structure your Express app. http://www.terlici.com/2014/08/25/best-practices-express-structure.html

There is also a GitHub repository applying the advice in the article. It is always up to date with the latest Express version.
https://github.com/terlici/base-express

How to set input type date's default value to today?

Thanks peter, now i change my code.

<input type='date' id='d1' name='d1'>

<script type="text/javascript">
var d1 = new Date();
var y1= d1.getFullYear();
var m1 = d1.getMonth()+1;
if(m1<10)
    m1="0"+m1;
var dt1 = d1.getDate();
if(dt1<10)
dt1 = "0"+dt1;
var d2 = y1+"-"+m1+"-"+dt1;
document.getElementById('d1').value=d2;
</script>

django no such table:

sqlall just prints the SQL, it doesn't execute it. syncdb will create tables that aren't already created, but it won't modify existing tables.

How to show validation message below each textbox using jquery?

Here you go:

JS:

$('form').on('submit', function (e) {
    e.preventDefault();

    if (!$('#email').val()) 
        $('#email').parent().append('<span class="error">Please enter your email address.</span>');


    if(!$('#password').val())
         $('#password').parent().append('<span class="error">Please enter your password.</span>');
});

CSS:

@charset "utf-8";
/* CSS Document */

/* ---------- FONTAWESOME ---------- */
/* ---------- http://fortawesome.github.com/Font-Awesome/ ---------- */
/* ---------- http://weloveiconfonts.com/ ---------- */

@import url(http://weloveiconfonts.com/api/?family=fontawesome);

/* ---------- ERIC MEYER'S RESET CSS ---------- */
/* ---------- http://meyerweb.com/eric/tools/css/reset/ ---------- */

@import url(http://meyerweb.com/eric/tools/css/reset/reset.css);

/* ---------- FONTAWESOME ---------- */

[class*="fontawesome-"]:before {
  font-family: 'FontAwesome', sans-serif;
}

/* ---------- GENERAL ---------- */

body {
    background-color: #C0C0C0;
    color: #000;
    font-family: "Varela Round", Arial, Helvetica, sans-serif;
    font-size: 16px;
    line-height: 1.5em;
}

input {
    border: none;
    font-family: inherit;
    font-size: inherit;
    font-weight: inherit;
    line-height: inherit;
    -webkit-appearance: none;
}

/* ---------- LOGIN ---------- */

#login {
    margin: 50px auto;
    width: 400px;
}

#login h2 {
    background-color: #f95252;
    -webkit-border-radius: 20px 20px 0 0;
    -moz-border-radius: 20px 20px 0 0;
    border-radius: 20px 20px 0 0;
    color: #fff;
    font-size: 28px;
    padding: 20px 26px;
}

#login h2 span[class*="fontawesome-"] {
    margin-right: 14px;
}

#login fieldset {
    background-color: #fff;
    -webkit-border-radius: 0 0 20px 20px;
    -moz-border-radius: 0 0 20px 20px;
    border-radius: 0 0 20px 20px;
    padding: 20px 26px;
}

#login fieldset div {
    color: #777;
    margin-bottom: 14px;
}

#login fieldset p:last-child {
    margin-bottom: 0;
}

#login fieldset input {
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
}

#login fieldset .error {
    display: block;
     color: #FF1000;
    font-size: 12px;
}
}

#login fieldset input[type="email"], #login fieldset input[type="password"] {
    background-color: #eee;
    color: #777;
    padding: 4px 10px;
    width: 328px;
}

#login fieldset input[type="submit"] {
    background-color: #33cc77;
    color: #fff;
    display: block;
    margin: 0 auto;
    padding: 4px 0;
    width: 100px;
}

#login fieldset input[type="submit"]:hover {
    background-color: #28ad63;
}

HTML:

<div id="login">

<h2><span class="fontawesome-lock"></span>Sign In</h2>

<form action="javascript:void(0);" method="POST">

    <fieldset>

        <div><label for="email">E-mail address</label></div>
        <div><input type="email" id="email" /></div>

        <div><label for="password">Password</label></div>
        <div><input type="password" id="password" /></div> <!-- JS because of IE support; better: placeholder="Email" -->

        <div><input type="submit" value="Sign In"></div>

    </fieldset>

</form>

And the fiddle: jsfiddle

iPhone UILabel text soft shadow

This answer to this similar question provides code for drawing a blurred shadow behind a UILabel. The author uses CGContextSetShadow() to generate the shadow for the drawn text.

How can I convert a date into an integer?

Here what you can try:

var d = Date.parse("2016-07-19T20:23:01.804Z");
alert(d); //this is in milliseconds

Spark Dataframe distinguish columns with duplicated name

This is how we can join two Dataframes on same column names in PySpark.

df = df1.join(df2, ['col1','col2','col3'])

If you do printSchema() after this then you can see that duplicate columns have been removed.

Create a remote branch on GitHub

It looks like github has a simple UI for creating branches. I opened the branch drop-down and it prompts me to "Find or create a branch ...". Type the name of your new branch, then click the "create" button that appears.

To retrieve your new branch from github, use the standard git fetch command.

create branch github ui

I'm not sure this will help your underlying problem, though, since the underlying data being pushed to the server (the commit objects) is the same no matter what branch it's being pushed to.

Angular 5 Scroll to top on every Route click

For some one who is looking for scroll function just add the function and call when ever needed

scrollbarTop(){

  window.scroll(0,0);
}

How to call stopservice() method of Service class from the calling activity class

I actually used pretty much the same code as you above. My service registration in the manifest is the following

<service android:name=".service.MyService" android:enabled="true">
            <intent-filter android:label="@string/menuItemStartService" >
                <action android:name="it.unibz.bluedroid.bluetooth.service.MY_SERVICE"/>
            </intent-filter>
        </service>

In the service class I created an according constant string identifying the service name like:

public class MyService extends ForeGroundService {
    public static final String MY_SERVICE = "it.unibz.bluedroid.bluetooth.service.MY_SERVICE";
   ...
}

and from the according Activity I call it with

startService(new Intent(MyService.MY_SERVICE));

and stop it with

stopService(new Intent(MyService.MY_SERVICE));

It works perfectly. Try to check your configuration and if you don't find anything strange try to debug whether your stopService get's called properly.

What is the best way to modify a list in a 'foreach' loop?

You can't change the enumerable collection while it is being enumerated, so you will have to make your changes before or after enumerating.

The for loop is a nice alternative, but if your IEnumerable collection does not implement ICollection, it is not possible.

Either:

1) Copy collection first. Enumerate the copied collection and change the original collection during the enumeration. (@tvanfosson)

or

2) Keep a list of changes and commit them after the enumeration.

PHP If Statement with Multiple Conditions

you can use in_array function of php

$array=array('abc', 'def', 'hij', 'klm', 'nop');

if (in_array($val,$array))
{
  echo 'Value found';
}

How do you comment out code in PowerShell?

There is a special way of inserting comments add the end of script:

....
exit 

Hi
Hello
We are comments
And not executed 

Anything after exit is not executed, and behave quite like comments.

Angularjs on page load call function

you can also use the below code.

function activateController(){
     console.log('HELLO WORLD');
}

$scope.$on('$viewContentLoaded', function ($evt, data) {
    activateController();
});

Group By Multiple Columns

.GroupBy(x => (x.MaterialID, x.ProductID))

How to redirect 'print' output to a file using python?

The easiest solution isn't through python; its through the shell. From the first line of your file (#!/usr/bin/python) I'm guessing you're on a UNIX system. Just use print statements like you normally would, and don't open the file at all in your script. When you go to run the file, instead of

./script.py

to run the file, use

./script.py > <filename>

where you replace <filename> with the name of the file you want the output to go in to. The > token tells (most) shells to set stdout to the file described by the following token.

One important thing that needs to be mentioned here is that "script.py" needs to be made executable for ./script.py to run.

So before running ./script.py,execute this command

chmod a+x script.py (make the script executable for all users)

How to catch a click event on a button?

Just declare a method,e.g:if ur button id is button1 then,

button1.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(Context, "Hello", Toast.LENGTH_SHORT).show();
        }
    });

If you want to make the imageview1 visible then in that method write:

imageview1.setVisibility(ImageView.VISIBLE);

Using node.js as a simple web server

There are already some great solutions for a simple nodejs server. There is a one more solution if you need live-reloading as you made changes to your files.

npm install lite-server -g

navigate your directory and do

lite-server

it will open browser for you with live-reloading.

How can I debug my JavaScript code?

You might also check out YUI Logger. All you have to do to use it is include a couple of tags in your HTML. It is a helpful addition to Firebug, which is more or less a must.

How to list the tables in a SQLite database file that was opened with ATTACH?

The ".schema" commando will list available tables and their rows, by showing you the statement used to create said tables:

sqlite> create table_a (id int, a int, b int);
sqlite> .schema table_a
CREATE TABLE table_a (id int, a int, b int);

MySQL table is marked as crashed and last (automatic?) repair failed

This is a 100% solution. I tried it myself.

myisamchk -r -v -f --sort_buffer_size=128M --key_buffer_size=128M /var/lib/mysql/databasename/tabloname

JavaScript operator similar to SQL "like"

No.

You want to use: .indexOf("foo") and then check the index. If it's >= 0, it contains that string.

How to open a new window on form submit

For a similar effect to form's target attribute, you can also use the formtarget attribute of input[type="submit]" or button[type="submit"].

From MDN:

...this attribute is a name or keyword indicating where to display the response that is received after submitting the form. This is a name of, or keyword for, a browsing context (for example, tab, window, or inline frame). If this attribute is specified, it overrides the target attribute of the elements's form owner. The following keywords have special meanings:

  • _self: Load the response into the same browsing context as the current one. This value is the default if the attribute is not specified.
  • _blank: Load the response into a new unnamed browsing context.
  • _parent: Load the response into the parent browsing context of the current one. If there is no parent, this option behaves the same way as _self.
  • _top: Load the response into the top-level browsing context (that is, the browsing context that is an ancestor of the current one, and has no parent). If there is no parent, this option behaves the same way as _self.

Why do people say that Ruby is slow?

First of all, slower with respect to what? C? Python? Let's get some numbers at the Computer Language Benchmarks Game:

Why is Ruby considered slow?

Depends on whom you ask. You could be told that:

  • Ruby is an interpreted language and interpreted languages will tend to be slower than compiled ones
  • Ruby uses garbage collection (though C#, which also uses garbage collection, comes out two orders of magnitude ahead of Ruby, Python, PHP etc. in the more algorithmic, less memory-allocation-intensive benchmarks above)
  • Ruby method calls are slow (although, because of duck typing, they are arguably faster than in strongly typed interpreted languages)
  • Ruby (with the exception of JRuby) does not support true multithreading
  • etc.

But, then again, slow with respect to what? Ruby 1.9 is about as fast as Python and PHP (within a 3x performance factor) when compared to C (which can be up to 300x faster), so the above (with the exception of threading considerations, should your application heavily depend on this aspect) are largely academic.

What are your options as a Ruby programmer if you want to deal with this "slowness"?

Write for scalability and throw more hardware at it (e.g. memory)

Which version of Ruby would best suit an application like Stack Overflow where speed is critical and traffic is intense?

Well, REE (combined with Passenger) would be a very good candidate.

Disable a link in Bootstrap

If what you're trying to do is disable an a link, there is no option to do this. I think you can find an answer that will work for you in this question here.

One option here is to use

<a href="/" onclick="return false;">123n</a>

Disabled href tag

How to make an introduction page with Doxygen

Have a look at the mainpage command.

Also, have a look this answer to another thread: How to include custom files in Doxygen. It states that there are three extensions which doxygen classes as additional documentation files: .dox, .txt and .doc. Files with these extensions do not appear in the file index but can be used to include additional information into your final documentation - very useful for documentation that is necessary but that is not really appropriate to include with your source code (for example, an FAQ)

So I would recommend having a mainpage.dox (or similarly named) file in your project directory to introduce you SDK. Note that inside this file you need to put one or more C/C++ style comment blocks.

How to redirect the output of print to a TXT file

Usinge the file argument in the print function, you can have different files per print:

print('Redirect output to file', file=open('/tmp/example.log', 'w'))

How to lookup JNDI resources on WebLogic?

You should be able to simply do this:

Context context = new InitialContext();
dataSource = (javax.sql.DataSource) context.lookup("jdbc/myDataSource");

If you are looking it up from a remote destination you need to use the WL initial context factory like this:

Hashtable<String, String> h = new Hashtable<String, String>(7);
h.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
h.put(Context.PROVIDER_URL, pURL); //For example "t3://127.0.0.1:7001"
h.put(Context.SECURITY_PRINCIPAL, pUsername);
h.put(Context.SECURITY_CREDENTIALS, pPassword);

InitialContext context = new InitialContext(h);
dataSource = (javax.sql.DataSource) context.lookup("jdbc/myDataSource");

weblogic.jndi.WLInitialContextFactory

Should I use != or <> for not equal in T-SQL?

It seems that Microsoft themselves prefer <> to != as evidenced in their table constraints. I personally prefer using != because I clearly read that as "not equal", but if you enter [field1 != field2] and save it as a constrait, the next time you query it, it will show up as [field1 <> field2]. This says to me that the correct way to do it is <>.

Use Toast inside Fragment

Making a Toast inside Fragment

 Toast.makeText(getActivity(), "Your Text Here!", Toast.LENGTH_SHORT).show();

OR

    Activity activityObj = this.getActivity();

    Toast.makeText(activityObj, "Your Text Here!", Toast.LENGTH_SHORT).show();

OR

Toast.makeText(this, "Your Text Here!", Toast.LENGTH_SHORT).show();

Spring's overriding bean

An example from official spring manual:

<bean id="inheritedTestBean" abstract="true"
    class="org.springframework.beans.TestBean">
  <property name="name" value="parent"/>
  <property name="age" value="1"/>
</bean>

<bean id="inheritsWithDifferentClass"
      class="org.springframework.beans.DerivedTestBean"
      parent="inheritedTestBean" init-method="initialize">
  <property name="name" value="override"/>
  <!-- the age property value of 1 will be inherited from  parent -->
</bean>

Is that what you was looking for? Updated link

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

If you try calling equals on a null object reference, then you'll get a null pointer exception thrown.

What's the best way to detect a 'touch screen' device using JavaScript?

There is something better than checking if they have a touchScreen, is to check if they are using it, plus that's easier to check.

if (window.addEventListener) {
    var once = false;
    window.addEventListener('touchstart', function(){
        if (!once) {
            once = true;
            // Do what you need for touch-screens only
        }
    });
}

How to filter an array/object by checking multiple values

You can use .filter() method of the Array object:

var filtered = workItems.filter(function(element) {
   // Create an array using `.split()` method
   var cats = element.category.split(' ');

   // Filter the returned array based on specified filters
   // If the length of the returned filtered array is equal to
   // length of the filters array the element should be returned  
   return cats.filter(function(cat) {
       return filtersArray.indexOf(cat) > -1;
   }).length === filtersArray.length;
});

http://jsfiddle.net/6RBnB/

Some old browsers like IE8 doesn't support .filter() method of the Array object, if you are using jQuery you can use .filter() method of jQuery object.

jQuery version:

var filtered = $(workItems).filter(function(i, element) {
   var cats = element.category.split(' ');

    return $(cats).filter(function(_, cat) {
       return $.inArray(cat, filtersArray) > -1;
    }).length === filtersArray.length;
});

Why does corrcoef return a matrix?

It allows you to compute correlation coefficients of >2 data sets, e.g.

>>> from numpy import *
>>> a = array([1,2,3,4,6,7,8,9])
>>> b = array([2,4,6,8,10,12,13,15])
>>> c = array([-1,-2,-2,-3,-4,-6,-7,-8])
>>> corrcoef([a,b,c])
array([[ 1.        ,  0.99535001, -0.9805214 ],
       [ 0.99535001,  1.        , -0.97172394],
       [-0.9805214 , -0.97172394,  1.        ]])

Here we can get the correlation coefficient of a,b (0.995), a,c (-0.981) and b,c (-0.972) at once. The two-data-set case is just a special case of N-data-set class. And probably it's better to keep the same return type. Since the "one value" can be obtained simply with

>>> corrcoef(a,b)[1,0]
0.99535001355530017

there's no big reason to create the special case.

How to create UILabel programmatically using Swift?

Swift 4.2 and Xcode 10 Initialize label before viewDidLoad.

lazy var topLeftLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "TopLeft"
    return label
}()

In viewDidLoad add label to the view and apply constraints.

override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(topLeftLabel)
    topLeftLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true
    topLeftLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
}

Adding a regression line on a ggplot

I found this function on a blog

 ggplotRegression <- function (fit) {

    `require(ggplot2)

    ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) + 
      geom_point() +
      stat_smooth(method = "lm", col = "red") +
      labs(title = paste("Adj R2 = ",signif(summary(fit)$adj.r.squared, 5),
                         "Intercept =",signif(fit$coef[[1]],5 ),
                         " Slope =",signif(fit$coef[[2]], 5),
                         " P =",signif(summary(fit)$coef[2,4], 5)))
    }`

once you loaded the function you could simply

ggplotRegression(fit)

you can also go for ggplotregression( y ~ x + z + Q, data)

Hope this helps.

How to compare objects by multiple fields

Its easy to do using Google's Guava library.

e.g. Objects.equal(name, name2) && Objects.equal(age, age2) && ...

More examples:

Vertical align in bootstrap table

vetrical-align: middle did not work for me for some reason (and it was being applied). I used this:

table.vertical-align > tbody > tr > td {
  display: flex;
  align-items: center;
}

Get raw POST body in Python Flask regardless of Content-Type header

Use request.get_data() to get the raw data, regardless of content type. The data is cached and you can subsequently access request.data, request.json, request.form at will.

If you access request.data first, it will call get_data with an argument to parse form data first. If the request has a form content type (multipart/form-data, application/x-www-form-urlencoded, or application/x-url-encoded) then the raw data will be consumed. request.data and request.json will appear empty in this case.

To delay JavaScript function call using jQuery

function sample() {
    alert("This is sample function");
}

$(function() {
    $("#button").click(function() {
        setTimeout(sample, 2000);
    });

});

jsFiddle.

If you want to encapsulate sample() there, wrap the whole thing in a self invoking function (function() { ... })().

Creating a BAT file for python script

You can use python code directly in batch file, https://gist.github.com/jadient/9849314.

@echo off & python -x "%~f0" %* & goto :eof
import sys
print("Hello World!")

See explanation, Python command line -x option.

Test if string begins with a string?

The best methods are already given but why not look at a couple of other methods for fun? Warning: these are more expensive methods but do serve in other circumstances.

The expensive regex method and the css attribute selector with starts with ^ operator

Option Explicit

Public Sub test()

    Debug.Print StartWithSubString("ab", "abc,d")

End Sub

Regex:

Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'required reference Microsoft VBScript Regular Expressions
    Dim re As VBScript_RegExp_55.RegExp
    Set re = New VBScript_RegExp_55.RegExp

    re.Pattern = "^" & substring

    StartWithSubString = re.test(testString)

End Function

Css attribute selector with starts with operator

Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'required reference Microsoft HTML Object Library
    Dim html As MSHTML.HTMLDocument
    Set html = New MSHTML.HTMLDocument

    html.body.innerHTML = "<div test=""" & testString & """></div>"

    StartWithSubString = html.querySelectorAll("[test^=" & substring & "]").Length > 0

End Function

How to pass the password to su/sudo/ssh without overriding the TTY?

The usual solution to this problem is setuiding a helper app that performs the task requiring superuser access: http://en.wikipedia.org/wiki/Setuid

Sudo is not meant to be used offline.

Later edit: SSH can be used with private-public key authentication. If the private key does not have a passphrase, ssh can be used without prompting for a password.

End of File (EOF) in C

EOF indicates "end of file". A newline (which is what happens when you press enter) isn't the end of a file, it's the end of a line, so a newline doesn't terminate this loop.

The code isn't wrong[*], it just doesn't do what you seem to expect. It reads to the end of the input, but you seem to want to read only to the end of a line.

The value of EOF is -1 because it has to be different from any return value from getchar that is an actual character. So getchar returns any character value as an unsigned char, converted to int, which will therefore be non-negative.

If you're typing at the terminal and you want to provoke an end-of-file, use CTRL-D (unix-style systems) or CTRL-Z (Windows). Then after all the input has been read, getchar() will return EOF, and hence getchar() != EOF will be false, and the loop will terminate.

[*] well, it has undefined behavior if the input is more than LONG_MAX characters due to integer overflow, but we can probably forgive that in a simple example.

Mongodb: failed to connect to server on first connect

I connected to a VPN and it worked. I was using school's WiFi.

from list of integers, get number closest to a given value

Iterate over the list and compare the current closest number with abs(currentNumber - myNumber):

def takeClosest(myList, myNumber):
    closest = myList[0]
    for i in range(1, len(myList)):
        if abs(i - myNumber) < closest:
            closest = i
    return closest

MySQLDump one INSERT statement for each data row

In newer versions change was made to the flags: from the documentation:

--extended-insert, -e

Write INSERT statements using multiple-row syntax that includes several VALUES lists. This results in a smaller dump file and speeds up inserts when the file is reloaded.

--opt

This option, enabled by default, is shorthand for the combination of --add-drop-table --add-locks --create-options --disable-keys --extended-insert --lock-tables --quick --set-charset. It gives a fast dump operation and produces a dump file that can be reloaded into a MySQL server quickly.

Because the --opt option is enabled by default, you only specify its converse, the --skip-opt to turn off several default settings. See the discussion of mysqldump option groups for information about selectively enabling or disabling a subset of the options affected by --opt.

--skip-extended-insert

Turn off extended-insert

How to make Git "forget" about a file that was tracked but is now in .gitignore?

The BFG is specifically designed for removing unwanted data like big files or passwords from Git repos, so it has a simple flag that will remove any large historical (not-in-your-current-commit) files: '--strip-blobs-bigger-than'

$ java -jar bfg.jar --strip-blobs-bigger-than 100M

If you'd like to specify files by name, you can do that too:

$ java -jar bfg.jar --delete-files *.mp4

The BFG is 10-1000x faster than git filter-branch, and generally much easier to use - check the full usage instructions and examples for more details.

Source: https://confluence.atlassian.com/bitbucket/reduce-repository-size-321848262.html

"Instantiating" a List in Java?

List is an interface, not a concrete class.
An interface is just a set of functions that a class can implement; it doesn't make any sense to instantiate an interface.

ArrayList is a concrete class that happens to implement this interface and all of the methods in it.

PHP checkbox set to check based on database value

This simplest ways is to add the "checked attribute.

<label for="tag_1">Tag 1</label>
<input type="checkbox" name="tag_1" id="tag_1" value="yes" 
    <?php if($tag_1_saved_value === 'yes') echo 'checked="checked"';?> />

MessageBox Buttons?

  1. Your call to MessageBox.Show needs to pass MessageBoxButtons.YesNo to get the Yes/No buttons instead of the OK button.

  2. Compare the result of that call (which will block execution until the dialog returns) to DialogResult.Yes....

if (MessageBox.Show("Are you sure?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
    // user clicked yes
}
else
{
    // user clicked no
}

What is the single most influential book every programmer should read?

Types and Programming Languages by Benjamin C Pierce for a thorough understanding of the underpinnings of programming languages.

Calling JMX MBean method from a shell script

I've developed jmxfuse which exposes JMX Mbeans as a Linux FUSE filesystem with similar functionality as the /proc fs. It relies on Jolokia as the bridge to JMX. Attributes and operations are exposed for reading and writing.

http://code.google.com/p/jmxfuse/

For example, to read an attribute:

me@oddjob:jmx$ cd log4j/root/attributes
me@oddjob:jmx$ cat priority

to write an attribute:

me@oddjob:jmx$ echo "WARN" > priority

to invoke an operation:

me@oddjob:jmx$ cd Catalina/none/none/WebModule/localhost/helloworld/operations/addParameter
me@oddjob:jmx$ echo "myParam myValue" > invoke

XML Document to String

Assuming doc is your instance of org.w3c.dom.Document:

TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString().replaceAll("\n|\r", "");

How to correctly represent a whitespace character

Which whitespace character? The empty string is pretty unambiguous - it's a sequence of 0 characters. However, " ", "\t" and "\n" are all strings containing a single character which is characterized as whitespace.

If you just mean a space, use a space. If you mean some other whitespace character, there may well be a custom escape sequence for it (e.g. "\t" for tab) or you can use a Unicode escape sequence ("\uxxxx"). I would discourage you from including non-ASCII characters in your source code, particularly whitespace ones.

EDIT: Now that you've explained what you want to do (which should have been in your question to start with) you'd be better off using Regex.Split with a regular expression of \s which represents whitespace:

Regex regex = new Regex(@"\s");
string[] bits = regex.Split(text.ToLower());

See the Regex Character Classes documentation for more information on other character classes.

Get first and last date of current month with JavaScript or jQuery

Very simple, no library required:

var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

or you might prefer:

var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);

EDIT

Some browsers will treat two digit years as being in the 20th century, so that:

new Date(14, 0, 1);

gives 1 January, 1914. To avoid that, create a Date then set its values using setFullYear:

var date = new Date();
date.setFullYear(14, 0, 1); // 1 January, 14

Javascript close alert box

no control over the dialog box, if you had control over the dialog box you could write obtrusive javascript code. (Its is not a good idea to use alert for anything except debugging)

Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory"

As a general rule (i.e. in vanilla kernels), fork/clone failures with ENOMEM occur specifically because of either an honest to God out-of-memory condition (dup_mm, dup_task_struct, alloc_pid, mpol_dup, mm_init etc. croak), or because security_vm_enough_memory_mm failed you while enforcing the overcommit policy.

Start by checking the vmsize of the process that failed to fork, at the time of the fork attempt, and then compare to the amount of free memory (physical and swap) as it relates to the overcommit policy (plug the numbers in.)

In your particular case, note that Virtuozzo has additional checks in overcommit enforcement. Moreover, I'm not sure how much control you truly have, from within your container, over swap and overcommit configuration (in order to influence the outcome of the enforcement.)

Now, in order to actually move forward I'd say you're left with two options:

  • switch to a larger instance, or
  • put some coding effort into more effectively controlling your script's memory footprint

NOTE that the coding effort may be all for naught if it turns out that it's not you, but some other guy collocated in a different instance on the same server as you running amock.

Memory-wise, we already know that subprocess.Popen uses fork/clone under the hood, meaning that every time you call it you're requesting once more as much memory as Python is already eating up, i.e. in the hundreds of additional MB, all in order to then exec a puny 10kB executable such as free or ps. In the case of an unfavourable overcommit policy, you'll soon see ENOMEM.

Alternatives to fork that do not have this parent page tables etc. copy problem are vfork and posix_spawn. But if you do not feel like rewriting chunks of subprocess.Popen in terms of vfork/posix_spawn, consider using suprocess.Popen only once, at the beginning of your script (when Python's memory footprint is minimal), to spawn a shell script that then runs free/ps/sleep and whatever else in a loop parallel to your script; poll the script's output or read it synchronously, possibly from a separate thread if you have other stuff to take care of asynchronously -- do your data crunching in Python but leave the forking to the subordinate process.

HOWEVER, in your particular case you can skip invoking ps and free altogether; that information is readily available to you in Python directly from procfs, whether you choose to access it yourself or via existing libraries and/or packages. If ps and free were the only utilities you were running, then you can do away with subprocess.Popen completely.

Finally, whatever you do as far as subprocess.Popen is concerned, if your script leaks memory you will still hit the wall eventually. Keep an eye on it, and check for memory leaks.

Generate random 5 characters string

Here are my random 5 cents ...

$random=function($a, $b) {
    return(
        substr(str_shuffle(('\\`)/|@'.
        password_hash(mt_rand(0,999999),
        PASSWORD_DEFAULT).'!*^&~(')),
        $a, $b)
    );
};

echo($random(0,5));

PHP's new password_hash() (* >= PHP 5.5) function is doing the job for generation of decently long set of uppercase and lowercase characters and numbers.

Two concat. strings before and after password_hash within $random function are suitable for change.

Paramteres for $random() *($a,$b) are actually substr() parameters. :)

NOTE: this doesn't need to be a function, it can be normal variable as well .. as one nasty singleliner, like this:

$random=(substr(str_shuffle(('\\`)/|@'.password_hash(mt_rand(0,999999), PASSWORD_DEFAULT).'!*^&~(')), 0, 5));

echo($random);

How to add a where clause in a MySQL Insert statement?

For Empty row how we can insert values on where clause

Try this

UPDATE table_name SET username="",password="" WHERE id =""

unsigned int vs. size_t

size_t is the size of a pointer.

So in 32 bits or the common ILP32 (integer, long, pointer) model size_t is 32 bits. and in 64 bits or the common LP64 (long, pointer) model size_t is 64 bits (integers are still 32 bits).

There are other models but these are the ones that g++ use (at least by default)

How to get the data-id attribute?

This piece of code will return the value of the data attributes eg: data-id, data-time, data-name etc.., I have shown for the id

<a href="#" id="click-demo" data-id="a1">Click</a>

js:

$(this).data("id");

// get the value of the data-id -> a1

$(this).data("id", "a2");

// this will change the data-id -> a2

$(this).data("id");

// get the value of the data-id -> a2

Delete a closed pull request from GitHub

This is the reply I received from Github when I asked them to delete a pull request:

"Thanks for getting in touch! Pull requests can't be deleted through the UI at the moment and we'll only delete pull requests when they contain sensitive information like passwords or other credentials."

Iterating through a string word by word

This is one way to do it:

string = "this is a string"
ssplit = string.split()
for word in ssplit:
    print (word)

Output:

this
is
a
string

avrdude: stk500v2_ReceiveMessage(): timeout

To my humble understanding this error arises with different scenarios

  1. you have selected the wrong port or you haven't at all. go to tools>ports ans select the com port with your Arduino connected to
  2. you have selected the wrong board. go to tools>board and look for the right board
  3. you have one of these arduino's replicas or you don't have the boot-loader installed on the micro-controller. I don't know the solution to this! if you know please edit my post and add the instructions.
  4. (windows only) you don't have the right drivers installed. you need to update them manually.
  5. sometimes when you have wires connected to the board this happens. you need to separate the board from any breadboard or wires you have installed and try uploading again. It seems pins 0 (RX) and 1 (TX), which can be used for serial communication, are problematic and better to be free while uploading the code.

  6. Sometimes it happens randomly for no specific reasons!

There are all kind of solutions all over the internet, sometimes hard to tell the difference with magic! Maybe Arduino team should think of better compiler errors helping users differentiate between these different causes.

The same problem happened to me and none of the solutions above worked. What happened was that I was using an Arduino uno and everything was fine, but when I bough an Arduino Mega 2560, no matter what sketch I tried to upload I got the error:

avrdude: stk500v2_ReceiveMessage(): timeout

And it was just on one of my windows computers and the other one was just ok out of the box.

Solution:

What solved my problem was to go to tools>boards>Boards Manager... and then on top left of the opened windows select "updatable" in "Type" section. Then select the items in the list and press update on right.

I'm not sure if this will solve everyone problem, but it at least solved mine.

In Python, how do I read the exif data for an image?

I usually use pyexiv2 to set exif information in JPG files, but when I import the library in a script QGIS script crash.

I found a solution using the library exif:

https://pypi.org/project/exif/

It's so easy to use, and with Qgis I don,'t have any problem.

In this code I insert GPS coordinates to a snapshot of screen:

from exif import Image
with open(file_name, 'rb') as image_file:
    my_image = Image(image_file)

my_image.make = "Python"
my_image.gps_latitude_ref=exif_lat_ref
my_image.gps_latitude=exif_lat
my_image.gps_longitude_ref= exif_lon_ref
my_image.gps_longitude= exif_lon

with open(file_name, 'wb') as new_image_file:
    new_image_file.write(my_image.get_file())

C# Listbox Item Double Click Event

For Winforms

private void listBox1_DoubleClick(object sender, MouseEventArgs e)
    {
        int index = this.listBox1.IndexFromPoint(e.Location);
        if (index != System.Windows.Forms.ListBox.NoMatches)
        {
            MessageBox.Show(listBox1.SelectedItem.ToString());
        }
    }

and

public Form()
{
    InitializeComponent();
    listBox1.MouseDoubleClick += new MouseEventHandler(listBox1_DoubleClick);
}

that should also, prevent for the event firing if you select an item then click on a blank area.

How can I know when an EditText loses focus?

Implement onFocusChange of setOnFocusChangeListener and there's a boolean parameter for hasFocus. When this is false, you've lost focus to another control.

 EditText txtEdit = (EditText) findViewById(R.id.edittxt);

 txtEdit.setOnFocusChangeListener(new OnFocusChangeListener() {          
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
               // code to execute when EditText loses focus
            }
        }
    });

How do you close/hide the Android soft keyboard using Java?

from so searching, here I found an answer that works for me

// Show soft-keyboard:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

// Hide soft-keyboard:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

insert multiple rows into DB2 database

other method

INSERT INTO tableName (col1, col2, col3, col4, col5)
select * from table(                        
                    values                                      
                    (val1, val2, val3, val4, val5),   
                    (val1, val2, val3, val4, val5),   
                    (val1, val2, val3, val4, val5),   
                    (val1, val2, val3, val4, val5)    
                    ) tmp

SyntaxError of Non-ASCII character

You should define source code encoding, add this to the top of your script:

# -*- coding: utf-8 -*-

The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:

import sys
print sys.getdefaultencoding()

Also see:

ES6 Class Multiple inheritance

From the page es6-features.org/#ClassInheritanceFromExpressions, it is possible to write an aggregation function to allow multiple inheritance:

class Rectangle extends aggregation(Shape, Colored, ZCoord) {}

var aggregation = (baseClass, ...mixins) => {
    let base = class _Combined extends baseClass {
        constructor (...args) {
            super(...args)
            mixins.forEach((mixin) => {
                mixin.prototype.initializer.call(this)
            })
        }
    }
    let copyProps = (target, source) => {
        Object.getOwnPropertyNames(source)
            .concat(Object.getOwnPropertySymbols(source))
            .forEach((prop) => {
            if (prop.match(/^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/))
                return
            Object.defineProperty(target, prop, Object.getOwnPropertyDescriptor(source, prop))
        })
    }
    mixins.forEach((mixin) => {
        copyProps(base.prototype, mixin.prototype)
        copyProps(base, mixin)
    })
    return base
}

But that is already provided in libraries like aggregation.

validate natural input number with ngpattern

<label>Mobile Number(*)</label>
<input id="txtMobile" ng-maxlength="10" maxlength="10" Validate-phone  required  name='strMobileNo' ng-model="formModel.strMobileNo" type="text"  placeholder="Enter Mobile Number">
<span style="color:red" ng-show="regForm.strMobileNo.$dirty && regForm.strMobileNo.$invalid"><span ng-show="regForm.strMobileNo.$error.required">Phone is required.</span>

the following code will help for phone number validation and the respected directive is

app.directive('validatePhone', function() {
var PHONE_REGEXP = /^[789]\d{9}$/;
  return {
    link: function(scope, elm) {
      elm.on("keyup",function(){
            var isMatchRegex = PHONE_REGEXP.test(elm.val());
            if( isMatchRegex&& elm.hasClass('warning') || elm.val() == ''){
              elm.removeClass('warning');
            }else if(isMatchRegex == false && !elm.hasClass('warning')){
              elm.addClass('warning');
            }
      });
    }
  }
});

How do you get a directory listing in C?

The strict answer is "you can't", as the very concept of a folder is not truly cross-platform.

On MS platforms you can use _findfirst, _findnext and _findclose for a 'c' sort of feel, and FindFirstFile and FindNextFile for the underlying Win32 calls.

Here's the C-FAQ answer:

http://c-faq.com/osdep/readdir.html

Get the correct week number of a given date

If you don't have .NET 5.0, extend the DateTime class to include week number.

public static class Extension {
    public static int Week(this DateTime date) {
        var day = (int)CultureInfo.CurrentCulture.Calendar.GetDayOfWeek(date);
        return CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date.AddDays(4 - (day == 0 ? 7 : day)), CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
    }
}

How can I find non-ASCII characters in MySQL?

One missing character from everyone's examples above is the termination character (\0). This is invisible to the MySQL console output and is not discoverable by any of the queries heretofore mentioned. The query to find it is simply:

select * from TABLE where COLUMN like '%\0%';

Run cURL commands from Windows console

Folks that don't literally need the curl executable, but rather just need to e.g. see or save the results of a GET request now and again, can use powershell directly. From a normal command prompt, type:

powershell -Command "(new-object net.webclient).DownloadString('http://example.com')"

which, while a bit wordy, is similar to typing

curl http://example.com/

in a more Unix-ish environment.

More information about net.webclient is available here: WebClient Methods (System.Net).

UPDATE: I like how ImranHafeez took this one step further in this answer. I'd prefer a simpler cmd-script however, maybe creating a curl.cmd file containing this:

@powershell -Command "(new-object net.webclient).DownloadString('%1')"

which could be called just like the Unix-ish example above:

curl http://example.com/

Make a negative number positive

The concept you are describing is called "absolute value", and Java has a function called Math.abs to do it for you. Or you could avoid the function call and do it yourself:

number = (number < 0 ? -number : number);

or

if (number < 0)
    number = -number;

How to create JNDI context in Spring Boot with Embedded Tomcat Container

In SpringBoot 2.1, I found another solution. Extend standard factory class method getTomcatWebServer. And then return it as a bean from anywhere.

public class CustomTomcatServletWebServerFactory extends TomcatServletWebServerFactory {

    @Override
    protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
        System.setProperty("catalina.useNaming", "true");
        tomcat.enableNaming();
        return new TomcatWebServer(tomcat, getPort() >= 0);
    }
}

@Component
public class TomcatConfiguration {
    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new CustomTomcatServletWebServerFactory();

        return factory;
    }

Loading resources from context.xml doesn't work though. Will try to find out.

Console errors. Failed to load resource: net::ERR_INSECURE_RESPONSE

For me the problem was the <base href="https://domain.ext/"> tag.

After removing, it was OK. Cannot really understand why it was a problem.

Postgres user does not exist?

psql -U postgres

Worked fine for me in case of db name: postgres & username: postgres. So you do not need to write sudo.

And in the case other db, you may try

psql -U yourdb postgres

As it is given in Postgres help:

psql [OPTION]... [DBNAME [USERNAME]]

Check if decimal value is null

A decimal will always have some default value. If you need to have a nullable type decimal, you can use decimal?. Then you can do myDecimal.HasValue

What is a void pointer in C++?

A void* does not mean anything. It is a pointer, but the type that it points to is not known.

It's not that it can return "anything". A function that returns a void* generally is doing one of the following:

  • It is dealing in unformatted memory. This is what operator new and malloc return: a pointer to a block of memory of a certain size. Since the memory does not have a type (because it does not have a properly constructed object in it yet), it is typeless. IE: void.
  • It is an opaque handle; it references a created object without naming a specific type. Code that does this is generally poorly formed, since this is better done by forward declaring a struct/class and simply not providing a public definition for it. Because then, at least it has a real type.
  • It returns a pointer to storage that contains an object of a known type. However, that API is used to deal with objects of a wide variety of types, so the exact type that a particular call returns cannot be known at compile time. Therefore, there will be some documentation explaining when it stores which kinds of objects, and therefore which type you can safely cast it to.

This construct is nothing like dynamic or object in C#. Those tools actually know what the original type is; void* does not. This makes it far more dangerous than any of those, because it is very easy to get it wrong, and there's no way to ask if a particular usage is the right one.

And on a personal note, if you see code that uses void*'s "often", you should rethink what code you're looking at. void* usage, especially in C++, should be rare, used primary for dealing in raw memory.

What does .shape[] do in "for i in range(Y.shape[0])"?

The shape attribute for numpy arrays returns the dimensions of the array. If Y has n rows and m columns, then Y.shape is (n,m). So Y.shape[0] is n.

In [46]: Y = np.arange(12).reshape(3,4)

In [47]: Y
Out[47]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

In [48]: Y.shape
Out[48]: (3, 4)

In [49]: Y.shape[0]
Out[49]: 3

How to make an HTTP request + basic auth in Swift

//create authentication base 64 encoding string

    let PasswordString = "\(txtUserName.text):\(txtPassword.text)"
    let PasswordData = PasswordString.dataUsingEncoding(NSUTF8StringEncoding)
    let base64EncodedCredential = PasswordData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
    //let base64EncodedCredential = PasswordData!.base64EncodedStringWithOptions(nil)

//create authentication url

    let urlPath: String = "http://...../auth"
    var url: NSURL = NSURL(string: urlPath)

//create and initialize basic authentication request

    var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
    request.setValue("Basic \(base64EncodedCredential)", forHTTPHeaderField: "Authorization")
    request.HTTPMethod = "GET"

//You can use one of below methods

//1 URL request with NSURLConnectionDataDelegate

    let queue:NSOperationQueue = NSOperationQueue()
    let urlConnection = NSURLConnection(request: request, delegate: self)
    urlConnection.start()

//2 URL Request with AsynchronousRequest

    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
        println(NSString(data: data, encoding: NSUTF8StringEncoding))
    }

//2 URL Request with AsynchronousRequest with json output

    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        var err: NSError
        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println("\(jsonResult)")
    })

//3 URL Request with SynchronousRequest

    var response: AutoreleasingUnsafePointer<NSURLResponse?>=nil
    var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error:nil)
    var err: NSError
    var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
    println("\(jsonResult)")

//4 URL Request with NSURLSession

    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let authString = "Basic \(base64EncodedCredential)"
    config.HTTPAdditionalHeaders = ["Authorization" : authString]
    let session = NSURLSession(configuration: config)

    session.dataTaskWithURL(url) {
        (let data, let response, let error) in
        if let httpResponse = response as? NSHTTPURLResponse {
            let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
            println(dataString)
        }
    }.resume()

// you may be get fatal error if you changed the request.HTTPMethod = "POST" when server request GET request

How to upgrade all Python packages with pip

More Robust Solution

For pip3, use this:

pip3 freeze --local |sed -rn 's/^([^=# \t\\][^ \t=]*)=.*/echo; echo Processing \1 ...; pip3 install -U \1/p' |sh

For pip, just remove the 3s as such:

pip freeze --local |sed -rn 's/^([^=# \t\\][^ \t=]*)=.*/echo; echo Processing \1 ...; pip install -U \1/p' |sh

OS X Oddity

OS X, as of July 2017, ships with a very old version of sed (a dozen years old). To get extended regular expressions, use -E instead of -r in the solution above.

Solving Issues with Popular Solutions

This solution is well designed and tested1, whereas there are problems with even the most popular solutions.

  • Portability issues due to changing pip command line features
  • Crashing of xargs because of common pip or pip3 child process failures
  • Crowded logging from the raw xargs output
  • Relying on a Python-to-OS bridge while potentially upgrading it3

The above command uses the simplest and most portable pip syntax in combination with sed and sh to overcome these issues completely. Details of the sed operation can be scrutinized with the commented version2.


Details

[1] Tested and regularly used in a Linux 4.8.16-200.fc24.x86_64 cluster and tested on five other Linux/Unix flavors. It also runs on Cygwin64 installed on Windows 10. Testing on iOS is needed.

[2] To see the anatomy of the command more clearly, this is the exact equivalent of the above pip3 command with comments:

# Match lines from pip's local package list output
# that meet the following three criteria and pass the
# package name to the replacement string in group 1.
# (a) Do not start with invalid characters
# (b) Follow the rule of no white space in the package names
# (c) Immediately follow the package name with an equal sign
sed="s/^([^=# \t\\][^ \t=]*)=.*"

# Separate the output of package upgrades with a blank line
sed="$sed/echo"

# Indicate what package is being processed
sed="$sed; echo Processing \1 ..."

# Perform the upgrade using just the valid package name
sed="$sed; pip3 install -U \1"

# Output the commands
sed="$sed/p"

# Stream edit the list as above
# and pass the commands to a shell
pip3 freeze --local | sed -rn "$sed" | sh

[3] Upgrading a Python or PIP component that is also used in the upgrading of a Python or PIP component can be a potential cause of a deadlock or package database corruption.

How to display length of filtered ng-repeat data

Since AngularJS 1.3 you can use aliases:

item in items | filter:x as results

and somewhere:

<span>Total {{results.length}} result(s).</span>

From docs:

You can also provide an optional alias expression which will then store the intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message when a filter is active on the repeater, but the filtered result set is empty.

For example: item in items | filter:x as results will store the fragment of the repeated items as results, but only after the items have been processed through the filter.

Amazon S3 direct file upload from client browser - private key disclosure

If you don't have any server side code, you security depends on the security of the access to your JavaScript code on the client side (ie everybody who has the code could upload something).

So I would recommend, to simply create a special S3 bucket which is public writeable (but not readable), so you don't need any signed components on the client side.

The bucket name (a GUID eg) will be your only defense against malicious uploads (but a potential attacker could not use your bucket to transfer data, because it is write only to him)

What's a .sh file?

sh files are unix (linux) shell executables files, they are the equivalent (but much more powerful) of bat files on windows.

So you need to run it from a linux console, just typing its name the same you do with bat files on windows.

Regular expression to match DNS hostname or IP Address?

on php: filter_var(gethostbyname($dns), FILTER_VALIDATE_IP) == true ? 'ip' : 'not ip'

How to overlay one div over another div

Here follows a simple solution 100% based on CSS. The "secret" is to use the display: inline-block in the wrapper element. The vertical-align: bottom in the image is a hack to overcome the 4px padding that some browsers add after the element.

Advice: if the element before the wrapper is inline they can end up nested. In this case you can "wrap the wrapper" inside a container with display: block - usually a good and old div.

_x000D_
_x000D_
.wrapper {_x000D_
    display: inline-block;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.hover {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    bottom: 0;_x000D_
    background-color: rgba(0, 188, 212, 0);_x000D_
    transition: background-color 0.5s;_x000D_
}_x000D_
_x000D_
.hover:hover {_x000D_
    background-color: rgba(0, 188, 212, 0.8);_x000D_
    // You can tweak with other background properties too (ie: background-image)..._x000D_
}_x000D_
_x000D_
img {_x000D_
    vertical-align: bottom;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
    <div class="hover"></div>_x000D_
    <img src="http://placehold.it/450x250" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

What's the difference between "super()" and "super(props)" in React when using es6 classes?

For react version 16.6.3, we use super(props) to initialize state element name : this.props.name

constructor(props){
    super(props);        
}
state = {
  name:this.props.name 
    //otherwise not defined
};

How to set host_key_checking=false in ansible inventory file?

Adding following to ansible config worked while using ansible ad-hoc commands:

[ssh_connection]
# ssh arguments to use
ssh_args = -o StrictHostKeyChecking=no

Ansible Version

ansible 2.1.6.0
config file = /etc/ansible/ansible.cfg

Fail to create Android virtual Device, "No system image installed for this Target"

In order to create an Android Wear emulator you need to follow the instructions below:

  1. If your version of Android SDK Tools is lower than 22.6, you must update

  2. Under Android 4.4.2, select Android Wear ARM EABI v7a System Image and install it.

  3. Under Extras, ensure that you have the latest version of the Android Support Library. If an update is available, select Android Support Library. If you're using Android Studio, also select Android Support Repository.

Below is the snapshot of what it should look like:

Screenshot1

Then you must check the following in order to create a Wearable AVD:

  1. For the Device, select Android Wear Square or Android Wear Round.

  2. For the Target, select Android 4.4.2 - API Level 19 (or higher, otherwise corresponding system image will not show up.).

  3. For the CPU/ABI, select Android Wear ARM (armeabi-v7a).

  4. For the Skin, select AndroidWearSquare or AndroidWearRound.

  5. Leave all other options set to their defaults and click OK.

Screenshot2

Then you are good to go. For more information you can always refer to the developer site.

How to have conditional elements and keep DRY with Facebook React's JSX?

Most examples are with one line of "html" that is rendered conditionally. This seems readable for me when I have multiple lines that needs to be rendered conditionally.

render: function() {
  // This will be renered only if showContent prop is true
  var content = 
    <div>
      <p>something here</p>
      <p>more here</p>
      <p>and more here</p>
    </div>;

  return (
    <div>
      <h1>Some title</h1>

      {this.props.showContent ? content : null}
    </div>
  );
}

First example is good because instead of null we can conditionally render some other content like {this.props.showContent ? content : otherContent}

But if you just need to show/hide content this is even better since Booleans, Null, and Undefined Are Ignored

render: function() {
  return (
    <div>
      <h1>Some title</h1>

      // This will be renered only if showContent prop is true
      {this.props.showContent &&
        <div>
          <p>something here</p>
          <p>more here</p>
          <p>and more here</p>
        </div>
      }
    </div>
  );
}

How to actually search all files in Visual Studio

One can access the "Find in Files" window via the drop-down menu selection and search all files in the Entire Solution: Edit > Find and Replace > Find in Files

enter image description here

Other, alternative is to open the "Find in Files" window via the "Standard Toolbars" button as highlighted in the below screen-short:

enter image description here

How to get an element by its href in jquery?

var myElement = $("a[href='http://www.stackoverflow.com']");

http://api.jquery.com/attribute-equals-selector/

Spaces cause split in path with PowerShell

You can escape the space by using single quotations and a backtick before the space:

$path = 'C:\Windows Services\MyService.exe'
$path -replace ' ', '` '
invoke-expression $path

How to suppress warnings globally in an R Script

You want options(warn=-1). However, note that warn=0 is not the safest warning level and it should not be assumed as the current one, particularly within scripts or functions. Thus the safest way to temporary turn off warnings is:

oldw <- getOption("warn")
options(warn = -1)

[your "silenced" code]

options(warn = oldw)

Writing unit tests in Python: How do I start?

The docs for unittest would be a good place to start.

Also, it is a bit late now, but in the future please consider writing unit tests before or during the project itself. That way you can use them to test as you go along, and (in theory) you can use them as regression tests, to verify that your code changes have not broken any existing code. This would give you the full benefit of writing test cases :)

Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime

Try this code:

CONVERT(varchar(15), date_started, 103)

Convert one date format into another in PHP

Easiest and simplest way to change date format in php

In PHP any date can be converted into the required date format using different scenarios for example to change any date format into Day, Date Month Year

$newdate = date("D, d M Y", strtotime($date));

It will show date in the following very well format

Mon, 16 Nov 2020

And if you have time as well in your existing date format for example if you have datetime format of SQL 2020-11-11 22:00:00 you can convert this into the required date format using the following

$newdateformat = date("D, d M Y H:i:s", strtotime($oldateformat));

It will show date in following well looking format

Sun, 15 Nov 2020 16:26:00

Base 64 encode and decode example code

Answer from 2021 in kotlin

Encode :

        val data: String = "Hello"
        val dataByteArray: ByteArray = data.toByteArray()
        val dataInBase64: String = Base64Utils.encode(dataByteArray)

Decode :

        val dataInBase64: String = "..."
        val dataByteArray: ByteArray = Base64Utils.decode(dataInBase64)
        val data: String = dataByteArray.toString()

Why is char[] preferred over String for passwords?

While other suggestions here seem valid, there is one other good reason. With plain String you have much higher chances of accidentally printing the password to logs, monitors or some other insecure place. char[] is less vulnerable.

Consider this:

public static void main(String[] args) {
    Object pw = "Password";
    System.out.println("String: " + pw);

    pw = "Password".toCharArray();
    System.out.println("Array: " + pw);
}

Prints:

String: Password
Array: [C@5829428e

Using Python, find anagrams for a list of words

def all_anagrams(words: [str]) -> [str]:
    word_dict = {}
    for word in words:
        sorted_word  = "".join(sorted(word))
        if sorted_word in word_dict:
            word_dict[sorted_word].append(word)
        else:
            word_dict[sorted_word] = [word]
    return list(word_dict.values())  

Doctrine and LIKE query

This is not possible with the magic methods, however you can achieve this using DQL (Doctrine Query Language). In your example, assuming you have entity named Orders with Product property, just go ahead and do the following:

$dql_query = $em->createQuery("
    SELECT o FROM AcmeCodeBundle:Orders o
    WHERE 
      o.OrderEmail = '[email protected]' AND
      o.Product LIKE 'My Products%'
");
$orders = $dql_query->getResult();

Should do exactly what you need.

OpenJDK availability for Windows OS

Red Hat announces they will distribute an OpenJDK for Windows platform: http://developers.redhat.com/blog/2016/06/27/openjdk-now-available-for-windows/

EDITED (thx to CaseyB comment): there is no PRODUCTION support on Windows. From the documentation:

All Red Hat distributions of OpenJDK 8 on Windows are supported for development of applications that work in conjunction with JBoss Middleware, so that you have the convenience and confidence to develop and test in Windows or Linux-based environments and deploy your solution to a 100% compatible, fully supported, OpenJDK 8 on Red Hat Enterprise Linux.

Select all child elements recursively in CSS

Use a white space to match all descendants of an element:

div.dropdown * {
    color: red;
}

x y matches every element y that is inside x, however deeply nested it may be - children, grandchildren and so on.

The asterisk * matches any element.

Official Specification: CSS 2.1: Chapter 5.5: Descendant Selectors

Bootstrap 3 collapsed menu doesn't close on click

My menu is not a navbar standard one, but i managed to auto collapse mine, using an "onclick" function and a ".click()".

<div class="main-header">
    <div class="container">
        <div id="menu-wrapper">
            <div class="row">

                <div class="logo-wrapper col-lg-4 col-md-6 col-sm-7 hidden-xs">

                </div> <!-- /.logo-wrapper -->

                <div class="logo-wrapper2 visible-xs col-xs-9">

                </div> <!-- /.smaller logo-wrapper -->

                <div class="col-lg-8 col-md-6 col-sm-5 col-xs-3 main-menu text-center">
                    <ul class="menu-first hidden-md hidden-sm hidden-xs">
                        <li class="active"><a href="#">item1</a></li> |
                        <li><a href="#our-team">item2</a></li> |
                        <li><a href="#services">item3</a></li> |
                        <li><a href="#elia">item4</a></li> |
                        <li><a href="#portfolio">item5</a></li> |
                        <li><a href="#contact">item6</a></li>
                    </ul>
                    <a href="#" class="toggle-menu visible-md visible-sm visible-xs"><i class="fa fa-bars"></i></a>
                </div> <!-- /.main-menu -->
            </div> <!-- /.row -->
        </div> <!-- /#menu-wrapper -->
        <div class="menu-responsive hidden-lg">
            <ul>
                <li class="active" onclick = $(".toggle-menu").click();><a href="#">item1</a></li>
                <li><a href="#our-team" onclick = $(".toggle-menu").click();>item2</a></li>
                <li><a href="#services" onclick = $(".toggle-menu").click();>item3</a></li>
                <li><a href="#elia" onclick = $(".toggle-menu").click();>item4</a></li>
                <li><a href="#portfolio" onclick = $(".toggle-menu").click();>item5</a></li>
                <li><a href="#contact" onclick = $(".toggle-menu").click();>item6</a></li>
            </ul>
        </div> <!-- /.menu-responsive -->
    </div> <!-- /.container -->
</div> <!-- /.main-header 

How to split a string of space separated numbers into integers?

Given: text = "42 0"

import re
numlist = re.findall('\d+',text)

print(numlist)

['42', '0']

Ruby - ignore "exit" in code

loop {   begin     Bar.new   rescue SystemExit     p $!  #: #<SystemExit: exit>   end } 

This will print #<SystemExit: exit> in an infinite loop, without ever exiting.

jQuery-UI datepicker default date

$("#birthdate" ).datepicker("setDate", new Date(1985,01,01))

MySQL - Using If Then Else in MySQL UPDATE or SELECT Queries

Here's a query to update a table based on a comparison of another table. If record is not found in tableB, it will update the "active" value to "n". If it's found, will set the value to NULL

UPDATE tableA
LEFT JOIN tableB ON tableA.id = tableB.id
SET active = IF(tableB.id IS NULL, 'n', NULL)";

Hope this helps someone else.

What does the keyword Set actually do in VBA?

From MSDN:

Set Keyword: In VBA, the Set keyword is necessary to distinguish between assignment of an object and assignment of the default property of the object. Since default properties are not supported in Visual Basic .NET, the Set keyword is not needed and is no longer supported.

How do I get extra data from intent on Android?

//  How to send value using intent from one class to another class
//  class A(which will send data)
    Intent theIntent = new Intent(this, B.class);
    theIntent.putExtra("name", john);
    startActivity(theIntent);
//  How to get these values in another class
//  Class B
    Intent i= getIntent();
    i.getStringExtra("name");
//  if you log here i than you will get the value of i i.e. john

How can I toggle word wrap in Visual Studio?

In VS Code === Version: 1.52.1

  1. Open VS Code settings

  2. From the settings find the settings.json file and open it

  3. add this code - "editor.accessibilitySupport": "off"

If you already added "editor.accessibilitySupport" with the value "on" before then simply turn it to "off". This is the code worked for me when I faced the same problem while working with one of my JS Project.

how to mysqldump remote db from local machine

One can invoke mysqldump locally against a remote server.

Example that worked for me:

mysqldump -h hostname-of-the-server -u mysql_user -p database_name > file.sql

I followed the mysqldump documentation on connection options.

Injecting @Autowired private field during testing

Look at this link

Then write your test case as

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"/applicationContext.xml"})
public class MyLauncherTest{

@Resource
private MyLauncher myLauncher ;

   @Test
   public void someTest() {
       //test code
   }
}

Best way to return a value from a python script

If you want your script to return values, just do return [1,2,3] from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:

Return values (from a wrapping-function)

(again, this would have to be run by a separate Python script and be imported in order to even do any good):

import ...
def main():
    # calculate stuff
    return [1,2,3]

Exit codes as indicators

(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)

import sys
# calculate and stuff
sys.exit(100)

And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.

(os._exit(100) also works, and is a bit more forceful)

Stdout as your relay

If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.

import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)

Are you running your script in a controlled scheduling environment then exit codes are the best way to go.

Files as conveyors

There's also the option to simply write information to a file, and store the result there.

# calculate
with open('finish.txt', 'wb') as fh:
    fh.write(str(5)+'\n')

And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.

Sockets as conveyors

If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.

Does a "Find in project..." feature exist in Eclipse IDE?

First customize your search dialog. Ctrl+H. Click on the Customize button and select inly File Search while deselecting all the others. Close the dialog.

Now you can search by selecting the word and hitting the Ctrl+H and then Enter.

Using GitLab token to clone without authentication

You can do it like this:

git clone https://gitlab-ci-token:<private token>@git.example.com/myuser/myrepo.git

failed to push some refs to [email protected]

I'm the only person working on my app and only work on it from my desktop, so the possibility that I managed to get the heroku repository above dev didn't make sense. BUT! I recently had a Heroku support rep look into my heroku account for a cache issue involving gem installs and he had changed something that caused heroku to return the same error as the one listed above. A git pull heroku master was all it took. Then I found the reps minor change and reverted it myself.

JSON Parse File Path

Since it is in the directory data/, You need to do:

file path is '../../data/file.json'

$.getJSON('../../data/file.json', function(data) {         
    alert(data);
});

Pure JS:

   var request = new XMLHttpRequest();
   request.open("GET", "../../data/file.json", false);
   request.send(null)
   var my_JSON_object = JSON.parse(request.responseText);
   alert (my_JSON_object.result[0]);

How to run a single RSpec test?

Run the commands from your project's root directory:

# run all specs in the project's spec folder
bundle exec rspec 

# run specs nested under a directory, like controllers
bundle exec rspec spec/controllers

# run a single test file
bundle exec rspec spec/controllers/groups_controller_spec.rb

# run a test or subset of tests within a file
# e.g., if the 'it', 'describe', or 'context' block you wish to test
# starts at line 45, run:
bundle exec rspec spec/controllers/groups_controller_spec.rb:45

Is there a Python caching library?

You might also take a look at the Memoize decorator. You could probably get it to do what you want without too much modification.

How to remove items from a list while iterating?

for i in range(len(somelist) - 1, -1, -1):
    if some_condition(somelist, i):
        del somelist[i]

You need to go backwards otherwise it's a bit like sawing off the tree-branch that you are sitting on :-)

Python 2 users: replace range by xrange to avoid creating a hardcoded list

How to get href value using jQuery?

It works... Tested in IE8 (don't forget to allow javascript to run if you're testing the file from your computer) and chrome.

How to create bitmap from byte array?

In addition, you can simply convert byte array to Bitmap.

var bmp = new Bitmap(new MemoryStream(imgByte));

You can also get Bitmap from file Path directly.

Bitmap bmp = new Bitmap(Image.FromFile(filePath));

Can Google Chrome open local links?

The LocalLinks extension from the most popular answer didn't work for me (given, I was trying to use file:// to open a directory in windows explorer, not a file), so I looked into another workaround. I found that this "Open in IE" extension is a good workaround: https://chrome.google.com/webstore/detail/open-in-ie/iajffemldkkhodaedkcpnbpfabiglmdi

This isn't an ideal fix, as instead of clicking the link, users will have to right-click and choose Open in IE, but it at least makes the link functional.

One thing to note though, in IE10 (and IE9 after a certain update point) you will have to add the site to your Trusted Sites (Internet Options > Security > Trusted sites). If the site is not in trusted sites, the file:// link does not work in IE either.

Add support library to Android Studio project

This is way more simpler with Maven dependency feature:

  1. Open File -> Project Structure... menu.
  2. Select Modules in the left pane, choose your project's main module in the middle pane and open Dependencies tab in the right pane.
  3. Click the plus sign in the right panel and select "Maven dependency" from the list. A Maven dependency dialog will pop up.
  4. Enter "support-v4" into the search field and click the icon with magnifying glass.
  5. Select "com.google.android:support-v4:r7@jar" from the drop-down list.
  6. Click "OK".
  7. Clean and rebuild your project.

Hope this will help!

How to dismiss ViewController in Swift?

Since you used push presented viewController, therefore, you can use

self.dismiss(animated: false, completion: nil)

How do I disable a Button in Flutter?

Enable and Disable functionality is same for most of the widgets.

Ex, button , switch, checkbox etc.

Just set the onPressed property as shown below

onPressed : null returns Disabled widget

onPressed : (){} or onPressed : _functionName returns Enabled widget

Does my application "contain encryption"?

All of this can be very confusing for an app developer that's simply using TLS to connect to their own web servers. Because ATS (App Transport Security) is becoming more important and we are encouraged to convert everything to https - I think more developers are going to encounter this issue.

My app simply exchanges data between our server and the user using the https protocol. Seeing the words "USES ENCRYPTION" in the disclaimers is a bit scary so I gave the US government office a call at their office and spoke to a representative of the Bureau of Industry and Security (BIS) http://www.bis.doc.gov/index.php/about-bis/contact-bis.

The representative asked me about my app and since it passed the "primary function test" in that it had nothing to do with security/communications and simply uses https as a channel for connecting my customer data to our servers - it fell in the EAR99 category which means it's exempt from getting government permission (see https://www.bis.doc.gov/index.php/licensing/commerce-control-list-classification/export-control-classification-number-eccn)

I hope this helps other app developers.

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

Try wrapping your dates in single quotes, like this:

'15-6-2005'

It should be able to parse the date this way.

How to find the process id of a running Java process on Windows? And how to kill the process alone?

  1. Open Git Bash
  2. Type ps -ef | grep java
  3. Find the pid of running jdk
  4. kill -9 [pid]

PHP file_get_contents() and setting request headers

Using the php cURL libraries will probably be the right way to go, as this library has more features than the simple file_get_contents(...).

An example:

<?php
$ch = curl_init();
$headers = array('HTTP_ACCEPT: Something', 'HTTP_ACCEPT_LANGUAGE: fr, en, da, nl', 'HTTP_CONNECTION: Something');

curl_setopt($ch, CURLOPT_URL, "http://localhost"); # URL to post to
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 ); # return into a variable
curl_setopt($ch, CURLOPT_HTTPHEADER, $header ); # custom headers, see above
$result = curl_exec( $ch ); # run!
curl_close($ch);
?>

Multiple axis line chart in excel

There is a way of displaying 3 Y axis see here.

Excel supports Secondary Axis, i.e. only 2 Y axis. Other way would be to chart the 3rd one separately, and overlay on top of the main chart.

Find length (size) of an array in jquery

       var mode = [];
                $("input[name='mode[]']:checked").each(function(i) {
                    mode.push($(this).val());
                })
 if(mode.length == 0)
                {
                   alert('Please select mode!')
                };

Disallow Twitter Bootstrap modal window from closing

I believe you want to set the backdrop value to static. If you want to avoid the window to close when using the Esc key, you have to set another value.

Example:

<a data-controls-modal="your_div_id"
   data-backdrop="static"
   data-keyboard="false"
   href="#">

OR if you are using JavaScript:

$('#myModal').modal({
  backdrop: 'static',
  keyboard: false
});

How to Set Selected value in Multi-Value Select in Jquery-Select2.?

var valoresArea=VALUES
// it has the multiple values to set separated by comma
var arrayArea = valoresArea.split(',');
$('#area').select2('val',arrayArea);

How can I plot a confusion matrix?

enter image description here

you can use plt.matshow() instead of plt.imshow() or you can use seaborn module's heatmap (see documentation) to plot the confusion matrix

import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt
array = [[33,2,0,0,0,0,0,0,0,1,3], 
        [3,31,0,0,0,0,0,0,0,0,0], 
        [0,4,41,0,0,0,0,0,0,0,1], 
        [0,1,0,30,0,6,0,0,0,0,1], 
        [0,0,0,0,38,10,0,0,0,0,0], 
        [0,0,0,3,1,39,0,0,0,0,4], 
        [0,2,2,0,4,1,31,0,0,0,2],
        [0,1,0,0,0,0,0,36,0,2,0], 
        [0,0,0,0,0,0,1,5,37,5,1], 
        [3,0,0,0,0,0,0,0,0,39,0], 
        [0,0,0,0,0,0,0,0,0,0,38]]
df_cm = pd.DataFrame(array, index = [i for i in "ABCDEFGHIJK"],
                  columns = [i for i in "ABCDEFGHIJK"])
plt.figure(figsize = (10,7))
sn.heatmap(df_cm, annot=True)

Getting the first character of a string with $str[0]

$str = 'abcdef';
echo $str[0];                 // a

Register 32 bit COM DLL to 64 bit Windows 7

The problem is likely you try to register a 32-bit library with 64-bit version of regsvr32. See this KB article - you need to run regsvr32 from windows\SysWOW64 for 32-bit libraries.

django admin - add custom form fields that are not part of the model

Either in your admin.py or in a separate forms.py you can add a ModelForm class and then declare your extra fields inside that as you normally would. I've also given an example of how you might use these values in form.save():

from django import forms
from yourapp.models import YourModel


class YourModelForm(forms.ModelForm):

    extra_field = forms.CharField()

    def save(self, commit=True):
        extra_field = self.cleaned_data.get('extra_field', None)
        # ...do something with extra_field here...
        return super(YourModelForm, self).save(commit=commit)

    class Meta:
        model = YourModel

To have the extra fields appearing in the admin just:

  1. edit your admin.py and set the form property to refer to the form you created above
  2. include your new fields in your fields or fieldsets declaration

Like this:

class YourModelAdmin(admin.ModelAdmin):

    form = YourModelForm

    fieldsets = (
        (None, {
            'fields': ('name', 'description', 'extra_field',),
        }),
    )

UPDATE: In django 1.8 you need to add fields = '__all__' to the metaclass of YourModelForm.

What version of Python is on my Mac?

You could have multiple Python versions on your macOS.

You may check that by command, type or which command, like:

which -a python python2 python2.7 python3 python3.6

Or type python in Terminal and hit Tab few times for auto completion, which is equivalent to:

compgen -c python

By default python/pip commands points to the first binary found in PATH environment variable depending what's actually installed. So before installing Python packages with Homebrew, the default Python is installed in /usr/bin which is shipped with your macOS (e.g. Python 2.7.10 on High Sierra). Any versions found in /usr/local (such as /usr/local/bin) are provided by external packages.

It is generally advised, that when working with multiple versions, for Python 2 you may use python2/pip2 command, respectively for Python 3 you can use python3/pip3, but it depends on your configuration which commands are available.

It is also worth to mention, that since release of Homebrew 1.5.0+ (on 19 January 2018), the python formula has been upgraded to Python 3.x and a python@2 formula will be added for installing Python 2.7. Before, python formula was pointing to Python 2.

For instance, if you've installed different version via Homebrew, try the following command:

brew list python python3

or:

brew list | grep ^python

it'll show you all Python files installed with the package.

Alternatively you may use apropos or locate python command to locate more Python related files.

To check any environment variables related to Python, run:

env | grep ^PYTHON

To address your issues:

  • Error: No such keg: /usr/local/Cellar/python

    Means you don't have Python installed via Homebrew. However double check by specifying only one package at a time (like brew list python python2 python3).

  • The locate database (/var/db/locate.database) does not exist.

    Follow the advice and run:

    sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist
    

    After the database is rebuild, you can use locate command.

Which version of MVC am I using?

Select the System.Web.Mvc assembly in the "References" folder in the solution explorer. Bring up the properties window (F4) and check the Version

Reference Properties

Skipping Iterations in Python

Example for Continue:

number = 0

for number in range(10):
   number = number + 1

   if number == 5:
      continue    # continue here

   print('Number is ' + str(number))

print('Out of loop')

Output:

Number is 1
Number is 2
Number is 3
Number is 4
Number is 6 # Note: 5 is skipped!!
Number is 7
Number is 8
Number is 9
Number is 10
Out of loop

System not declared in scope?

Chances are that you've not included the header file that declares system().

In order to be able to compile C++ code that uses functions which you don't (manually) declare yourself, you have to pull in the declarations. These declarations are normally stored in so-called header files that you pull into the current translation unit using the #include preprocessor directive. As the code does not #include the header file in which system() is declared, the compilation fails.

To fix this issue, find out which header file provides you with the declaration of system() and include that. As mentioned in several other answers, you most likely want to add #include <cstdlib>

How do I close an open port from the terminal on the Mac?

To find the process try:

sudo lsof -i :portNumber

Kill the process which is currently using the port using its PID

kill PID

and then check to see if the port closed. If not, try:

kill -9 PID

I would only do the following if the previous didnt work

sudo kill -9 PID

Just to be safe. Again depending on how you opened the port, this may not matter.

C++ Cout & Cin & System "Ambiguous"

This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.

Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.

In this case I'd ask why you're including both cstdlib and stdlib.h; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib puts them in the namespace std in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!

Anyway, your use of using namespace std (which I would recommend against, in future) means that std::system from cstdlib now conflicts with system from stdlib.h. I can't explain what's going on with std::cout and std::cin.

Try removing #include <stdlib.h> and see what happens.

If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.

When 1 px border is added to div, Div size increases, Don't want to do that

.filter_list_button_remove {
    border: 1px solid transparent; 
    background-color: transparent;
}
.filter_list_button_remove:hover {
    border: 1px solid; 
}

Changing project port number in Visual Studio 2013

Well, I simply could not find this (for me) mythical "Use dynamic ports" option. I have post screenshots.

enter image description here

On a more constructive note, I believe that the port numbers are to be found in the solution file AND CRUCIALLY cross referenced against the IIS Express config file

C:\Users\<username>\Documents\IISExpress\config\applicationhost.config

I tried editing the port number in just the solution file but strange things happened. I propose (no time yet) that it needs a consistent edit across both the solution file and the config file.

JDBC connection to MSSQL server in windows authentication mode

From your exception trace, it looks like there is multiple possibility for this problem

1). You have to check that your port "1433" is blocked by firewall or not. If you find that it is blocked then you should have to write "Inbound Rule". It if found in control panel -> windows firewall -> Advance Setting (Option found at Left hand side) -> Inbound Rule.

2). In SQL Server configuration Manager, your TCP/IP protocol will find in disable mode. So, you should have to enable it.

Push Notifications in Android Platform

Firebase Cloud Messaging (FCM) is the new version of GCM. FCM is a cross-platform messaging solution that allows you to send messages securely and for free. Inherits GCM's central infrastructure to deliver messages reliably on Android, iOS, Web (javascript), Unity and C ++.

As of April 10, 2018, Google has disapproved of GCM. The GCM server and client APIs are deprecated and will be removed on April 11, 2019. Google recommends migrating GCM applications to Firebase Cloud Messaging (FCM), which inherits the reliable and scalable GCM infrastructure.

Resource

How can I tell if a DOM element is visible in the current viewport?

The most accepted answers don't work when zooming in Google Chrome on Android. In combination with Dan's answer, to account for Chrome on Android, visualViewport must be used. The following example only takes the vertical check into account and uses jQuery for the window height:

var Rect = YOUR_ELEMENT.getBoundingClientRect();
var ElTop = Rect.top, ElBottom = Rect.bottom;
var WindowHeight = $(window).height();
if(window.visualViewport) {
    ElTop -= window.visualViewport.offsetTop;
    ElBottom -= window.visualViewport.offsetTop;
    WindowHeight = window.visualViewport.height;
}
var WithinScreen = (ElTop >= 0 && ElBottom <= WindowHeight);

W3WP.EXE using 100% CPU - where to start?

If you identify a page that takes time to load, use SharePoint's Developer Dashboard to see which component takes time.

How can I add C++11 support to Code::Blocks compiler?

Use g++ -std=c++11 -o <output_file_name> <file_to_be_compiled>

Break a previous commit into multiple commits

git rebase --interactive can be used to split a commit into smaller commits. The Git docs on rebase have a concise walkthrough of the process - Splitting Commits:

In interactive mode, you can mark commits with the action "edit". However, this does not necessarily mean that git rebase expects the result of this edit to be exactly one commit. Indeed, you can undo the commit, or you can add other commits. This can be used to split a commit into two:

  • Start an interactive rebase with git rebase -i <commit>^, where <commit> is the commit you want to split. In fact, any commit range will do, as long as it contains that commit.

  • Mark the commit you want to split with the action "edit".

  • When it comes to editing that commit, execute git reset HEAD^. The effect is that the HEAD is rewound by one, and the index follows suit. However, the working tree stays the same.

  • Now add the changes to the index that you want to have in the first commit. You can use git add (possibly interactively) or git gui (or both) to do that.

  • Commit the now-current index with whatever commit message is appropriate now.

  • Repeat the last two steps until your working tree is clean.

  • Continue the rebase with git rebase --continue.

If you are not absolutely sure that the intermediate revisions are consistent (they compile, pass the testsuite, etc.) you should use git stash to stash away the not-yet-committed changes after each commit, test, and amend the commit if fixes are necessary.

Finding a substring within a list in Python

Use a simple for loop:

seq = ['abc123', 'def456', 'ghi789']
sub = 'abc'

for text in seq:
    if sub in text:
        print(text)

yields

abc123

Can I disable a CSS :hover effect via JavaScript?

Use a second class that has only the hover assigned:

HTML

 <a class="myclass myclass_hover" href="#">My anchor</a>

CSS

 .myclass { 
   /* all anchor styles */
 }
 .myclass_hover:hover {
   /* example color */
   color:#00A;
 }

Now you can use Jquery to remove the class, for instance if the element has been clicked:

JQUERY

 $('.myclass').click( function(e) {
    e.preventDefault();
    $(this).removeClass('myclass_hover');
 });

Hope this answer is helpful.

how to set default main class in java?

You can set the Main-Class attribute in the jar file's manifest to point to which file you want to run automatically.

How to call a JavaScript function from PHP?

I don't accept the naysayers' answers.

If you find some special package that makes it work, then you can do it yourself! So, I don't buy those answers.

onClick is a kludge that involves the end-user, hence not acceptable.

@umesh came close, but it was not a standalone program. Here is such (adapted from his Answer):

<script type="text/javascript">
function JSFunction() {
    alert('In test Function');   // This demonstrates that the function was called
}
</script>

<?php
// Call a JS function "from" php

if (true) {   // This if() is to point out that you might
              // want to call JSFunction conditionally
    // An echo like this is how you implant the 'call' in a way
    // that it will be invoked in the client.
    echo '<script type="text/javascript">
         JSFunction();
    </script>';
}

How to prevent line-break in a column of a table cell (not a single cell)?

Just add

style="white-space:nowrap;"

Example:

<table class="blueTable" style="white-space:nowrap;">
   <tr>
      <td>My name is good</td>
    </tr>
 </table>

Random float number generation

If you know that your floating point format is IEEE 754 (almost all modern CPUs including Intel and ARM) then you can build a random floating point number from a random integer using bit-wise methods. This should only be considered if you do not have access to C++11's random or Boost.Random which are both much better.

float rand_float()
{
    // returns a random value in the range [0.0-1.0)

    // start with a bit pattern equating to 1.0
    uint32_t pattern = 0x3f800000;

    // get 23 bits of random integer
    uint32_t random23 = 0x7fffff & (rand() << 8 ^ rand());

    // replace the mantissa, resulting in a number [1.0-2.0)
    pattern |= random23;

    // convert from int to float without undefined behavior
    assert(sizeof(float) == sizeof(uint32_t));
    char buffer[sizeof(float)];
    memcpy(buffer, &pattern, sizeof(float));
    float f;
    memcpy(&f, buffer, sizeof(float));

    return f - 1.0;
}

This will give a better distribution than one using division.

Keyboard shortcut to comment lines in Sublime Text 3

In case anyone has had further issues with Sublime 3 on Windows 7, the above suggestions all did not work for me. However, when I 1 - reran the app as administrator and 2 - highlighted, and chose Edit -> Comment -> toggle comment, afterwards I was able to use a user preferences set keybinding to toggle comments. I don't really have an explanation for why it worked, except that it did.

How to Solve Max Connection Pool Error

Check against any long running queries in your database.

Increasing your pool size will only make your webapp live a little longer (and probably get a lot slower)

You can use sql server profiler and filter on duration / reads to see which querys need optimization.

I also see you're probably keeping a global connection?

blnMainConnectionIsCreatedLocal

Let .net do the pooling for you and open / close your connection with a using statement.

Suggestions:

  1. Always open and close a connection like this, so .net can manage your connections and you won't run out of connections:

        using (SqlConnection conn = new SqlConnection(connectionString))
        {
         conn.Open();
         // do some stuff
        } //conn disposed
    
  2. As I mentioned, check your query with sql server profiler and see if you can optimize it. Having a slow query with many requests in a web app can give these timeouts too.

How to grep recursively, but only in files with certain extensions?

I am aware this question is a bit dated, but I would like to share the method I normally use to find .c and .h files:

tree -if | grep \\.[ch]\\b | xargs -n 1 grep -H "#include"

or if you need the line number as well:

tree -if | grep \\.[ch]\\b | xargs -n 1 grep -nH "#include"

How to make bootstrap column height to 100% row height?

You can solve that using display table.

Here is the updated JSFiddle that solves your problem.

CSS

.body {
    display: table;
    background-color: green;
}

.left-side {
    background-color: blue;
    float: none;
    display: table-cell;
    border: 1px solid;
}

.right-side {
    background-color: red;
    float: none;
    display: table-cell;
    border: 1px solid;
}

HTML

<div class="row body">
        <div class="col-xs-9 left-side">
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
        </div>
        <div class="col-xs-3 right-side">
            asdfdf
        </div>
    </div>

Replacing all non-alphanumeric characters with empty strings

Guava's CharMatcher provides a concise solution:

output = CharMatcher.javaLetterOrDigit().retainFrom(input);