Programs & Examples On #Business application

Remove border radius from Select tag in bootstrap 3

the class is called:

.form-control { border-radius: 0; }

be sure to insert the override after including bootstraps css.

If you ONLY want to remove the radius on select form-controls use

select.form-control { ... }

instead

EDIT: works for me on chrome, firefox, opera, and safari, IE9+ (all running on linux/safari & IE on playonlinux)

Extracting specific columns in numpy array

I assume you wanted columns 1 and 9?

To select multiple columns at once, use

X = data[:, [1, 9]]

To select one at a time, use

x, y = data[:, 1], data[:, 9]

With names:

data[:, ['Column Name1','Column Name2']]

You can get the names from data.dtype.names

Android : How to set onClick event for Button in List item of ListView

This has been discussed in many posts but still I could not figure out a solution with:

android:focusable="false"
android:focusableInTouchMode="false"
android:focusableInTouchMode="false"

Below solution will work with any of the ui components : Button, ImageButtons, ImageView, Textview. LinearLayout, RelativeLayout clicks inside a listview cell and also will respond to onItemClick:

Adapter class - getview():

    @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                view = lInflater.inflate(R.layout.my_ref_row, parent, false);
            }
            final Organization currentOrg = organizationlist.get(position).getOrganization();

            TextView name = (TextView) view.findViewById(R.id.name);
            Button btn = (Button) view.findViewById(R.id.btn_check);
            btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    context.doSelection(currentOrg);

                }
            });

       if(currentOrg.isSelected()){
            btn.setBackgroundResource(R.drawable.sub_search_tick);
        }else{
            btn.setBackgroundResource(R.drawable.sub_search_tick_box);
        }

    }

In this was you can get the button clicked object to the activity. (Specially when you want the button to act as a check box with selected and non-selected states):

    public void doSelection(Organization currentOrg) {
        Log.e("Btn clicked ", currentOrg.getOrgName());
        if (currentOrg.isSelected() == false) {
            currentOrg.setSelected(true);
        } else {
            currentOrg.setSelected(false);
        }
        adapter.notifyDataSetChanged();

    }

Displaying files (e.g. images) stored in Google Drive on a website

Solution provided by Niutech worked for me i.e.

http://googledrive.com/host/<folderID>/<filename>

But there are 2 outstanding issues

  1. You cannot have 2 files with the same name in the same folder in the drive else this link won't work.

  2. It is not yet clear but Google seems to be planning to deprecate image hosting via drive. please see the link below. https://support.google.com/richmedia/answer/6098968?hl=en

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

int(b, 2)  # Convert a binary string to a decimal int.

PHP - remove all non-numeric characters from a string

You can use preg_replace in this case;

$res = preg_replace("/[^0-9]/", "", "Every 6 Months" );

$res return 6 in this case.

If want also to include decimal separator or thousand separator check this example:

$res = preg_replace("/[^0-9.]/", "", "$ 123.099");

$res returns "123.099" in this case

Include period as decimal separator or thousand separator: "/[^0-9.]/"

Include coma as decimal separator or thousand separator: "/[^0-9,]/"

Include period and coma as decimal separator and thousand separator: "/[^0-9,.]/"

Firestore Getting documents id from collection

I've finally found the solution. Victor was close with the doc data.

const racesCollection: AngularFirestoreCollection<Race>;
return racesCollection.snapshotChanges().map(actions => {       
  return actions.map(a => {
    const data = a.payload.doc.data() as Race;
    data.id = a.payload.doc.id;
    return data;
  });
});

ValueChanges() doesn't include metadata, therefor we must use SnapshotChanges() when we require the document id and then map it properly as stated here https://github.com/angular/angularfire2/blob/master/docs/firestore/collections.md

PostgreSQL database default location on Linux

/var/lib/postgresql/[version]/data/

At least in Gentoo Linux and Ubuntu 14.04 by default.

You can find postgresql.conf and look at param data_directory. If it is commented then database directory is the same as this config file directory.

WPF binding to Listbox selectedItem

For me, I usually use DataContext together in order to bind two-depth property such as this question.

<TextBlock DataContext="{Binding SelectedRule}" Text="{Binding Name}" />

Or, I prefer to use ElementName because it achieves bindings only with view controls.

<TextBlock DataContext="{Binding ElementName=lbRules, Path=SelectedItem}" Text="{Binding Name}" />

jquery datatables default sort

This worked for me:

       jQuery('#tblPaging').dataTable({
            "sort": true,
            "pageLength": 20
        });

Selected value for JSP drop down using JSTL

Maybe I don't completely understand the accepted answer so it didn't work for me.

What i did was simply to check if the variable is null, assign it to a known value from my database. Which seems to be similar to the accepted answer whereby you first declare an known value and set it to selected

<select name="department">
    <c:forEach var="item" items="${dept}">
        <option value="${item.key}">${item.value}</option>
    </c:forEach>
</select>

because none of the options are selected, thus item = null

<%
    if(item == null){
        item = "selectedDept"; //known value from your database
    }
%>

This way if the user then selects another option, my IF clause will not catch it and assign to the fixed value that was declared at the start. My concept could be wrong here but it works for me

WPF Databinding: How do I access the "parent" data context?

This also works in Silverlight 5 (perhaps earlier as well but i haven't tested it). I used the relative source like this and it worked fine.

RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=telerik:RadGridView}"

How do Common Names (CN) and Subject Alternative Names (SAN) work together?

To be absolutely correct you should put all the names into the SAN field.

The CN field should contain a Subject Name not a domain name, but when the Netscape found out this SSL thing, they missed to define its greatest market. Simply there was not certificate field defined for the Server URL.

This was solved to put the domain into the CN field, and nowadays usage of the CN field is deprecated, but still widely used. The CN can hold only one domain name.

The general rules for this: CN - put here your main URL (for compatibility) SAN - put all your domain here, repeat the CN because its not in right place there, but its used for that...

If you found a correct implementation, the answers for your questions will be the followings:

  • Has this setup a special meaning, or any [dis]advantages over setting both CNs? You cant set both CNs, because CN can hold only one name. You can make with 2 simple CN certificate instead one CN+SAN certificate, but you need 2 IP addresses for this.

  • What happens on server-side if the other one, host.domain.tld, is being requested? It doesn't matter whats happen on server side.

In short: When a browser client connects to this server, then the browser sends encrypted packages, which are encrypted with the public key of the server. Server decrypts the package, and if server can decrypt, then it was encrypted for the server.

The server doesn't know anything from the client before decrypt, because only the IP address is not encrypted trough the connection. This is why you need 2 IPs for 2 certificates. (Forget SNI, there is too much XP out there still now.)

On client side the browser gets the CN, then the SAN until all of the are checked. If one of the names matches for the site, then the URL verification was done by the browser. (im not talking on the certificate verification, of course a lot of ocsp, crl, aia request and answers travels on the net every time.)

LinearLayout not expanding inside a ScrollView

The solution is to use

android:fillViewport="true"

on Scroll view and moreover try to use

"wrap_content" instead of "fill_parent" as "fill_parent"

is deprecated now.

center a row using Bootstrap 3

What you are doing is not working, because you apply the margin: auto to the full-width column.

Wrap it in a div and center that one. E.g:

<div class="i-am-centered">
  <div class="row">...</div>
</div>

.

.i-am-centered { margin: auto; max-width: 300px;}

http://www.bootply.com/93751

Its a cleaner solution anyway, as it is more expressive and as you usually don't want to mess with the grid.

Multiline strings in VB.NET

Multi-line strings are available since the Visual Studio 2015.

Dim sql As String = "
    SELECT ID, Description
    FROM inventory
    ORDER BY DateAdded
"

You can combine them with string interpolation to maximize usefullness:

Dim primaryKey As String = "ID"
Dim inventoryTable As String = "inventory"

Dim sql As String = $"
    SELECT {primaryKey}, Description
    FROM {inventoryTable}
    ORDER BY DateAdded
"

Note that interpolated strings begin with $ and you need to take care of ", { and } contained inside – convert them into "", {{ or }} respectively.

Here you can see actual syntax highlighting of interpolated parts of the above code example:

enter image description here

If you wonder if their recognition by the Visual Studio editor also works with refactoring (e.g. mass-renaming the variables), then you are right, code refactoring works with these. Not mentioning that they also support IntelliSense, reference counting or code analysis.

C#: How do you edit items and subitems in a listview?

Click the items in the list view. Add a button that will edit the selected items. Add the code

try
{              
    LSTDEDUCTION.SelectedItems[0].SubItems[1].Text = txtcarName.Text;
    LSTDEDUCTION.SelectedItems[0].SubItems[0].Text = txtcarBrand.Text;
    LSTDEDUCTION.SelectedItems[0].SubItems[2].Text = txtCarName.Text;
}
catch{}

ASP.NET MVC Html.ValidationSummary(true) does not display model errors

You can try,

<div asp-validation-summary="All" class="text-danger"></div>

Reading CSV file and storing values into an array

I usually use this parser from codeproject, since there's a bunch of character escapes and similar that it handles for me.

How to generate Class Diagram (UML) on Android Studio (IntelliJ Idea)

Update 24.3.2016

I have found this guide from VP https://knowhow.visual-paradigm.com/technical-support/running-vp-in-android-studio/ created on September 8, 2015.

Good to know - it is possible to integrate VP into Android studio (in my case 1.5.1) now. Do not forget to backup your Android Studio settings (you can find them in Users%userName/.AndroidStudioX.X on Windows) ahead of installation.

I was trying to make it work, but created vp project did not contain any diagrams. Maybe someone else will have more luck.


I was using this manual http://www.visual-paradigm.com/support/documents/vpuserguide/2381/2385/66578_creatingauml.html to make Visual Paradigm working in Android studio, but action in 2. did not invoke dialogue in 3. So I Have asked Visual Paradigm support for help and they replied that Android Studio integration is not supported right now.

Reply from Visual paradigm reply from Apr 17 2015:

Thank you for your inquiry and I'm very sorry that at the moment we only support integrate with the standard IntelliJ IDEA, but not integrate with the Android Studio. We may consider to support it in our future release, and I'll keep you post once there any update on this topics. Feel free to contact me for any questions and wish you have a good day!

This post was deleted, so I will try to make it more clear.

As such I am considering previous answers as misleading and not useful. Therefore I thing that it is important for others to know that, before they lose their time trying to make it working.

Ruby String to Date Conversion

str = "Tue, 10 Aug 2010 01:20:19 -0400 (EDT)"
str.to_date
=> Tue, 10 Aug 2010

What is JSON and why would I use it?

The JSON format is often used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML.

Get value of c# dynamic property via string

d.GetType().GetProperty("value2")

returns a PropertyInfo object.

So then do

propertyInfo.GetValue(d)

How do you declare string constants in C?

One advantage (albeit very slight) of defining string constants is that you can concatenate them at compile time:

#define HELLO "hello"
#define WORLD "world"

puts( HELLO WORLD );

Not sure that's really an advantage, but it is a technique that cannot be used with const char *'s.

How to make a rest post call from ReactJS code?

Straight from the React docs:

fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  })
})

(This is posting JSON, but you could also do, for example, multipart-form.)

"The POM for ... is missing, no dependency information available" even though it exists in Maven Repository

In my case the reason was since the remote repo artifact (non-central) had dependencies from the Maven Central in the .pom file, and the older version of mvn (older than 3.6.0) was used. So, it tried to check the Maven Central artifacts mentioned in the remote repo's .pom for the specific artifact I've added to my dependencies and faced the Maven Central http access issue behind the scenes (I believe the same as described there: Maven dependencies are failing with a 501 error - that is about using https access to Maven Central by default and prohibiting the http access).

Using more recent Maven (from 3.1 to 3.6.0) made it use https to check Maven Central repo dependencies mentioned in the .pom files of the remote repositories and I no longer face the issue.

how to concatenate two dictionaries to create a new one in Python?

Use the dict constructor

d1={1:2,3:4}
d2={5:6,7:9}
d3={10:8,13:22}

d4 = reduce(lambda x,y: dict(x, **y), (d1, d2, d3))

As a function

from functools import partial
dict_merge = partial(reduce, lambda a,b: dict(a, **b))

The overhead of creating intermediate dictionaries can be eliminated by using thedict.update() method:

from functools import reduce
def update(d, other): d.update(other); return d
d4 = reduce(update, (d1, d2, d3), {})

Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH

It could be even caused by your ad blocker.

Try to disable it or adding an exception for the domain from which the images come from.

Could not load type 'XXX.Global'

This one drove me completely insane and I couldn't find anything helpful to solve it. This is probably not the reason most people have this issue but I just hope that someone else will benefit from this answer.

What caused my problem was a <clear /> statement in the <assemblies> config section. I had added this because in production it had been required because there were multiple unrelated applications on the same hosting plan and I didn't want any of them to be affected by others. The more correct solution would have been to have just used web config transforms on publish.

Hope this helps someone else!

IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

create schema tableName authorization dbo
go
IF OBJECT_ID ('tableName.put_fieldValue', 'P' ) IS NOT NULL 
drop proc tableName.put_fieldValue
go
create proc tableName.put_fieldValue(@fieldValue int) as
declare @tableid int = 0
select @tableid = tableid from table where fieldValue=''
if @tableid = 0 begin
   insert into table(fieldValue) values('')
   select @tableid = scope_identity()
end
return @tableid
go
declare @tablid int = 0
exec @tableid = tableName.put_fieldValue('')

Use string contains function in oracle SQL query

By lines I assume you mean rows in the table person. What you're looking for is:

select p.name
from   person p
where  p.name LIKE '%A%'; --contains the character 'A'

The above is case sensitive. For a case insensitive search, you can do:

select p.name
from   person p
where  UPPER(p.name) LIKE '%A%'; --contains the character 'A' or 'a'

For the special character, you can do:

select p.name
from   person p
where  p.name LIKE '%'||chr(8211)||'%'; --contains the character chr(8211)

The LIKE operator matches a pattern. The syntax of this command is described in detail in the Oracle documentation. You will mostly use the % sign as it means match zero or more characters.

Create a git patch from the uncommitted changes in the current working directory

To create a patch with both modified & new files (staged) you can run:

git diff HEAD > file_name.patch

Is object empty?

here my solution

function isEmpty(value) {
    if(Object.prototype.toString.call(value) === '[object Array]') {
        return value.length == 0;
    } else if(value != null && typeof value === 'object') {
        return Object.getOwnPropertyNames(value).length  == 0;
    } else {
        return !(value || (value === 0));
    }
}

Chears

Is it possible to decrypt MD5 hashes?

MD5 is a hashing algorithm, you can not revert the hash value.

You should add "change password feature", where the user gives another password, calculates the hash and store it as a new password.

How do I detect IE 8 with jQuery?

document.documentMode is undefined if the browser is not IE8,

it returns 8 for standards mode and 7 for 'compatable to IE7'

If it is running as IE7 there are a lot of css and dom features that won't be supported.

How does a Java HashMap handle different objects with the same hash code?

A hashmap works like this (this is a little bit simplified, but it illustrates the basic mechanism):

It has a number of "buckets" which it uses to store key-value pairs in. Each bucket has a unique number - that's what identifies the bucket. When you put a key-value pair into the map, the hashmap will look at the hash code of the key, and store the pair in the bucket of which the identifier is the hash code of the key. For example: The hash code of the key is 235 -> the pair is stored in bucket number 235. (Note that one bucket can store more then one key-value pair).

When you lookup a value in the hashmap, by giving it a key, it will first look at the hash code of the key that you gave. The hashmap will then look into the corresponding bucket, and then it will compare the key that you gave with the keys of all pairs in the bucket, by comparing them with equals().

Now you can see how this is very efficient for looking up key-value pairs in a map: by the hash code of the key the hashmap immediately knows in which bucket to look, so that it only has to test against what's in that bucket.

Looking at the above mechanism, you can also see what requirements are necessary on the hashCode() and equals() methods of keys:

  • If two keys are the same (equals() returns true when you compare them), their hashCode() method must return the same number. If keys violate this, then keys that are equal might be stored in different buckets, and the hashmap would not be able to find key-value pairs (because it's going to look in the same bucket).

  • If two keys are different, then it doesn't matter if their hash codes are the same or not. They will be stored in the same bucket if their hash codes are the same, and in this case, the hashmap will use equals() to tell them apart.

Remove all HTMLtags in a string (with the jquery text() function)

I found in my specific case that I just needed to trim the content. Maybe not the answer asked in the question. But I thought I should add this answer anyway.

$(myContent).text().trim()

Receiving "Attempted import error:" in react app

i had the same issue, but I just typed export on top and erased the default one on the bottom. Scroll down and check the comments.

import React, { Component } from "react";

export class Counter extends Component { // type this  
export default Counter; // this is eliminated  

How to get a thread and heap dump of a Java process on Windows that's not running in a console

You can use jmap to get a dump of any process running, assuming you know the pid.

Use Task Manager or Resource Monitor to get the pid. Then

jmap -dump:format=b,file=cheap.hprof <pid>

to get the heap for that process.

How to use ADB in Android Studio to view an SQLite DB

Depending on devices you might not find sqlite3 command in adb shell. In that case you might want to follow this :

adb shell

$ run-as package.name
$ cd ./databases/
$ ls -l #Find the current permissions - r=4, w=2, x=1
$ chmod 666 ./dbname.db
$ exit
$ exit
adb pull /data/data/package.name/databases/dbname.db ~/Desktop/
adb push ~/Desktop/dbname.db /data/data/package.name/databases/dbname.db
adb shell
$ run-as package.name
$ chmod 660 ./databases/dbname.db #Restore original permissions
$ exit
$ exit

for reference go to https://stackoverflow.com/a/17177091/3758972.

There might be cases when you get "remote object not found" after following above procedure. Then change permission of your database folder to 755 in adb shell.

$ chmod 755 databases/

But please mind that it'll work only on android version < 21.

Entity Framework: One Database, Multiple DbContexts. Is this a bad idea?

Reminder: If you do combine multiple contexts make sure you cut n paste all the functionality in your various RealContexts.OnModelCreating() into your single CombinedContext.OnModelCreating().

I just wasted time hunting down why my cascade delete relationships weren't being preserved only to discover that I hadn't ported the modelBuilder.Entity<T>()....WillCascadeOnDelete(); code from my real context into my combined context.

Resolve host name to an ip address

This is hard to answer without more detail about the network architecture. Some things to investigate are:

  • Is it possible that client and/or server is behind a NAT device, a firewall, or similar?
  • Is any of the IP addresses involved a "local" address, like 192.168.x.y or 10.x.y.z?
  • What are the host names, are they "real" DNS:able names or something more local and/or Windows-specific?
  • How does the client look up the server? There must be a place in code or config data that holds the host name, simply try using the IP there instead if you want to avoid the lookup.

npm ERR! network getaddrinfo ENOTFOUND

Instead of setting the proxy usingnpm config set http_proxy=http://address:8080 go to ~/.npmrc and remove the proxy config. This resolved my issue.

How To Save Canvas As An Image With canvas.toDataURL()?

I created a small library that does this (along with some other handy conversions). It's called reimg, and it's really simple to use.

ReImg.fromCanvas(yourCanvasElement).toPng()

ORDER BY using Criteria API

For Hibernate 5.2 and above, use CriteriaBuilder as follows

CriteriaBuilder builder = sessionFactory.getCriteriaBuilder();
CriteriaQuery<Cat> query = builder.createQuery(Cat.class);
Root<Cat> rootCat = query.from(Cat.class);
Join<Cat,Mother> joinMother = rootCat.join("mother");  // <-attribute name
Join<Mother,Kind> joinMotherKind = joinMother.join("kind");
query.select(rootCat).orderBy(builder.asc(joinMotherKind.get("value")));
Query<Cat> q = sessionFactory.getCurrentSession().createQuery(query);
List<Cat> cats = q.getResultList();

Row count on the Filtered data

Rowz = Application.WorksheetFunction.Subtotal(2, Range("A2:A" & Rows(Rows.Count).End(xlUp).Row))

This worked for me quite well

This app won't run unless you update Google Play Services (via Bazaar)

This app won't run unless you update Google Play Services. I have tried it for such a long much time, but still I didn't get the map... Only a blank screen is appearing, even if I modified my Google Play Service given by the below comment..


Check your play services manifest file and check the version code for the APK file com.google.android.gms. In the below, it is "3136110". Download these APK files and install from a DOS prompt, but before installation run your target emulator.

package="com.google.android.gms"
android:versionCode="3136110"
android:versionName="3.1.36 (673201-10)

I got these APK files from this link.

Send HTTP GET request with header

You do it exactly as you showed with this line:

get.setHeader("Content-Type", "application/x-zip");

So your header is fine and the problem is some other input to the web service. You'll want to debug that on the server side.

Can you have multiple $(document).ready(function(){ ... }); sections?

It's legal, but sometimes it cause undesired behaviour. As an Example I used the MagicSuggest library and added two MagicSuggest inputs in a page of my project and used seperate document ready functions for each initializations of inputs. The very first Input initialization worked, but not the second one and also not giving any error, Second Input didn't show up. So, I always recommend to use one Document Ready Function.

Looping Over Result Sets in MySQL

Something like this should do the trick (However, read after the snippet for more info)

CREATE PROCEDURE GetFilteredData()
BEGIN
  DECLARE bDone INT;

  DECLARE var1 CHAR(16);    -- or approriate type
  DECLARE Var2 INT;
  DECLARE Var3 VARCHAR(50);

  DECLARE curs CURSOR FOR  SELECT something FROM somewhere WHERE some stuff;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;

  DROP TEMPORARY TABLE IF EXISTS tblResults;
  CREATE TEMPORARY TABLE IF NOT EXISTS tblResults  (
    --Fld1 type,
    --Fld2 type,
    --...
  );

  OPEN curs;

  SET bDone = 0;
  REPEAT
    FETCH curs INTO var1,, b;

    IF whatever_filtering_desired
       -- here for whatever_transformation_may_be_desired
       INSERT INTO tblResults VALUES (var1, var2, var3 ...);
    END IF;
  UNTIL bDone END REPEAT;

  CLOSE curs;
  SELECT * FROM tblResults;
END

A few things to consider...

Concerning the snippet above:

  • may want to pass part of the query to the Stored Procedure, maybe particularly the search criteria, to make it more generic.
  • If this method is to be called by multiple sessions etc. may want to pass a Session ID of sort to create a unique temporary table name (actually unnecessary concern since different sessions do not share the same temporary file namespace; see comment by Gruber, below)
  • A few parts such as the variable declarations, the SELECT query etc. need to be properly specified

More generally: trying to avoid needing a cursor.

I purposely named the cursor variable curs[e], because cursors are a mixed blessing. They can help us implement complicated business rules that may be difficult to express in the declarative form of SQL, but it then brings us to use the procedural (imperative) form of SQL, which is a general feature of SQL which is neither very friendly/expressive, programming-wise, and often less efficient performance-wise.

Maybe you can look into expressing the transformation and filtering desired in the context of a "plain" (declarative) SQL query.

Most efficient way to prepend a value to an array

I'm not sure about more efficient in terms of big-O but certainly using the unshift method is more concise:

var a = [1, 2, 3, 4];
a.unshift(0);
a; // => [0, 1, 2, 3, 4]

[Edit]

This jsPerf benchmark shows that unshift is decently faster in at least a couple of browsers, regardless of possibly different big-O performance if you are ok with modifying the array in-place. If you really can't mutate the original array then you would do something like the below snippet, which doesn't seem to be appreciably faster than your solution:

a.slice().unshift(0); // Use "slice" to avoid mutating "a".

[Edit 2]

For completeness, the following function can be used instead of OP's example prependArray(...) to take advantage of the Array unshift(...) method:

function prepend(value, array) {
  var newArray = array.slice();
  newArray.unshift(value);
  return newArray;
}

var x = [1, 2, 3];
var y = prepend(0, x);
y; // => [0, 1, 2, 3];
x; // => [1, 2, 3];

Boolean Field in Oracle

Either 1/0 or Y/N with a check constraint on it. ether way is fine. I personally prefer 1/0 as I do alot of work in perl, and it makes it really easy to do perl Boolean operations on database fields.

If you want a really in depth discussion of this question with one of Oracles head honchos, check out what Tom Kyte has to say about this Here

Set height of chart in Chart.js

Just to add on to the answer given by @numediaweb

In case you're banging your head against the wall because after following the instructions to set maintainAspectRatio=false: I originally copied my code from an example I got on a website on using Chart.js with Angular 2+:

        <div style="display: block">
          <canvas baseChart
                  [datasets]="chartData"
                  [labels]="chartLabels"
                  [options]="chartOptions"
                  [legend]="chartLegend"
                  [colors]="chartColors"
                  [chartType]="chartType">
          </canvas>
        </div>

To make this work correctly you must remove the embedded (and unnecessary) style="display: block" Instead define a class for the enclosing div, and define its height in CSS.

Once you do that, the chart should have responsive width but fixed height.

What are the date formats available in SimpleDateFormat class?

Date and time formats are well described below

SimpleDateFormat (Java Platform SE 7) - Date and Time Patterns

There could be n Number of formats you can possibly make. ex - dd/MM/yyyy or YYYY-'W'ww-u or you can mix and match the letters to achieve your required pattern. Pattern letters are as follow.

  • G - Era designator (AD)
  • y - Year (1996; 96)
  • Y - Week Year (2009; 09)
  • M - Month in year (July; Jul; 07)
  • w - Week in year (27)
  • W - Week in month (2)
  • D - Day in year (189)
  • d - Day in month (10)
  • F - Day of week in month (2)
  • E - Day name in week (Tuesday; Tue)
  • u - Day number of week (1 = Monday, ..., 7 = Sunday)
  • a - AM/PM marker
  • H - Hour in day (0-23)
  • k - Hour in day (1-24)
  • K - Hour in am/pm (0-11)
  • h - Hour in am/pm (1-12)
  • m - Minute in hour (30)
  • s - Second in minute (55)
  • S - Millisecond (978)
  • z - General time zone (Pacific Standard Time; PST; GMT-08:00)
  • Z - RFC 822 time zone (-0800)
  • X - ISO 8601 time zone (-08; -0800; -08:00)

To parse:

2000-01-23T04:56:07.000+0000

Use: new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

How to redirect to Index from another controller?

You can use local redirect. Following codes are jumping the HomeController's Index page:

public class SharedController : Controller
    {
        // GET: /<controller>/
        public IActionResult _Layout(string btnLogout)
        {
            if (btnLogout != null)
            {
                return LocalRedirect("~/Index");
            }

            return View();
        }
}

How to find a Java Memory Leak

You really need to use a memory profiler that tracks allocations. Take a look at JProfiler - their "heap walker" feature is great, and they have integration with all of the major Java IDEs. It's not free, but it isn't that expensive either ($499 for a single license) - you will burn $500 worth of time pretty quickly struggling to find a leak with less sophisticated tools.

Page redirect with successful Ajax request

Another option is:

window.location.replace("your_url")

urllib2 and json

This is what worked for me:

import json
import requests
url = 'http://xxx.com'
payload = {'param': '1', 'data': '2', 'field': '4'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data = json.dumps(payload), headers = headers)

How to launch another aspx web page upon button click?

You should use:

protected void btn1_Click(object sender, EventArgs e)
{
    Response.Redirect("otherpage.aspx");
}

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

Once I also got that same type of error.

I.E:

C:\oracle\product\10.2.0\db_2>SQLPLUS SYS AS SYSDBA
Error 6 initializing SQL*Plus
Message file sp1<lang>.msb not found
SP2-0750: You may need to set ORACLE_HOME to your Oracle software directory

This error is occurring as the home path is not correctly set. To rectify this, if you are using Windows, run the below query:

C:\oracle\product\10.2.0\db_2>SET ORACLE_HOME=C:\oracle\product\10.2.0\db_2
C:\oracle\product\10.2.0\db_2>SQLPLUS SYS AS SYSDBA

SQL*Plus: Release 10.2.0.3.0 - Production on Tue Apr 16 13:17:42 2013

Copyright (c) 1982, 2006, Oracle.  All Rights Reserved.

Or if you are using Linux, then replace set with export for the above command like so:

C:\oracle\product\10.2.0\db_2>EXPORT ORACLE_HOME='C:\oracle\product\10.2.0\db_2'
C:\oracle\product\10.2.0\db_2>SQLPLUS SYS AS SYSDBA

SQL*Plus: Release 10.2.0.3.0 - Production on Tue Apr 16 13:17:42 2013

Copyright (c) 1982, 2006, Oracle.  All Rights Reserved.

Oracle query to fetch column names

The only way that I was able to get the column names was using the following query:

select COLUMN_NAME
FROM all_tab_columns atc
WHERE table_name like 'USERS'

get basic SQL Server table structure information

For total columns information use below syntax : Use "DBName" go Exec SP_Columns "TableName"

For total table information use below syntax : Use "DBName" go Exec SP_help "Table Name"

Java: Multiple class declarations in one file

According to Effective Java 2nd edition (Item 13):

"If a package-private top-level class (or interface) is used by only one class, consider making the top-level class a private nested class of the sole class that uses it (Item 22). This reduces its accessibility from all the classes in its package to the one class that uses it. But it is far more important to reduce the accessibility of a gratuitously public class than a package-private top-level class: ... "

The nested class may be static or non-static based on whether the member class needs access to the enclosing instance (Item 22).

import error: 'No module named' *does* exist

If you have a script with the same name as your module in another directory, it will use that instead. For example:

module.py

module
|
|--module
|  |
|  |--__init__.py
|  |--module.py

This will make it so that the first module.py is being used, not the second one.

Importing PNG files into Numpy?

I changed a bit and it worked like this, dumped into one single array, provided all the images are of same dimensions.

png = []
for image_path in glob.glob("./train/*.png"):
    png.append(misc.imread(image_path))    

im = np.asarray(png)

print 'Importing done...', im.shape

Redirect stderr to stdout in C shell

I think this is the correct answer for csh.

xxx >/dev/stderr

Note most csh are really tcsh in modern environments:

rmockler> ls -latr /usr/bin/csh

lrwxrwxrwx 1 root root 9 2011-05-03 13:40 /usr/bin/csh -> /bin/tcsh

using a backtick embedded statement to portray this as follows:

echo "`echo 'standard out1'` `echo 'error out1' >/dev/stderr` `echo 'standard out2'`" | tee -a /tmp/test.txt ; cat /tmp/test.txt

if this works for you please bump up to 1. The other suggestions don't work for my csh environment.

How to change the default message of the required field in the popover of form-control in bootstrap?

Combination of Mritunjay and Bartu's answers are full answer to this question. I copying the full example.

<input class="form-control" type="email"  required="" placeholder="username"
 oninvalid="this.setCustomValidity('Please Enter valid email')"
 oninput="setCustomValidity('')"></input>

Here,

this.setCustomValidity('Please Enter valid email')" - Display the custom message on invalidated of the field

oninput="setCustomValidity('')" - Remove the invalidate message on validated filed.

How to use onSavedInstanceState example please

If Data Is not Loaded From savedInstanceState use following code.
The problem is url call is not to complete fully so, check if data is loaded then to show the instanceState value.

//suppose data is not Loaded to savedInstanceState at 1st swipe
if (savedInstanceState == null && !mAlreadyLoaded){
    mAlreadyLoaded = true;
    GetStoryData();//Url Call
} else {
    if (listArray != null) {  //Data Array From JsonArray(ListArray)
        System.out.println("LocalData  " + listArray);
        view.findViewById(R.id.progressBar).setVisibility(View.GONE);
    }else{
        GetStoryData();//Url Call
    }
}

How to support placeholder attribute in IE8 and 9

You could use this jQuery plugin: https://github.com/mathiasbynens/jquery-placeholder

But your link seems to be also a good solution.

Is there a way to add/remove several classes in one single instruction with classList?

The standard definiton allows only for adding or deleting a single class. A couple of small wrapper functions can do what you ask :

function addClasses (el, classes) {
  classes = Array.prototype.slice.call (arguments, 1);
  console.log (classes);
  for (var i = classes.length; i--;) {
    classes[i] = classes[i].trim ().split (/\s*,\s*|\s+/);
    for (var j = classes[i].length; j--;)
      el.classList.add (classes[i][j]);
  }
}

function removeClasses (el, classes) {
  classes = Array.prototype.slice.call (arguments, 1);
  for (var i = classes.length; i--;) {
    classes[i] = classes[i].trim ().split (/\s*,\s*|\s+/);
    for (var j = classes[i].length; j--;)
      el.classList.remove (classes[i][j]);
  }
}

These wrappers allow you to specify the list of classes as separate arguments, as strings with space or comma separated items, or a combination. For an example see http://jsfiddle.net/jstoolsmith/eCqy7

Regex allow a string to only contain numbers 0 - 9 and limit length to 45

The first matches any number of digits within your string (allows other characters too, i.e.: "039330a29"). The second allows only 45 digits (and not less). So just take the better from both:

^\d{1,45}$

where \d is the same like [0-9].

HTML table with horizontal scrolling (first column fixed)

Based on skube's approach, I found the minimal set of CSS I needed was:

_x000D_
_x000D_
.horizontal-scroll-except-first-column {_x000D_
  width: 100%;_x000D_
  overflow: auto;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table {_x000D_
  margin-left: 8em;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table > * > tr > th:first-child,_x000D_
.horizontal-scroll-except-first-column > table > * > tr > td:first-child {_x000D_
  position: absolute;_x000D_
  width: 8em;_x000D_
  margin-left: -8em;_x000D_
  background: #ccc;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table > * > tr > th,_x000D_
.horizontal-scroll-except-first-column > table > * > tr > td {_x000D_
  /* Without this, if a cell wraps onto two lines, the first column_x000D_
   * will look bad, and may need padding. */_x000D_
  white-space: nowrap;_x000D_
}
_x000D_
<div class="horizontal-scroll-except-first-column">_x000D_
  <table>_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>FIXED</td> <td>22222</td> <td>33333</td> <td>44444</td> <td>55555</td> <td>66666</td> <td>77777</td> <td>88888</td> <td>99999</td> <td>AAAAA</td> <td>BBBBB</td> <td>CCCCC</td> <td>DDDDD</td> <td>EEEEE</td> <td>FFFFF</td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

The response content cannot be parsed because the Internet Explorer engine is not available, or

In your invoke web request just use the parameter -UseBasicParsing

e.g. in your script (line 2) you should use:

$rss = Invoke-WebRequest -UseBasicParsing

According to the documentation, this parameter is necessary on systems where IE isn't installed or configured.

Uses the response object for HTML content without Document Object Model (DOM) parsing. This parameter is required when Internet Explorer is not installed on the computers, such as on a Server Core installation of a Windows Server operating system.

static function in C

When there is a need to restrict access to some functions, we'll use the static keyword while defining and declaring a function.

            /* file ab.c */ 
static void function1(void) 
{ 
  puts("function1 called"); 
} 
And store the following code in another file ab1.c

/* file ab1.c  */ 
int main(void) 
{ 
 function1();  
  getchar(); 
  return 0;   
} 
/* in this code, we'll get a "Undefined reference to function1".Because function 1 is declared static in file ab.c and can't be used in ab1.c */

How to force a hover state with jQuery?

You will have to use a class, but don't worry, it's pretty simple. First we'll assign your :hover rules to not only apply to physically-hovered links, but also to links that have the classname hovered.

a:hover, a.hovered { color: #ccff00; }

Next, when you click #btn, we'll toggle the .hovered class on the #link.

$("#btn").click(function() {
   $("#link").toggleClass("hovered");
});

If the link has the class already, it will be removed. If it doesn't have the class, it will be added.

How to encode a URL in Swift

XCODE 8, SWIFT 3.0

From grokswift

Creating URLs from strings is a minefield for bugs. Just miss a single / or accidentally URL encode the ? in a query and your API call will fail and your app won’t have any data to display (or even crash if you didn’t anticipate that possibility). Since iOS 8 there’s a better way to build URLs using NSURLComponents and NSURLQueryItems.

func createURLWithComponents() -> URL? {
    var urlComponents = URLComponents()
    urlComponents.scheme = "http"
    urlComponents.host = "maps.googleapis.com"
    urlComponents.path = "/maps/api/geocode/json"

    let addressQuery = URLQueryItem(name: "address", value: "American Tourister, Abids Road, Bogulkunta, Hyderabad, Andhra Pradesh, India")
    urlComponents.queryItems = [addressQuery]

    return urlComponents.url
}

Below is the code to access url using guard statement.

guard let url = createURLWithComponents() else {
            print("invalid URL")
            return nil
      }
      print(url)

Output:

http://maps.googleapis.com/maps/api/geocode/json?address=American%20Tourister,%20Abids%20Road,%20Bogulkunta,%20Hyderabad,%20Andhra%20Pradesh,%20India

Read More: Building URLs With NSURLComponents and NSURLQueryItems

How to join entries in a set into one string?

You have the join statement backwards try:

print ', '.join(set_3)

In jQuery, what's the best way of formatting a number to 2 decimal places?

Maybe something like this, where you could select more than one element if you'd like?

$("#number").each(function(){
    $(this).val(parseFloat($(this).val()).toFixed(2));
});

Parsing JSON in Excel VBA

Thanks a lot Codo.

I've just updated and completed what you have done to :

  • serialize the json (I need it to inject the json in a text-like document)
  • add, remove and update node (who knows)

    Option Explicit
    
    Private ScriptEngine As ScriptControl
    
    Public Sub InitScriptEngine()
        Set ScriptEngine = New ScriptControl
        ScriptEngine.Language = "JScript"
        ScriptEngine.AddCode "function getProperty(jsonObj, propertyName) { return jsonObj[propertyName]; } "
        ScriptEngine.AddCode "function getType(jsonObj, propertyName) {return typeof(jsonObj[propertyName]);}"
        ScriptEngine.AddCode "function getKeys(jsonObj) { var keys = new Array(); for (var i in jsonObj) { keys.push(i); } return keys; } "
        ScriptEngine.AddCode "function addKey(jsonObj, propertyName, value) { jsonObj[propertyName] = value; return jsonObj;}"
        ScriptEngine.AddCode "function removeKey(jsonObj, propertyName) { var json = jsonObj; delete json[propertyName]; return json }"
    End Sub
    Public Function removeJSONProperty(ByVal JsonObject As Object, propertyName As String)
        Set removeJSONProperty = ScriptEngine.Run("removeKey", JsonObject, propertyName)
    End Function
    
    Public Function updateJSONPropertyValue(ByVal JsonObject As Object, propertyName As String, value As String) As Object
        Set updateJSONPropertyValue = ScriptEngine.Run("removeKey", JsonObject, propertyName)
        Set updateJSONPropertyValue = ScriptEngine.Run("addKey", JsonObject, propertyName, value)
    End Function
    
    
    
    Public Function addJSONPropertyValue(ByVal JsonObject As Object, propertyName As String, value As String) As Object
        Set addJSONPropertyValue = ScriptEngine.Run("addKey", JsonObject, propertyName, value)
    End Function
    Public Function DecodeJsonString(ByVal JsonString As String)
    InitScriptEngine
        Set DecodeJsonString = ScriptEngine.Eval("(" + JsonString + ")")
    End Function
    
    Public Function GetProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Variant
        GetProperty = ScriptEngine.Run("getProperty", JsonObject, propertyName)
    End Function
    
    Public Function GetObjectProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Object
        Set GetObjectProperty = ScriptEngine.Run("getProperty", JsonObject, propertyName)
    End Function
    
    Public Function SerializeJSONObject(ByVal JsonObject As Object) As String()
        Dim Length As Integer
        Dim KeysArray() As String
        Dim KeysObject As Object
        Dim Index As Integer
        Dim Key As Variant
        Dim tmpString As String
        Dim tmpJSON As Object
        Dim tmpJSONArray() As Variant
        Dim tmpJSONObject() As Variant
        Dim strJsonObject As String
        Dim tmpNbElement As Long, i As Long
        InitScriptEngine
        Set KeysObject = ScriptEngine.Run("getKeys", JsonObject)
    
        Length = GetProperty(KeysObject, "length")
        ReDim KeysArray(Length - 1)
        Index = 0
        For Each Key In KeysObject
        tmpString = ""
            If ScriptEngine.Run("getType", JsonObject, Key) = "object" Then
        'MsgBox "object " & SerializeJSONObject(GetObjectProperty(JsonObject, Key))(0)
                Set tmpJSON = GetObjectProperty(JsonObject, Key)
                strJsonObject = VBA.Replace(ScriptEngine.Run("getKeys", tmpJSON), " ", "")
                tmpNbElement = Len(strJsonObject) - Len(VBA.Replace(strJsonObject, ",", ""))
    
                If VBA.IsNumeric(Left(ScriptEngine.Run("getKeys", tmpJSON), 1)) = True Then
    
                    ReDim tmpJSONArray(tmpNbElement)
                    For i = 0 To tmpNbElement
                        tmpJSONArray(i) = GetProperty(tmpJSON, i)
                    Next
                        tmpString = "[" & Join(tmpJSONArray, ",") & "]"
                Else
                    tmpString = "{" & Join(SerializeJSONObject(tmpJSON), ", ") & "}"
                End If
    
            Else
                    tmpString = GetProperty(JsonObject, Key)
    
            End If
    
            KeysArray(Index) = Key & ": " & tmpString
            Index = Index + 1
        Next
    
        SerializeJSONObject = KeysArray
    
    End Function
    
    Public Function GetKeys(ByVal JsonObject As Object) As String()
        Dim Length As Integer
        Dim KeysArray() As String
        Dim KeysObject As Object
        Dim Index As Integer
        Dim Key As Variant
    InitScriptEngine
        Set KeysObject = ScriptEngine.Run("getKeys", JsonObject)
        Length = GetProperty(KeysObject, "length")
        ReDim KeysArray(Length - 1)
        Index = 0
        For Each Key In KeysObject
            KeysArray(Index) = Key
            Index = Index + 1
        Next
        GetKeys = KeysArray
    End Function
    

Responsive bootstrap 3 timepicker?

As an update to the OP's question, I can confirm that the timepicker found at http://jdewit.github.io/bootstrap-timepicker/ does in fact work with Bootstrap 3 now with no problems at all.

NullInjectorError: No provider for AngularFirestore

I take that to my app.module. After the imports it should be works

providers: [
    { provide: LocationStrategy, useClass: HashLocationStrategy },
    { provide: FirestoreSettingsToken, useValue: {} }
  ],

My Version:

Angular CLI: 7.2.4
Node: 10.15.0
Angular: 7.2.5
... common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.12.4
@angular-devkit/build-angular     0.12.4
@angular-devkit/build-optimizer   0.12.4
@angular-devkit/build-webpack     0.12.4
@angular-devkit/core              7.2.4
@angular-devkit/schematics        7.2.4
@angular/animations               8.0.0-beta.4+7.sha-3c7ce82
@angular/cdk                      7.3.2-3ae6eb2
@angular/cli                      7.2.4
@angular/fire                     5.1.1
@angular/flex-layout              7.0.0-beta.23
@angular/material                 7.3.2-3ae6eb2
@ngtools/webpack                  7.2.4
@schematics/angular               7.2.4
@schematics/update                0.12.4
rxjs                              6.3.3
typescript                        3.2.4
webpack                           4.28.4

How do I prevent a Gateway Timeout with FastCGI on Nginx

Proxy timeouts are well, for proxies, not for FastCGI...

The directives that affect FastCGI timeouts are client_header_timeout, client_body_timeout and send_timeout.

Edit: Considering what's found on nginx wiki, the send_timeout directive is responsible for setting general timeout of response (which was bit misleading). For FastCGI there's fastcgi_read_timeout which is affecting the fastcgi process response timeout.

HTH.

Programmatically get own phone number in iOS

Update: capability appears to have been removed by Apple on or around iOS 4


Just to expand on an earlier answer, something like this does it for me:

NSString *num = [[NSUserDefaults standardUserDefaults] stringForKey:@"SBFormattedPhoneNumber"];

Note: This retrieves the "Phone number" that was entered during the iPhone's iTunes activation and can be null or an incorrect value. It's NOT read from the SIM card.

At least that does in 2.1. There are a couple of other interesting keys in NSUserDefaults that may also not last. (This is in my app which uses a UIWebView)

WebKitJavaScriptCanOpenWindowsAutomatically
NSInterfaceStyle
TVOutStatus
WebKitDeveloperExtrasEnabledPreferenceKey

and so on.

Not sure what, if anything, the others do.

Javascript Print iframe contents only

I would not expect that to work

try instead

window.frames["printf"].focus();
window.frames["printf"].print();

and use

<iframe id="printf" name="printf"></iframe>

Alternatively try good old

var newWin = window.frames["printf"];
newWin.document.write('<body onload="window.print()">dddd</body>');
newWin.document.close();

if jQuery cannot hack it

Live Demo

Change keystore password from no password to a non blank password

On my system the password is 'changeit'. On blank if I hit enter then it complains about short password. Hope this helps

enter image description here

Trim last 3 characters of a line WITHOUT using sed, or perl, etc

Note: This answer is somewhat intended to be a joke, but it actually does work...

#!/bin/bash
outfile="/tmp/$RANDOM"
cfile="$outfile.c"
echo '#include <stdio.h>
int main(void){int e=1;char c;while((c=getc(stdin))!=-1){if(c==10)e=1;if(c==32)e=0;if(e)putc(c,stdout);}}' >> "$cfile"
gcc -o "$outfile" "$cfile"
rm "$cfile"
cat somedata.txt | "$outfile"
rm "$outfile"

You can replace cat somedata.txt with a different command.

Rename multiple files in a folder, add a prefix (Windows)

I know it's an old question but I learned alot from the various answers but came up with my own solution as a function. This should dynamically add the parent folder as a prefix to all files that matches a certain pattern but only if it does not have that prefix already.

function Add-DirectoryPrefix($pattern) {
    # To debug, replace the Rename-Item with Select-Object
    Get-ChildItem -Path .\* -Filter $pattern -Recurse | 
        Where-Object {$_.Name -notlike ($_.Directory.Name + '*')} | 
        Rename-Item -NewName {$_.Directory.Name + '-' + $_.Name}
        # Select-Object -Property Directory,Name,@{Name = 'NewName'; Expression= {$_.Directory.Name + '-' + $_.Name}}
}

https://gist.github.com/kmpm/4f94e46e569ae0a4e688581231fa9e00

Datetime format Issue: String was not recognized as a valid DateTime

change the culture and try out like this might work for you

string[] formats= { "MM/dd/yyyy HH:mm" }
var dateTime = DateTime.ParseExact("04/30/2013 23:00", 
     formats, new CultureInfo("en-US"), DateTimeStyles.None);

Check for details : DateTime.ParseExact Method (String, String[], IFormatProvider, DateTimeStyles)

How to remove specific element from an array using python

Using filter() and lambda would provide a neat and terse method of removing unwanted values:

newEmails = list(filter(lambda x : x != '[email protected]', emails))

This does not modify emails. It creates the new list newEmails containing only elements for which the anonymous function returned True.

Comparing two maps

Quick Answer

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

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

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

boolean equals(Object o)

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

Implementation in Java Source (java.util.AbstractMap)

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

 // Comparison and hashing

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

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

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

        return true;
    }

Comparing two different types of Maps

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

Code:

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

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

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

Output:

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

Is there a better way to do optional function parameters in JavaScript?

I find this to be the simplest, most readable way:

if (typeof myVariable === 'undefined') { myVariable = 'default'; }
//use myVariable here

Paul Dixon's answer (in my humble opinion) is less readable than this, but it comes down to preference.

insin's answer is much more advanced, but much more useful for big functions!

EDIT 11/17/2013 9:33pm: I've created a package for Node.js that makes it easier to "overload" functions (methods) called parametric.

Refresh/reload the content in Div using jquery/ajax

Try this

html code

 <div id="refresh">
    <input type="text" />
    <input type="button" id="click" />
 </div>

jQuery code

 <script>
    $('#click').click(function(){
    var div=$('#refresh').html();
    $.ajax({
        url: '/path/to/file.php',
        type: 'POST',
        dataType: 'json',
        data: {param1: 'value1'},
    })
    .done(function(data) {
if(data.success=='ok'){
        $('#refresh').html(div);
}else{
// show errors.
}
    })
    .fail(function() {
        console.log("error");
    })
    .always(function() {
        console.log("complete");
    });
    });

</script>

php page code path=/path/to/file.php

<?php
   header('Content-Type: application/json');
   $done=true;
   if($done){
       echo json_encode(['success'=>'ok']);
   }
?>

Cannot read property 'push' of undefined when combining arrays

answer to your question is simple order is not a object make it an array. var order = new Array(); order.push(/item to push/); when ever this error appears just check the left of which property the error is in this case it is push which is order[] so it is undefined.

How to stop IIS asking authentication for default website on localhost

What worked for me is ,,,

Click Start>control panel>Administrative Tools>Internet Information Services

Expand the left tree, right-click your WebSite>Properties

Click on Directory Security, then in "Anonymous access and authentication control" click on Edit

Enable Anonymous access>browse> enter the credentials of the admin (like Administrator) (check names),> Click OK

Apply the settings and it should work fine.

How do you stash an untracked file?

How do you stash an untracked file?

git stash --include-untracked

How do I separate an integer into separate digits in an array in JavaScript?

You can get a list of string from your number, by converting it to a string, and then splitting it with an empty string. The result will be an array of strings, each containing a digit:

const num = 124124124
const strArr = `${num}`.split("")

OR to build on this, map each string digit and convert them to a Number:

const intArr = `${num}`.split("").map(x => Number(x))

Reverse the ordering of words in a string

import java.util.Scanner;

public class revString {
   static char[] str;

   public static void main(String[] args) {
    //Initialize string
    //str = new char[] { 'h', 'e', 'l', 'l', 'o', ' ', 'a', ' ', 'w', 'o',
    //'r', 'l', 'd' };
    getInput();

    // reverse entire string
    reverse(0, str.length - 1);

    // reverse the words (delimeted by space) back to normal
    int i = 0, j = 0;
    while (j < str.length) {

        if (str[j] == ' ' || j == str.length - 1) {

            int m = i;
            int n;

            //dont include space in the swap. 
            //(special case is end of line)
            if (j == str.length - 1)
                n = j;
            else
                n = j -1;


            //reuse reverse
            reverse(m, n);

            i = j + 1;

        }
        j++;
    }

    displayArray();
}

private static void reverse(int i, int j) {

    while (i < j) {

        char temp;
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;

        i++;
        j--;
    }
}
private static void getInput() {
    System.out.print("Enter string to reverse: ");
    Scanner scan = new Scanner(System.in);
    str = scan.nextLine().trim().toCharArray(); 
}

private static void displayArray() {
    //Print the array
    for (int i = 0; i < str.length; i++) {
        System.out.print(str[i]);
    }
}

}

firefox proxy settings via command line

This is the final compiled solution which worked for me... Tried and tested...

Steps to Change Proxy settings in Mozilla Firefox via cmd in Windows

  1. cd /D "%APPDATA%\Mozilla\Firefox\Profiles"
  2. cd *.default

To Replace Already Present Proxy Settings with User-defined ones

  1. powershell -Command "(gc prefs.js) -replace 'user_pref(\"network.proxy.http\", \"already present IP\")\;', 'user_pref(\"network.proxy.http\", \"your http proxy ip\");' | Set-Content prefs.js"
  2. powershell -Command "(gc prefs.js) -replace 'user_pref(\"network.proxy.http_port\", already present port)\;', 'user_pref(\"network.proxy.http_port\", your http proxy port);' | Set-Content prefs.js"
  3. powershell -Command "(gc prefs.js) -replace 'user_pref(\"network.proxy.share_proxy_settings\", already present value)\;', 'user_pref(\"network.proxy.share_proxy_settings\", true);' | Set-Content prefs.js"
  4. powershell -Command "(gc prefs.js) -replace 'user_pref(\"network.proxy.type\", already present value)\;', 'user_pref(\"network.proxy.type\", 1);' | Set-Content prefs.js"

    0 - No Proxy

    1 - Manual Proxy Configuration

    4 - Auto detect Proxy Settings

    5 - Use System Settings(default)

  5. cd %windir%

To Check Already Present Proxy Settings

  1. cd C:\Users\{username}\AppData\Roaming\Mozilla\Firefox\Profiles\sat2m7dr.default\
  2. find /i "network.proxy" prefs.js

To Start Firefox from CMD using your defined proxy settings

  1. cd C:\Program Files\
  2. cd "Mozilla Firefox"
  3. firefox.exe -ProfileManager
  4. Select default from the list (default-release is selected by default) and click ok.

NOTE: You may not have to run step 14 again. Instead you can directly run firefox.exe

How to get all values from python enum class?

This is basically available in a 'protected' attribute of the Enum class:

list(Color._value2member_map_.keys())

"Data too long for column" - why?

There is an hard limit on how much data can be stored in a single row of a mysql table, regardless of the number of columns or the individual column length.

As stated in the OFFICIAL DOCUMENTATION

The maximum row size constrains the number (and possibly size) of columns because the total length of all columns cannot exceed this size. For example, utf8 characters require up to three bytes per character, so for a CHAR(255) CHARACTER SET utf8 column, the server must allocate 255 × 3 = 765 bytes per value. Consequently, a table cannot contain more than 65,535 / 765 = 85 such columns.

Storage for variable-length columns includes length bytes, which are assessed against the row size. For example, a VARCHAR(255) CHARACTER SET utf8 column takes two bytes to store the length of the value, so each value can take up to 767 bytes.

Here you can find INNODB TABLES LIMITATIONS

Leap year calculation

Simply Because year 2000 is a leap year and it is divisible by 100 and dividable by 4. SO to guarantee it is correct leap we need to ensure it is divisible by 400. 2000 % 4 = 0 2000 % 100 = 0 According to algorithm it's not leap, but it is dividable by 400 2000 % 400 = 0 so it is leap.

How to see the changes in a Git commit?

To see author and time by commit use git show COMMIT. Which will result in something like this:

commit 13414df70354678b1b9304ebe4b6d204810f867e
Merge: a2a2894 3a1ba8f
Author: You <[email protected]>
Date:   Fri Jul 24 17:46:42 2015 -0700

     Merge remote-tracking branch 'origin/your-feature'

If you want to see which files had been changed, run the following with the values from the Merge line above git diff --stat a2a2894 3a1ba8f.

If you want to see the actual diff, run git --stat a2a2894 3a1ba8f

What methods of ‘clearfix’ can I use?

The overflow property can be used to clear floats with no additional mark-up:

.container { overflow: hidden; }

This works for all browsers except IE6, where all you need to do is enable hasLayout (zoom being my preferred method):

.container { zoom: 1; }

http://www.quirksmode.org/css/clearing.html

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

np.isnan can be applied to NumPy arrays of native dtype (such as np.float64):

In [99]: np.isnan(np.array([np.nan, 0], dtype=np.float64))
Out[99]: array([ True, False], dtype=bool)

but raises TypeError when applied to object arrays:

In [96]: np.isnan(np.array([np.nan, 0], dtype=object))
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Since you have Pandas, you could use pd.isnull instead -- it can accept NumPy arrays of object or native dtypes:

In [97]: pd.isnull(np.array([np.nan, 0], dtype=float))
Out[97]: array([ True, False], dtype=bool)

In [98]: pd.isnull(np.array([np.nan, 0], dtype=object))
Out[98]: array([ True, False], dtype=bool)

Note that None is also considered a null value in object arrays.

How do I add a Maven dependency in Eclipse?

You need to be using a Maven plugin for Eclipse in order to do this properly. The m2e plugin is built into the latest version of Eclipse, and does a decent if not perfect job of integrating Maven into the IDE. You will want to create your project as a 'Maven Project'. Alternatively you can import an existing Maven POM into your workspace to automatically create projects. Once you have your Maven project in the IDE, simply open up the POM and add your dependency to it.

Now, if you do not have a Maven plugin for Eclipse, you will need to get the jar(s) for the dependency in question and manually add them as classpath references to your project. This could get unpleasant as you will need not just the top level JAR, but all its dependencies as well.

Basically, I recommend you get a decent Maven plugin for Eclipse and let it handle the dependency management for you.

Python datetime - setting fixed hour and minute after using strptime to get day,month,year

Use datetime.replace:

from datetime import datetime
dt = datetime.strptime('26 Sep 2012', '%d %b %Y')
newdatetime = dt.replace(hour=11, minute=59)

ffmpeg usage to encode a video to H264 codec format

I have a Centos 5 system that I wasn't able to get this working on. So I built a new Fedora 17 system (actually a VM in VMware), and followed the steps at the ffmpeg site to build the latest and greatest ffmpeg.

I took some shortcuts - I skipped all the yum erase commands, added freshrpms according to their instructions:

wget http://ftp.freshrpms.net/pub/freshrpms/fedora/linux/9/freshrpms-release/freshrpms-release-1.1-1.fc.noarch.rpm
rpm -ivh rpmfusion-free-release-stable.noarch.rpm

Then I loaded the stuff that was already readily available:

yum install lame libogg libtheora libvorbis lame-devel libtheora-devel

Afterwards, I only built the following from scratch: libvpx vo-aacenc-0.1.2 x264 yasm-1.2.0 ffmpeg

Then this command encoded with no problems (the audio was already in AAC, so I didn't recode it):

ffmpeg -i input.mov -c:v libx264 -preset slow -crf 22 -c:a copy output.mp4

The result looks just as good as the original to me, and is about 1/4 of the size!

Check if a number has a decimal place/is a whole number

Simple, but effective!

Math.floor(number) === number;

How to push a docker image to a private repository

You need to tag your image correctly first with your registryhost:

docker tag [OPTIONS] IMAGE[:TAG] [REGISTRYHOST/][USERNAME/]NAME[:TAG]

Then docker push using that same tag.

docker push NAME[:TAG]

Example:

docker tag 518a41981a6a myRegistry.com/myImage
docker push myRegistry.com/myImage

Process all arguments except the first one (in a bash script)

http://wiki.bash-hackers.org/scripting/posparams

It explains the use of shift (if you want to discard the first N parameters) and then implementing Mass Usage

Class is inaccessible due to its protection level

First thing, try a full rebuild. Clean and build (or just use rebuild). Every once in a long while that resolves bizarre build issues for me.

Next, comment out the rest of the code that is not in your example you have posted. Compile. Does that work?

If so, start adding segments back until one breaks it.

If not, make all the classes public and try again.

If that still fails, maybe try putting the trimmed down classes in the same file and rebuilding. At that point, there would be absolutely no reason for access issues. If that still fails, take up carpentry.

How to determine when a Git branch was created?

First, if you branch was created within gc.reflogexpire days (default 90 days, i.e. around 3 months), you can use git log -g <branch> or git reflog show <branch> to find first entry in reflog, which would be creation event, and looks something like below (for git log -g):

Reflog: <branch>@{<nn>} (C R Eator <[email protected]>)
Reflog message: branch: Created from <some other branch>

You would get who created a branch, how many operations ago, and from which branch (well, it might be just "Created from HEAD", which doesn't help much).

That is what MikeSep said in his answer.


Second, if you have branch for longer than gc.reflogexpire and you have run git gc (or it was run automatically), you would have to find common ancestor with the branch it was created from. Take a look at config file, perhaps there is branch.<branchname>.merge entry, which would tell you what branch this one is based on.

If you know that the branch in question was created off master branch (forking from master branch), for example, you can use the following command to see common ancestor:

git show $(git merge-base <branch> master)

You can also try git show-branch <branch> master, as an alternative.

This is what gbacon said in his response.

2 "style" inline css img tags?

if use Inline CSS you use

<img src="http://img705.imageshack.us/img705/119/original120x75.png" style="height:100px;width:100px;" alt="705"/>

Otherwise you can use class properties which related with a separate css file (styling your website) as like In CSS File

.imgSize {height:100px;width:100px;}

In HTML File

<img src="http://img705.imageshack.us/img705/119/original120x75.png" style="height:100px;width:100px;" alt="705"/>

OpenSSL Command to check if a server is presenting a certificate

I was getting the below as well trying to get out to github.com as our proxy re-writes the HTTPS connection with their self-signed cert:

no peer certificate available No client certificate CA names sent

In my output there was also:

Protocol : TLSv1.3

I added -tls1_2 and it worked fine and now I can see which CA it is using on the outgoing request. e.g.:
openssl s_client -connect github.com:443 -tls1_2

Get 2 Digit Number For The Month

For me the quickest solution was

DATE_FORMAT(CURDATE(),'%m')

Count number of occurences for each unique value

If you need to have the number of unique values as an additional column in the data frame containing your values (a column which may represent sample size for example), plyr provides a neat way:

data_frame <- data.frame(v = rep(c(1,2, 2, 2), 25))

library("plyr")
data_frame <- ddply(data_frame, .(v), transform, n = length(v))

Failing to run jar file from command line: “no main manifest attribute”

In Eclipse: right-click on your project -> Export -> JAR file

At last page with options (when there will be no Next button active) you will see settings for Main class:. You need to set here class with main method which should be executed by default (like when JAR file will be double-clicked).

Differences between TCP sockets and web sockets, one more time

When you send bytes from a buffer with a normal TCP socket, the send function returns the number of bytes of the buffer that were sent. If it is a non-blocking socket or a non-blocking send then the number of bytes sent may be less than the size of the buffer. If it is a blocking socket or blocking send, then the number returned will match the size of the buffer but the call may block. With WebSockets, the data that is passed to the send method is always either sent as a whole "message" or not at all. Also, browser WebSocket implementations do not block on the send call.

But there are more important differences on the receiving side of things. When the receiver does a recv (or read) on a TCP socket, there is no guarantee that the number of bytes returned corresponds to a single send (or write) on the sender side. It might be the same, it may be less (or zero) and it might even be more (in which case bytes from multiple send/writes are received). With WebSockets, the recipient of a message is event-driven (you generally register a message handler routine), and the data in the event is always the entire message that the other side sent.

Note that you can do message based communication using TCP sockets, but you need some extra layer/encapsulation that is adding framing/message boundary data to the messages so that the original messages can be re-assembled from the pieces. In fact, WebSockets is built on normal TCP sockets and uses frame headers that contains the size of each frame and indicate which frames are part of a message. The WebSocket API re-assembles the TCP chunks of data into frames which are assembled into messages before invoking the message event handler once per message.

Select from multiple tables without a join?

You could try something like this:

SELECT ...
FROM (
    SELECT f1,f2,f3 FROM table1
    UNION
    SELECT f1,f2,f3 FROM table2
)
WHERE ...

Calculate AUC in R?

Calculating AUC with Metrics package is very easy and straightforward:

library(Metrics)

actual <- c(0, 0, 1, 1)
predicted <- c(.1, .3, .3, .9)

auc(actual, predicted)

0.875

overlay a smaller image on a larger image python OpenCv

A simple way to achieve what you want:

import cv2
s_img = cv2.imread("smaller_image.png")
l_img = cv2.imread("larger_image.jpg")
x_offset=y_offset=50
l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img

the result image

Update

I suppose you want to take care of the alpha channel too. Here is a quick and dirty way of doing so:

s_img = cv2.imread("smaller_image.png", -1)

y1, y2 = y_offset, y_offset + s_img.shape[0]
x1, x2 = x_offset, x_offset + s_img.shape[1]

alpha_s = s_img[:, :, 3] / 255.0
alpha_l = 1.0 - alpha_s

for c in range(0, 3):
    l_img[y1:y2, x1:x2, c] = (alpha_s * s_img[:, :, c] +
                              alpha_l * l_img[y1:y2, x1:x2, c])

result image with alpha

How to use WinForms progress bar?

There is Task exists, It is unnesscery using BackgroundWorker, Task is more simple. for example:

ProgressDialog.cs:

   public partial class ProgressDialog : Form
    {
        public System.Windows.Forms.ProgressBar Progressbar { get { return this.progressBar1; } }

        public ProgressDialog()
        {
            InitializeComponent();
        }

        public void RunAsync(Action action)
        {
            Task.Run(action);
        }
    }

Done! Then you can reuse ProgressDialog anywhere:

var progressDialog = new ProgressDialog();
progressDialog.Progressbar.Value = 0;
progressDialog.Progressbar.Maximum = 100;

progressDialog.RunAsync(() =>
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000)
        this.progressDialog.Progressbar.BeginInvoke((MethodInvoker)(() => {
            this.progressDialog.Progressbar.Value += 1;
        }));
    }
});

progressDialog.ShowDialog();

python int( ) function

Integers (int for short) are the numbers you count with 0, 1, 2, 3 ... and their negative counterparts ... -3, -2, -1 the ones without the decimal part.

So once you introduce a decimal point, your not really dealing with integers. You're dealing with rational numbers. The Python float or decimal types are what you want to represent or approximate these numbers.

You may be used to a language that automatically does this for you(Php). Python, though, has an explicit preference for forcing code to be explicit instead implicit.

What does a (+) sign mean in an Oracle SQL WHERE clause?

This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.

In standard SQL one would write:

SELECT t0.foo, t1.bar
  FROM FIRST_TABLE t0
 RIGHT OUTER JOIN SECOND_TABLE t1;

Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]

Cannot find java. Please use the --jdkhome switch

NetBeans 8.2 - Cannot locate java installation in specified jdkhome?

Answer: Edit the netbeans.conf file.

Close NetBeans, start Notepad or another text editor as Administrator. Right click on the Notepad application and choose "Run as administrator" and then open netbeans.conf with it. Change netbeans_jdkhome=”C:\Program Files...whatever”.

React Native add bold or italics to single words in <Text> field

For a more web-like feel:

const B = (props) => <Text style={{fontWeight: 'bold'}}>{props.children}</Text>
<Text>I am in <B>bold</B> yo.</Text>

Get the last three chars from any string - Java

This method would be helpful :

String rightPart(String text,int length)
{
    if (text.length()<length) return text;
    String raw = "";
    for (int i = 1; i <= length; i++) {
        raw += text.toCharArray()[text.length()-i];
    }
    return new StringBuilder(raw).reverse().toString();
}

IndexError: too many indices for array

The message that you are getting is not for the default Exception of Python:

For a fresh python list, IndexError is thrown only on index not being in range (even docs say so).

>>> l = []
>>> l[1]
IndexError: list index out of range

If we try passing multiple items to list, or some other value, we get the TypeError:

>>> l[1, 2]
TypeError: list indices must be integers, not tuple

>>> l[float('NaN')]
TypeError: list indices must be integers, not float

However, here, you seem to be using matplotlib that internally uses numpy for handling arrays. On digging deeper through the codebase for numpy, we see:

static NPY_INLINE npy_intp
unpack_tuple(PyTupleObject *index, PyObject **result, npy_intp result_n)
{
    npy_intp n, i;
    n = PyTuple_GET_SIZE(index);
    if (n > result_n) {
        PyErr_SetString(PyExc_IndexError,
                        "too many indices for array");
        return -1;
    }
    for (i = 0; i < n; i++) {
        result[i] = PyTuple_GET_ITEM(index, i);
        Py_INCREF(result[i]);
    }
    return n;
}

where, the unpack method will throw an error if it the size of the index is greater than that of the results.

So, Unlike Python which raises a TypeError on incorrect Indexes, Numpy raises the IndexError because it supports multidimensional arrays.

ComboBox: Adding Text and Value to an Item (no Binding Source)

//set 
comboBox1.DisplayMember = "Value"; 
//to add 
comboBox1.Items.Add(new KeyValuePair("2", "This text is displayed")); 
//to access the 'tag' property 
string tag = ((KeyValuePair< string, string >)comboBox1.SelectedItem).Key; 
MessageBox.Show(tag);

How to fix 'sudo: no tty present and no askpass program specified' error?

I faced this issue when working on an Ubuntu 20.04 server.

I was trying to run a sudo command from a remote machine to deploy an app to the server. However when I run the command I get the error:

sudo: no tty present and no askpass program specified
The remote script failed with exit code 1

Here's how I fixed it:

The issue is caused by executing a sudo command which tries to request for a password, but sudo does not have access to a tty to prompt the user for a passphrase. As it can’t find a tty, sudo falls back to an askpass method but can’t find an askpass command configured, so the sudo command fails.

To fix this you need to be able to run sudo for that specific user with no password requirements. The no password requirements is configured in the /etc/sudoers file. To configure it run either of the commands below:

sudo nano /etc/sudoers

OR

sudo visudo

Note: This opens the /etc/sudoers file using your default editor.

Next, Add the following line at the bottom of the file:

# Allow my_user to run all commands without password
my_user ALL=(ALL) NOPASSWD:ALL

Note: Replace my_user with your actual user

If you want the user to run specific commands you can specify them

# Allow my_user to run specific commands without password
my_user ALL=(ALL) NOPASSWD:/bin/myCommand

OR

# Allow my_user to run specific commands without password
my_user ALL=(ALL) NOPASSWD: /bin/myCommand, /bin/myCommand, /bin/myCommand

Save the changes and exit the file.

For more help, read the resource in this link: sudo: no tty present and no askpass program specified

That's all.

I hope this helps

Why does my Eclipse keep not responding?

Try this, it worked for me!

If you happen to have Eclipse not responding anymore sometimes, the reason could be that you sit on a 64bit machine where eclipse needs more memory. Be sure to have (at least) the following configurations in your eclipse.ini (I even use bigger values for the PermSizes):

-Xms512m
-Xmx1024m
-XX:PermSize=64m
-XX:MaxPermSize=128m

Makefile, header dependencies

Here's a two-liner:

CPPFLAGS = -MMD
-include $(OBJS:.c=.d)

This works with the default make recipe, as long as you have a list of all your object files in OBJS.

What processes are using which ports on unix?

netstat -pln

EDIT: linux only, on other UNIXes netstat may not support all these options.

Is it safe to expose Firebase apiKey to the public?

I am not convinced to expose security/config keys to client. I would not call it secure, not because some one can steal all private information from first day, because someone can make excessive request, and drain your quota and make you owe to Google a lot of money.

You need to think about many concepts from restricting people not to access where they are not supposed to be, DOS attacks etc.

I would more prefer the client first will hit to your web server, there you put what ever first hand firewall, captcha , cloudflare, custom security in between the client and server, or between server and firebase and you are good to go. At least you can first stop suspect activity before it reaches to firebase. You will have much more flexibility.

I only see one good usage scenario for using client based config for internal usages. For example, you have internal domain, and you are pretty sure outsiders cannot access there, so you can setup environment like browser -> firebase type.

Troubleshooting "Illegal mix of collations" error in mysql

This is generally caused by comparing two strings of incompatible collation or by attempting to select data of different collation into a combined column.

The clause COLLATE allows you to specify the collation used in the query.

For example, the following WHERE clause will always give the error you posted:

WHERE 'A' COLLATE latin1_general_ci = 'A' COLLATE latin1_general_cs

Your solution is to specify a shared collation for the two columns within the query. Here is an example that uses the COLLATE clause:

SELECT * FROM table ORDER BY key COLLATE latin1_general_ci;

Another option is to use the BINARY operator:

BINARY str is the shorthand for CAST(str AS BINARY).

Your solution might look something like this:

SELECT * FROM table WHERE BINARY a = BINARY b;

or,

SELECT * FROM table ORDER BY BINARY a;

What's the source of Error: getaddrinfo EAI_AGAIN?

updating the npm to latest fixes this problem for me.

npm install npm@latest

this issue is related to your network connectivity. hence can be temporary. on a stable internet connection this issue was hardly observed.

How to detect running app using ADB command

No need to use grep. ps in Android can filter by COMM value (last 15 characters of the package name in case of java app)

Let's say we want to check if com.android.phone is running:

adb shell ps m.android.phone
USER     PID   PPID  VSIZE  RSS     WCHAN    PC         NAME
radio     1389  277   515960 33964 ffffffff 4024c270 S com.android.phone

Filtering by COMM value option has been removed from ps in Android 7.0. To check for a running process by name in Android 7.0 you can use pidof command:

adb shell pidof com.android.phone

It returns the PID if such process was found or an empty string otherwise.

How to BULK INSERT a file into a *temporary* table where the filename is a variable?

You could always construct the #temp table in dynamic SQL. For example, right now I guess you have been trying:

CREATE TABLE #tmp(a INT, b INT, c INT);

DECLARE @sql NVARCHAR(1000);

SET @sql = N'BULK INSERT #tmp ...' + @variables;

EXEC master.sys.sp_executesql @sql;

SELECT * FROM #tmp;

This makes it tougher to maintain (readability) but gets by the scoping issue:

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'CREATE TABLE #tmp(a INT, b INT, c INT);

BULK INSERT #tmp ...' + @variables + ';

SELECT * FROM #tmp;';

EXEC master.sys.sp_executesql @sql;

EDIT 2011-01-12

In light of how my almost 2-year old answer was suddenly deemed incomplete and unacceptable, by someone whose answer was also incomplete, how about:

CREATE TABLE #outer(a INT, b INT, c INT);

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'SET NOCOUNT ON; 

CREATE TABLE #inner(a INT, b INT, c INT);

BULK INSERT #inner ...' + @variables + ';

SELECT * FROM #inner;';

INSERT #outer EXEC master.sys.sp_executesql @sql;

How to use the COLLATE in a JOIN in SQL Server?

As a general rule, you can use Database_Default collation so you don't need to figure out which one to use. However, I strongly suggest reading Simons Liew's excellent article Understanding the COLLATE DATABASE_DEFAULT clause in SQL Server

SELECT *
  FROM [FAEB].[dbo].[ExportaComisiones] AS f
  JOIN [zCredifiel].[dbo].[optPerson] AS p
  ON (p.vTreasuryId = f.RFC) COLLATE Database_Default 

Domain Account keeping locking out with correct password every few minutes

Download Microsoft Account Lockout Tools. Use LockoutStatus to find the last DC that didn't pre-authenticate the user that is having issues. Note date and time. Log into that DC, find that timeframe and check Client Address. Logoff from those servers.

Regular expression to limit number of characters to 10

It might be beneficial to add greedy matching to the end of the string, so you can accept strings > than 10 and the regex will only return up to the first 10 chars. /^[a-z0-9]{0,10}$?/

How to use null in switch

Given:

public enum PersonType {
    COOL_GUY(1),
    JERK(2);

    private final int typeId;
    private PersonType(int typeId) {
        this.typeId = typeId;
    }

    public final int getTypeId() {
        return typeId;
    }

    public static PersonType findByTypeId(int typeId) {
        for (PersonType type : values()) {
            if (type.typeId == typeId) {
                return type;
            }
        }
        return null;
    }
}

For me, this typically aligns with a look-up table in a database (for rarely-updated tables only).

However, when I try to use findByTypeId in a switch statement (from, most likely, user input)...

int userInput = 3;
PersonType personType = PersonType.findByTypeId(userInput);
switch(personType) {
case COOL_GUY:
    // Do things only a cool guy would do.
    break;
case JERK:
    // Push back. Don't enable him.
    break;
default:
    // I don't know or care what to do with this mess.
}

...as others have stated, this results in an NPE @ switch(personType) {. One work-around (i.e., "solution") I started implementing was to add an UNKNOWN(-1) type.

public enum PersonType {
    UNKNOWN(-1),
    COOL_GUY(1),
    JERK(2);
    ...
    public static PersonType findByTypeId(int id) {
        ...
        return UNKNOWN;
    }
}

Now, you don't have to do null-checking where it counts and you can choose to, or not to, handle UNKNOWN types. (NOTE: -1 is an unlikely identifier in a business scenario, but obviously choose something that makes sense for your use-case).

Split text file into smaller multiple text file using command line

I have created a simple program for this and your question helped me complete the solution... I added one more feature and few configurations. In case you want to add a specific character/ string after every few lines (configurable). Please go through the notes. I have added the code files : https://github.com/mohitsharma779/FileSplit

What are SP (stack) and LR in ARM?

SP is the stack register a shortcut for typing r13. LR is the link register a shortcut for r14. And PC is the program counter a shortcut for typing r15.

When you perform a call, called a branch link instruction, bl, the return address is placed in r14, the link register. the program counter pc is changed to the address you are branching to.

There are a few stack pointers in the traditional ARM cores (the cortex-m series being an exception) when you hit an interrupt for example you are using a different stack than when running in the foreground, you dont have to change your code just use sp or r13 as normal the hardware has done the switch for you and uses the correct one when it decodes the instructions.

The traditional ARM instruction set (not thumb) gives you the freedom to use the stack in a grows up from lower addresses to higher addresses or grows down from high address to low addresses. the compilers and most folks set the stack pointer high and have it grow down from high addresses to lower addresses. For example maybe you have ram from 0x20000000 to 0x20008000 you set your linker script to build your program to run/use 0x20000000 and set your stack pointer to 0x20008000 in your startup code, at least the system/user stack pointer, you have to divide up the memory for other stacks if you need/use them.

Stack is just memory. Processors normally have special memory read/write instructions that are PC based and some that are stack based. The stack ones at a minimum are usually named push and pop but dont have to be (as with the traditional arm instructions).

If you go to http://github.com/lsasim I created a teaching processor and have an assembly language tutorial. Somewhere in there I go through a discussion about stacks. It is NOT an arm processor but the story is the same it should translate directly to what you are trying to understand on the arm or most other processors.

Say for example you have 20 variables you need in your program but only 16 registers minus at least three of them (sp, lr, pc) that are special purpose. You are going to have to keep some of your variables in ram. Lets say that r5 holds a variable that you use often enough that you dont want to keep it in ram, but there is one section of code where you really need another register to do something and r5 is not being used, you can save r5 on the stack with minimal effort while you reuse r5 for something else, then later, easily, restore it.

Traditional (well not all the way back to the beginning) arm syntax:

...
stmdb r13!,{r5}
...temporarily use r5 for something else...
ldmia r13!,{r5}
...

stm is store multiple you can save more than one register at a time, up to all of them in one instruction.

db means decrement before, this is a downward moving stack from high addresses to lower addresses.

You can use r13 or sp here to indicate the stack pointer. This particular instruction is not limited to stack operations, can be used for other things.

The ! means update the r13 register with the new address after it completes, here again stm can be used for non-stack operations so you might not want to change the base address register, leave the ! off in that case.

Then in the brackets { } list the registers you want to save, comma separated.

ldmia is the reverse, ldm means load multiple. ia means increment after and the rest is the same as stm

So if your stack pointer were at 0x20008000 when you hit the stmdb instruction seeing as there is one 32 bit register in the list it will decrement before it uses it the value in r13 so 0x20007FFC then it writes r5 to 0x20007FFC in memory and saves the value 0x20007FFC in r13. Later, assuming you have no bugs when you get to the ldmia instruction r13 has 0x20007FFC in it there is a single register in the list r5. So it reads memory at 0x20007FFC puts that value in r5, ia means increment after so 0x20007FFC increments one register size to 0x20008000 and the ! means write that number to r13 to complete the instruction.

Why would you use the stack instead of just a fixed memory location? Well the beauty of the above is that r13 can be anywhere it could be 0x20007654 when you run that code or 0x20002000 or whatever and the code still functions, even better if you use that code in a loop or with recursion it works and for each level of recursion you go you save a new copy of r5, you might have 30 saved copies depending on where you are in that loop. and as it unrolls it puts all the copies back as desired. with a single fixed memory location that doesnt work. This translates directly to C code as an example:

void myfun ( void )
{
   int somedata;
}

In a C program like that the variable somedata lives on the stack, if you called myfun recursively you would have multiple copies of the value for somedata depending on how deep in the recursion. Also since that variable is only used within the function and is not needed elsewhere then you perhaps dont want to burn an amount of system memory for that variable for the life of the program you only want those bytes when in that function and free that memory when not in that function. that is what a stack is used for.

A global variable would not be found on the stack.

Going back...

Say you wanted to implement and call that function you would have some code/function you are in when you call the myfun function. The myfun function wants to use r5 and r6 when it is operating on something but it doesnt want to trash whatever someone called it was using r5 and r6 for so for the duration of myfun() you would want to save those registers on the stack. Likewise if you look into the branch link instruction (bl) and the link register lr (r14) there is only one link register, if you call a function from a function you will need to save the link register on each call otherwise you cant return.

...
bl myfun
    <--- the return from my fun returns here
...


myfun:
stmdb sp!,{r5,r6,lr}
sub sp,#4 <--- make room for the somedata variable
...
some code here that uses r5 and r6
bl more_fun <-- this modifies lr, if we didnt save lr we wouldnt be able to return from myfun
   <---- more_fun() returns here
...
add sp,#4 <-- take back the stack memory we allocated for the somedata variable
ldmia sp!,{r5,r6,lr}
mov pc,lr <---- return to whomever called myfun.

So hopefully you can see both the stack usage and link register. Other processors do the same kinds of things in a different way. for example some will put the return value on the stack and when you execute the return function it knows where to return to by pulling a value off of the stack. Compilers C/C++, etc will normally have a "calling convention" or application interface (ABI and EABI are names for the ones ARM has defined). if every function follows the calling convention, puts parameters it is passing to functions being called in the right registers or on the stack per the convention. And each function follows the rules as to what registers it does not have to preserve the contents of and what registers it has to preserve the contents of then you can have functions call functions call functions and do recursion and all kinds of things, so long as the stack does not go so deep that it runs into the memory used for globals and the heap and such, you can call functions and return from them all day long. The above implementation of myfun is very similar to what you would see a compiler produce.

ARM has many cores now and a few instruction sets the cortex-m series works a little differently as far as not having a bunch of modes and different stack pointers. And when executing thumb instructions in thumb mode you use the push and pop instructions which do not give you the freedom to use any register like stm it only uses r13 (sp) and you cannot save all the registers only a specific subset of them. the popular arm assemblers allow you to use

push {r5,r6}
...
pop {r5,r6}

in arm code as well as thumb code. For the arm code it encodes the proper stmdb and ldmia. (in thumb mode you also dont have the choice as to when and where you use db, decrement before, and ia, increment after).

No you absolutly do not have to use the same registers and you dont have to pair up the same number of registers.

push {r5,r6,r7}
...
pop {r2,r3}
...
pop {r1}

assuming there is no other stack pointer modifications in between those instructions if you remember the sp is going to be decremented 12 bytes for the push lets say from 0x1000 to 0x0FF4, r5 will be written to 0xFF4, r6 to 0xFF8 and r7 to 0xFFC the stack pointer will change to 0x0FF4. the first pop will take the value at 0x0FF4 and put that in r2 then the value at 0x0FF8 and put that in r3 the stack pointer gets the value 0x0FFC. later the last pop, the sp is 0x0FFC that is read and the value placed in r1, the stack pointer then gets the value 0x1000, where it started.

The ARM ARM, ARM Architectural Reference Manual (infocenter.arm.com, reference manuals, find the one for ARMv5 and download it, this is the traditional ARM ARM with ARM and thumb instructions) contains pseudo code for the ldm and stm ARM istructions for the complete picture as to how these are used. Likewise well the whole book is about the arm and how to program it. Up front the programmers model chapter walks you through all of the registers in all of the modes, etc.

If you are programming an ARM processor you should start by determining (the chip vendor should tell you, ARM does not make chips it makes cores that chip vendors put in their chips) exactly which core you have. Then go to the arm website and find the ARM ARM for that family and find the TRM (technical reference manual) for the specific core including revision if the vendor has supplied that (r2p0 means revision 2.0 (two point zero, 2p0)), even if there is a newer rev, use the manual that goes with the one the vendor used in their design. Not every core supports every instruction or mode the TRM tells you the modes and instructions supported the ARM ARM throws a blanket over the features for the whole family of processors that that core lives in. Note that the ARM7TDMI is an ARMv4 NOT an ARMv7 likewise the ARM9 is not an ARMv9. ARMvNUMBER is the family name ARM7, ARM11 without a v is the core name. The newer cores have names like Cortex and mpcore instead of the ARMNUMBER thing, which reduces confusion. Of course they had to add the confusion back by making an ARMv7-m (cortex-MNUMBER) and the ARMv7-a (Cortex-ANUMBER) which are very different families, one is for heavy loads, desktops, laptops, etc the other is for microcontrollers, clocks and blinking lights on a coffee maker and things like that. google beagleboard (Cortex-A) and the stm32 value line discovery board (Cortex-M) to get a feel for the differences. Or even the open-rd.org board which uses multiple cores at more than a gigahertz or the newer tegra 2 from nvidia, same deal super scaler, muti core, multi gigahertz. A cortex-m barely brakes the 100MHz barrier and has memory measured in kbytes although it probably runs of a battery for months if you wanted it to where a cortex-a not so much.

sorry for the very long post, hope it is useful.

How to detect chrome and safari browser (webkit)

jQuery provides that:

if ($.browser.webkit){
    ...
}

Further reading at http://api.jquery.com/jQuery.browser/

Update

As noted in other answers/comments, it's always better to check for feature support than agent info. jQuery also provides an object for that: jQuery.support. Check the documentation to see the detailed list features to check for.

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

I have a simple example to show how to do angular 2 rc6 dynamic component.

Say, you have a dynamic html template = template1 and want to dynamic load, firstly wrap into component

@Component({template: template1})
class DynamicComponent {}

here template1 as html, may be contains ng2 component

From rc6, have to have @NgModule wrap this component. @NgModule, just like module in anglarJS 1, it decouple different part of ng2 application, so:

@Component({
  template: template1,

})
class DynamicComponent {

}
@NgModule({
  imports: [BrowserModule,RouterModule],
  declarations: [DynamicComponent]
})
class DynamicModule { }

(Here import RouterModule as in my example there is some route components in my html as you can see later on)

Now you can compile DynamicModule as: this.compiler.compileModuleAndAllComponentsAsync(DynamicModule).then( factory => factory.componentFactories.find(x => x.componentType === DynamicComponent))

And we need put above in app.moudule.ts to load it, please see my app.moudle.ts. For more and full details check: https://github.com/Longfld/DynamicalRouter/blob/master/app/MyRouterLink.ts and app.moudle.ts

and see demo: http://plnkr.co/edit/1fdAYP5PAbiHdJfTKgWo?p=preview

Difference between maven scope compile and provided for JAR packaging

  • compile

Make available into class path, don't add this dependency into final jar if it is normal jar; but add this jar into jar if final jar is a single jar (for example, executable jar)

  • provided

Dependency will be available at run time environment so don't add this dependency in any case; even not in single jar (i.e. executable jar etc)

Copy row but with new id

This works in MySQL all versions and Amazon RDS Aurora:

INSERT INTO my_table SELECT 0,tmp.* FROM tmp;

or

Setting the index column to NULL and then doing the INSERT.

But not in MariaDB, I tested version 10.

Display Last Saved Date on worksheet

May be this time stamp fit you better Code

Function LastInputTimeStamp() As Date
  LastInputTimeStamp = Now()
End Function

and each time you input data in defined cell (in my example below it is cell C36) you'll get a new constant time stamp. As an example in Excel file may use this

=IF(C36>0,LastInputTimeStamp(),"")

Failed to authenticate on SMTP server error using gmail

Change the .env file as follow

MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls

And the go to the gmail security section ->Allow Less secure app access

Then run

php artisan config:clear

Refresh the site

How to view instagram profile picture in full-size?

replace "150x150" with 720x720 and remove /vp/ from the link.it should work.

Delete specified file from document directory

Swift 3.0:

func removeImage(itemName:String, fileExtension: String) {
  let fileManager = FileManager.default
  let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  guard let dirPath = paths.first else {
      return
  }  
  let filePath = "\(dirPath)/\(itemName).\(fileExtension)"
  do {
    try fileManager.removeItem(atPath: filePath)
  } catch let error as NSError {
    print(error.debugDescription)
  }}

Thanks to @Anil Varghese, I wrote very similiar code in swift 2.0:

static func removeImage(itemName:String, fileExtension: String) {
  let fileManager = NSFileManager.defaultManager()
  let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
  let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
  let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  guard let dirPath = paths.first else {
    return
  }
  let filePath = "\(dirPath)/\(itemName).\(fileExtension)"
  do {
    try fileManager.removeItemAtPath(filePath)
  } catch let error as NSError {
    print(error.debugDescription)
  }
}

GitHub: How to make a fork of public repository private?

GitHub now has an import option that lets you choose whatever you want your new imported repository public or private

Github Repository import

How to convert list to string

By using ''.join

list1 = ['1', '2', '3']
str1 = ''.join(list1)

Or if the list is of integers, convert the elements before joining them.

list1 = [1, 2, 3]
str1 = ''.join(str(e) for e in list1)

For loop in Objective-C

The traditional for loop in Objective-C is inherited from standard C and takes the following form:

for (/* Instantiate local variables*/ ; /* Condition to keep looping. */ ; /* End of loop expressions */)
{
    // Do something.
}

For example, to print the numbers from 1 to 10, you could use the for loop:

for (int i = 1; i <= 10; i++)
{
    NSLog(@"%d", i);
}

On the other hand, the for in loop was introduced in Objective-C 2.0, and is used to loop through objects in a collection, such as an NSArray instance. For example, to loop through a collection of NSString objects in an NSArray and print them all out, you could use the following format.

for (NSString* currentString in myArrayOfStrings)
{
    NSLog(@"%@", currentString);
}

This is logically equivilant to the following traditional for loop:

for (int i = 0; i < [myArrayOfStrings count]; i++)
{
    NSLog(@"%@", [myArrayOfStrings objectAtIndex:i]);
}

The advantage of using the for in loop is firstly that it's a lot cleaner code to look at. Secondly, the Objective-C compiler can optimize the for in loop so as the code runs faster than doing the same thing with a traditional for loop.

Hope this helps.

What is Dispatcher Servlet in Spring?

DispatcherServlet is Spring MVC's implementation of the front controller pattern.

See description in the Spring docs here.

Essentially, it's a servlet that takes the incoming request, and delegates processing of that request to one of a number of handlers, the mapping of which is specific in the DispatcherServlet configuration.

How do I test axios in Jest?

I could do that following the steps:

  1. Create a folder __mocks__/ (as pointed by @Januartha comment)
  2. Implement an axios.js mock file
  3. Use my implemented module on test

The mock will happen automatically

Example of the mock module:

module.exports = {
    get: jest.fn((url) => {
        if (url === '/something') {
            return Promise.resolve({
                data: 'data'
            });
        }
    }),
    post: jest.fn((url) => {
        if (url === '/something') {
            return Promise.resolve({
                data: 'data'
            });
        }
        if (url === '/something2') {
            return Promise.resolve({
                data: 'data2'
            });
        }
    }),
    create: jest.fn(function () {
        return this;
    })
};

The program can't start because libgcc_s_dw2-1.dll is missing

Including -static-libgcc on the compiling line, solves the issue

g++ my.cpp -o my.exe -static-libgcc

According to: @hardmath

You can also, create an alias on your profile [ .profile ] if you're on MSYS2 for example

alias g++="g++ -static-libgcc"

Now your GCC command goes thru too ;-)

Remeber to restart your Terminal

How to select bottom most rows?

Sorry, but I don't think I see any correct answers in my opinion.

The TOP x function shows the records in undefined order. From that definition follows that a BOTTOM function can not be defined.

Independent of any index or sort order. When you do an ORDER BY y DESC you get the rows with the highest y value first. If this is an autogenerated ID, it should show the records last added to the table, as suggested in the other answers. However:

  • This only works if there is an autogenerated id column
  • It has a significant performance impact if you compare that with the TOP function

The correct answer should be that there is not, and cannot be, an equivalent to TOP for getting the bottom rows.

How do I set a JLabel's background color?

For the Background, make sure you have imported java.awt.Color into your package.

In your main method, i.e. public static void main(String[] args), call the already imported method:

JLabel name_of_your_label=new JLabel("the title of your label");
name_of_your_label.setBackground(Color.the_color_you_wish);
name_of_your_label.setOpaque(true);

NB: Setting opaque will affect its visibility. Remember the case sensitivity in Java.

What is the difference between spark.sql.shuffle.partitions and spark.default.parallelism?

spark.default.parallelism is the default number of partition set by spark which is by default 200. and if you want to increase the number of partition than you can apply the property spark.sql.shuffle.partitions to set number of partition in the spark configuration or while running spark SQL.

Normally this spark.sql.shuffle.partitions it is being used when we have a memory congestion and we see below error: spark error:java.lang.IllegalArgumentException: Size exceeds Integer.MAX_VALUE

so set your can allocate a partition as 256 MB per partition and that you can use to set for your processes.

also If number of partitions is near to 2000 then increase it to more than 2000. As spark applies different logic for partition < 2000 and > 2000 which will increase your code performance by decreasing the memory footprint as data default is highly compressed if >2000.

How to set space between listView Items in Android

@Asahi pretty much hit the nail on the head, but I just wanted to add a bit of XML for anyone maybe floating in here later via google:

<ListView android:id="@+id/MyListView"
  android:layout_height="match_parent"
  android:layout_width="match_parent"
  android:divider="@android:color/transparent"
  android:dividerHeight="10.0sp"/>

For some reason, values such as "10", "10.0", and "10sp" all are rejected by Android for the dividerHeight value. It wants a floating point number and a unit, such as "10.0sp". As @Goofyahead notes, you can also use display-independent pixels for this value (ie, "10dp").

How to get current PHP page name

You can use basename() and $_SERVER['PHP_SELF'] to get current page file name

echo basename($_SERVER['PHP_SELF']); /* Returns The Current PHP File Name */

Is there a way to detect if an image is blurry?

During some work with an auto-focus lens, I came across this very useful set of algorithms for detecting image focus. It's implemented in MATLAB, but most of the functions are quite easy to port to OpenCV with filter2D.

It's basically a survey implementation of many focus measurement algorithms. If you want to read the original papers, references to the authors of the algorithms are provided in the code. The 2012 paper by Pertuz, et al. Analysis of focus measure operators for shape from focus (SFF) gives a great review of all of these measure as well as their performance (both in terms of speed and accuracy as applied to SFF).

EDIT: Added MATLAB code just in case the link dies.

function FM = fmeasure(Image, Measure, ROI)
%This function measures the relative degree of focus of 
%an image. It may be invoked as:
%
%   FM = fmeasure(Image, Method, ROI)
%
%Where 
%   Image,  is a grayscale image and FM is the computed
%           focus value.
%   Method, is the focus measure algorithm as a string.
%           see 'operators.txt' for a list of focus 
%           measure methods. 
%   ROI,    Image ROI as a rectangle [xo yo width heigth].
%           if an empty argument is passed, the whole
%           image is processed.
%
%  Said Pertuz
%  Abr/2010


if ~isempty(ROI)
    Image = imcrop(Image, ROI);
end

WSize = 15; % Size of local window (only some operators)

switch upper(Measure)
    case 'ACMO' % Absolute Central Moment (Shirvaikar2004)
        if ~isinteger(Image), Image = im2uint8(Image);
        end
        FM = AcMomentum(Image);

    case 'BREN' % Brenner's (Santos97)
        [M N] = size(Image);
        DH = Image;
        DV = Image;
        DH(1:M-2,:) = diff(Image,2,1);
        DV(:,1:N-2) = diff(Image,2,2);
        FM = max(DH, DV);        
        FM = FM.^2;
        FM = mean2(FM);

    case 'CONT' % Image contrast (Nanda2001)
        ImContrast = inline('sum(abs(x(:)-x(5)))');
        FM = nlfilter(Image, [3 3], ImContrast);
        FM = mean2(FM);

    case 'CURV' % Image Curvature (Helmli2001)
        if ~isinteger(Image), Image = im2uint8(Image);
        end
        M1 = [-1 0 1;-1 0 1;-1 0 1];
        M2 = [1 0 1;1 0 1;1 0 1];
        P0 = imfilter(Image, M1, 'replicate', 'conv')/6;
        P1 = imfilter(Image, M1', 'replicate', 'conv')/6;
        P2 = 3*imfilter(Image, M2, 'replicate', 'conv')/10 ...
            -imfilter(Image, M2', 'replicate', 'conv')/5;
        P3 = -imfilter(Image, M2, 'replicate', 'conv')/5 ...
            +3*imfilter(Image, M2, 'replicate', 'conv')/10;
        FM = abs(P0) + abs(P1) + abs(P2) + abs(P3);
        FM = mean2(FM);

    case 'DCTE' % DCT energy ratio (Shen2006)
        FM = nlfilter(Image, [8 8], @DctRatio);
        FM = mean2(FM);

    case 'DCTR' % DCT reduced energy ratio (Lee2009)
        FM = nlfilter(Image, [8 8], @ReRatio);
        FM = mean2(FM);

    case 'GDER' % Gaussian derivative (Geusebroek2000)        
        N = floor(WSize/2);
        sig = N/2.5;
        [x,y] = meshgrid(-N:N, -N:N);
        G = exp(-(x.^2+y.^2)/(2*sig^2))/(2*pi*sig);
        Gx = -x.*G/(sig^2);Gx = Gx/sum(Gx(:));
        Gy = -y.*G/(sig^2);Gy = Gy/sum(Gy(:));
        Rx = imfilter(double(Image), Gx, 'conv', 'replicate');
        Ry = imfilter(double(Image), Gy, 'conv', 'replicate');
        FM = Rx.^2+Ry.^2;
        FM = mean2(FM);

    case 'GLVA' % Graylevel variance (Krotkov86)
        FM = std2(Image);

    case 'GLLV' %Graylevel local variance (Pech2000)        
        LVar = stdfilt(Image, ones(WSize,WSize)).^2;
        FM = std2(LVar)^2;

    case 'GLVN' % Normalized GLV (Santos97)
        FM = std2(Image)^2/mean2(Image);

    case 'GRAE' % Energy of gradient (Subbarao92a)
        Ix = Image;
        Iy = Image;
        Iy(1:end-1,:) = diff(Image, 1, 1);
        Ix(:,1:end-1) = diff(Image, 1, 2);
        FM = Ix.^2 + Iy.^2;
        FM = mean2(FM);

    case 'GRAT' % Thresholded gradient (Snatos97)
        Th = 0; %Threshold
        Ix = Image;
        Iy = Image;
        Iy(1:end-1,:) = diff(Image, 1, 1);
        Ix(:,1:end-1) = diff(Image, 1, 2);
        FM = max(abs(Ix), abs(Iy));
        FM(FM<Th)=0;
        FM = sum(FM(:))/sum(sum(FM~=0));

    case 'GRAS' % Squared gradient (Eskicioglu95)
        Ix = diff(Image, 1, 2);
        FM = Ix.^2;
        FM = mean2(FM);

    case 'HELM' %Helmli's mean method (Helmli2001)        
        MEANF = fspecial('average',[WSize WSize]);
        U = imfilter(Image, MEANF, 'replicate');
        R1 = U./Image;
        R1(Image==0)=1;
        index = (U>Image);
        FM = 1./R1;
        FM(index) = R1(index);
        FM = mean2(FM);

    case 'HISE' % Histogram entropy (Krotkov86)
        FM = entropy(Image);

    case 'HISR' % Histogram range (Firestone91)
        FM = max(Image(:))-min(Image(:));


    case 'LAPE' % Energy of laplacian (Subbarao92a)
        LAP = fspecial('laplacian');
        FM = imfilter(Image, LAP, 'replicate', 'conv');
        FM = mean2(FM.^2);

    case 'LAPM' % Modified Laplacian (Nayar89)
        M = [-1 2 -1];        
        Lx = imfilter(Image, M, 'replicate', 'conv');
        Ly = imfilter(Image, M', 'replicate', 'conv');
        FM = abs(Lx) + abs(Ly);
        FM = mean2(FM);

    case 'LAPV' % Variance of laplacian (Pech2000)
        LAP = fspecial('laplacian');
        ILAP = imfilter(Image, LAP, 'replicate', 'conv');
        FM = std2(ILAP)^2;

    case 'LAPD' % Diagonal laplacian (Thelen2009)
        M1 = [-1 2 -1];
        M2 = [0 0 -1;0 2 0;-1 0 0]/sqrt(2);
        M3 = [-1 0 0;0 2 0;0 0 -1]/sqrt(2);
        F1 = imfilter(Image, M1, 'replicate', 'conv');
        F2 = imfilter(Image, M2, 'replicate', 'conv');
        F3 = imfilter(Image, M3, 'replicate', 'conv');
        F4 = imfilter(Image, M1', 'replicate', 'conv');
        FM = abs(F1) + abs(F2) + abs(F3) + abs(F4);
        FM = mean2(FM);

    case 'SFIL' %Steerable filters (Minhas2009)
        % Angles = [0 45 90 135 180 225 270 315];
        N = floor(WSize/2);
        sig = N/2.5;
        [x,y] = meshgrid(-N:N, -N:N);
        G = exp(-(x.^2+y.^2)/(2*sig^2))/(2*pi*sig);
        Gx = -x.*G/(sig^2);Gx = Gx/sum(Gx(:));
        Gy = -y.*G/(sig^2);Gy = Gy/sum(Gy(:));
        R(:,:,1) = imfilter(double(Image), Gx, 'conv', 'replicate');
        R(:,:,2) = imfilter(double(Image), Gy, 'conv', 'replicate');
        R(:,:,3) = cosd(45)*R(:,:,1)+sind(45)*R(:,:,2);
        R(:,:,4) = cosd(135)*R(:,:,1)+sind(135)*R(:,:,2);
        R(:,:,5) = cosd(180)*R(:,:,1)+sind(180)*R(:,:,2);
        R(:,:,6) = cosd(225)*R(:,:,1)+sind(225)*R(:,:,2);
        R(:,:,7) = cosd(270)*R(:,:,1)+sind(270)*R(:,:,2);
        R(:,:,7) = cosd(315)*R(:,:,1)+sind(315)*R(:,:,2);
        FM = max(R,[],3);
        FM = mean2(FM);

    case 'SFRQ' % Spatial frequency (Eskicioglu95)
        Ix = Image;
        Iy = Image;
        Ix(:,1:end-1) = diff(Image, 1, 2);
        Iy(1:end-1,:) = diff(Image, 1, 1);
        FM = mean2(sqrt(double(Iy.^2+Ix.^2)));

    case 'TENG'% Tenengrad (Krotkov86)
        Sx = fspecial('sobel');
        Gx = imfilter(double(Image), Sx, 'replicate', 'conv');
        Gy = imfilter(double(Image), Sx', 'replicate', 'conv');
        FM = Gx.^2 + Gy.^2;
        FM = mean2(FM);

    case 'TENV' % Tenengrad variance (Pech2000)
        Sx = fspecial('sobel');
        Gx = imfilter(double(Image), Sx, 'replicate', 'conv');
        Gy = imfilter(double(Image), Sx', 'replicate', 'conv');
        G = Gx.^2 + Gy.^2;
        FM = std2(G)^2;

    case 'VOLA' % Vollath's correlation (Santos97)
        Image = double(Image);
        I1 = Image; I1(1:end-1,:) = Image(2:end,:);
        I2 = Image; I2(1:end-2,:) = Image(3:end,:);
        Image = Image.*(I1-I2);
        FM = mean2(Image);

    case 'WAVS' %Sum of Wavelet coeffs (Yang2003)
        [C,S] = wavedec2(Image, 1, 'db6');
        H = wrcoef2('h', C, S, 'db6', 1);   
        V = wrcoef2('v', C, S, 'db6', 1);   
        D = wrcoef2('d', C, S, 'db6', 1);   
        FM = abs(H) + abs(V) + abs(D);
        FM = mean2(FM);

    case 'WAVV' %Variance of  Wav...(Yang2003)
        [C,S] = wavedec2(Image, 1, 'db6');
        H = abs(wrcoef2('h', C, S, 'db6', 1));
        V = abs(wrcoef2('v', C, S, 'db6', 1));
        D = abs(wrcoef2('d', C, S, 'db6', 1));
        FM = std2(H)^2+std2(V)+std2(D);

    case 'WAVR'
        [C,S] = wavedec2(Image, 3, 'db6');
        H = abs(wrcoef2('h', C, S, 'db6', 1));   
        V = abs(wrcoef2('v', C, S, 'db6', 1));   
        D = abs(wrcoef2('d', C, S, 'db6', 1)); 
        A1 = abs(wrcoef2('a', C, S, 'db6', 1));
        A2 = abs(wrcoef2('a', C, S, 'db6', 2));
        A3 = abs(wrcoef2('a', C, S, 'db6', 3));
        A = A1 + A2 + A3;
        WH = H.^2 + V.^2 + D.^2;
        WH = mean2(WH);
        WL = mean2(A);
        FM = WH/WL;
    otherwise
        error('Unknown measure %s',upper(Measure))
end
 end
%************************************************************************
function fm = AcMomentum(Image)
[M N] = size(Image);
Hist = imhist(Image)/(M*N);
Hist = abs((0:255)-255*mean2(Image))'.*Hist;
fm = sum(Hist);
end

%******************************************************************
function fm = DctRatio(M)
MT = dct2(M).^2;
fm = (sum(MT(:))-MT(1,1))/MT(1,1);
end

%************************************************************************
function fm = ReRatio(M)
M = dct2(M);
fm = (M(1,2)^2+M(1,3)^2+M(2,1)^2+M(2,2)^2+M(3,1)^2)/(M(1,1)^2);
end
%******************************************************************

A few examples of OpenCV versions:

// OpenCV port of 'LAPM' algorithm (Nayar89)
double modifiedLaplacian(const cv::Mat& src)
{
    cv::Mat M = (Mat_<double>(3, 1) << -1, 2, -1);
    cv::Mat G = cv::getGaussianKernel(3, -1, CV_64F);

    cv::Mat Lx;
    cv::sepFilter2D(src, Lx, CV_64F, M, G);

    cv::Mat Ly;
    cv::sepFilter2D(src, Ly, CV_64F, G, M);

    cv::Mat FM = cv::abs(Lx) + cv::abs(Ly);

    double focusMeasure = cv::mean(FM).val[0];
    return focusMeasure;
}

// OpenCV port of 'LAPV' algorithm (Pech2000)
double varianceOfLaplacian(const cv::Mat& src)
{
    cv::Mat lap;
    cv::Laplacian(src, lap, CV_64F);

    cv::Scalar mu, sigma;
    cv::meanStdDev(lap, mu, sigma);

    double focusMeasure = sigma.val[0]*sigma.val[0];
    return focusMeasure;
}

// OpenCV port of 'TENG' algorithm (Krotkov86)
double tenengrad(const cv::Mat& src, int ksize)
{
    cv::Mat Gx, Gy;
    cv::Sobel(src, Gx, CV_64F, 1, 0, ksize);
    cv::Sobel(src, Gy, CV_64F, 0, 1, ksize);

    cv::Mat FM = Gx.mul(Gx) + Gy.mul(Gy);

    double focusMeasure = cv::mean(FM).val[0];
    return focusMeasure;
}

// OpenCV port of 'GLVN' algorithm (Santos97)
double normalizedGraylevelVariance(const cv::Mat& src)
{
    cv::Scalar mu, sigma;
    cv::meanStdDev(src, mu, sigma);

    double focusMeasure = (sigma.val[0]*sigma.val[0]) / mu.val[0];
    return focusMeasure;
}

No guarantees on whether or not these measures are the best choice for your problem, but if you track down the papers associated with these measures, they may give you more insight. Hope you find the code useful! I know I did.

Setting PayPal return URL and making it auto return?

I think that the idea of setting the Auto Return values as described above by Kevin is a bit strange!

Say, for example, that you have a number of websites that use the same PayPal account to handle your payments, or say that you have a number of sections in one website that perform different purchasing tasks, and require different return-addresses when the payment is completed. If I put a button on my page as described above in the 'Sample form using PHP for direct payments' section, you can see that there is a line there:

input type="hidden" name="return" value="https://www.yoursite.com/checkout_complete.php"

where you set the individual return value. Why does it have to be set generally, in the profile section as well?!?!

Also, because you can only set one value in the Profile Section, it means (AFAIK) that you cannot use the Auto Return on a site with multiple actions.

Comments please??

How to automatically crop and center an image

There is another way you can crop image centered:

.thumbnail{position: relative; overflow: hidden; width: 320px; height: 640px;}
.thumbnail img{
    position: absolute; top: -999px; bottom: -999px; left: -999px; right: -999px;
    width: auto !important; height: 100% !important; margin: auto;
}
.thumbnail img.vertical{width: 100% !important; height: auto !important;}

The only thing you will need is to add class "vertical" to vertical images, you can do it with this code:

jQuery(function($) {
    $('img').one('load', function () {
        var $img = $(this);
        var tempImage1 = new Image();
        tempImage1.src = $img.attr('src');
        tempImage1.onload = function() {
            var ratio = tempImage1.width / tempImage1.height;
            if(!isNaN(ratio) && ratio < 1) $img.addClass('vertical');
        }
    }).each(function () {
        if (this.complete) $(this).load();
    });
});

Note: "!important" is used to override possible width, height attributes on img tag.

re.sub erroring with "Expected string or bytes-like object"

The simplest solution is to apply Python str function to the column you are trying to loop through.

If you are using pandas, this can be implemented as:

dataframe['column_name']=dataframe['column_name'].apply(str)

Trim Whitespaces (New Line and Tab space) in a String in Oracle

TRANSLATE (column_name, 'd'||CHR(10)||CHR(13), 'd')

The 'd' is a dummy character, because translate does not work if the 3rd parameter is null.

Concatenate two JSON objects

var baseArrayOfJsonObjects = [{},{}];
for (var i=0; i<arrayOfJsonObjectsFromAjax.length; i++) {
    baseArrayOfJsonObjects.push(arrayOfJsonObjectsFromAjax[i]);
}

Implement touch using Python?

If you don't mind the try-except then...

def touch_dir(folder_path):
    try:
        os.mkdir(folder_path)
    except FileExistsError:
        pass

One thing to note though, if a file exists with the same name then it won't work and will fail silently.

Detect if checkbox is checked or unchecked in Angular.js ng-change event

The state of the checkbox will be reflected on whatever model you have it bound to, in this case, $scope.answers[item.questID]

How can I selectively escape percent (%) in Python strings?

If you are using Python 3.6 or newer, you can use f-string:

>>> test = "have it break."
>>> selectiveEscape = f"Print percent % in sentence and not {test}"
>>> print(selectiveEscape)
... Print percent % in sentence and not have it break.

Is it possible to assign numeric value to an enum in Java?

I realize this is an older question, but it comes up first in a Google search, and among the excellent answers provided, I didn't see anything fully comprehensive, so I did a little more digging and I ended up writing an enum class that not only allowed me to assign multiple custom values to the enum constants, I even added a method that allows me to assign values to them on the fly during code execution.

This enum class is for a "server" program that I run on a Raspberry Pi. The program receives commands from a client then it executes terminal commands that make adjustments to a webcam that is affixed to my 3D printer.

Using the Linux program 'v4l2-ctl' on the Pi, you can extract all of the possible adjustment commands for a given attached webcam, which also provides the setting datatype, the min and max values, the number of value steps in a given value range etc., so I took all of those and put them in an enum and created an enum interface that makes it easy to both set and get values for each command as well as a simple method to get the actual terminal command that is executed (using the Process and Runtime classes) in order to adjust the setting.

It is a rather large class and I apologize for that, but for me, it's always easier to learn something when I can see it working in full context, so I decided not to scale it down. However, even though it's large, it is definitely simple and it should be obvious what's happening in the class with minimal effort.

package constants;

import java.util.HashMap;
import java.util.Map;

public enum PICam {
    BRIGHTNESS                  ("brightness",                  0,      "int",      0,      100,    1,  50),
    CONTRAST                    ("contrast",                    1,      "int",      100,    100,    1,  0),
    SATURATION                  ("saturation",                  2,      "int",      100,    100,    1,  0),
    RED_BALANCE                 ("red_balance",                 3,      "intmenu",  1,      7999,   1,  1000),
    BLUE_BALANCE                ("blue_balance",                4,      "int",      1,      7999,   1,  1000),
    HORIZONTAL_FLIP             ("horizontal_flip",             5,      "bool",     0,      1,      1,  0),
    VERTICAL_FLIP               ("vertical_flip",               6,      "bool",     0,      1,      1,  0),
    POWER_LINE_FREQUENCY        ("power_line_frequency",        7,      "menu",     0,      3,      1,  1),
    SHARPNESS                   ("sharpness",                   8,      "int",      100,    100,    1,  0),
    COLOR_EFFECTS               ("color_effects",               9,      "menu",     0,      15,     1,  0),
    ROTATE                      ("rotate",                      10,     "int",      0,      360,    90, 0),
    COLOR_EFFECTS_CBCR          ("color_effects_cbcr",          11,     "int",      0,      65535,  1,  32896),
    VIDEO_BITRATE_MODE          ("video_bitrate_mode",          12,     "menu",     0,      1,      1,  0),
    VIDEO_BITRATE               ("video_bitrate",               13,     "int",      25000,  25000000,   25000,  10000000),
    REPEAT_SEQUENCE_HEADER      ("repeat_sequence_header",      14,     "bool",     0,      1,      1,  0),
    H264_I_FRAME_PERIOD         ("h_264_i_frame_period",        15,     "int",      0,      2147483647,1,   60),
    H264_LEVEL                  ("h_264_level",                 16,     "menu",     0,      11,     1,  11),
    H264_PROFILE                ("h_264_profile",               17,     "menu",     0,      4,      1,  4),
    AUTO_EXPOSURE               ("auto_exposure",               18,     "menu",     0,      3,      1,  0),
    EXPOSURE_TIME_ABSOLUTE      ("exposure_time_absolute",      19,     "int",      1,      10000,  1,  1000),
    EXPOSURE_DYNAMIC_FRAMERATE  ("exposure_dynamic_framerate",  20,     "bool",     0,      1,      1,  0),
    AUTO_EXPOSURE_BIAS          ("auto_exposure_bias",          21,     "intmenu",  0,      24,     1,  12),
    WHITE_BALANCE_AUTO_PRESET   ("white_balance_auto_preset",   22,     "menu",     0,      9,      1,  1),
    IMAGE_STABILIZATION         ("image_stabilization",         23,     "bool",     0,      1,      1,  0),
    ISO_SENSITIVITY             ("iso_sensitivity",             24,     "intmenu",  0,      4,      1,  0),
    ISO_SENSITIVITY_AUTO        ("iso_sensitivity_auto",        25,     "menu",     0,      1,      1,  1),
    EXPOSURE_METERING_MODE      ("exposure_metering_mode",      26,     "menu",     0,      2,      1,  0),
    SCENE_MODE                  ("scene_mode",                  27,     "menu",     0,      13,     1,  0),
    COMPRESSION_QUALITY         ("compression_quality",         28,     "int",      1,      100,    1,  30);


    private static final Map<String, PICam>    LABEL_MAP       = new HashMap<>();
    private static final Map<Integer, PICam>   INDEX_MAP       = new HashMap<>();
    private static final Map<String, PICam>    TYPE_MAP        = new HashMap<>();
    private static final Map<Integer, PICam>   MIN_MAP         = new HashMap<>();
    private static final Map<Integer, PICam>   MAX_MAP         = new HashMap<>();
    private static final Map<Integer, PICam>   STEP_MAP        = new HashMap<>();
    private static final Map<Integer, PICam>   DEFAULT_MAP     = new HashMap<>();
    private static final Map<Integer, Integer> THIS_VALUE_MAP  = new HashMap<>();

    private static final String                baseCommandLine = "/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=";

    static {
        for (PICam e: values()) {
            LABEL_MAP.put(e.label, e);
            INDEX_MAP.put(e.index, e);
            TYPE_MAP.put(e.type, e);
            MIN_MAP.put(e.min, e);
            MAX_MAP.put(e.max, e);
            STEP_MAP.put(e.step, e);
            DEFAULT_MAP.put(e.defaultValue, e);
        }
    }

    public final String label;
    public final int index;
    public final String type;
    public final int min;
    public final int max;
    public final int step;
    public final int defaultValue;

    private PICam(String label, int index, String type, int min, int max, int step, int defaultValue) {
        this.label = label;
        this.index = index;
        this.type = type;
        this.min = min;
        this.max = max;
        this.step = step;
        this.defaultValue = defaultValue;
    }

    public static void setValue(Integer index, Integer value) {
        if (THIS_VALUE_MAP.containsKey(index)) THIS_VALUE_MAP.replace(index, value);
        else THIS_VALUE_MAP.put(index, value);
    }

    public Integer getValue (Integer index) {
        return THIS_VALUE_MAP.getOrDefault(index, null);
    }

    public static PICam getLabel(String label) {
        return LABEL_MAP.get(label);
    }

    public static PICam getType(String type) {
        return TYPE_MAP.get(type);
    }

    public static PICam getMin(int min) {
        return MIN_MAP.get(min);
    }

    public static PICam getMax(int max) {
        return MAX_MAP.get(max);
    }

    public static PICam getStep(int step) {
        return STEP_MAP.get(step);
    }

    public static PICam getDefault(int defaultValue) {
        return DEFAULT_MAP.get(defaultValue);
    }

    public static String getCommandFor(int index, int newValue) {
        PICam picam = INDEX_MAP.get(index);
        String commandValue = "";
        if ("bool".equals(picam.type)) {
            commandValue = (newValue == 0) ? "false" : "true";
        }
        else {
            commandValue = String.valueOf(newValue);
        }
        return baseCommandLine + INDEX_MAP.get(index).label + "=" + commandValue;
    }

    public static String getCommandFor(PICam picam, Integer newValue) {
        String commandValue = "";
        if ("bool".equals(picam.type)) {
            commandValue = (newValue == 0) ? "false" : "true";
        }
        else {
            commandValue = String.valueOf(newValue);
        }
        return baseCommandLine + INDEX_MAP.get(picam.index).label + "=" + commandValue;
    }

    public static String getCommandFor(PICam piCam) {
        int    newValue     = piCam.defaultValue;
        String commandValue = "";
        if ("bool".equals(piCam.type)) {
            commandValue = (newValue == 0) ? "false" : "true";
        }
        else {
            commandValue = String.valueOf(newValue);
        }
        return baseCommandLine + piCam.label + "=" + commandValue;
    }

    public static String getCommandFor(Integer index) {
        PICam piCam = INDEX_MAP.get(index);
        int    newValue     = piCam.defaultValue;
        String commandValue = "";
        if ("bool".equals(piCam.type)) {
            commandValue = (newValue == 0) ? "false" : "true";
        }
        else {
            commandValue = String.valueOf(newValue);
        }
        return baseCommandLine + piCam.label + "=" + commandValue;
    }
}

Here are some ways that the class can be interacted with:

This code:

public static void test() {
    PICam.setValue(0,127); //Set brightness to 125
    PICam.setValue(PICam.SHARPNESS,143); //Set sharpness to 125
    String command1 = PICam.getSetCommandStringFor(PICam.BRIGHTNESS); //Get command line string to include the brightness value that we previously set referencing it by enum constant.
    String command2 = PICam.getSetCommandStringFor(0); //Get command line string to include the brightness value that we previously set referencing it by index number.
    String command3 = PICam.getDefaultCamString(PICam.BRIGHTNESS); //Get command line string with the default value
    String command4 = PICam.getSetCommandStringFor(PICam.SHARPNESS); //Get command line string with the sharpness value that we previously set.
    String command5 = PICam.getDefaultCamString(PICam.SHARPNESS); //Get command line string with the default sharpness value.
    System.out.println(command1);
    System.out.println(command2);
    System.out.println(command3);
    System.out.println(command4);
    System.out.println(command5);
}

Produces these results:

/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=brightness=127
/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=brightness=127
/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=brightness=50
/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=sharpness=143
/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=sharpness=0

Arduino Tools > Serial Port greyed out

install rx-tx lib for java run this command in terminal

sudo apt-get install librxtx-java -y

output port

sudo usermod -aG dialout $USER 
sudo apt-get install gnome-system-tools 

help regconize usb device

List of tables, db schema, dump etc using the Python sqlite3 API

I'm not familiar with the Python API but you can always use

SELECT * FROM sqlite_master;

How do I get which JRadioButton is selected from a ButtonGroup

import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.JRadioButton;
import javax.swing.JToggleButton;

public class RadioButton extends JRadioButton {

    public class RadioButtonModel extends JToggleButton.ToggleButtonModel {
        public Object[] getSelectedObjects() {
            if ( isSelected() ) {
                return new Object[] { RadioButton.this };
            } else {
                return new Object[0];
            }
        }

        public RadioButton getButton() { return RadioButton.this; }
    }

    public RadioButton() { super(); setModel(new RadioButtonModel()); }
    public RadioButton(Action action) { super(action); setModel(new RadioButtonModel()); }
    public RadioButton(Icon icon) { super(icon); setModel(new RadioButtonModel()); }
    public RadioButton(String text) { super(text); setModel(new RadioButtonModel()); }
    public RadioButton(Icon icon, boolean selected) { super(icon, selected); setModel(new RadioButtonModel()); }
    public RadioButton(String text, boolean selected) { super(text, selected); setModel(new RadioButtonModel()); }
    public RadioButton(String text, Icon icon) { super(text, icon); setModel(new RadioButtonModel()); }
    public RadioButton(String text, Icon icon, boolean selected) { super(text, icon, selected); setModel(new RadioButtonModel()); }

    public static void main(String[] args) {
        RadioButton b1 = new RadioButton("A");
        RadioButton b2 = new RadioButton("B");
        ButtonGroup group = new ButtonGroup();
        group.add(b1);
        group.add(b2);
        b2.setSelected(true);
        RadioButtonModel model = (RadioButtonModel)group.getSelection();
        System.out.println(model.getButton().getText());
    }
}

For homebrew mysql installs, where's my.cnf?

run

sudo find / -name my.cnf

Usually the first result is the correct one. Should be in

/usr/local/etc/

How to use ClassLoader.getResources() correctly?

The Spring Framework has a class which allows to recursively search through the classpath:

PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
resolver.getResources("classpath*:some/package/name/**/*.xml");

Trigger change event <select> using jquery

$('#edit_user_details').find('select').trigger('change');

It would change the select html tag drop-down item with id="edit_user_details".

How to get access token from FB.login method in javascript SDK

_x000D_
_x000D_
window.fbAsyncInit = function () {_x000D_
    FB.init({_x000D_
        appId: 'Your-appId',_x000D_
        cookie: false,  // enable cookies to allow the server to access _x000D_
        // the session_x000D_
        xfbml: true,  // parse social plugins on this page_x000D_
        version: 'v2.0' // use version 2.0_x000D_
    });_x000D_
};_x000D_
_x000D_
// Load the SDK asynchronously_x000D_
(function (d, s, id) {_x000D_
    var js, fjs = d.getElementsByTagName(s)[0];_x000D_
    if (d.getElementById(id)) return;_x000D_
    js = d.createElement(s); js.id = id;_x000D_
    js.src = "//connect.facebook.net/en_US/sdk.js";_x000D_
    fjs.parentNode.insertBefore(js, fjs);_x000D_
}(document, 'script', 'facebook-jssdk'));_x000D_
_x000D_
   _x000D_
function fb_login() {_x000D_
    FB.login(function (response) {_x000D_
_x000D_
        if (response.authResponse) {_x000D_
            console.log('Welcome!  Fetching your information.... ');_x000D_
            //console.log(response); // dump complete info_x000D_
            access_token = response.authResponse.accessToken; //get access token_x000D_
            user_id = response.authResponse.userID; //get FB UID_x000D_
_x000D_
            FB.api('/me', function (response) {_x000D_
                var email = response.email;_x000D_
                var name = response.name;_x000D_
                window.location = 'http://localhost:12962/Account/FacebookLogin/' + email + '/' + name;_x000D_
                // used in my mvc3 controller for //AuthenticationFormsAuthentication.SetAuthCookie(email, true);          _x000D_
            });_x000D_
_x000D_
        } else {_x000D_
            //user hit cancel button_x000D_
            console.log('User cancelled login or did not fully authorize.');_x000D_
_x000D_
        }_x000D_
    }, {_x000D_
        scope: 'email'_x000D_
    });_x000D_
}
_x000D_
<!-- custom image -->_x000D_
<a href="#" onclick="fb_login();"><img src="/Public/assets/images/facebook/facebook_connect_button.png" /></a>_x000D_
_x000D_
<!-- Facebook button -->_x000D_
<fb:login-button scope="public_profile,email" onlogin="fb_login();">_x000D_
                </fb:login-button>
_x000D_
_x000D_
_x000D_

Set System.Drawing.Color values

using System;
using System.Drawing;
public struct MyColor
    {
        private byte a, r, g, b;        
        public byte A
        {
            get
            {
                return this.a;
            }
        }
        public byte R
        {
            get
            {
                return this.r;
            }
        }
        public byte G
        {
            get
            {
                return this.g;
            }
        }
        public byte B
        {
            get
            {
                return this.b;
            }
        }       
        public MyColor SetAlpha(byte value)
        {
            this.a = value;
            return this;
        }
        public MyColor SetRed(byte value)
        {
            this.r = value;
            return this;
        }
        public MyColor SetGreen(byte value)
        {
            this.g = value;
            return this;
        }
        public MyColor SetBlue(byte value)
        {
            this.b = value;
            return this;
        }
        public int ToArgb()
        {
            return (int)(A << 24) || (int)(R << 16) || (int)(G << 8) || (int)(B);
        }
        public override string ToString ()
        {
            return string.Format ("[MyColor: A={0}, R={1}, G={2}, B={3}]", A, R, G, B);
        }

        public static MyColor FromArgb(byte alpha, byte red, byte green, byte blue)
        {
            return new MyColor().SetAlpha(alpha).SetRed(red).SetGreen(green).SetBlue(blue);
        }
        public static MyColor FromArgb(byte red, byte green, byte blue)
        {
            return MyColor.FromArgb(255, red, green, blue);
        }
        public static MyColor FromArgb(byte alpha, MyColor baseColor)
        {
            return MyColor.FromArgb(alpha, baseColor.R, baseColor.G, baseColor.B);
        }
        public static MyColor FromArgb(int argb)
        {
            return MyColor.FromArgb(argb & 255, (argb >> 8) & 255, (argb >> 16) & 255, (argb >> 24) & 255);
        }   
        public static implicit operator Color(MyColor myColor)
        {           
            return Color.FromArgb(myColor.ToArgb());
        }
        public static implicit operator MyColor(Color color)
        {
            return MyColor.FromArgb(color.ToArgb());
        }
    }

What is an NP-complete in computer science?

NP-Complete means something very specific and you have to be careful or you will get the definition wrong. First, an NP problem is a yes/no problem such that

  1. There is polynomial-time proof for every instance of the problem with a "yes" answer that the answer is "yes", or (equivalently)
  2. There exists a polynomial-time algorithm (possibly using random variables) that has a non-zero probability of answering "yes" if the answer to an instance of the problem is "yes" and will say "no" 100% of the time if the answer is "no." In other words, the algorithm must have a false-negative rate less than 100% and no false positives.

A problem X is NP-Complete if

  1. X is in NP, and
  2. For any problem Y in NP, there is a "reduction" from Y to X: a polynomial-time algorithm that transforms any instance of Y into an instance of X such that the answer to the Y-instance is "yes" if and only if the answer X-instance is "yes".

If X is NP-complete and a deterministic, polynomial-time algorithm exists that can solve all instances of X correctly (0% false-positives, 0% false-negatives), then any problem in NP can be solved in deterministic-polynomial-time (by reduction to X).

So far, nobody has come up with such a deterministic polynomial-time algorithm, but nobody has proven one doesn't exist (there's a million bucks for anyone who can do either: the is the P = NP problem). That doesn't mean that you can't solve a particular instance of an NP-Complete (or NP-Hard) problem. It just means you can't have something that will work reliably on all instances of a problem the same way you could reliably sort a list of integers. You might very well be able to come up with an algorithm that will work very well on all practical instances of a NP-Hard problem.

What is Bit Masking?

Masking means to keep/change/remove a desired part of information. Lets see an image-masking operation; like- this masking operation is removing any thing that is not skin-

enter image description here

We are doing AND operation in this example. There are also other masking operators- OR, XOR.


Bit-Masking means imposing mask over bits. Here is a bit-masking with AND-

     1 1 1 0 1 1 0 1   [input]
(&)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     0 0 1 0 1 1 0 0  [output]

So, only the middle 4 bits (as these bits are 1 in this mask) remain.

Lets see this with XOR-

     1 1 1 0 1 1 0 1   [input]
(^)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     1 1 0 1 0 0 0 1  [output]

Now, the middle 4 bits are flipped (1 became 0, 0 became 1).


So, using bit-mask we can access individual bits [examples]. Sometimes, this technique may also be used for improving performance. Take this for example-

bool isOdd(int i) {
    return i%2;
}

This function tells if an integer is odd/even. We can achieve the same result with more efficiency using bit-mask-

bool isOdd(int i) {
    return i&1;
}

Short Explanation: If the least significant bit of a binary number is 1 then it is odd; for 0 it will be even. So, by doing AND with 1 we are removing all other bits except for the least significant bit i.e.:

     55  ->  0 0 1 1 0 1 1 1   [input]
(&)   1  ->  0 0 0 0 0 0 0 1    [mask]
---------------------------------------
      1  <-  0 0 0 0 0 0 0 1  [output]

CSS Positioning Elements Next to each other

If you want them to be displayed side by side, why is sideContent the child of mainContent? make them siblings then use:

float:left; display:inline; width: 49%;

on both of them.

#mainContent, #sideContent {float:left; display:inline; width: 49%;}

Adding an image to a PDF using iTextSharp and scale it properly

Personally, I use something close from fubo's solution and it works well:

image.ScaleToFit(document.PageSize);
image.SetAbsolutePosition(0,0);

How do I properly compare strings in C?

Welcome to the concept of the pointer. Generations of beginning programmers have found the concept elusive, but if you wish to grow into a competent programmer, you must eventually master this concept — and moreover, you are already asking the right question. That's good.

Is it clear to you what an address is? See this diagram:

----------     ----------
| 0x4000 |     | 0x4004 |
|    1   |     |    7   |
----------     ----------

In the diagram, the integer 1 is stored in memory at address 0x4000. Why at an address? Because memory is large and can store many integers, just as a city is large and can house many families. Each integer is stored at a memory location, as each family resides in a house. Each memory location is identified by an address, as each house is identified by an address.

The two boxes in the diagram represent two distinct memory locations. You can think of them as if they were houses. The integer 1 resides in the memory location at address 0x4000 (think, "4000 Elm St."). The integer 7 resides in the memory location at address 0x4004 (think, "4004 Elm St.").

You thought that your program was comparing the 1 to the 7, but it wasn't. It was comparing the 0x4000 to the 0x4004. So what happens when you have this situation?

----------     ----------
| 0x4000 |     | 0x4004 |
|    1   |     |    1   |
----------     ----------

The two integers are the same but the addresses differ. Your program compares the addresses.

Apply pandas function to column to create multiple new columns?

I've looked several ways of doing this and the method shown here (returning a pandas series) doesn't seem to be most efficient.

If we start with a largeish dataframe of random data:

# Setup a dataframe of random numbers and create a 
df = pd.DataFrame(np.random.randn(10000,3),columns=list('ABC'))
df['D'] = df.apply(lambda r: ':'.join(map(str, (r.A, r.B, r.C))), axis=1)
columns = 'new_a', 'new_b', 'new_c'

The example shown here:

# Create the dataframe by returning a series
def method_b(v):
    return pd.Series({k: v for k, v in zip(columns, v.split(':'))})
%timeit -n10 -r3 df.D.apply(method_b)

10 loops, best of 3: 2.77 s per loop

An alternative method:

# Create a dataframe from a series of tuples
def method_a(v):
    return v.split(':')
%timeit -n10 -r3 pd.DataFrame(df.D.apply(method_a).tolist(), columns=columns)

10 loops, best of 3: 8.85 ms per loop

By my reckoning it's far more efficient to take a series of tuples and then convert that to a DataFrame. I'd be interested to hear people's thinking though if there's an error in my working.

Automated testing for REST Api

I implemented many automation cases based on REST Assured , a jave DSL for testing restful service. https://code.google.com/p/rest-assured/

The syntax is easy, it supports json and xml. https://code.google.com/p/rest-assured/wiki/Usage

Before that, I tried SOAPUI and had some issues with the free version. Plus the cases are in xml files which hard to extend and reuse, simply I don't like

SSL Connection / Connection Reset with IISExpress

Make sure to remove any previous 'localhost' certificates as those could conflict with the one generated by IIS Express. I had this same error (ERR_SSL_PROTOCOL_ERROR), and it took me many hours to finally figure it out after trying out many many "solutions". My mistake was that I had created my own 'localhost' certificate and there were two of them. I had to delete both and have IIS Express recreate it.

Here is how you can check for and remove 'localhost' certificate:

  • On Start, type ? mmc.exe
  • File ? Add/Remove Snap-in...
  • Select Certificates ? Add> ? Computer account ? Local computer
  • Check under Certificates > Personal > Certificates
  • Make sure the localhost certificate that exist has a friendly name "IIS Express Development Certificate". If not, delete it. Or if multiple, delete all.

On Visual Studio, select project and under property tab, enable SSL=true. Save, Build and Run. IIS Express will generate a new 'localhost' certificate.

Note: If it doesn't work, try these: make sure to disable IIS Express on VS project and stopping all running app on it prior to removing 'localhost' certificate. Also, you can go to 'control panel > programs' and Repair IIS Express.

How to print to console in pytest?

I originally came in here to find how to make PyTest print in VSCode's console while running/debugging the unit test from there. This can be done with the following launch.json configuration. Given .venv the virtual environment folder.

    "version": "0.2.0",
    "configurations": [
        {
            "name": "PyTest",
            "type": "python",
            "request": "launch",
            "stopOnEntry": false,
            "pythonPath": "${config:python.pythonPath}",
            "module": "pytest",
            "args": [
                "-sv"
            ],
            "cwd": "${workspaceRoot}",
            "env": {},
            "envFile": "${workspaceRoot}/.venv",
            "debugOptions": [
                "WaitOnAbnormalExit",
                "WaitOnNormalExit",
                "RedirectOutput"
            ]
        }
    ]
}

How do I upload a file with the JS fetch API?

To submit a single file, you can simply use the File object from the input's .files array directly as the value of body: in your fetch() initializer:

const myInput = document.getElementById('my-input');

// Later, perhaps in a form 'submit' handler or the input's 'change' handler:
fetch('https://example.com/some_endpoint', {
  method: 'POST',
  body: myInput.files[0],
});

This works because File inherits from Blob, and Blob is one of the permissible BodyInit types defined in the Fetch Standard.

How to show MessageBox on asp.net?

MessageBox doesn't exist in ASP.NET. If you need functionality in the browser, like showing a message box, then you need to opt for javascript. ASP.NET provides you with means to inject javascript which gets rendered and executed when the html sent to the browser's loaded and displayed. You can use the following code in the Page_Load for example:

Type cstype = this.GetType();

// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;

// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, "PopupScript"))
{
    String cstext = "alert('Hello World');";
    cs.RegisterStartupScript(cstype, "PopupScript", cstext, true);
}

This sample's taken from MSDN.

Set padding for UITextField with UITextBorderStyleNone

Nate Flink's answer is my favourite, but don't forget about right/left views. E.g for UITextField subclass:

override func rightViewRectForBounds(bounds: CGRect) -> CGRect {
    let rightViewBounds = super.rightViewRectForBounds(bounds)

    return CGRectMake(CGRectGetMinX(rightViewBounds) - 10, CGRectGetMinY(rightViewBounds), CGRectGetWidth(rightViewBounds), CGRectGetHeight(rightViewBounds))
}

Above code set right padding for rightView of UITextField.

Test if remote TCP port is open from a shell script

If you want to use nc but don't have a version that support -z, try using --send-only:

nc --send-only <IP> <PORT> </dev/null

and with timeout:

nc -w 1 --send-only <IP> <PORT> </dev/null

and without DNS lookup if it's an IP:

nc -n -w 1 --send-only <IP> <PORT> </dev/null

It returns the codes as the -z based on if it can connect or not.

Can promises have multiple arguments to onFulfilled?

Since functions in Javascript can be called with any number of arguments, and the document doesn't place any restriction on the onFulfilled() method's arguments besides the below clause, I think that you can pass multiple arguments to the onFulfilled() method as long as the promise's value is the first argument.

2.2.2.1 it must be called after promise is fulfilled, with promise’s value as its first argument.

Bash: If/Else statement in one line

You can make full use of the && and || operators like this:

ps aux | grep some_proces[s] > /tmp/test.txt && echo 1 || echo 0

For excluding grep itself, you could also do something like:

ps aux | grep some_proces | grep -vw grep > /tmp/test.txt && echo 1 || echo 0