Programs & Examples On #Glm

For questions relating to generalized linear models. For the GLM math library, see [tag:glm-math].

How to succinctly write a formula with many variables from a data frame?

A slightly different approach is to create your formula from a string. In the formula help page you will find the following example :

## Create a formula for a model with a large number of variables:
xnam <- paste("x", 1:25, sep="")
fmla <- as.formula(paste("y ~ ", paste(xnam, collapse= "+")))

Then if you look at the generated formula, you will get :

R> fmla
y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 + 
    x12 + x13 + x14 + x15 + x16 + x17 + x18 + x19 + x20 + x21 + 
    x22 + x23 + x24 + x25

How to store Node.js deployment settings/configuration files?

npm i config

In config/default.json
{
    "app": {
        "port": 3000
    },
    "db": {
        "port": 27017,
        "name": "dev_db_name"
    }
}

In config/production.json
{
    "app": {
        "port": 4000
    },
    "db": {
        "port": 27000,
        "name": "prod_db_name"
    }
}

In index.js

const config = require('config');

let appPort = config.get('app.port');
console.log(`Application port: ${appPort}`);

let dbPort = config.get('db.port');
console.log(`Database port: ${dbPort}`);

let dbName = config.get('db.name');
console.log(`Database name: ${dbName}`);

console.log('NODE_ENV: ' + config.util.getEnv('NODE_ENV'));

$ node index.js
Application port: 3000
Database port: 27017
Database name: dev_db_name
NODE_ENV: development

For production
$ set NODE_ENV=production
$ node index.js
Application port: 4000
Database port: 27000
Database name: prod_db_name
NODE_ENV: production

android listview item height

The trick for me was not setting the height -- but instead setting the minHeight. This must be applied to the root view of whatever layout your custom adapter is using to render each row.

SQL Server: How to use UNION with two queries that BOTH have a WHERE clause?

declare @T1 table(ID int, ReceivedDate datetime, [type] varchar(10))
declare @T2 table(ID int, ReceivedDate datetime, [type] varchar(10))

insert into @T1 values(1, '20010101', '1')
insert into @T1 values(2, '20010102', '1')
insert into @T1 values(3, '20010103', '1')

insert into @T2 values(10, '20010101', '2')
insert into @T2 values(20, '20010102', '2')
insert into @T2 values(30, '20010103', '2')

;with cte1 as
(
  select *,
    row_number() over(order by ReceivedDate desc) as rn
  from @T1
  where [type] = '1'
),
cte2 as
(
  select *,
    row_number() over(order by ReceivedDate desc) as rn
  from @T2
  where [type] = '2'
)
select *
from cte1
where rn <= 2
union all
select *
from cte2
where rn <= 2

Deserialize a JSON array in C#

This code is working fine for me,

var a = serializer.Deserialize<List<Entity>>(json);

How to check that a string is parseable to a double?

Something like below should suffice :-

String decimalPattern = "([0-9]*)\\.([0-9]*)";  
String number="20.00";  
boolean match = Pattern.matches(decimalPattern, number);
System.out.println(match); //if true then decimal else not  

AngularJS dynamic routing

As of AngularJS 1.1.3, you can now do exactly what you want using the new catch-all parameter.

https://github.com/angular/angular.js/commit/7eafbb98c64c0dc079d7d3ec589f1270b7f6fea5

From the commit:

This allows routeProvider to accept parameters that matches substrings even when they contain slashes if they are prefixed with an asterisk instead of a colon. For example, routes like edit/color/:color/largecode/*largecode will match with something like this http://appdomain.com/edit/color/brown/largecode/code/with/slashs.

I have tested it out myself (using 1.1.5) and it works great. Just keep in mind that each new URL will reload your controller, so to keep any kind of state, you may need to use a custom service.

How can I account for period (AM/PM) using strftime?

You used %H (24 hour format) instead of %I (12 hour format).

Extract digits from string - StringUtils Java

A very simple solution, if separated by comma or if not separated by comma

public static void main(String[] args) {

    String input = "a,1,b,2,c,3,d,4";
    input = input.replaceAll(",", "");

    String alpha ="";
    String num = "";

    char[] c_arr = input.toCharArray();

    for(char c: c_arr) {
        if(Character.isDigit(c)) {
            alpha = alpha + c;
        }
        else {
            num = num+c;
        }
    }

    System.out.println("Alphabet: "+ alpha);
    System.out.println("num: "+ num);

}

Check whether a path is valid in Python without creating a file at the path's target

if os.path.exists(filePath):
    #the file is there
elif os.access(os.path.dirname(filePath), os.W_OK):
    #the file does not exists but write privileges are given
else:
    #can not write there

Note that path.exists can fail for more reasons than just the file is not there so you might have to do finer tests like testing if the containing directory exists and so on.


After my discussion with the OP it turned out, that the main problem seems to be, that the file name might contain characters that are not allowed by the filesystem. Of course they need to be removed but the OP wants to maintain as much human readablitiy as the filesystem allows.

Sadly I do not know of any good solution for this. However Cecil Curry's answer takes a closer look at detecting the problem.

PostgreSQL: days/months/years between two dates

Here is a complete example with output. psql (10.1, server 9.5.10).

You get 58, not some value less than 30.
Remove age() function, solved the problem that previous post mentioned.

drop table t;
create table t(
    d1 date
);

insert into t values(current_date - interval '58 day');

select d1
, current_timestamp - d1::timestamp date_diff
, date_part('day', current_timestamp - d1::timestamp)
from t;

     d1     |        date_diff        | date_part
------------+-------------------------+-----------
 2018-05-21 | 58 days 21:41:07.992731 |        58

C++ Compare char array with string

In this code you are not comparing string values, you are comparing pointer values. If you want to compare string values you need to use a string comparison function such as strcmp.

if ( 0 == strcmp(var1, "dev")) {
  ..
}

What does "Content-type: application/json; charset=utf-8" really mean?

I was using HttpClient and getting back response header with content-type of application/json, I lost characters such as foreign languages or symbol that used unicode since HttpClient is default to ISO-8859-1. So, be explicit as possible as mentioned by @WesternGun to avoid any possible problem.

There is no way handle that due to server doesn't handle requested-header charset (method.setRequestHeader("accept-charset", "UTF-8");) for me and I had to retrieve response data as draw bytes and convert it into String using UTF-8. So, it is recommended to be explicit and avoid assumption of default value.

htaccess redirect all pages to single page

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?olddomain\.com$ [NC]
RewriteRule ^(.*)$ "http://www.thenewdomain.com/" [R=301,L]

Short circuit Array.forEach like calling break

You can use every method:

[1,2,3].every(function(el) {
    return !(el === 1);
});

ES6

[1,2,3].every( el => el !== 1 )

for old browser support use:

if (!Array.prototype.every)
{
  Array.prototype.every = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this &&
          !fun.call(thisp, this[i], i, this))
        return false;
    }

    return true;
  };
}

more details here.

Find the host name and port using PSQL commands

This is non-sql method. Instructions are given on the image itself. Select the server that you want to find the info about and then follow the steps.

enter image description here

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

do you try

[{"name":"myEnterprise", "departments":["HR"]}]

the square brace is the key point.

How to suspend/resume a process in Windows?

#pragma comment(lib,"ntdll.lib")
EXTERN_C NTSTATUS NTAPI NtSuspendProcess(IN HANDLE ProcessHandle);

void SuspendSelf(){
    NtSuspendProcess(GetCurrentProcess());
}

ntdll contains the exported function NtSuspendProcess, pass the handle to a process to do the trick.

CSS: background image on background color

body 
{
background-image:url('image/img2.jpg');
margin: 0px;
 padding: 0px;
}

insert vertical divider line between two nested divs, not full height

Can't think of a only css solution, but couldn't you just had a div between those 2 and set in the css the properties to look like a line like shown in the image? If you are using divs as they were table cells this is a pretty simple solution to the problem

Arithmetic operation resulted in an overflow. (Adding integers)

This error occurred for me when a value was returned as -1.#IND due to a division by zero. More info on IEEE floating-point exceptions in C++ here on SO and by John Cook

For the one who has downvoted this answer (and did not specify why), the reason why this answer can be significant to some is that a division by zero will lead to an infinitely large number and thus a value that doesn't fit in an Int32 (or even Int64). So the error you receive will be the same (Arithmetic operation resulted in an overflow) but the reason is slightly different.

map function for objects (instead of arrays)

No native methods, but lodash#mapValues will do the job brilliantly

_.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; });
// ? { 'a': 3, 'b': 6, 'c': 9 }

How do I use Notepad++ (or other) with msysgit?

This works for me

git config --global core.editor C:/Progra~1/Notepad++/notepad++.exe

MVC Form not able to post List of objects

Please read this: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
You should set indicies for your html elements "name" attributes like planCompareViewModel[0].PlanId, planCompareViewModel[1].PlanId to make binder able to parse them into IEnumerable.
Instead of @foreach (var planVM in Model) use for loop and render names with indexes.

add/remove active class for ul list with jquery?

this will point to the <ul> selected by .nav-list. You can use delegation instead!

$('.nav-list').on('click', 'li', function() {
    $('.nav-list li.active').removeClass('active');
    $(this).addClass('active');
});

React Router with optional path parameter

If you are looking to do an exact match, use the following syntax: (param)?.

Eg.

<Route path={`my/(exact)?/path`} component={MyComponent} />

The nice thing about this is that you'll have props.match to play with, and you don't need to worry about checking the value of the optional parameter:

{ props: { match: { "0": "exact" } } }

Hibernate Annotations - Which is better, field or property access?

Are we there yet

That's an old presentation but Rod suggests that annotation on property access encourages anemic domain models and should not be the "default" way to annotate.

How do you truncate all tables in a database using TSQL?

Here's the king daddy of database wiping scripts. It will clear all tables and reseed them correctly:

SET QUOTED_IDENTIFIER ON;
EXEC sp_MSforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER TABLE ? NOCHECK CONSTRAINT ALL'  
EXEC sp_MSforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER TABLE ? DISABLE TRIGGER ALL'  
EXEC sp_MSforeachtable 'SET QUOTED_IDENTIFIER ON; DELETE FROM ?'  
EXEC sp_MSforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER TABLE ? CHECK CONSTRAINT ALL'  
EXEC sp_MSforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER TABLE ? ENABLE TRIGGER ALL' 
EXEC sp_MSforeachtable 'SET QUOTED_IDENTIFIER ON';

IF NOT EXISTS (
    SELECT
        *
    FROM
        SYS.IDENTITY_COLUMNS
        JOIN SYS.TABLES ON SYS.IDENTITY_COLUMNS.Object_ID = SYS.TABLES.Object_ID
    WHERE
        SYS.TABLES.Object_ID = OBJECT_ID('?') AND SYS.IDENTITY_COLUMNS.Last_Value IS NULL
)
AND OBJECTPROPERTY( OBJECT_ID('?'), 'TableHasIdentity' ) = 1

    DBCC CHECKIDENT ('?', RESEED, 0) WITH NO_INFOMSGS;

Enjoy, but be careful!

Unable to verify leaf signature

Just putting this here in case it helps someone, my case was different and a bit of an odd mix. I was getting this on a request that was accessed via superagent - the problem had nothing to do with certificates (which were setup properly) and all to do with the fact that I was then passing the superagent result through the async module's waterfall callback. To fix: Instead of passing the entire result, just pass result.body through the waterfall's callback.

How to convert an ArrayList containing Integers to primitive int array?

If you are using there's also another way to do this.

int[] arr = list.stream().mapToInt(i -> i).toArray();

What it does is:

  • getting a Stream<Integer> from the list
  • obtaining an IntStream by mapping each element to itself (identity function), unboxing the int value hold by each Integer object (done automatically since Java 5)
  • getting the array of int by calling toArray

You could also explicitly call intValue via a method reference, i.e:

int[] arr = list.stream().mapToInt(Integer::intValue).toArray();

It's also worth mentioning that you could get a NullPointerException if you have any null reference in the list. This could be easily avoided by adding a filtering condition to the stream pipeline like this:

                       //.filter(Objects::nonNull) also works
int[] arr = list.stream().filter(i -> i != null).mapToInt(i -> i).toArray();

Example:

List<Integer> list = Arrays.asList(1, 2, 3, 4);
int[] arr = list.stream().mapToInt(i -> i).toArray(); //[1, 2, 3, 4]

list.set(1, null); //[1, null, 3, 4]
arr = list.stream().filter(i -> i != null).mapToInt(i -> i).toArray(); //[1, 3, 4]

How to make the Facebook Like Box responsive?

None of the css trick worked for me (in my case the fb-like box was pulled right with "float:right"). However, what worked without any additional tricks is an IFRAME version of the button code. I.e.:

<iframe src="//www.facebook.com/plugins/like.php?href=..." 
        scrolling="no" frameborder="0" 
        style="border:none; overflow:hidden; width:71px; height:21px;" 
        allowTransparency="true">
</iframe>

(Note custom width in style, and no need to include additional javascript.)

Android Studio installation on Windows 7 fails, no JDK found

Install the latest JDK in your system from JDK 7 and JRE 7 Installation Guide.

JAVA_HOME -> C:\Program Files\Java\jdk1.7.0_4
path -> C:\Program Files\Java\jdk1.7.0_4\bin

Ansible: create a user with sudo privileges

To create a user with sudo privileges is to put the user into /etc/sudoers, or make the user a member of a group specified in /etc/sudoers. And to make it password-less is to additionally specify NOPASSWD in /etc/sudoers.

Example of /etc/sudoers:

## Allow root to run any commands anywhere
root    ALL=(ALL)       ALL

## Allows people in group wheel to run all commands
%wheel  ALL=(ALL)       ALL

## Same thing without a password
%wheel  ALL=(ALL)       NOPASSWD: ALL

And instead of fiddling with /etc/sudoers file, we can create a new file in /etc/sudoers.d/ directory since this directory is included by /etc/sudoers by default, which avoids the possibility of breaking existing sudoers file, and also eliminates the dependency on the content inside of /etc/sudoers.

To achieve above in Ansible, refer to the following:

- name: sudo without password for wheel group
  copy:
    content: '%wheel ALL=(ALL:ALL) NOPASSWD:ALL'
    dest: /etc/sudoers.d/wheel_nopasswd
    mode: 0440

You may replace %wheel with other group names like %sudoers or other user names like deployer.

Javascript format date / time

You can do that:

function formatAMPM(date) { // This is to display 12 hour format like you asked
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + ' ' + ampm;
  return strTime;
}

var myDate = new Date();
var displayDate = myDate.getMonth()+ '/' +myDate.getDate()+ '/' +myDate.getFullYear()+ ' ' +formatAMPM(myDate);
console.log(displayDate);

Fiddle

Exiting from python Command Line

This works for me, best way to come out of python prompt.

exit()

node.js: cannot find module 'request'

I was running into the same problem, here is how I got it working..

open terminal:

mkdir testExpress
cd testExpress
npm install request

or

sudo npm install -g request // If you would like to globally install.

now don't use

node app.js or node test.js, you will run into this problem doing so. You can also print the problem that is being cause by using this command.. "node -p app.js"

The above command to start nodeJs has been deprecated. Instead use

npm start

You should see this..

[email protected] start /Users/{username}/testExpress
node ./bin/www

Open your web browser and check for localhost:3000

You should see Express install (Welcome to Express)

Connect different Windows User in SQL Server Management Studio (2005 or later)

Hold shift and right click on SQL Server Mangement studion icon. You can Run as other windows account user.

combining two string variables

you need to take out the quotes:

soda = a + b

(You want to refer to the variables a and b, not the strings "a" and "b")

Convert the values in a column into row names in an existing data frame

It looks like the one-liner got even simpler along the line (currently using R 3.5.3):

# generate original data.frame
df <- data.frame(a = letters[1:10], b = 1:10, c = LETTERS[1:10])
# use first column for row names
df <- data.frame(df, row.names = 1)

The column used for row names is removed automatically.

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

This is the right way to clear this error.

export ORACLE_HOME=/u01/app/oracle/product/10.2.0/db_1 sqlplus / as sysdba

Converting a double to an int in Javascript without rounding

A trick to truncate that avoids a function call entirely is

var number = 2.9
var truncated = number - number % 1;
console.log(truncated); // 2 

To round a floating-point number to the nearest integer, use the addition/subtraction trick. This works for numbers with absolute value < 2 ^ 51.

var number = 2.9
var rounded = number + 6755399441055744.0 - 6755399441055744.0;  // (2^52 + 2^51)
console.log(rounded); // 3 

Note:

Halfway values are rounded to the nearest even using "round half to even" as the tie-breaking rule. Thus, for example, +23.5 becomes +24, as does +24.5. This variant of the round-to-nearest mode is also called bankers' rounding.

The magic number 6755399441055744.0 is explained in the stackoverflow post "A fast method to round a double to a 32-bit int explained".

_x000D_
_x000D_
// Round to whole integers using arithmetic operators
let trunc = (v) => v - v % 1;
let ceil  = (v) => trunc(v % 1 > 0 ? v + 1 : v);
let floor = (v) => trunc(v % 1 < 0 ? v - 1 : v);
let round = (v) => trunc(v < 0 ? v - 0.5 : v + 0.5);

let roundHalfEven = (v) => v + 6755399441055744.0 - 6755399441055744.0; // (2^52 + 2^51)

console.log("number  floor   ceil  round  trunc");
var array = [1.5, 1.4, 1.0, -1.0, -1.4, -1.5];
array.forEach(x => {
    let f = x => (x).toString().padStart(6," ");
    console.log(`${f(x)} ${f(floor(x))} ${f(ceil(x))} ${f(round(x))} ${f(trunc(x))}`);  
});
_x000D_
_x000D_
_x000D_

ImportError: No module named sklearn.cross_validation

It must relate to the renaming and deprecation of cross_validation sub-module to model_selection. Try substituting cross_validation to model_selection

How to decompile to java files intellij idea

Someone had gave good answers. I made another instruction clue step by step. First, open your studio and search. You can find the decompier is Fernflower.

enter image description here

Second, we can find it in the plugins directory.

/Applications/Android Studio.app/Contents/plugins/java-decompiler/lib/java-decompiler.jar

Third, run it, you will get the usage

java -cp "/Applications/Android Studio.app/Contents/plugins/java-decompiler/lib/java-decompiler.jar" org.jetbrains.java.decompiler.main.decompiler.ConsoleDecompiler

Usage: java -jar fernflower.jar [-<option>=<value>]* [<source>]+ <destination>
Example: java -jar fernflower.jar -dgs=true c:\my\source\ c:\my.jar d:\decompiled\

Finally, The studio's nest options for decompiler list as follows according IdeaDecompiler.kt

-hdc=0 -dgs=1 -rsy=1 -rbr=1 -lit=1 -nls=1 -mpm=60 -lac=1

IFernflowerPreferences.HIDE_DEFAULT_CONSTRUCTOR to "0",
        IFernflowerPreferences.DECOMPILE_GENERIC_SIGNATURES to "1",
        IFernflowerPreferences.REMOVE_SYNTHETIC to "1",
        IFernflowerPreferences.REMOVE_BRIDGE to "1",
        IFernflowerPreferences.LITERALS_AS_IS to "1",
        IFernflowerPreferences.NEW_LINE_SEPARATOR to "1",
        **IFernflowerPreferences.BANNER to BANNER,**
        IFernflowerPreferences.MAX_PROCESSING_METHOD to 60,
        **IFernflowerPreferences.INDENT_STRING to indent,**
        **IFernflowerPreferences.IGNORE_INVALID_BYTECODE to "1",**
        IFernflowerPreferences.VERIFY_ANONYMOUS_CLASSES to "1",
         **IFernflowerPreferences.UNIT_TEST_MODE to if (ApplicationManager.getApplication().isUnitTestMode) "1" else "0")**

I cant find the sutialbe option for the asterisk items.

Hope these steps will make the question clear.

Why do I get "MismatchSenderId" from GCM server side?

With the deprecation of GCM and removal of its APIs, it appears that you could see MismatchSenderId if you try to use GCM after May 29, 2019. See the Google GCM and FCM FAQ for more details.

WAMP server, localhost is not working

First stop IIS from startmenu by typing IIS manager, Edit c:/wamp/wampmanager.tpl file so the WAMP menu points to localhost:80. Find http://localhost and change it to htttp://localhost:80 also, if you think something else has already grabbed port 80, that is why its not working..,then, Run

wampmanager->Apache->Service->Test port 80

This will launch a command window and tell you what is using port 80. Whatever it is, will need to be re-configured to use another port or for example if its IIS and you dont use IIS it should be un-installed. Further you can use 'net stop' command to stop desired service.

Convert Base64 string to an image file?

if($_SERVER['REQUEST_METHOD']=='POST'){
$image_no="5";//or Anything You Need
$image = $_POST['image'];
$path = "uploads/".$image_no.".png";

$status = file_put_contents($path,base64_decode($image));
if($status){
 echo "Successfully Uploaded";
}else{
 echo "Upload failed";
}
}

Bulk Insert into Oracle database: Which is better: FOR Cursor loop or a simple Select?

As you can see by reading the other answers, there are a lot of options available. If you are just doing < 10k rows you should go with the second option.

In short, for approx > 10k all the way to say a <100k. It is kind of a gray area. A lot of old geezers will bark at big rollback segments. But honestly hardware and software have made amazing progress to where you may be able to get away with option 2 for a lot of records if you only run the code a few times. Otherwise you should probably commit every 1k-10k or so rows. Here is a snippet that I use. I like it because it is short and I don't have to declare a cursor. Plus it has the benefits of bulk collect and forall.

begin
    for r in (select rownum rn, t.* from foo t) loop
        insert into bar (A,B,C) values (r.A,r.B,r.C);
        if mod(rn,1000)=0 then
            commit;
        end if;
    end;
    commit;
end;

I found this link from the oracle site that illustrates the options in more detail.

Pointer to 2D arrays in C

Both your examples are equivalent. However, the first one is less obvious and more "hacky", while the second one clearly states your intention.

int (*pointer)[280];
pointer = tab1;

pointer points to an 1D array of 280 integers. In your assignment, you actually assign the first row of tab1. This works since you can implicitly cast arrays to pointers (to the first element).

When you are using pointer[5][12], C treats pointer as an array of arrays (pointer[5] is of type int[280]), so there is another implicit cast here (at least semantically).

In your second example, you explicitly create a pointer to a 2D array:

int (*pointer)[100][280];
pointer = &tab1;

The semantics are clearer here: *pointer is a 2D array, so you need to access it using (*pointer)[i][j].

Both solutions use the same amount of memory (1 pointer) and will most likely run equally fast. Under the hood, both pointers will even point to the same memory location (the first element of the tab1 array), and it is possible that your compiler will even generate the same code.

The first solution is "more advanced" since one needs quite a deep understanding on how arrays and pointers work in C to understand what is going on. The second one is more explicit.

Numbering rows within groups in a data frame

Another base R solution would be to split the data frame per cat, after that using lapply: add a column with number 1:nrow(x). The last step is to have your final data frame back with do.call, that is:

        df_split <- split(df, df$cat)
        df_lapply <- lapply(df_split, function(x) {
          x$num <- seq_len(nrow(x))
          return(x)
        })
        df <- do.call(rbind, df_lapply)

Do the parentheses after the type name make a difference with new?

The rules for new are analogous to what happens when you initialize an object with automatic storage duration (although, because of vexing parse, the syntax can be slightly different).

If I say:

int my_int; // default-initialize ? indeterminate (non-class type)

Then my_int has an indeterminate value, since it is a non-class type. Alternatively, I can value-initialize my_int (which, for non-class types, zero-initializes) like this:

int my_int{}; // value-initialize ? zero-initialize (non-class type)

(Of course, I can't use () because that would be a function declaration, but int() works the same as int{} to construct a temporary.)

Whereas, for class types:

Thing my_thing; // default-initialize ? default ctor (class type)
Thing my_thing{}; // value-initialize ? default-initialize ? default ctor (class type)

The default constructor is called to create a Thing, no exceptions.

So, the rules are more or less:

  • Is it a class type?
    • YES: The default constructor is called, regardless of whether it is value-initialized (with {}) or default-initialized (without {}). (There is some additional prior zeroing behavior with value-initialization, but the default constructor is always given the final say.)
    • NO: Were {} used?
      • YES: The object is value-initialized, which, for non-class types, more or less just zero-initializes.
      • NO: The object is default-initialized, which, for non-class types, leaves it with an indeterminate value (it effectively isn't initialized).

These rules translate precisely to new syntax, with the added rule that () can be substituted for {} because new is never parsed as a function declaration. So:

int* my_new_int = new int; // default-initialize ? indeterminate (non-class type)
Thing* my_new_thing = new Thing; // default-initialize ? default ctor (class type)
int* my_new_zeroed_int = new int(); // value-initialize ? zero-initialize (non-class type)
     my_new_zeroed_int = new int{}; // ditto
       my_new_thing = new Thing(); // value-initialize ? default-initialize ? default ctor (class type)

(This answer incorporates conceptual changes in C++11 that the top answer currently does not; notably, a new scalar or POD instance that would end up an with indeterminate value is now technically now default-initialized (which, for POD types, technically calls a trivial default constructor). While this does not cause much practical change in behavior, it does simplify the rules somewhat.)

Git push requires username and password

You basically have two options.

If you use the same user on both machines you need to copy the .pub key to your PC, so GitHub knows that you are the same user.

If you have created a new .pub file for your PC and want to treat the machines as different users, you need to register the new .pub file on the GitHub website.

If this still doesn't work it might be because ssh is not configured correctly and that ssh fail to find the location of your keys. Try

ssh -vv [email protected]

To get more information why SSH fails.

How to check whether an object is a date?

Yet another variant:

Date.prototype.isPrototypeOf(myDateObject)

How do I read a string entered by the user in C?

I think the best and safest way to read strings entered by the user is using getline()

Here's an example how to do this:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
    char *buffer = NULL;
    int read;
    unsigned int len;
    read = getline(&buffer, &len, stdin);
    if (-1 != read)
        puts(buffer);
    else
        printf("No line read...\n");

    printf("Size read: %d\n Len: %d\n", read, len);
    free(buffer);
    return 0;
}

How can I delay a method call for 1 second?

Use in Swift 3

perform(<Selector>, with: <object>, afterDelay: <Time in Seconds>)

using stored procedure in entity framework

You need to create a model class that contains all stored procedure properties like below. Also because Entity Framework model class needs primary key, you can create a fake key by using Guid.

public class GetFunctionByID
{
    [Key]
    public Guid? GetFunctionByID { get; set; }

    // All the other properties.
}

then register the GetFunctionByID model class in your DbContext.

public class FunctionsContext : BaseContext<FunctionsContext>
{
    public DbSet<App_Functions> Functions { get; set; }
    public DbSet<GetFunctionByID> GetFunctionByIds {get;set;}
}

When you call your stored procedure, just see below:

var functionId = yourIdParameter;
var result =  db.Database.SqlQuery<GetFunctionByID>("GetFunctionByID @FunctionId", new SqlParameter("@FunctionId", functionId)).ToList());

How do you check "if not null" with Eloquent?

We can use

Model::whereNotNull('sent_at');

Or

Model::whereRaw('sent_at is not null');

Why do I get "warning longer object length is not a multiple of shorter object length"?

You don't give a reproducible example but your warning message tells you exactly what the problem is.

memb only has a length of 10. I'm guessing the length of dih_y2$MemberID isn't a multiple of 10. When using ==, R spits out a warning if it isn't a multiple to let you know that it's probably not doing what you're expecting it to do. == does element-wise checking for equality. I suspect what you want to do is find which of the elements of dih_y2$MemberID are also in the vector memb. To do this you would want to use the %in% operator.

dih_col <- which(dih_y2$MemeberID %in% memb)

How to use a servlet filter in Java to change an incoming servlet request url?

A simple JSF Url Prettyfier filter based in the steps of BalusC's answer. The filter forwards all the requests starting with the /ui path (supposing you've got all your xhtml files stored there) to the same path, but adding the xhtml suffix.

public class UrlPrettyfierFilter implements Filter {

    private static final String JSF_VIEW_ROOT_PATH = "/ui";

    private static final String JSF_VIEW_SUFFIX = ".xhtml";

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = ((HttpServletRequest) request);
        String requestURI = httpServletRequest.getRequestURI();
        //Only process the paths starting with /ui, so as other requests get unprocessed. 
        //You can register the filter itself for /ui/* only, too
        if (requestURI.startsWith(JSF_VIEW_ROOT_PATH) 
                && !requestURI.contains(JSF_VIEW_SUFFIX)) {
            request.getRequestDispatcher(requestURI.concat(JSF_VIEW_SUFFIX))
                .forward(request,response);
        } else {
            chain.doFilter(httpServletRequest, response);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}

How to increase size of DOSBox window?

Here's how to change the dosbox.conf file in Linux to increase the size of the window. I actually DID what follows, so I can say it works (in 32-bit PCLinuxOS fullmontyKDE, anyway). The question's answer is in the .conf file itself.

You find this file in Linux at /home/(username)/.dosbox . In Konqueror or Dolphin, you must first check 'Hidden files' or you won't see the folder. Open it with KWrite superuser or your fav editor.

  1. Save the file with another name like 'dosbox-0.74original.conf' to preserve the original file in case you need to restore it.
  2. Search on 'resolution' and carefully read what the conf file says about changing it. There are essentially two variables: resolution and output. You want to leave fullresolution alone for now. Your question was about WINDOW, not full. So look for windowresolution, see what the comments in conf file say you can do. The best suggestion is to use a bigger-window resolution like 900x800 (which is what I used on a 1366x768 screen), but NOT the actual resolution of your machine (which would make the window fullscreen, and you said you didn't want that). Be specific, replacing the 'windowresolution=original' with 'windowresolution=900x800' or other dimensions. On my screen, that doubled the window size just as it does with the max Font tab in Windows Properties (for the exe file; as you'll see below the ==== marks, 32-bit Windows doesn't need Dosbox).

Then, search on 'output', and as the instruction in the conf file warns, if and only if you have 'hardware scaling', change the default 'output=surface' to something else; he then lists the optional other settings. I changed it to 'output=overlay'. There's one other setting to test: aspect. Search the file for 'aspect', and change the 'false' to 'true' if you want an even bigger window. When I did this, the window took up over half of the screen. With 'false' left alone, I had a somewhat smaller window (I use widescreen monitors, whether laptop or desktop, maybe that's why).

So after you've made the changes, save the file with the original name of dosbox-0.74.conf . Then, type dosbox at the command line or create a Launcher (in KDE, this is a right click on the desktop) with the command dosbox. You still have to go through the mount command (i.e., mount c~ c:\123 if that's the location and file you'll execute). I'm sure there's a way to make a script, but haven't yet learned how to do that.

Pythonic way to return list of every nth item in a larger list

newlist = oldlist[::10]

This picks out every 10th element of the list.

What represents a double in sql server?

float in SQL Server actually has [edit:almost] the precision of a "double" (in a C# sense).

float is a synonym for float(53). 53 is the bits of the mantissa.

.NET double uses 54 bits for the mantissa.

How to discard local commits in Git?

As an aside, apart from the answer by mipadi (which should work by the way), you should know that doing:

git branch -D master
git checkout master

also does exactly what you want without having to redownload everything (your quote paraphrased). That is because your local repo contains a copy of the remote repo (and that copy is not the same as your local directory, it is not even the same as your checked out branch).

Wiping out a branch is perfectly safe and reconstructing that branch is very fast and involves no network traffic. Remember, git is primarily a local repo by design. Even remote branches have a copy on the local. There's only a bit of metadata that tells git that a specific local copy is actually a remote branch. In git, all files are on your hard disk all the time.

If you don't have any branches other than master, you should:

git checkout -b 'temp'
git branch -D master
git checkout master
git branch -D temp

Disabling same-origin policy in Safari

Most of these answers are old. The latest Safari 14.0.2 (in 2021), has the option to Disable Cross-Origin Restrictions, however, it doesn't work if the paths have ../../ kind of path names; even though Safari correctly resolves to a local file path, it still doesn't permit loading the file, even though it exists. This is a recent bug in Safari 14 that didn't happen in 13.

How to access the GET parameters after "?" in Express?

A nice technique i've started using with some of my apps on express is to create an object which merges the query, params, and body fields of express's request object.

//./express-data.js
const _ = require("lodash");

class ExpressData {

    /*
    * @param {Object} req - express request object
    */
    constructor (req) {

        //Merge all data passed by the client in the request
        this.props = _.merge(req.body, req.params, req.query);
     }

}

module.exports = ExpressData;

Then in your controller body, or anywhere else in scope of the express request chain, you can use something like below:

//./some-controller.js

const ExpressData = require("./express-data.js");
const router = require("express").Router();


router.get("/:some_id", (req, res) => {

    let props = new ExpressData(req).props;

    //Given the request "/592363122?foo=bar&hello=world"
    //the below would log out 
    // {
    //   some_id: 592363122,
    //   foo: 'bar',
    //   hello: 'world'
    // }
    console.log(props);

    return res.json(props);
});

This makes it nice and handy to just "delve" into all of the "custom data" a user may have sent up with their request.

Note

Why the 'props' field? Because that was a cut-down snippet, I use this technique in a number of my APIs, I also store authentication / authorisation data onto this object, example below.

/*
 * @param {Object} req - Request response object
*/
class ExpressData {

    /*
    * @param {Object} req - express request object
    */
    constructor (req) {

        //Merge all data passed by the client in the request
        this.props = _.merge(req.body, req.params, req.query);

        //Store reference to the user
        this.user = req.user || null;

        //API connected devices (Mobile app..) will send x-client header with requests, web context is implied.
        //This is used to determine how the user is connecting to the API 
        this.client = (req.headers) ? (req.headers["x-client"] || (req.client || "web")) : "web";
    }
} 

Making a Sass mixin with optional arguments

I know its not exactly the answer you were searching for but you could pass "null" as last argument when @include box-shadow mixin, like this @include box-shadow(12px, 14px, 2px, green, null); Now, if that argument is only one in that property than that property (and its (default) value) won't get compiled. If there are two or more args on that "line" only ones that you nulled won't get compiled (your case).

CSS output is exactly as you wanted it, but you have to write your nulls :)

  @include box-shadow(12px, 14px, 2px, green, null);

  // compiles to ...

  -webkit-box-shadow: 12px 14px 2px green;  
  -moz-box-shadow: 12px 14px 2px green;  
  box-shadow: 12px 14px 2px green;

Docker remove <none> TAG images

docker image prune removes all dangling images (those with tag none). docker image prune -a would also remove any images that have no container that uses them.

The difference between dangling and unused images is explained in this stackoverflow thread.

How do I list all tables in a schema in Oracle SQL?

select * from cat;

it will show all tables in your schema cat synonym of user_catalog

C++ String array sorting

We can sort() function to sort string array.

Procedure :

  1. At first determine the size string array.

  2. use sort function . sort(array_name, array_name+size)

  3. Iterate through string array/


Code Snippet

#include<bits/stdc++.h>
using namespace std;

int main()
{
    ios::sync_with_stdio(false);

    string name[] = {"john", "bobby", "dear", "test1", "catherine", "nomi", "shinta", "martin", "abe", "may", "zeno", "zack", "angeal", "gabby"};

    int len = sizeof(name)/sizeof(name[0]);

    sort(name, name+len);

    for(string n: name)
    {
         cout<<n<<" ";
    }
    cout<<endl;

    return 0;
}

scipy.misc module has no attribute imread?

The only way I could get the .png file I'm working with in as uint8 was with OpenCv.

cv2.imread(file) actually returned numpy.ndarray with dtype=uint8

Circular gradient in android

I guess you should add android:centerColor

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
  android:startColor="#FFFFFF"
  android:centerColor="#000000"
  android:endColor="#FFFFFF"
  android:angle="0" />
</shape>

This example displays a horizontal gradient from white to black to white.

Difference between Spring MVC and Spring Boot

  • Spring MVC is a complete HTTP oriented MVC framework managed by the Spring Framework and based in Servlets. It would be equivalent to JSF in the JavaEE stack. The most popular elements in it are classes annotated with @Controller, where you implement methods you can access using different HTTP requests. It has an equivalent @RestController to implement REST-based APIs.
  • Spring boot is a utility for setting up applications quickly, offering an out of the box configuration in order to build Spring-powered applications. As you may know, Spring integrates a wide range of different modules under its umbrella, as spring-core, spring-data, spring-web (which includes Spring MVC, by the way) and so on. With this tool you can tell Spring how many of them to use and you'll get a fast setup for them (you are allowed to change it by yourself later on).

So, Spring MVC is a framework to be used in web applications and Spring Boot is a Spring based production-ready project initializer. You might find useful visiting the Spring MVC tag wiki as well as the Spring Boot tag wiki in SO.

How to check if an option is selected?

use

 $("#mySelectBox option:selected");

to test if its a particular option myoption:

 if($("#mySelectBox option:selected").text() == myoption){
          //...
 }

Git cli: get user info from username

Add my two cents, if you're using windows commnad line:

git config --list | findstr user.name will give username directly.

The findstr here is quite similar to grep in linux.

Emulate ggplot2 default color palette

These answers are all very good, but I wanted to share another thing I discovered on stackoverflow that is really quite useful, here is the direct link

Basically, @DidzisElferts shows how you can get all the colours, coordinates, etc that ggplot uses to build a plot you created. Very nice!

p <- ggplot(mpg,aes(x=class,fill=class)) + geom_bar()
ggplot_build(p)$data
[[1]]
     fill  y count x ndensity ncount  density PANEL group ymin ymax xmin xmax
1 #F8766D  5     5 1        1      1 1.111111     1     1    0    5 0.55 1.45
2 #C49A00 47    47 2        1      1 1.111111     1     2    0   47 1.55 2.45
3 #53B400 41    41 3        1      1 1.111111     1     3    0   41 2.55 3.45
4 #00C094 11    11 4        1      1 1.111111     1     4    0   11 3.55 4.45
5 #00B6EB 33    33 5        1      1 1.111111     1     5    0   33 4.55 5.45
6 #A58AFF 35    35 6        1      1 1.111111     1     6    0   35 5.55 6.45
7 #FB61D7 62    62 7        1      1 1.111111     1     7    0   62 6.55 7.45

Checking whether a String contains a number value in Java

 try{
      Integer.parseInt(string);
      return true;
}catch (Exception  e){
      return false;
}

or you can do it himself:

 for ( int i = 0; i < string.length; ++i ) {
      if ( !( string[i] >= '0' || string[i] <= '9' ) )
           return false;
 }
 return true;

Of course is also function isDigit

How to load image (and other assets) in Angular an project?

1 . Add this line on top in component.

declare var require: any

2 . add this line in your component class.

imgname= require("../images/imgname.png");
  1. add this 'imgname' in img src tag on html page.

    <img src={{imgname}} alt="">

error: Libtool library used but 'LIBTOOL' is undefined

Fixed it. I needed to run libtoolize in the directory, then re-run:

  • aclocal

  • autoheader

How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?

If you bind your datasource to a datatable for example, you need to set the properties after the binding is done:

        private void dgv_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
            dgv.AutoResizeColumns();
            dgv.AllowUserToResizeColumns = true;
        }

iPhone and WireShark

I have successfully captured HTTP traffic using Fiddler2 as a proxy, which can be installed on any Windows PC on your network.

  1. In Fiddler, Tools -> Fiddler Options -> Connections -> [x] Allow remote computers to connect.
  2. Make sure your windows firewall is disabled.
  3. On the iphone/ipod, go to your wireless settings, use a manual proxy server, enter the fiddler machine's ip address and the same port (defaults to 8888).

How to terminate a Python script

from sys import exit
exit()

As a parameter you can pass an exit code, which will be returned to OS. Default is 0.

How to debug in Django, the good way?

I've pushed django-pdb to PyPI. It's a simple app that means you don't need to edit your source code every time you want to break into pdb.

Installation is just...

  1. pip install django-pdb
  2. Add 'django_pdb' to your INSTALLED_APPS

You can now run: manage.py runserver --pdb to break into pdb at the start of every view...

bash: manage.py runserver --pdb
Validating models...

0 errors found
Django version 1.3, using settings 'testproject.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

GET /
function "myview" in testapp/views.py:6
args: ()
kwargs: {}

> /Users/tom/github/django-pdb/testproject/testapp/views.py(7)myview()
-> a = 1
(Pdb)

And run: manage.py test --pdb to break into pdb on test failures/errors...

bash: manage.py test testapp --pdb
Creating test database for alias 'default'...
E
======================================================================
>>> test_error (testapp.tests.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ".../django-pdb/testproject/testapp/tests.py", line 16, in test_error
    one_plus_one = four
NameError: global name 'four' is not defined
======================================================================

> /Users/tom/github/django-pdb/testproject/testapp/tests.py(16)test_error()
-> one_plus_one = four
(Pdb)

The project's hosted on GitHub, contributions are welcome of course.

How do I make an HTML text box show a hint when empty?

Another option, if you're happy to have this feature only for newer browsers, is to use the support offered by HTML 5's placeholder attribute:

<input name="email" placeholder="Email Address">

In the absence of any styles, in Chrome this looks like:

enter image description here

You can try demos out here and in HTML5 Placeholder Styling with CSS.

Be sure to check the browser compatibility of this feature. Support in Firefox was added in 3.7. Chrome is fine. Internet Explorer only added support in 10. If you target a browser that does not support input placeholders, you can use a jQuery plugin called jQuery HTML5 Placeholder, and then just add the following JavaScript code to enable it.

$('input[placeholder], textarea[placeholder]').placeholder();

Remove excess whitespace from within a string

Not sure exactly what you want but here are two situations:

  1. If you are just dealing with excess whitespace on the beginning or end of the string you can use trim(), ltrim() or rtrim() to remove it.

  2. If you are dealing with extra spaces within a string consider a preg_replace of multiple whitespaces " "* with a single whitespace " ".

Example:

$foo = preg_replace('/\s+/', ' ', $foo);

Understanding inplace=True

inplace=True is used depending if you want to make changes to the original df or not.

df.drop_duplicates()

will only make a view of dropped values but not make any changes to df

df.drop_duplicates(inplace  = True)

will drop values and make changes to df.

Hope this helps.:)

<SELECT multiple> - how to allow only one item selected?

You want only one option by default, but the user can select multiple options by pressing the CTRL key. This is (already) exactly how the SELECT multiple is meant to behave.

See this: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select_multiple

Can you please clarify your question?

How to: Install Plugin in Android Studio

File-> Settings->Under IDE Settings click on Plugins. Now in right side window Click on Browse repositories and there you can find the plugins. Select which one you want and click on install

SQL, How to Concatenate results?

In my opinion, if you are using SQL Server 2017 or later, using STRING_AGG( ... ) is the best solution:

More at:

https://stackoverflow.com/a/42778050/1260488

Difference between "managed" and "unmanaged"

Managed code is a differentiation coined by Microsoft to identify computer program code that requires and will only execute under the "management" of a Common Language Runtime virtual machine (resulting in Bytecode).

http://en.wikipedia.org/wiki/Managed_code

http://www.developer.com/net/cplus/article.php/2197621/Managed-Unmanaged-Native-What-Kind-of-Code-Is-This.htm

Bootstrap 3 - jumbotron background image effect

After inspecting the sample website you provided, I found that the author might achieve the effect by using a library called Stellar.js, take a look at the library site, cheers!

How to save a plot into a PDF file without a large margin around

This works for displaying purposes:

set(gca(), 'LooseInset', get(gca(), 'TightInset'));

Should work for printing as well.

Opening popup windows in HTML

HTML alone does not support this. You need to use some JS.

And also consider nowadays people use popup blocker in browsers.

<a href="javascript:window.open('document.aspx','mypopuptitle','width=600,height=400')">open popup</a>

MySQL - ERROR 1045 - Access denied

I had the same error, but it was because password_expired was set to Y. You can fix that issue by following the same approach as the currently accepted answer, but instead executing the MySQL query:

UPDATE mysql.user SET password_expired = 'N' WHERE User='root';

How do you fix the "element not interactable" exception?

Found a workaround years later after encountering the same problem again - unable to click element even though it SHOULD be clickable. The solution is to catch ElementNotInteractable exception and attempt to execute a script to click the element.

Example in Typescript

async clickElement(element: WebElement) {
    try {
        return await element.click();
    } catch (error) {
        if (error.name == 'ElementNotInteractableError') {
            return await this.driver.executeScript((element: WebElement) => {
                element.click();
            }, element);
        }
    }
}

Convert a python dict to a string and back

Why not to use Python 3's inbuilt ast library's function literal_eval. It is better to use literal_eval instead of eval

import ast
str_of_dict = "{'key1': 'key1value', 'key2': 'key2value'}"
ast.literal_eval(str_of_dict)

will give output as actual Dictionary

{'key1': 'key1value', 'key2': 'key2value'}

And If you are asking to convert a Dictionary to a String then, How about using str() method of Python.

Suppose the dictionary is :

my_dict = {'key1': 'key1value', 'key2': 'key2value'}

And this will be done like this :

str(my_dict)

Will Print :

"{'key1': 'key1value', 'key2': 'key2value'}"

This is the easy as you like.

Get month and year from a datetime in SQL Server 2005

Yes, you can use datename(month,intime) to get the month in text.

How to get name of calling function/method in PHP?

The simplest way of getting parent function name is:

$caller = next(debug_backtrace())['function'];

DOM element to corresponding vue.js component

In Vue.js 2 Inside a Vue Instance or Component:

  • Use this.$el to get the HTMLElement the instance/component was mounted to

From an HTMLElement:

  • Use .__vue__ from the HTMLElement
    • E.g. var vueInstance = document.getElementById('app').__vue__;

Having a VNode in a variable called vnode you can:

  • use vnode.elm to get the element that VNode was rendered to
  • use vnode.context to get the VueComponent instance that VNode's component was declared (this usually returns the parent component, but may surprise you when using slots.
  • use vnode.componentInstance to get the Actual VueComponent instance that VNode is about

Source, literally: vue/flow/vnode.js.

Runnable Demo:

_x000D_
_x000D_
Vue.config.productionTip = false; // disable developer version warning
console.log('-------------------')

Vue.component('my-component', {
  template: `<input>`,
  mounted: function() {
    console.log('[my-component] is mounted at element:', this.$el);
  }
});

Vue.directive('customdirective', {
  bind: function (el, binding, vnode) {
    console.log('[DIRECTIVE] My Element is:', vnode.elm);
    console.log('[DIRECTIVE] My componentInstance is:', vnode.componentInstance);
    console.log('[DIRECTIVE] My context is:', vnode.context);
    // some properties, such as $el, may take an extra tick to be set, thus you need to...
    Vue.nextTick(() => console.log('[DIRECTIVE][AFTER TICK] My context is:', vnode.context.$el))
  }
})

new Vue({
  el: '#app',
  mounted: function() {
    console.log('[ROOT] This Vue instance is mounted at element:', this.$el);
    
    console.log('[ROOT] From the element to the Vue instance:', document.getElementById('app').__vue__);
    console.log('[ROOT] Vue component instance of my-component:', document.querySelector('input').__vue__);
  }
})
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>

<h1>Open the browser's console</h1>
<div id="app">
  <my-component v-customdirective=""></my-component>
</div>
_x000D_
_x000D_
_x000D_

Is there a way to override class variables in Java?

Why would you want to override variables when you could easily reassign them in the subClasses.

I follow this pattern to work around the language design. Assume a case where you have a weighty service class in your framework which needs be used in different flavours in multiple derived applications.In that case , the best way to configure the super class logic is by reassigning its 'defining' variables.

public interface ExtensibleService{
void init();
}

public class WeightyLogicService implements ExtensibleService{
    private String directoryPath="c:\hello";

    public void doLogic(){
         //never forget to call init() before invocation or build safeguards
         init();
       //some logic goes here
   }

   public void init(){}    

}

public class WeightyLogicService_myAdaptation extends WeightyLogicService {
   @Override
   public void init(){
    directoryPath="c:\my_hello";
   }

}

How do I detect if Python is running as a 64-bit application?

import platform
platform.architecture()

From the Python docs:

Queries the given executable (defaults to the Python interpreter binary) for various architecture information.

Returns a tuple (bits, linkage) which contain information about the bit architecture and the linkage format used for the executable. Both values are returned as strings.

how to configure config.inc.php to have a loginform in phpmyadmin

First of all, you do not have to develop any form yourself : phpMyAdmin, depending on its configuration (i.e. config.inc.php) will display an identification form, asking for a login and password.

To get that form, you should not use :

$cfg['Servers'][$i]['auth_type'] = 'config';

But you should use :

$cfg['Servers'][$i]['auth_type'] = 'cookie';

(At least, that's what I have on a server which prompts for login/password, using a form)


For more informations, you can take a look at the documentation :

'config' authentication ($auth_type = 'config') is the plain old way: username and password are stored in config.inc.php.

'cookie' authentication mode ($auth_type = 'cookie') as introduced in 2.2.3 allows you to log in as any valid MySQL user with the help of cookies.
Username and password are stored in cookies during the session and password is deleted when it ends.

base 64 encode and decode a string in angular (2+)

Use btoa("yourstring")

more info: https://developer.mozilla.org/en/docs/Web/API/WindowBase64/Base64_encoding_and_decoding

TypeScript is a superset of Javascript, it can use existing Javascript libraries and web APIs

Undo git update-index --assume-unchanged <file>

To synthesize the excellent original answers from @adardesign, @adswebwork and @AnkitVishwakarma, and comments from @Bdoserror, @Retsam, @seanf, and @torek, with additional documentation links and concise aliases...

Basic Commands

To reset a file that is assume-unchanged back to normal:

git update-index --no-assume-unchanged <file>

To list all files that are assume-unchanged:

git ls-files -v | grep '^[a-z]' | cut -c3-

To reset all assume-unchanged files back to normal:

git ls-files -v | grep '^[a-z]' | cut -c3- | xargs git update-index --no-assume-unchanged --

Note: This command which has been listed elsewhere does not appear to reset all assume-unchanged files any longer (I believe it used to and previously listed it as a solution):

git update-index --really-refresh

Shortcuts

To make these common tasks easy to execute in git, add/update the following alias section to .gitconfig for your user (e.g. ~/.gitconfig on a *nix or macOS system):

[alias]
    hide = update-index --assume-unchanged
    unhide = update-index --no-assume-unchanged
    unhide-all = ! git ls-files -v | grep '^[a-z]' | cut -c3- | xargs git unhide --
    hidden = ! git ls-files -v | grep '^[a-z]' | cut -c3-

How do I use a delimiter with Scanner.useDelimiter in Java?

For example:

String myInput = null;
Scanner myscan = new Scanner(System.in).useDelimiter("\\n");
System.out.println("Enter your input: ");
myInput = myscan.next();
System.out.println(myInput);

This will let you use Enter as a delimiter.

Thus, if you input:

Hello world (ENTER)

it will print 'Hello World'.

Center a H1 tag inside a DIV

You can add line-height:51px to #AlertDiv h1 if you know it's only ever going to be one line. Also add text-align:center to #AlertDiv.

#AlertDiv {
    top:198px;
    left:365px;
    width:62px;
    height:51px;
    color:white;
    position:absolute;
    text-align:center;
    background-color:black;
}

#AlertDiv h1 {
    margin:auto;
    line-height:51px;
    vertical-align:middle;
}

The demo below also uses negative margins to keep the #AlertDiv centered on both axis, even when the window is resized.

Demo: jsfiddle.net/KaXY5

Where to install Android SDK on Mac OS X?

From http://developer.android.com/sdk/index.html, it seems that you can install the SDK anywhere, so long as you

  1. "execute the android tool in the <sdk>/tools/ folder"
  2. Add the <sdk>/tools directory to your system path

More info can be found here: http://developer.android.com/sdk/installing.html

Android Studio Stuck at Gradle Download on create new project

I found the same issue happening on my laptop, despite waiting for quite a long time. This is what I did and it worked for me. Just force close the Android Studio and launch it again. This time, just open the existing project and let it take care of finishing up the process of building/downloading.

Another option that you could possibly try is that if you look into File --> Settings, there is an option for Gradle location. You could go to the Gradle download site, download a local distribution of Gradle and point the Gradle location to that local directory.

jQuery event handlers always execute in order they were bound - any way around this?

Chris Chilvers' advice should be the first course of action but sometimes we're dealing with third party libraries that makes this challenging and requires us to do naughty things... which this is. IMO it's a crime of presumption similar to using !important in CSS.

Having said that, building on Anurag's answer, here are a few additions. These methods allow for multiple events (e.g. "keydown keyup paste"), arbitrary positioning of the handler and reordering after the fact.

$.fn.bindFirst = function (name, fn) {
    this.bindNth(name, fn, 0);
}

$.fn.bindNth(name, fn, index) {
    // Bind event normally.
    this.bind(name, fn);
    // Move to nth position.
    this.changeEventOrder(name, index);
};

$.fn.changeEventOrder = function (names, newIndex) {
    var that = this;
    // Allow for multiple events.
    $.each(names.split(' '), function (idx, name) {
        that.each(function () {
            var handlers = $._data(this, 'events')[name.split('.')[0]];
            // Validate requested position.
            newIndex = Math.min(newIndex, handlers.length - 1);
            handlers.splice(newIndex, 0, handlers.pop());
        });
    });
};

One could extrapolate on this with methods that would place a given handler before or after some other given handler.

What is default color for text in textview?

There is no default color. It means that every device can have own.

Where IN clause in LINQ

from state in _objedatasource.StateList()
where listofcountrycodes.Contains(state.CountryCode)
select state

Wheel file installation

you can follow the below command to install using the wheel file at your local

pip install /users/arpansaini/Downloads/h5py-3.0.0-cp39-cp39-macosx_10_9_x86_64.whl

How to install wget in macOS?

I update mac to Sierra , 10.12.3

My wget stop working.

When I tried to install by typing

brew install wget --with-libressl

I got the following warning

Warning: wget-1.19.1 already installed, it's just not linked.

Then tried to unsintall by typing

brew uninstall wget --with-libressl

Then I reinstalled by typing

brew install wget --with-libressl

Finally I got it worked.Thank God!

Best way to copy from one array to another

I think your assignment is backwards:

a[i] = b[i];

should be:

b[i] = a[i];

How to list all the files in android phone by using adb shell?

I might be wrong but "find -name __" works fine for me. (Maybe it's just my phone.) If you just want to list all files, you can try

adb shell ls -R /

You probably need the root permission though.

Edit: As other answers suggest, use ls with grep like this:

adb shell ls -Ral yourDirectory | grep -i yourString

eg.

adb shell ls -Ral / | grep -i myfile

-i is for ignore-case. and / is the root directory.

How to split long commands over multiple lines in PowerShell

Another method for cleaner argument passing would be splatting.

Define your parameters and values as a hashtable like this:

$params = @{ 'class' = 'Win32_BIOS';
             'computername'='SERVER-R2';
             'filter'='drivetype=3';
             'credential'='Administrator' }

And then call your commandlet like this:

Get-WmiObject @params

Microsoft Docs: About Splatting

TechNet Magazine 2011: Windows PowerShell: Splatting

Looks like it works with Powershell 2.0 and up

How do I convert a String to an int in Java?

Some of the ways to convert String into Int are as follows:

  1. You can use Integer.parseInt():

    String test = "4568";
    int new = Integer.parseInt(test);
    
  2. Also you can use Integer.valueOf():

    String test = "4568";
    int new = Integer.valueOf(test);
    

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

Python: create dictionary using dict() with integer keys?

a = dict(one=1, two=2, three=3)

Providing keyword arguments as in this example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.

Entity framework linq query Include() multiple children entities

How do you construct a LINQ to Entities query to load child objects directly, instead of calling a Reference property or Load()

There is no other way - except implementing lazy loading.

Or manual loading....

myobj = context.MyObjects.First();
myobj.ChildA.Load();
myobj.ChildB.Load();
...

How to check if a column exists in Pandas

Just to suggest another way without using if statements, you can use the get() method for DataFrames. For performing the sum based on the question:

df['sum'] = df.get('A', df['B']) + df['C']

The DataFrame get method has similar behavior as python dictionaries.

How to solve maven 2.6 resource plugin dependency?

This issue is happening due to change of protocol from http to https for central repository. please refer following link for more details. https://support.sonatype.com/hc/en-us/articles/360041287334-Central-501-HTTPS-Required 

In order to fix the problem, copy following into your pom.ml file. This will set the repository url to use https.

<repositories>
        <repository>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <releases>
                <updatePolicy>never</updatePolicy>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
        </pluginRepository>
    </pluginRepositories>

How to quickly edit values in table in SQL Server Management Studio?

Go to Tools > Options. In the tree on the left, select SQL Server Object Explorer. Set the option "Value for Edit Top Rows command" to 0. It'll now allow you to view and edit the entire table from the context menu.

(HTML) Download a PDF file instead of opening them in browser when clicked

You can use download.js (https://github.com/rndme/download and http://danml.com/download.html). If the file is in an external URL, you must make an Ajax request, but if it is not, then you can use the function:

download(Path, name, mime)

Read their documentation for more details in the GitHub.

git diff file against its last change

This does exist, but it's actually a feature of git log:

git log -p [--follow] [-1] <path>

Note that -p can also be used to show the inline diff from a single commit:

git log -p -1 <commit>

Options used:

  • -p (also -u or --patch) is hidden deeeeeeeep in the git-log man page, and is actually a display option for git-diff. When used with log, it shows the patch that would be generated for each commit, along with the commit information—and hides commits that do not touch the specified <path>. (This behavior is described in the paragraph on --full-diff, which causes the full diff of each commit to be shown.)
  • -1 shows just the most recent change to the specified file (-n 1 can be used instead of -1); otherwise, all non-zero diffs of that file are shown.
  • --follow is required to see changes that occurred prior to a rename.

As far as I can tell, this is the only way to immediately see the last set of changes made to a file without using git log (or similar) to either count the number of intervening revisions or determine the hash of the commit.

To see older revisions changes, just scroll through the log, or specify a commit or tag from which to start the log. (Of course, specifying a commit or tag returns you to the original problem of figuring out what the correct commit or tag is.)

Credit where credit is due:

  • I discovered log -p thanks to this answer.
  • Credit to FranciscoPuga and this answer for showing me the --follow option.
  • Credit to ChrisBetti for mentioning the -n 1 option and atatko for mentioning the -1 variant.
  • Credit to sweaver2112 for getting me to actually read the documentation and figure out what -p "means" semantically.

How do I hide anchor text without hiding the anchor?

Mini tip:

I had the following scenario:

<a href="/page/">My link text
:after
</a>

I hided the text with font-size: 0, so I could use a FontAwesome icon for it. This worked on Chrome 36, Firefox 31 and IE9+.

I wouldn't recommend color: transparent because the text stil exists and is selectable. Using line-height: 0px didn't allow me to use :after. Maybe because my element was a inline-block.

Visibility: hidden: Didn't allow me to use :after.

text-indent: -9999px;: Also moved the :after element

Computing cross-correlation function?

If you are looking for a rapid, normalized cross correlation in either one or two dimensions I would recommend the openCV library (see http://opencv.willowgarage.com/wiki/ http://opencv.org/). The cross-correlation code maintained by this group is the fastest you will find, and it will be normalized (results between -1 and 1).

While this is a C++ library the code is maintained with CMake and has python bindings so that access to the cross correlation functions is convenient. OpenCV also plays nicely with numpy. If I wanted to compute a 2-D cross-correlation starting from numpy arrays I could do it as follows.

import numpy
import cv

#Create a random template and place it in a larger image
templateNp = numpy.random.random( (100,100) )
image = numpy.random.random( (400,400) )
image[:100, :100] = templateNp

#create a numpy array for storing result
resultNp = numpy.zeros( (301, 301) )

#convert from numpy format to openCV format
templateCv = cv.fromarray(numpy.float32(template))
imageCv = cv.fromarray(numpy.float32(image))
resultCv =  cv.fromarray(numpy.float32(resultNp))

#perform cross correlation
cv.MatchTemplate(templateCv, imageCv, resultCv, cv.CV_TM_CCORR_NORMED)

#convert result back to numpy array
resultNp = np.asarray(resultCv)

For just a 1-D cross-correlation create a 2-D array with shape equal to (N, 1 ). Though there is some extra code involved to convert to an openCV format the speed-up over scipy is quite impressive.

What is the best way to determine a session variable is null or empty in C#?

This method also does not assume that the object in the Session variable is a string

if((Session["MySessionVariable"] ?? "").ToString() != "")
    //More code for the Code God

So basically replaces the null variable with an empty string before converting it to a string since ToString is part of the Object class

MySQL select rows where left join is null

Here is a query that returns only the rows where no correspondance has been found in both columns user_one and user_two of table2:

SELECT T1.*
FROM table1 T1
LEFT OUTER JOIN table2 T2A ON T2A.user_one = T1.id
LEFT OUTER JOIN table2 T2B ON T2B.user_two = T1.id
WHERE T2A.user_one IS NULL
    AND T2B.user_two IS NULL

There is one jointure for each column (user_one and user_two) and the query only returns rows that have no matching jointure.

Hope this will help you.

cin and getline skipping input

If you're using getline after cin >> something, you need to flush the newline out of the buffer in between.

My personal favourite for this if no characters past the newline are needed is cin.sync(). However, it is implementation defined, so it might not work the same way as it does for me. For something solid, use cin.ignore(). Or make use of std::ws to remove leading whitespace if desirable:

int a;

cin >> a;
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n'); 
//discard characters until newline is found

//my method: cin.sync(); //discard unread characters

string s;
getline (cin, s); //newline is gone, so this executes

//other method: getline(cin >> ws, s); //remove all leading whitespace

How to check if an element of a list is a list (in Python)?

  1. Work out what specific properties of a list you want the items to have. Do they need to be indexable? Sliceable? Do they need an .append() method?

  2. Look up the abstract base class which describes that particular type in the collections module.

  3. Use isinstance:

    isinstance(x, collections.MutableSequence)
    

You might ask "why not just use type(x) == list?" You shouldn't do that, because then you won't support things that look like lists. And part of the Python mentality is duck typing:

I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck

In other words, you shouldn't require that the objects are lists, just that they have the methods you will need. The collections module provides a bunch of abstract base classes, which are a bit like Java interfaces. Any type that is an instance of collections.Sequence, for example, will support indexing.

Where can I download IntelliJ IDEA Color Schemes?

Since it is hard to find good themes for IntelliJ IDEA, I've created this site: https://github.com/sdvoynikov/color-themes (note: site archived to GitHub repo) where there is a large collection of themes. There are 270 themes for now and the site is growing.

Screenshot of the site

P.S.: Help me and other people — do not forget to upvote when you download themes from this site!

How to detect the swipe left or Right in Android?

After a full day working on this feature finally able to get the right answer.

First, create the following classes:

import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by hoshyar on 1/19/17.
 */

public class SwipeDetector implements View.OnTouchListener {

    public static enum Action {
        LR, // Left to Right
        RL, // Right to Left
        TB, // Top to bottom
        BT, // Bottom to Top
        None // when no action was detected
    }

    private static final String logTag = "Swipe";
    private static final int MIN_DISTANCE = 100;
    private float downX, downY, upX, upY;
    private Action mSwipeDetected = Action.None;

    public boolean swipeDetected() {
        return mSwipeDetected != Action.None;
    }

    public Action getAction() {
        return mSwipeDetected;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = event.getX();
                downY = event.getY();
                mSwipeDetected = Action.None;
                return false;

            case MotionEvent.ACTION_MOVE:
                upX = event.getX();
                upY = event.getY();

                float deltaX = downX - upX;
                float deltaY = downY - upY;
                Log.i(logTag,String.valueOf(deltaX));
                Log.i(logTag,String.valueOf(deltaX));

                if (deltaY>0 && deltaY<10 && deltaX<0 || deltaY==0 && deltaX>-15 && deltaX<0){
                    Log.i(logTag,"to right");
                }if (deltaY>=0 && deltaY<10 && deltaX>0 || deltaY<0 && deltaX>15 && deltaX<40){
                Log.i(logTag,"to left");
            }





                if (Math.abs(deltaX) > MIN_DISTANCE) {
                    // left or right
                    if (deltaX < 0) {
                        mSwipeDetected = Action.LR;
                        return false;
                    }
                    if (deltaX > 0) {


                        mSwipeDetected = Action.RL;
                        return false;
                    }
                } else if (Math.abs(deltaY) > MIN_DISTANCE) {


                    if (deltaY < 0) {
                        Log.i(logTag,"to bottom");
                        mSwipeDetected = Action.TB;
                        return false;
                    }
                    if (deltaY > 0) {
                        Log.i(logTag,"to up");
                        mSwipeDetected = Action.BT;
                        return false;
                    }
                }
                return true;
        }
        return false;
    }
}

Finally on the object that you want to apply. My example:

SwipeDetector swipeDetector = new SwipeDetector();
listView.setOnTouchListener(swipeDetector);

Good luck .

How to get the timezone offset in GMT(Like GMT+7:00) from android device?

public static String timeZone()
{
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());
    String   timeZone = new SimpleDateFormat("Z").format(calendar.getTime());
    return timeZone.substring(0, 3) + ":"+ timeZone.substring(3, 5);
}

returns like +03:30

Android Studio marks R in red with error message "cannot resolve symbol R", but build succeeds

Recently I import my project into Android studio, a part of R are marked in red with the error meesage "cannot resolve symbol R",but the compilation succeeds and the application runs.

Develop evirment:

  • IDE: Android studio 3.1.2
  • System: Mac Os

Solution:

step1:

Find the configuration file for Android studio
My path:

/Applications/Android Studio.app/Contents/bin/idea.properties

step2:

Change 2500:

idea.max.intellisense.filesize=2500  

to 5000 or more:

idea.max.intellisense.filesize=5000  

X-Frame-Options on apache

What did it for me was the following, I've added the following directive in both the http <VirtualHost *:80> and https <VirtualHost *:443> virtual host blocks:

ServerName your-app.com
ServerAlias www.your-app.com

Header always unset X-Frame-Options
Header set X-Frame-Options "SAMEORIGIN"

The reasoning behind this? Well by default if set, the server does not reset the X-Frame-Options header so we need to first always remove the default value, in my case it was DENY, and then with the next rule we set it to the desired value, in my case SAMEORIGIN. Of course you can use the Header set X-Frame-Options ALLOW-FROM ... rule as well.

moment.js get current time in milliseconds?

You could subtract the current time stamp from 12 AM of the same day.

Using current timestamp:

moment().valueOf() - moment().startOf('day').valueOf()

Using arbitrary day:

moment(someDate).valueOf() - moment(someDate).startOf('day').valueOf()

Upgrade Node.js to the latest version on Mac OS

This is just to add some info for people who didn't have Node installed with Homebrew but getting that very error when trying to install packages with npm on Mac OS X.

I found this good article explaining how to completely remove Node whichever the way you originally installed it.

After node, npm and n were completely removed from my machine, I just reinstalled Node.js using the official .pckg installer from Node website and everything just went back to normal.

Hope this helps out someone.

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

You can disable need to run Internet Explorer's first launch configuration by running this PowerShell script, it will adjust corresponding registry property:

Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Internet Explorer\Main" -Name "DisableFirstRunCustomize" -Value 2

After this, WebClient will work without problems

Allowing Java to use an untrusted certificate for SSL/HTTPS connection

Here is some relevant code:

// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
    new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkClientTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
        public void checkServerTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    }
};

// Install the all-trusting trust manager
try {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}

// Now you can access an https URL without having the certificate in the truststore
try {
    URL url = new URL("https://hostname/index.html");
} catch (MalformedURLException e) {
}

This will completely disable SSL checking—just don't learn exception handling from such code!

To do what you want, you would have to implement a check in your TrustManager that prompts the user.

Regex to Match Symbols: !$%^&*()_+|~-=`{}[]:";'<>?,./

A simple way to achieve this is the negative set [^\w\s]. This essentially catches:

  • Anything that is not an alphanumeric character (letters and numbers)
  • Anything that is not a space, tab, or line break (collectively referred to as whitespace)

For some reason [\W\S] does not work the same way, it doesn't do any filtering. A comment by Zael on one of the answers provides something of an explanation.

Calling Python in Java?

You can call any language from java using Java Native Interface

What is "Connect Timeout" in sql server connection string?

Connection Timeout=30 means that the database server has 30 seconds to establish a connection.

Connection Timeout specifies the time limit (in seconds), within which the connection to the specified server must be made, otherwise an exception is thrown i.e. It specifies how long you will allow your program to be held up while it establishes a database connection.

DataSource=server;
InitialCatalog=database;
UserId=username;
Password=password;
Connection Timeout=30

SqlConnection.ConnectionTimeout. specifies how many seconds the SQL Server service has to respond to a connection attempt. This is always set as part of the connection string.

Notes:

  • The value is expressed in seconds, not milliseconds.

  • The default value is 30 seconds.

  • A value of 0 means to wait indefinitely and never time out.

In addition, SqlCommand.CommandTimeout specifies the timeout value of a specific query running on SQL Server, however this is set via the SqlConnection object/setting (depending on your programming language), and not in the connection string i.e. It specifies how long you will allow your program to be held up while the command is run.

Can we execute a java program without a main() method?

Yes You can compile and execute without main method By using static block. But after static block executed (printed) you will get an error saying no main method found.

And Latest INFO --> YOU cant Do this with JAVA 7 version. IT will not execute.

{
    static
    {
        System.out.println("Hello World!");
        System.exit(0); // prevents “main method not found” error
    }
}

But this will not execute with JAVA 7 version.

How to load assemblies in PowerShell?

Make sure you have below features are installed in order

  1. Microsoft System CLR Types for SQL Server
  2. Microsoft SQL Server Shared Management Objects
  3. Microsoft Windows PowerShell Extensions

Also you may need to load

Add-Type -Path "C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.Smo.dll"
Add-Type -Path "C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.SqlWmiManagement.dll"

Eclipse doesn't stop at breakpoints

Please un check this from the Eclipse Menu.

Run->Skip all breakpoints.

I think this will be enabled permanently once You select the Remove all Break points option in the Debug/Breakpoints window.

Removing duplicates in the lists

Very simple way in Python 3:

>>> n = [1, 2, 3, 4, 1, 1]
>>> n
[1, 2, 3, 4, 1, 1]
>>> m = sorted(list(set(n)))
>>> m
[1, 2, 3, 4]

Best Java obfuscator?

We've had much better luck encrypting the jars rather than obfuscating. We use Classguard.

How to get all groups that a user is a member of?

First, import the activedirectory module:

import-module activedirectory

Then issue this command:

Get-ADGroupMember -Identity $group | foreach-object {
    Write-Host $_.SamAccountName
}

This will display the members of the specified group.

Properly escape a double quote in CSV

Not only double quotes, you will be in need for single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

Use fputcsv() to write, and fgetcsv() to read, which will take care of all.

SQL Query to search schema of all tables

Same thing but in ANSI way

SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME IN ( SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'CreateDate' )

Using lambda expressions for event handlers

EventHandler handler = (s, e) => MessageBox.Show("Woho");

button.Click += handler;
button.Click -= handler;

Installation of SQL Server Business Intelligence Development Studio

It sounds like you have installed SQL Server 2005 Express Edition, which does not include SSIS or the Business Intelligence Development Studio.

BIDS is only provided with the (not free) Standard, Enterprise and Developer Editions.

EDIT

This information was correct for SQL Server 2005. Since SQL Server 2014, Developer Edition has been free. BIDS has been replaced by SQL Server Data Tools, a free plugin for Visual Studio (including the free Visual Studio Community Edition).

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)

Count number of occurrences of a pattern in a file (even on same line)

Ripgrep, which is a fast alternative to grep, has just introduced the --count-matches flag allowing counting each match in version 0.9 (I'm using the above example to stay consistent):

> echo afoobarfoobar | rg --count foo
1
> echo afoobarfoobar | rg --count-matches foo
2

As asked by OP, ripgrep allows for regex pattern as well (--regexp <PATTERN>). Also it can print each (line) match on a separate line:

> echo -e "line1foo\nline2afoobarfoobar" | rg foo
line1foo
line2afoobarfoobar

Writing html form data to a txt file without the use of a webserver

I know this is old, but it's the first example of saving form data to a txt file I found in a quick search. So I've made a couple edits to the above code that makes it work more smoothly. It's now easier to add more fields, including the radio button as @user6573234 requested.

https://jsfiddle.net/cgeiser/m0j7Lwyt/1/

<!DOCTYPE html>
<html>
<head>
<style>
form * {
  display: block;
  margin: 10px;
}
</style>
<script language="Javascript" >
function download() {
  var filename = window.document.myform.docname.value;
  var name =  window.document.myform.name.value;
  var text =  window.document.myform.text.value;
  var problem =  window.document.myform.problem.value;
  
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 
    "Your Name: " + encodeURIComponent(name) + "\n\n" +
    "Problem: " + encodeURIComponent(problem) + "\n\n" +
    encodeURIComponent(text)); 

  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}
</script>
</head>
<body>
<form name="myform" method="post" >
  <input type="text" id="docname" value="test.txt" />
  <input type="text" id="name" placeholder="Your Name" />
  <div style="display:unblock">
    Option 1 <input type="radio" value="Option 1" onclick="getElementById('problem').value=this.value; getElementById('problem').show()" style="display:inline" />
    Option 2 <input type="radio" value="Option 2" onclick="getElementById('problem').value=this.value;" style="display:inline" />
    <input type="text" id="problem" />
  </div>
  <textarea rows=3 cols=50 id="text" />Please type in this box. 
When you click the Download button, the contents of this box will be downloaded to your machine at the location you specify. Pretty nifty. </textarea>
  
  <input id="download_btn" type="submit" class="btn" style="width: 125px" onClick="download();" />
  
</form>
</body>
</html>

How to read an external properties file in Maven

This answer to a similar question describes how to extend the properties plugin so it can use a remote descriptor for the properties file. The descriptor is basically a jar artifact containing a properties file (the properties file is included under src/main/resources).

The descriptor is added as a dependency to the extended properties plugin so it is on the plugin's classpath. The plugin will search the classpath for the properties file, read the file''s contents into a Properties instance, and apply those properties to the project's configuration so they can be used elsewhere.

undefined reference to WinMain@16 (codeblocks)

When there's no project, Code::Blocks only compiles and links the current file. That file, from your picture, is secrypt.cpp, which does not have a main function. In order to compile and link both source files, you'll need to do it manually or add them to the same project.

Contrary to what others are saying, using a Windows subsystem with main will still work, but there will be no console window.

Your other attempt, compiling and linking just trial.cpp, never links secrypt.cpp. This would normally result in an undefined reference to jRegister(), but you've declared the function inside main instead of calling it. Change main to:

int main()
{
    jRegister();

    return 0;
}

Getting the application's directory from a WPF application

Here is another:

System.Reflection.Assembly.GetExecutingAssembly().Location

How to update std::map after using the find method?

You can use std::map::at member function, it returns a reference to the mapped value of the element identified with key k.

std::map<char,int> mymap = {
                               { 'a', 0 },
                               { 'b', 0 },
                           };

  mymap.at('a') = 10;
  mymap.at('b') = 20;

How to delete Tkinter widgets from a window?

I found that when the widget is part of a function and the grid_remove is part of another function it does not remove the label. In this example...

def somefunction(self):
    Label(self, text=" ").grid(row = 0, column = 0)
    self.text_ent = Entry(self)
    self.text_ent.grid(row = 1, column = 0)
def someotherfunction(self):
    somefunction.text_ent.grid_remove()

...there is no valid way of removing the Label.

The only solution I could find is to give the label a name and make it global:

def somefunction(self):
    global label
    label = Label(self, text=" ")
    label.grid(row = 0, column = 0)
    self.text_ent = Entry(self)
    self.text_ent.grid(row = 1, column = 0)
def someotherfunction(self):
    global label
    somefunction.text_ent.grid_remove()
    label.grid_remove()

When I ran into this problem there was a class involved, one function being in the class and one not, so I'm not sure the global label lines are really needed in the above.

Get the Selected value from the Drop down box in PHP

You have to give a name attribute on your <select /> element, and then use it from the $_POST or $_GET (depending on how you transmit data) arrays in PHP. Be sure to sanitize user input, though.

How to center a "position: absolute" element

    <div class="centered_content"> content </div>
    <style type="text/css">
    .centered_content {
       text-align: center;
       position: absolute;
       left: 0;
       right: 0;
    }
    </style>

see demo on: http://jsfiddle.net/MohammadDayeh/HrZLC/

text-align: center; works with a position: absolute element when adding left: 0; right: 0;

Get size of all tables in database

Here is a way to get all tables' sizes quickly with the following steps:

  1. Write the given T-SQL commands to list all database tables:

    select 'exec sp_spaceused ' + TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_TYPE = 'BASE TABLE'
    
  2. Now copy the list of database tables, and copy it into a new query analyzer window

    exec sp_spaceused table1
    exec sp_spaceused table2
    exec sp_spaceused table3
    exec sp_spaceused table4
    exec sp_spaceused table5
    
  3. In SQL query analyzer, select from top tool bar option Results to file (Ctrl + Shift + F).

  4. Now finally hit the Execute button red marked from the above tool bar.

  5. The Database size of all tables is now stored in a file on your computer.

    Enter image description here

Difference between git checkout --track origin/branch and git checkout -b branch origin/branch

The two commands have the same effect (thanks to Robert Siemer’s answer for pointing it out).

The practical difference comes when using a local branch named differently:

  • git checkout -b mybranch origin/abranch will create mybranch and track origin/abranch
  • git checkout --track origin/abranch will only create 'abranch', not a branch with a different name.

(That is, as commented by Sebastian Graf, if the local branch did not exist already.
If it did, you would need git checkout -B abranch origin/abranch)


Note: with Git 2.23 (Q3 2019), that would use the new command git switch:

git switch -c <branch> --track <remote>/<branch>

If the branch exists in multiple remotes and one of them is named by the checkout.defaultRemote configuration variable, we'll use that one for the purposes of disambiguation, even if the <branch> isn't unique across all remotes.
Set it to e.g. checkout.defaultRemote=origin to always checkout remote branches from there if <branch> is ambiguous but exists on the 'origin' remote.

Here, '-c' is the new '-b'.


First, some background: Tracking means that a local branch has its upstream set to a remote branch:

# git config branch.<branch-name>.remote origin
# git config branch.<branch-name>.merge refs/heads/branch

git checkout -b branch origin/branch will:

  • create/reset branch to the point referenced by origin/branch.
  • create the branch branch (with git branch) and track the remote tracking branch origin/branch.

When a local branch is started off a remote-tracking branch, Git sets up the branch (specifically the branch.<name>.remote and branch.<name>.merge configuration entries) so that git pull will appropriately merge from the remote-tracking branch.
This behavior may be changed via the global branch.autosetupmerge configuration flag. That setting can be overridden by using the --track and --no-track options, and changed later using git branch --set-upstream-to.


And git checkout --track origin/branch will do the same as git branch --set-upstream-to):

 # or, since 1.7.0
 git branch --set-upstream upstream/branch branch
 # or, since 1.8.0 (October 2012)
 git branch --set-upstream-to upstream/branch branch
 # the short version remains the same:
 git branch -u upstream/branch branch

It would also set the upstream for 'branch'.

(Note: git1.8.0 will deprecate git branch --set-upstream and replace it with git branch -u|--set-upstream-to: see git1.8.0-rc1 announce)


Having an upstream branch registered for a local branch will:

  • tell git to show the relationship between the two branches in git status and git branch -v.
  • directs git pull without arguments to pull from the upstream when the new branch is checked out.

See "How do you make an existing git branch track a remote branch?" for more.

C# Inserting Data from a form into an access Database

This answer will help in case, If you are working with Data Bases then mostly take the help of try-catch block statement, which will help and guide you with your code. Here i am showing you that how to insert some values in Data Base with a Button Click Event.

 private void button2_Click(object sender, EventArgs e)
    {
        System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
        conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
    @"Data source= C:\Users\pir fahim shah\Documents\TravelAgency.accdb";

     try
       {
           conn.Open();
           String ticketno=textBox1.Text.ToString();                 
           String Purchaseprice=textBox2.Text.ToString();
           String sellprice=textBox3.Text.ToString();
           String my_querry = "INSERT INTO Table1(TicketNo,Sellprice,Purchaseprice)VALUES('"+ticketno+"','"+sellprice+"','"+Purchaseprice+"')";

            OleDbCommand cmd = new OleDbCommand(my_querry, conn);
            cmd.ExecuteNonQuery();

            MessageBox.Show("Data saved successfuly...!");
          }
         catch (Exception ex)
         {
             MessageBox.Show("Failed due to"+ex.Message);
         }
         finally
         {
             conn.Close();
         }

npm install error - unable to get local issuer certificate

I have encountered the same issue. This command didn't work for me either:

npm config set strict-ssl false

After digging deeper, I found out that this link was block by our IT admin.

http://registry.npmjs.org/npm

So if you are facing the same issue, make sure this link is accessible to your browser first.

maxlength ignored for input type="number" in Chrome

I have two ways for you do that

First: Use type="tel", it'll work like type="number" in mobile, and accept maxlength:

<input type="tel" />

Second: Use a little bit of JavaScript:

<!-- maxlength="2" -->
<input type="tel" onKeyDown="if(this.value.length==2 && event.keyCode!=8) return false;" />

Scrollable Menu with Bootstrap - Menu expanding its container when it should not

Do everything in the inline of UL tag

<ul class="dropdown-menu scrollable-menu" role="menu" style="height: auto;max-height: 200px; overflow-x: hidden;">
                <li><a href="#">Action</a></li>
                <li><a href="#">Another action</a></li>
                <li><a href="#">Something else here</a></li>
                <li><a href="#">Action</a></li>
                ..
                <li><a href="#">Action</a></li>
                <li><a href="#">Another action</a></li>
            </ul>

What does void do in java?

Void doesn't return anything; it tells the compiler the method doesn't have a return value.

ASP.NET MVC JsonResult Date Format

Format the date within the query.

var _myModel = from _m in model.ModelSearch(word)
    select new { date = ((DateTime)_m.Date).ToShortDateString() };

The only problem with this solution is that you won't get any results if ANY of the date values are null. To get around this you could either put conditional statements in your query BEFORE you select the date that ignores date nulls or you could set up a query to get all the results and then loop through all of that info using a foreach loop and assign a value to all dates that are null BEFORE you do your SELECT new.

Example of both:

var _test = from _t in adc.ItemSearchTest(word)
                        where _t.Date != null
                        select new { date = ((DateTime)_t.Date).ToShortDateString() };

The second option requires another query entirely so you can assign values to all nulls. This and the foreach loop would have to be BEFORE your query that selects the values.

var _testA = from _t in adc.ItemSearchTest(word)
                         select _i;

            foreach (var detail in _testA)
            {
                if (detail.Date== null)
                {
                    detail.Date= Convert.ToDateTime("1/1/0001");
                }
            }

Just an idea which I found easier than all of the javascript examples.

How to get datas from List<Object> (Java)?

You should try something like this

List xx= (List) list.get(0)
String id = (String) xx.get(0)

or if you have a House value object the result of the query is of the same type, then

House myhouse = (House) list.get(0);

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

Taking for granted that the JSON you posted is actually what you are seeing in the browser, then the problem is the JSON itself.

The JSON snippet you have posted is malformed.

You have posted:

[{
        "name" : "shopqwe",
        "mobiles" : [],
        "address" : {
            "town" : "city",
            "street" : "streetqwe",
            "streetNumber" : "59",
            "cordX" : 2.229997,
            "cordY" : 1.002539
        },
        "shoe"[{
                "shoeName" : "addidas",
                "number" : "631744030",
                "producent" : "nike",
                "price" : 999.0,
                "sizes" : [30.0, 35.0, 38.0]
            }]

while the correct JSON would be:

[{
        "name" : "shopqwe",
        "mobiles" : [],
        "address" : {
            "town" : "city",
            "street" : "streetqwe",
            "streetNumber" : "59",
            "cordX" : 2.229997,
            "cordY" : 1.002539
        },
        "shoe" : [{
                "shoeName" : "addidas",
                "number" : "631744030",
                "producent" : "nike",
                "price" : 999.0,
                "sizes" : [30.0, 35.0, 38.0]
            }
        ]
    }
]

How do I get the HTML code of a web page in PHP?

Simple way: Use file_get_contents():

$page = file_get_contents('http://stackoverflow.com/questions/ask');

Please note that allow_url_fopen must be true in you php.ini to be able to use URL-aware fopen wrappers.

More advanced way: If you cannot change your PHP configuration, allow_url_fopen is false by default and if ext/curl is installed, use the cURL library to connect to the desired page.

Java Array Sort descending?

without explicit comparator:

Collections.sort(list, Collections.reverseOrder());

with explicit comparator:

Collections.sort(list, Collections.reverseOrder(new Comparator()));

Continuous CSS rotation animation on hover, animated back to 0deg on hover out

<script>
var deg = 0

function rotate(id)
{
    deg = deg+45;
    var txt = 'rotate('+deg+'deg)';
    $('#'+id).css('-webkit-transform',txt);
}
</script>

What I do is something very easy... declare a global variable at the start... and then increment the variable however much I like, and use .css of jquery to increment.

Android 6.0 multiple permissions

Small code :

 public static final int MULTIPLE_PERMISSIONS = 10; // code you want.

 String[] permissions= new String[]{
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.ACCESS_FINE_LOCATION};


if (checkPermissions())
         //  permissions  granted.    
}

private  boolean checkPermissions() {
        int result;
        List<String> listPermissionsNeeded = new ArrayList<>();
        for (String p:permissions) {
            result = ContextCompat.checkSelfPermission(getActivity(),p);
            if (result != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(p);
            }
        }
        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),MULTIPLE_PERMISSIONS );
            return false;
        }
        return true;
    }


   @Override
    public void onRequestPermissionsResult(int requestCode, String permissionsList[], int[] grantResults) {
        switch (requestCode) {
            case MULTIPLE_PERMISSIONS:{
                if (grantResults.length > 0) {
                String permissionsDenied = "";
                for (String per : permissionsList) {
                    if(grantResults[0] == PackageManager.PERMISSION_DENIED){
                        permissionsDenied += "\n" + per;

                    } 

                }
                // Show permissionsDenied 
                updateViews();
            }
                return;
            }
        }
     }

List of Android permissions normal permissions and dangerous permissions in API 23

Get CPU Usage from Windows Command Prompt

typeperf "\processor(_total)\% processor time"

does work on Win7, you just need to extract the percent value yourself from the last quoted string.

Hamcrest compare collections

With existing Hamcrest libraries (as of v.2.0.0.0) you are forced to use Collection.toArray() method on your Collection in order to use containsInAnyOrder Matcher. Far nicer would be to add this as a separate method to org.hamcrest.Matchers:

public static <T> org.hamcrest.Matcher<java.lang.Iterable<? extends T>> containsInAnyOrder(Collection<T> items) {
    return org.hamcrest.collection.IsIterableContainingInAnyOrder.<T>containsInAnyOrder((T[]) items.toArray());
}

Actually I ended up adding this method to my custom test library and use it to increase readability of my test cases (due to less verbosity).

Git: Installing Git in PATH with GitHub client for Windows

I would like to add one more thing to what the other answers have said. It is not compulsory that path will be:

C:\Users\<user>\AppData\Local\GitHub\PortableGit_<guid>\bin\git.exe

In my computer I did not found Git there.

BUT git and cmd are located in

git.exe

C:\Program Files\Git\bin\git.exe

cmd

C:\Program Files\Git\cmd

To add into PATH:

  • Right-Click on My Computer
  • Click on Advanced System Settings
  • Click on Environment Variables
  • Then, under System Variables, look for the path variable and click edit
  • Add the path to git’s bin and cmd at the end of the string like this:

    ;C:\Program Files\Git\bin\git.exe;C:\Program Files\Git\cmd

OR

;C:\Users\<user>\AppData\Local\GitHub\PortableGit_<guid>\bin;C:\Users\<user>\AppData\Local\GitHub\PortableGit_<guid>\cmd

To verify, restart cmd and type git --version in cmd

getting only name of the class Class.getName()

or programmaticaly

String s = String.class.getName();
s = s.substring(s.lastIndexOf('.') + 1);

Python and SQLite: insert into table

conn = sqlite3.connect('/path/to/your/sqlite_file.db')
c = conn.cursor()
for item in my_list:
  c.execute('insert into tablename values (?,?,?)', item)

Visual Studio Error: (407: Proxy Authentication Required)

I faced the same error with my Visual Studio Team Services account (formerly Visual Studio Online, Team Foundation Service).

I simply entered the credentials using the VS 2013 "Connect to Team Foundation Server" Window, and then connected it to the Visual Studio Team Services Team Project. It worked this way.

Change output format for MySQL command line results to CSV

It is how to save results to CSV on the client-side without additional non-standard tools. This example uses only mysql client and awk.

One-line:

mysql --skip-column-names --batch -e 'select * from dump3' t | awk -F'\t' '{ sep=""; for(i = 1; i <= NF; i++) { gsub(/\\t/,"\t",$i); gsub(/\\n/,"\n",$i); gsub(/\\\\/,"\\",$i); gsub(/"/,"\"\"",$i); printf sep"\""$i"\""; sep=","; if(i==NF){printf"\n"}}}'

Logical explanation of what is needed to do

  1. First, let see how data looks like in RAW mode (with --raw option). the database and table are respectively t and dump3

    You can see the field starting from "new line" (in the first row) is splitted into three lines due to new lines placed in the value.

mysql --skip-column-names --batch --raw -e 'select * from dump3' t

one line        2       new line
quotation marks " backslash \ two quotation marks "" two backslashes \\ two tabs                new line
the end of field

another line    1       another line description without any special chars
  1. OUTPUT data in batch mode (without --raw option) - each record changed to the one-line texts by escaping characters like \ <tab> and new-lines
mysql --skip-column-names --batch -e 'select * from dump3' t

one line      2  new line\nquotation marks " backslash \\ two quotation marks "" two backslashes \\\\ two tabs\t\tnew line\nthe end of field
another line  1  another line description without any special chars
  1. And data output in CSV format

The clue is to save data in CSV format with escaped characters.

The way to do that is to convert special entities which mysql --batch produces (\t as tabs \\ as backshlash and \n as newline) into equivalent bytes for each value (field). Then whole value is escaped by " and enclosed also by ". Btw - using the same characters for escaping and enclosing gently simplifies output and processing, because you don't have two special characters. For this reason all you have to do with values (from csv format perspective) is to change " to "" whithin values. In more common way (with escaping and enclosing respectively \ and ") you would have to first change \ to \\ and then change " into \".

And the commands' explanation step by step:

# we produce one-line output as showed in step 2.
mysql --skip-column-names --batch -e 'select * from dump3' t

# set fields separator to  because mysql produces in that way
| awk -F'\t' 

# this start iterating every line/record from the mysql data - standard behaviour of awk
'{ 

# field separator is empty because we don't print a separator before the first output field
sep=""; 

-- iterating by every field and converting the field to csv proper value
for(i = 1; i <= NF; i++) { 
-- note: \\ two shlashes below mean \ for awk because they're escaped

-- changing \t into byte corresponding to <tab> 
    gsub(/\\t/, "\t",$i); 

-- changing \n into byte corresponding to new line
    gsub(/\\n/, "\n",$i); 

-- changing two \\ into one \  
    gsub(/\\\\/,"\\",$i);

-- changing value into CSV proper one literally - change " into ""
    gsub(/"/,   "\"\"",$i); 

-- print output field enclosed by " and adding separator before
    printf sep"\""$i"\"";  

-- separator is set after first field is processed - because earlier we don't need it
    sep=","; 

-- adding new line after the last field processed - so this indicates csv record separator
    if(i==NF) {printf"\n"} 
    }
}'

Command-line Tool to find Java Heap Size and Memory Used (Linux)?

In terms of Java heap size, in Linux, you can use

ps aux | grep java

or

ps -ef | grep java

and look for -Xms, -Xmx to find out the initial and maximum heap size specified.

However, if -Xms or -Xmx is absent for the Java process you are interested in, it means your Java process is using the default heap sizes. You can use the following command to find out the default sizes.

java -XX:+PrintFlagsFinal -version | grep HeapSize

or a particular jvm, for example,

/path/to/jdk1.8.0_102/bin/java -XX:+PrintFlagsFinal -version | grep HeapSize

and look for InitialHeapSize and MaxHeapSize, which is in bytes.

Viewing all defined variables

To get the names:

for name in vars().keys():
  print(name)

To get the values:

for value in vars().values():
  print(value)

vars() also takes an optional argument to find out which vars are defined within an object itself.

ArrayList filter

As you didn't give us very much information, I'm assuming the language you're writing the code in is C#. First of all: Prefer System.Collections.Generic.List over an ArrayList. Secondly: One way would be to loop through every item in the list and check whether it contains "How". Another way would be to use LINQ. Here's a quick example that filters out every item which doesn't contain "How":

var list = new List<string>();
list.AddRange(new string[] {
    "How are you?",
    "How you doing?",
    "Joe",
    "Mike", });

foreach (string str in list.Where(s => s.Contains("How")))
{
    Console.WriteLine(str);
}
Console.ReadLine();

How to configure socket connect timeout

I had the Same problem when connecting to a Socket and I came up with the below solution ,It works Fine for me. `

private bool CheckConnectivityForProxyHost(string hostName, int port)
       {
           if (string.IsNullOrEmpty(hostName))
               return false;

           bool isUp = false;
           Socket testSocket = null;

           try
           {

               testSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
               IPAddress ip = null;
               if (testSocket != null && NetworkingCollaboratorBase.GetResolvedConnecionIPAddress(hostName, out ip))//Use a method to resolve your IP
               {
                   IPEndPoint ipEndPoint = new IPEndPoint(ip, port);

                   isUp = false;
//time out 5 Sec
                  CallWithTimeout(ConnectToProxyServers, 5000, testSocket, ipEndPoint);

                       if (testSocket != null && testSocket.Connected)
                       {
                           isUp = true;
                       }
                   }

               }
           }
           catch (Exception ex)
           {
               isUp = false;
           }
           finally
           {
               try
               {
                   if (testSocket != null)
                   {
                       testSocket.Shutdown(SocketShutdown.Both);
                   }
               }
               catch (Exception ex)
               {

               }
               finally
               {
                   if (testSocket != null)
                       testSocket.Close();
               }

           }

           return isUp;
       }


 private void CallWithTimeout(Action<Socket, IPEndPoint> action, int timeoutMilliseconds, Socket socket, IPEndPoint ipendPoint)
       {
           try
           {
               Action wrappedAction = () =>
               {
                   action(socket, ipendPoint);
               };

               IAsyncResult result = wrappedAction.BeginInvoke(null, null);

               if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
               {
                   wrappedAction.EndInvoke(result);
               }

           }
           catch (Exception ex)
           {

           }
       }

  private void ConnectToProxyServers(Socket testSocket, IPEndPoint ipEndPoint)
       {
           try
           {
               if (testSocket == null || ipEndPoint == null)
                   return;

                   testSocket.Connect(ipEndPoint);

           }
           catch (Exception ex)
           {

           }
       } 

Calculating sum of repeated elements in AngularJS ng-repeat

Simple Solution

Here is a simple solution. No additional for loop required.

HTML part

         <table ng-init="ResetTotalAmt()">
                <tr>
                    <th>Product</th>
                    <th>Quantity</th>
                    <th>Price</th>
                </tr>

                <tr ng-repeat="product in cart.products">
                    <td ng-init="CalculateSum(product)">{{product.name}}</td>
                    <td>{{product.quantity}}</td>
                    <td>{{product.price * product.quantity}} €</td>
                </tr>

                <tr>
                    <td></td>
                    <td>Total :</td>
                    <td>{{cart.TotalAmt}}</td> // Here is the total value of my cart
                </tr>

           </table>

Script Part

 $scope.cart.TotalAmt = 0;
 $scope.CalculateSum= function (product) {
   $scope.cart.TotalAmt += (product.price * product.quantity);
 }
//It is enough to Write code $scope.cart.TotalAmt =0; in the function where the cart.products get allocated value. 
$scope.ResetTotalAmt = function (product) {
   $scope.cart.TotalAmt =0;
 }

Valid characters in a Java class name

You can have almost any character, including most Unicode characters! The exact definition is in the Java Language Specification under section 3.8: Identifiers.

An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. ...

Letters and digits may be drawn from the entire Unicode character set, ... This allows programmers to use identifiers in their programs that are written in their native languages.

An identifier cannot have the same spelling (Unicode character sequence) as a keyword (§3.9), boolean literal (§3.10.3), or the null literal (§3.10.7), or a compile-time error occurs.

However, see this question for whether or not you should do that.

How do I delete an item or object from an array using ng-click?

Pass the id that you want to remove from the array to the given function 

from the controller( Function can be in the same controller but prefer to keep it in a service)

    function removeInfo(id) {
    let item = bdays.filter(function(item) {
      return bdays.id=== id;
    })[0];
    let index = bdays.indexOf(item);
    data.device.splice(indexOfTabDetails, 1);
  }

How to convert an int value to string in Go?

You can use fmt.Sprintf or strconv.FormatFloat

For example

package main

import (
    "fmt"
)

func main() {
    val := 14.7
    s := fmt.Sprintf("%f", val)
    fmt.Println(s)
}

Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location

Based on the current user's latitude, longitude and the distance you wants to find,the sql query is given below.

SELECT * FROM(
    SELECT *,(((acos(sin((@latitude*pi()/180)) * sin((Latitude*pi()/180))+cos((@latitude*pi()/180)) * cos((Latitude*pi()/180)) * cos(((@longitude - Longitude)*pi()/180))))*180/pi())*60*1.1515*1.609344) as distance FROM Distances) t
WHERE distance <= @distance

@latitude and @longitude are the latitude and longitude of the point. Latitude and longitude are the columns of distances table. Value of pi is 22/7

How can I create keystore from an existing certificate (abc.crt) and abc.key files?

The easiest is probably to create a PKCS#12 file using OpenSSL:

openssl pkcs12 -export -in abc.crt -inkey abc.key -out abc.p12

You should be able to use the resulting file directly using the PKCS12 keystore type.

If you really need to, you can convert it to JKS using keytool -importkeystore (available in keytool from Java 6):

keytool -importkeystore -srckeystore abc.p12 \
        -srcstoretype PKCS12 \
        -destkeystore abc.jks \
        -deststoretype JKS

How to do a GitHub pull request

I've started a project to help people making their first GitHub pull request. You can do the hands-on tutorial to make your first PR here

The workflow is simple as

  • Fork the repo in github
  • Get clone url by clicking on clone repo button
  • Go to terminal and run git clone <clone url you copied earlier>
  • Make a branch for changes you're makeing git checkout -b branch-name
  • Make necessary changes
  • Commit your changes git commit
  • Push your changes to your fork on GitHub git push origin branch-name
  • Go to your fork on GitHub to see a Compare and pull request button
  • Click on it and give necessary details

JSON formatter in C#?

Even simpler one that I just wrote:

public class JsonFormatter
{
    public static string Indent = "    ";

    public static string PrettyPrint(string input)
    {
        var output = new StringBuilder(input.Length * 2);
        char? quote = null;
        int depth = 0;

        for(int i=0; i<input.Length; ++i)
        {
            char ch = input[i];

            switch (ch)
            {
                case '{':
                case '[':
                    output.Append(ch);
                    if (!quote.HasValue)
                    {
                        output.AppendLine();
                        output.Append(Indent.Repeat(++depth));
                    }
                    break;
                case '}':
                case ']':
                    if (quote.HasValue)  
                        output.Append(ch);
                    else
                    {
                        output.AppendLine();
                        output.Append(Indent.Repeat(--depth));
                        output.Append(ch);
                    }
                    break;
                case '"':
                case '\'':
                    output.Append(ch);
                    if (quote.HasValue)
                    {
                        if (!output.IsEscaped(i))
                            quote = null;
                    }
                    else quote = ch;
                    break;
                case ',':
                    output.Append(ch);
                    if (!quote.HasValue)
                    {
                        output.AppendLine();
                        output.Append(Indent.Repeat(depth));
                    }
                    break;
                case ':':
                    if (quote.HasValue) output.Append(ch);
                    else output.Append(" : ");
                    break;
                default:
                    if (quote.HasValue || !char.IsWhiteSpace(ch)) 
                        output.Append(ch);
                    break;
            }
        }

        return output.ToString();
    }
}

Necessary extensions:

    public static string Repeat(this string str, int count)
    {
        return new StringBuilder().Insert(0, str, count).ToString();
    }

    public static bool IsEscaped(this string str, int index)
    {
        bool escaped = false;
        while (index > 0 && str[--index] == '\\') escaped = !escaped;
        return escaped;
    }

    public static bool IsEscaped(this StringBuilder str, int index)
    {
        return str.ToString().IsEscaped(index);
    }

Sample output:

{
    "status" : "OK",
    "results" : [
        {
            "types" : [
                "locality",
                "political"
            ],
            "formatted_address" : "New York, NY, USA",
            "address_components" : [
                {
                    "long_name" : "New York",
                    "short_name" : "New York",
                    "types" : [
                        "locality",
                        "political"
                    ]
                },
                {
                    "long_name" : "New York",
                    "short_name" : "New York",
                    "types" : [
                        "administrative_area_level_2",
                        "political"
                    ]
                },
                {
                    "long_name" : "New York",
                    "short_name" : "NY",
                    "types" : [
                        "administrative_area_level_1",
                        "political"
                    ]
                },
                {
                    "long_name" : "United States",
                    "short_name" : "US",
                    "types" : [
                        "country",
                        "political"
                    ]
                }
            ],
            "geometry" : {
                "location" : {
                    "lat" : 40.7143528,
                    "lng" : -74.0059731
                },
                "location_type" : "APPROXIMATE",
                "viewport" : {
                    "southwest" : {
                        "lat" : 40.5788964,
                        "lng" : -74.2620919
                    },
                    "northeast" : {
                        "lat" : 40.8495342,
                        "lng" : -73.7498543
                    }
                },
                "bounds" : {
                    "southwest" : {
                        "lat" : 40.4773990,
                        "lng" : -74.2590900
                    },
                    "northeast" : {
                        "lat" : 40.9175770,
                        "lng" : -73.7002720
                    }
                }
            }
        }
    ]
}

How to manually include external aar package using new Gradle Android Build System

The below approach works with latest Android studio (> v0.8.x):

  • Save the aar file under app module's libs folder (eg: <project>/<app>/libs/myaar.aar)

  • Add the below to build.gradle of your "app" module folder (not your project root build.gradle). Note the name in compile line, it is myaar@aar not myaar.aar.

    dependencies {
        compile 'package.name.of.your.aar:myaar@aar'
    }
    
    repositories{
        flatDir{
            dirs 'libs'
        }
    }
    
  • Click Tools -> Android -> Sync Project with Gradle Files

How to copy a collection from one database to another in MongoDB

I know this question has been answered however I personally would not do @JasonMcCays answer due to the fact that cursors stream and this could cause an infinite cursor loop if the collection is still being used. Instead I would use a snapshot():

http://www.mongodb.org/display/DOCS/How+to+do+Snapshotted+Queries+in+the+Mongo+Database

@bens answer is also a good one and works well for hot backups of collections not only that but mongorestore does not need to share the same mongod.