Programs & Examples On #Provider

DO NOT USE — this tag is being cleaned up. Use [android-contentprovider], [provider-model], or whatever more specific tag is appropriate instead.

How do I run a VBScript in 32-bit mode on a 64-bit machine?

We can force vbscript always run with 32 bit mode by changing "system32" to "sysWOW64" in default value of key "Computer\HKLM\SOFTWARE]\Classes\VBSFile\Shell\Open\Command"

MVC4 HTTP Error 403.14 - Forbidden

Try

<system.webServer>
   <modules runAllManagedModulesForAllRequests="true"/> 
 </system.webServer>

Via

https://serverfault.com/questions/405395/unable-to-get-anything-except-403-from-a-net-4-5-website

How do I cast a JSON Object to a TypeScript class?

I used this library here: https://github.com/pleerock/class-transformer

<script lang="ts">
    import { plainToClass } from 'class-transformer';
</script>

Implementation:

private async getClassTypeValue() {
  const value = await plainToClass(ProductNewsItem, JSON.parse(response.data));
}

Sometimes you will have to parse the JSON values for plainToClass to understand that it is a JSON formatted data

Fastest way to check if a string matches a regexp in ruby?

What about re === str (case compare)?

Since it evaluates to true or false and has no need for storing matches, returning match index and that stuff, I wonder if it would be an even faster way of matching than =~.


Ok, I tested this. =~ is still faster, even if you have multiple capture groups, however it is faster than the other options.

BTW, what good is freeze? I couldn't measure any performance boost from it.

Permutations in JavaScript?

Functional answer using flatMap:

const getPermutationsFor = (arr, permutation = []) =>
  arr.length === 0
    ? [permutation]
    : arr.flatMap((item, i, arr) =>
        getPermutationsFor(
          arr.filter((_,j) => j !== i),
          [...permutation, item]
        )
      );

Reducing MongoDB database file size

Compact all collections in current database

db.getCollectionNames().forEach(function (collectionName) {
    print('Compacting: ' + collectionName);
    db.runCommand({ compact: collectionName });
});

Adding a parameter to the URL with JavaScript

Following function will help you to add,update and delete parameters to or from URL.

//example1and

var myURL = '/search';

myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?location=california

myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?location=new%20york

myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search

//example2

var myURL = '/search?category=mobile';

myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?category=mobile&location=california

myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?category=mobile&location=new%20york

myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search?category=mobile

//example3

var myURL = '/search?location=texas';

myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?location=california

myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?location=new%20york

myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search

//example4

var myURL = '/search?category=mobile&location=texas';

myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?category=mobile&location=california

myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?category=mobile&location=new%20york

myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search?category=mobile

//example5

var myURL = 'https://example.com/search?location=texas#fragment';

myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?location=california#fragment

myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?location=new%20york#fragment

myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search#fragment

Here is the function.

function updateUrl(url,key,value){
      if(value!==undefined){
        value = encodeURI(value);
      }
      var hashIndex = url.indexOf("#")|0;
      if (hashIndex === -1) hashIndex = url.length|0;
      var urls = url.substring(0, hashIndex).split('?');
      var baseUrl = urls[0];
      var parameters = '';
      var outPara = {};
      if(urls.length>1){
          parameters = urls[1];
      }
      if(parameters!==''){
        parameters = parameters.split('&');
        for(k in parameters){
          var keyVal = parameters[k];
          keyVal = keyVal.split('=');
          var ekey = keyVal[0];
          var evalue = '';
          if(keyVal.length>1){
              evalue = keyVal[1];
          }
          outPara[ekey] = evalue;
        }
      }

      if(value!==undefined){
        outPara[key] = value;
      }else{
        delete outPara[key];
      }
      parameters = [];
      for(var k in outPara){
        parameters.push(k + '=' + outPara[k]);
      }

      var finalUrl = baseUrl;

      if(parameters.length>0){
        finalUrl += '?' + parameters.join('&'); 
      }

      return finalUrl + url.substring(hashIndex); 
  }

Upper memory limit?

Python can use all memory available to its environment. My simple "memory test" crashes on ActiveState Python 2.6 after using about

1959167 [MiB]

On jython 2.5 it crashes earlier:

 239000 [MiB]

probably I can configure Jython to use more memory (it uses limits from JVM)

Test app:

import sys

sl = []
i = 0
# some magic 1024 - overhead of string object
fill_size = 1024
if sys.version.startswith('2.7'):
    fill_size = 1003
if sys.version.startswith('3'):
    fill_size = 497
print(fill_size)
MiB = 0
while True:
    s = str(i).zfill(fill_size)
    sl.append(s)
    if i == 0:
        try:
            sys.stderr.write('size of one string %d\n' % (sys.getsizeof(s)))
        except AttributeError:
            pass
    i += 1
    if i % 1024 == 0:
        MiB += 1
        if MiB % 25 == 0:
            sys.stderr.write('%d [MiB]\n' % (MiB))

In your app you read whole file at once. For such big files you should read the line by line.

How to disable spring security for particular url

This may be not the full answer to your question, however if you are looking for way to disable csrf protection you can do:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/web/admin/**").hasAnyRole(ADMIN.toString(), GUEST.toString())
                .anyRequest().permitAll()
                .and()
                .formLogin().loginPage("/web/login").permitAll()
                .and()
                .csrf().ignoringAntMatchers("/contact-email")
                .and()
                .logout().logoutUrl("/web/logout").logoutSuccessUrl("/web/").permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("admin").roles(ADMIN.toString())
                .and()
                .withUser("guest").password("guest").roles(GUEST.toString());
    }

}

I have included full configuration but the key line is:

.csrf().ignoringAntMatchers("/contact-email")

I don't understand -Wl,-rpath -Wl,

One other thing. You may need to specify the -L option as well - eg

-Wl,-rpath,/path/to/foo -L/path/to/foo -lbaz

or you may end up with an error like

ld: cannot find -lbaz

Restart container within pod

Both pod and container are ephemeral, try to use the following command to stop the specific container and the k8s cluster will restart a new container.

kubectl exec -it [POD_NAME] -c [CONTAINER_NAME] -- /bin/sh -c "kill 1"

This will send a SIGTERM signal to process 1, which is the main process running in the container. All other processes will be children of process 1, and will be terminated after process 1 exits. See the kill manpage for other signals you can send.

Unable to start MySQL server

In my case, I went for

MySQL install Uninstall only the MySQL Server Install again

Make sure the Path is the same for example (if your installer warns you of a conflict): C:\Program Files...etc... C:\Program Files...etc...

If they are the same, it should work fine.

How to reference image resources in XAML?

If the image is in your resources folder and its build action is set to Resource. You can reference the image in XAML as follows:

"pack://application:,,,/Resources/Search.png"

Assuming you do not have any folder structure under the Resources folder and it is an application. For example I use:

ImageSource="pack://application:,,,/Resources/RibbonImages/CloseButton.png"

when I have a folder named RibbonImages under Resources folder.

How to detect current state within directive

If you are using ui-router, try $state.is();

You can use it like so:

$state.is('stateName');

Per the documentation:

$state.is ... similar to $state.includes, but only checks for the full state name.

Convert a RGB Color Value to a Hexadecimal String

You can use

String hex = String.format("#%02x%02x%02x", r, g, b);  

Use capital X's if you want your resulting hex-digits to be capitalized (#FFFFFF vs. #ffffff).

Check if a value is in an array or not with Excel VBA

The below function would return '0' if there is no match and a 'positive integer' in case of matching:


Function IsInArray(stringToBeFound As String, arr As Variant) As Integer IsInArray = InStr(Join(arr, ""), stringToBeFound) End Function ______________________________________________________________________________

Note: the function first concatenates the entire array content to a string using 'Join' (not sure if the join method uses looping internally or not) and then checks for a macth within this string using InStr.

PHP - Copy image to my server direct from URL

Two ways, if you're using PHP5 (or higher)

copy('http://www.google.co.in/intl/en_com/images/srpr/logo1w.png', '/tmp/file.png');

If not, use file_get_contents

//Get the file
$content = file_get_contents("http://www.google.co.in/intl/en_com/images/srpr/logo1w.png");
//Store in the filesystem.
$fp = fopen("/location/to/save/image.png", "w");
fwrite($fp, $content);
fclose($fp);

From this SO post

ggplot2 plot without axes, legends, etc

I didn't find this solution here. It removes all of it using the cowplot package:

library(cowplot)

p + theme_nothing() +
theme(legend.position="none") +
scale_x_continuous(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0)) +
labs(x = NULL, y = NULL)

Just noticed that the same thing can be accomplished using theme.void() like this:

p + theme_void() +
theme(legend.position="none") +
scale_x_continuous(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0)) +
labs(x = NULL, y = NULL)

How can I verify if a Windows Service is running

Here you get all available services and their status in your local machine.

ServiceController[] services = ServiceController.GetServices();
foreach(ServiceController service in services)
{
    Console.WriteLine(service.ServiceName+"=="+ service.Status);
}

You can Compare your service with service.name property inside loop and you get status of your service. For details go with the http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.aspx also http://msdn.microsoft.com/en-us/library/microsoft.windows.design.servicemanager(v=vs.90).aspx

Git Extensions: Win32 error 487: Couldn't reserve space for cygwin's heap, Win32 error 0

I had the same problem. I found solution here http://jakob.engbloms.se/archives/1403

c:\msysgit\bin>rebase.exe -b 0x50000000 msys-1.0.dll

For me solution was slightly different. It was

C:\Program Files (x86)\Git\bin>rebase.exe -b 0x50000000 msys-1.0.dll

Before you rebase dlls, you should make sure it is not in use:

tasklist /m msys-1.0.dll

And make a backup:

copy msys-1.0.dll msys-1.0.dll.bak

If the rebase command fails with something like:

ReBaseImage (msys-1.0.dll) failed with last error = 6

You will need to perform the following steps in order:

  1. Copy the dll to another directory
  2. Rebase the copy using the commands above
  3. Replace the original dll with the copy.

If any issue run the commands as Administrator

Remove end of line characters from Java string

static byte[] discardWhitespace(byte[] data) {
    byte groomedData[] = new byte[data.length];
    int bytesCopied = 0;

    for (int i = 0; i < data.length; i++) {
        switch (data[i]) {
            case (byte) '\n' :
            case (byte) '\r' :
                break;
            default:
                groomedData[bytesCopied++] = data[i];
        }
    }

    byte packedData[] = new byte[bytesCopied];

    System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);

    return packedData;
}

Code found on commons-codec project.

How do I measure a time interval in C?

On Linux you can use clock_gettime():

clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); // get initial time-stamp

// ... do stuff ... //

clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end);   // get final time-stamp

double t_ns = (double)(end.tv_sec - start.tv_sec) * 1.0e9 +
              (double)(end.tv_nsec - start.tv_nsec);
                                                 // subtract time-stamps and
                                                 // multiply to get elapsed
                                                 // time in ns

Typescript: Type 'string | undefined' is not assignable to type 'string'

As of TypeScript 3.7 you can use nullish coalescing operator ??. You can think of this feature as a way to “fall back” to a default value when dealing with null or undefined

let name1:string = person.name ?? '';

The ?? operator can replace uses of || when trying to use a default value and can be used when dealing with booleans, numbers, etc. where || cannot be used.

As of TypeScript 4 you can use ??= assignment operator as a ??= b which is an alternative to a = a ?? b;

Convert alphabet letters to number in Python

Here is my solution for a problem where you want to convert all the letters in a string with position of those letters in English alphabet and return a string of those nos.

https://gist.github.com/bondnotanymore/e0f1dcaacfb782348e74fac8b224769e

Let me know if you want to understand it in detail.I have used the following concepts - List comprehension - Dictionary comprehension

How to quickly and conveniently disable all console.log statements in my code?

After doing some research and development for this problem, I came across this solution which will hide warnings/Errors/Logs as per your choice.

    (function () {
    var origOpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function () {        
        console.warn = function () { };
        window['console']['warn'] = function () { };
        this.addEventListener('load', function () {                        
            console.warn('Something bad happened.');
            window['console']['warn'] = function () { };
        });        
    };
})();

Add this code before JQuery plugin (e.g /../jquery.min.js) even as this is JavaScript code that does not require JQuery. Because some warnings are in JQuery itself.

Thanks!!

A table name as a variable

Declare  @tablename varchar(50) 
set @tablename = 'Your table Name' 
EXEC('select * from ' + @tablename)

Android getText from EditText field

Try out this will solve ur problem ....

EditText etxt = (EditText)findviewbyid(R.id.etxt);
String str_value = etxt.getText().toString();

What's the valid way to include an image with no src?

Another option is to embed a blank image. Any image that suits your purpose will do, but the following example encodes a GIF that is only 26 bytes - from http://probablyprogramming.com/2009/03/15/the-tiniest-gif-ever

<img src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" width="0" height="0" alt="" />

Edit based on comment below:

Of course, you must consider your browser support requirements. No support for IE7 or less is notable. http://caniuse.com/datauri

How should I remove all the leading spaces from a string? - swift

To remove all spaces from the string:

let space_removed_string = (yourstring?.components(separatedBy: " ").joined(separator: ""))!

Have a variable in images path in Sass?

Was searching around for an answer to the same question, but think I found a better solution: http://blog.grayghostvisuals.com/compass/image-url/

Basically, you can set your image path in config.rb and you use the image-url() helper

How to use global variables in React Native?

Try to use global.foo = bar in index.android.js or index.ios.js, then you can call in other file js.

Python list sort in descending order

Here is another way


timestamps.sort()
timestamps.reverse()
print(timestamps)

C char* to int conversion

atoi can do that for you

Example:

char string[] = "1234";
int sum = atoi( string );
printf("Sum = %d\n", sum ); // Outputs: Sum = 1234

When should I use cross apply over inner join?

I guess it should be readability ;)

CROSS APPLY will be somewhat unique for people reading to tell them that a UDF is being used which will be applied to each row from the table on the left.

Ofcourse, there are other limitations where a CROSS APPLY is better used than JOIN which other friends have posted above.

How to move Docker containers between different hosts?

Use this script: https://github.com/ricardobranco777/docker-volumes.sh

This does preserve data in volumes.

Example usage:

# Stop the container   
docker stop $CONTAINER

# Create a new image   
docker commit $CONTAINER $CONTAINER

# Save image
docker save -o $CONTAINER.tar $CONTAINER

# Save the volumes (use ".tar.gz" if you want compression)
docker-volumes.sh $CONTAINER save $CONTAINER-volumes.tar

# Copy image and volumes to another host
scp $CONTAINER.tar $CONTAINER-volumes.tar $USER@$HOST:

# On the other host:
docker load -i $CONTAINER.tar
docker create --name $CONTAINER [<PREVIOUS CONTAINER OPTIONS>] $CONTAINER

# Load the volumes
docker-volumes.sh $CONTAINER load $CONTAINER-volumes.tar

# Start container
docker start $CONTAINER

Yii2 data provider default sorting

if you have CRUD (index) and you need set default sorting your controller for GridView, or ListView, or more... Example

public function actionIndex()
{
    $searchModel = new NewsSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    // set default sorting
    $dataProvider->sort->defaultOrder = ['id' => SORT_DESC];

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

you need add

$dataProvider->sort->defaultOrder = ['id' => SORT_DESC];

Python - Dimension of Data Frame

Summary of all ways to get info on dimensions of DataFrame or Series

There are a number of ways to get information on the attributes of your DataFrame or Series.

Create Sample DataFrame and Series

df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df

     a  b
0  5.0  9
1  2.0  2
2  NaN  4

s = df['a']
s

0    5.0
1    2.0
2    NaN
Name: a, dtype: float64

shape Attribute

The shape attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.

df.shape
(3, 2)

s.shape
(3,)

len function

To get the number of rows of a DataFrame or get the length of a Series, use the len function. An integer will be returned.

len(df)
3

len(s)
3

size attribute

To get the total number of elements in the DataFrame or Series, use the size attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len function:

df.size
6

s.size
3

ndim attribute

The ndim attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:

df.ndim
2

s.ndim
1

The tricky count method

The count method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.

df.count() # by default, get the count of each column

a    2
b    3
dtype: int64


df.count(axis='columns') # change direction to get count of each row

0    2
1    2
2    1
dtype: int64

For a Series, there is only one axis for computation and so it just returns a scalar:

s.count()
2

Use the info method for retrieving metadata

The info method returns the number of non-missing values and data types of each column

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a    2 non-null float64
b    3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes

The difference between fork(), vfork(), exec() and clone()

  • vfork() is an obsolete optimization. Before good memory management, fork() made a full copy of the parent's memory, so it was pretty expensive. since in many cases a fork() was followed by exec(), which discards the current memory map and creates a new one, it was a needless expense. Nowadays, fork() doesn't copy the memory; it's simply set as "copy on write", so fork()+exec() is just as efficient as vfork()+exec().

  • clone() is the syscall used by fork(). with some parameters, it creates a new process, with others, it creates a thread. the difference between them is just which data structures (memory space, processor state, stack, PID, open files, etc) are shared or not.

How can I clear the terminal in Visual Studio Code?

I am using Visual Studio Code 1.52.1 on windows 10 machine.'cls' or 'Clear' doesn't clear the terminal.

just write

exit

It will close the terminal and press

ctrl+shift+`

to open new terminal.

How do I get my Python program to sleep for 50 milliseconds?

Use time.sleep():

import time
time.sleep(50 / 1000)

See the Python documentation: https://docs.python.org/library/time.html#time.sleep

How to add new DataRow into DataTable?

You can try with this code - based on Rows.Add method

DataTable table = new DataTable();
DataRow row = table.NewRow();
table.Rows.Add(row);

Link : https://msdn.microsoft.com/en-us/library/9yfsd47w.aspx

Superscript in Python plots

If you want to write unit per meter (m^-1), use $m^{-1}$), which means -1 inbetween {}

Example: plt.ylabel("Specific Storage Values ($m^{-1}$)", fontsize = 12 )

Foreach with JSONArray and JSONObject

Apparently, org.json.simple.JSONArray implements a raw Iterator. This means that each element is considered to be an Object. You can try to cast:

for(Object o: arr){
    if ( o instanceof JSONObject ) {
        parse((JSONObject)o);
    }
}

This is how things were done back in Java 1.4 and earlier.

Origin http://localhost is not allowed by Access-Control-Allow-Origin

There are 2 calls that need to set the correct headers. Initially there is a preflight check so you need something like...

app.get('/item', item.list);
app.options('/item', item.preflight);

and then have the following functions...

exports.list = function (req, res) {
Items.allItems(function (err, items) {
    ...
        res.header('Access-Control-Allow-Origin', "*");     // TODO - Make this more secure!!
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST');
        res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept');
        res.send(items);
      }
   );
};

and for the pre-flight checks

exports.preflight = function (req, res) {
Items.allItems(function (err, items) {
        res.header('Access-Control-Allow-Origin', "*");     // TODO - Make this more secure!!
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST');
        res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept');
        res.send(200);
    }
  );
};

You can consolidate the res.header() code into a single function if you want.

Also as stated above, be careful of using res.header('Access-Control-Allow-Origin', "*") this means anyone can access your site!

How to check if curl is enabled or disabled

<?php

// Script to test if the CURL extension is installed on this server

// Define function to test
function _is_curl_installed() {
    if  (in_array  ('curl', get_loaded_extensions())) {
        return true;
    }
    else {
        return false;
    }
}

// Ouput text to user based on test
if (_is_curl_installed()) {
  echo "cURL is <span style=\"color:blue\">installed</span> on this server";
} else {
  echo "cURL is NOT <span style=\"color:red\">installed</span> on this server";
}
?>

or a simple one -

<?
phpinfo();
?>

Just search for curl

source - http://www.mattsbits.co.uk/item-164.html

PHP check if url parameter exists

Use isset()

$matchFound = (isset($_GET["id"]) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';

EDIT: This is added for the completeness sake. $_GET in php is a reserved variable that is an associative array. Hence, you could also make use of 'array_key_exists(mixed $key, array $array)'. It will return a boolean that the key is found or not. So, the following also will be okay.

$matchFound = (array_key_exists("id", $_GET)) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';

How to convert list to string

>>> L = [1,2,3]       
>>> " ".join(str(x) for x in L)
'1 2 3'

Multi-line strings in PHP

$xml="l\rn";
$xml.="vv";

echo $xml;

But you should really look into http://us3.php.net/simplexml

How to capitalize the first letter of a String in Java?

If Input is UpperCase ,then Use following :

str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();

If Input is LowerCase ,then Use following :

str.substring(0, 1).toUpperCase() + str.substring(1);

TypeScript and field initializers

To init a class without redeclaring all the properties for defaults:

class MyClass{ 
  prop1!: string  //required to be passed in
  prop2!: string  //required to be passed in
  prop3 = 'some default'
  prop4 = 123

  constructor(opts:{prop1:string, prop2:string} & Partial<MyClass>){
    Object.assign(this,opts)
  }
}

This combines some of the already excellent answers

how to fix java.lang.IndexOutOfBoundsException

This error happens because your list lstpp is empty (Nothing at index 0). So either there is a bug in your getResult() function, or the empty list is normal and you need to handle this case (By checking the size of the list before, or catching the exception).

How to get data from Magento System Configuration

$configValue = Mage::getStoreConfig('sectionName/groupName/fieldName');

sectionName, groupName and fieldName are present in etc/system.xml file of your module.

The above code will automatically fetch config value of currently viewed store.

If you want to fetch config value of any other store than the currently viewed store then you can specify store ID as the second parameter to the getStoreConfig function as below:

$store = Mage::app()->getStore(); // store info
$configValue = Mage::getStoreConfig('sectionName/groupName/fieldName', $store);

MySQL root access from all hosts

In my case the "bind-address" setting was the problem. Commenting this setting in my.cnf did not help, because in my case mysql set the default to 127.0.0.1 for some reason.

To verify what setting MySql is currently using, open the command line on your local box:

mysql -h localhost -u myname -pmypass mydb

Read out the current setting:

Show variables where variable_name like "bind%"

You should see 0.0.0.0 here if you want to allow access from all hosts. If this is not the case, edit your /etc/mysql/my.cnf and set bind-address under the [mysqld] section:

bind-address=0.0.0.0

Finally restart your MySql server to pick up the new setting:

sudo service mysql restart

Try again and check if the new setting has been picked up.

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Note: If you are using Bootstrap + AngularJS + UI Bootstrap, .left .right and .next classes are never added. Using the example at the following link and the CSS from Robert McKee answer works. I wanted to comment because it took 3 days to find a full solution. Hope this helps others!

https://angular-ui.github.io/bootstrap/#/carousel

Code snip from UI Bootstrap Demo at the above link.

angular.module('ui.bootstrap.demo').controller('CarouselDemoCtrl', function ($scope) {
  $scope.myInterval = 5000;
  var slides = $scope.slides = [];
  $scope.addSlide = function() {
    var newWidth = 600 + slides.length + 1;
    slides.push({
      image: 'http://placekitten.com/' + newWidth + '/300',
      text: ['More','Extra','Lots of','Surplus'][slides.length % 4] + ' ' +
        ['Cats', 'Kittys', 'Felines', 'Cutes'][slides.length % 4]
    });
  };
  for (var i=0; i<4; i++) {
    $scope.addSlide();
  }
});

Html From UI Bootstrap, Notice I added the .fade class to the example.

<div ng-controller="CarouselDemoCtrl">
    <div style="height: 305px">
        <carousel class="fade" interval="myInterval">
          <slide ng-repeat="slide in slides" active="slide.active">
            <img ng-src="{{slide.image}}" style="margin:auto;">
            <div class="carousel-caption">
              <h4>Slide {{$index}}</h4>
              <p>{{slide.text}}</p>
            </div>
          </slide>
        </carousel>
    </div>
</div>

CSS from Robert McKee's answer above

.carousel.fade {
opacity: 1;
}
.carousel.fade .item {
-moz-transition: opacity ease-in-out .7s;
-o-transition: opacity ease-in-out .7s;
-webkit-transition: opacity ease-in-out .7s;
transition: opacity ease-in-out .7s;
left: 0 !important;
opacity: 0;
top:0;
position:absolute;
width: 100%;
display:block !important;
z-index:1;
}
.carousel.fade .item:first-child {
top:auto;
position:relative;
}
.carousel.fade .item.active {
opacity: 1;
-moz-transition: opacity ease-in-out .7s;
-o-transition: opacity ease-in-out .7s;
-webkit-transition: opacity ease-in-out .7s;
transition: opacity ease-in-out .7s;
z-index:2;
}
/*
Added z-index to raise the left right controls to the top
*/
.carousel-control {
z-index:3;
}

Running code after Spring Boot starts

It is as simple as this:

@EventListener(ApplicationReadyEvent.class)
public void doSomethingAfterStartup() {
    System.out.println("hello world, I have just started up");
}

Tested on version 1.5.1.RELEASE

Show ImageView programmatically

int id = getResources().getIdentifier("gameover", "drawable", getPackageName());
ImageView imageView = new ImageView(this);
LinearLayout.LayoutParams vp = 
    new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
                    LayoutParams.WRAP_CONTENT);
imageView.setLayoutParams(vp);        
imageView.setImageResource(id);        
someLinearLayout.addView(imageView); 

Detect the Internet connection is offline?

IE 8 will support the window.navigator.onLine property.

But of course that doesn't help with other browsers or operating systems. I predict other browser vendors will decide to provide that property as well given the importance of knowing online/offline status in Ajax applications.

Until that happens, either XHR or an Image() or <img> request can provide something close to the functionality you want.

Update (2014/11/16)

Major browsers now support this property, but your results will vary.

Quote from Mozilla Documentation:

In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking.

In Firefox and Internet Explorer, switching the browser to offline mode sends a false value. All other conditions return a true value.

Rails raw SQL example

I want to work with exec_query of the ActiveRecord class, because it returns the mapping of the query transforming into object, so it gets very practical and productive to iterate with the objects when the subject is Raw SQL.

Example:

values = ActiveRecord::Base.connection.exec_query("select * from clients")
p values

and return this complete query:

[{"id": 1, "name": "user 1"}, {"id": 2, "name": "user 2"}, {"id": 3, "name": "user 3"}]

To get only list of values

p values.rows

[[1, "user 1"], [2, "user 2"], [3, "user 3"]]

To get only fields columns

p values.columns

["id", "name"]

MySQL select 10 random rows from 600K rows fast

I think here is a simple and yet faster way, I tested it on the live server in comparison with a few above answer and it was faster.

 SELECT * FROM `table_name` WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `table_name` ) ORDER BY id LIMIT 30; 

//Took 0.0014secs against a table of 130 rows

SELECT * FROM `table_name` WHERE 1 ORDER BY RAND() LIMIT 30

//Took 0.0042secs against a table of 130 rows

 SELECT name
FROM random AS r1 JOIN
   (SELECT CEIL(RAND() *
                 (SELECT MAX(id)
                    FROM random)) AS id)
    AS r2
WHERE r1.id >= r2.id
ORDER BY r1.id ASC
LIMIT 30

//Took 0.0040secs against a table of 130 rows

Disabling tab focus on form elements

Similar to Yipio, I added notab="notab" as an attribute to any element I wanted to disable the tab too. My jQuery is then one line.

$('input[notab=notab]').on('keydown', function(e){ if (e.keyCode == 9)  e.preventDefault() });

Btw, keypress doesn't work for many control keys.

Proxy with urllib2

In Addition to the accepted answer: My scipt gave me an error

File "c:\Python23\lib\urllib2.py", line 580, in proxy_open
    if '@' in host:
TypeError: iterable argument required

Solution was to add http:// in front of the proxy string:

proxy = urllib2.ProxyHandler({'http': 'http://proxy.xy.z:8080'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com')

Add an image in a WPF button

Please try the below XAML snippet:

<Button Width="300" Height="50">
  <StackPanel Orientation="Horizontal">
    <Image Source="Pictures/img.jpg" Width="20" Height="20"/>
    <TextBlock Text="Blablabla" VerticalAlignment="Center" />
  </StackPanel>
</Button>

In XAML elements are in a tree structure. So you have to add the child control to its parent control. The below code snippet also works fine. Give a name for your XAML root grid as 'MainGrid'.

Image img = new Image();
img.Source = new BitmapImage(new Uri(@"foo.png"));

StackPanel stackPnl = new StackPanel();
stackPnl.Orientation = Orientation.Horizontal;
stackPnl.Margin = new Thickness(10);
stackPnl.Children.Add(img);

Button btn = new Button();
btn.Content = stackPnl;
MainGrid.Children.Add(btn);

Python: Is there an equivalent of mid, right, and left from BASIC?

You can use this method also it will act like that

thadari=[1,2,3,4,5,6]

#Front Two(Left)
print(thadari[:2])
[1,2]

#Last Two(Right)# edited
print(thadari[-2:])
[5,6]

#mid
mid = len(thadari) //2

lefthalf = thadari[:mid]
[1,2,3]
righthalf = thadari[mid:]
[4,5,6]

Hope it will help

Endless loop in C/C++

The idiom designed into the C language (and inherited into C++) for infinite looping is for(;;): the omission of a test form. The do/while and while loops do not have this special feature; their test expressions are mandatory.

for(;;) does not express "loop while some condition is true that happens to always be true". It expresses "loop endlessly". No superfluous condition is present.

Therefore, the for(;;) construct is the canonical endless loop. This is a fact.

All that is left to opinion is whether or not to write the canonical endless loop, or to choose something baroque which involves extra identifiers and constants, to build a superfluous expression.

Even if the test expression of while were optional, which it isn't, while(); would be strange. while what? By contrast, the answer to the question for what? is: why, ever---for ever! As a joke some programmers of days past have defined blank macros, so they could write for(ev;e;r);.

while(true) is superior to while(1) because at least it doesn't involve the kludge that 1 represents truth. However, while(true) didn't enter into C until C99. for(;;) exists in every version of C going back to the language described in the 1978 book K&R1, and in every dialect of C++, and even related languages. If you're coding in a code base written in C90, you have to define your own true for while (true).

while(true) reads badly. While what is true? We don't really want to see the identifier true in code, except when we are initializing boolean variables or assigning to them. true need not ever appear in conditional tests. Good coding style avoids cruft like this:

if (condition == true) ...

in favor of:

if (condition) ...

For this reason while (0 == 0) is superior to while (true): it uses an actual condition that tests something, which turns into a sentence: "loop while zero is equal to zero." We need a predicate to go nicely with "while"; the word "true" isn't a predicate, but the relational operator == is.

Webfont Smoothing and Antialiasing in Firefox and Opera

Case: Light text with jaggy web font on dark background Firefox (v35)/Windows
Example: Google Web Font Ruda

Surprising solution -
adding following property to the applied selectors:

selector {
    text-shadow: 0 0 0;
}

Actually, result is the same just with text-shadow: 0 0;, but I like to explicitly set blur-radius.

It's not an universal solution, but might help in some cases. Moreover I haven't experienced (also not thoroughly tested) negative performance impacts of this solution so far.

How do I get the calling method name and type using reflection?

Technically, you can use StackTrace, but this is very slow and will not give you the answers you expect a lot of the time. This is because during release builds optimizations can occur that will remove certain method calls. Hence you can't be sure in release whether stacktrace is "correct" or not.

Really, there isn't any foolproof or fast way of doing this in C#. You should really be asking yourself why you need this and how you can architect your application, so you can do what you want without knowing which method called it.

Open links in new window using AngularJS

you can use:

$window.open(url, windowName, attributes);

Add views below toolbar in CoordinatorLayout

As of Android studio 3.4, You need to put this line in your Layout which holds the RecyclerView.

app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior"

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

It is simple just write java -XshowSettings:properties on your command line in windows and then paste all the files in the path shown by the java.library.path.

correct configuration for nginx to localhost?

Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.

 server {
            listen       80;
            server_name  localhost;

            access_log  logs/localhost.access.log  main;

            location / {
                root /var/www/board/public;
                index index.html index.htm index.php;
            }
       }

What is a Sticky Broadcast?

The value of a sticky broadcast is the value that was last broadcast and is currently held in the sticky cache. This is not the value of a broadcast that was received right now. I suppose you can say it is like a browser cookie that you can access at any time. The sticky broadcast is now deprecated, per the docs for sticky broadcast methods (e.g.):

This method was deprecated in API level 21. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.

How to convert InputStream to FileInputStream

Long story short: Don't use FileInputStream as a parameter or variable type. Use the abstract base class, in this case InputStream instead.

Pass array to MySQL stored routine

Simply use FIND_IN_SET like that:

mysql> SELECT FIND_IN_SET('b','a,b,c,d');
        -> 2

so you can do:

select * from Fruits where FIND_IN_SET(fruit, fruitArray) > 0

How to create byte array from HttpPostedFile

Use a BinaryReader object to return a byte array from the stream like:

byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
    fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}

ReferenceError: $ is not defined

Use Google CDN for fast loading:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

How to perform a for-each loop over all the files under a specified path?

Here is a better way to loop over files as it handles spaces and newlines in file names:

#!/bin/bash

find . -type f -iname "*.txt" -print0 | while IFS= read -r -d $'\0' line; do
    echo "$line"
    ls -l "$line"    
done

Is there any way to delete local commits in Mercurial?

hg strip is what you are looking for. It's analogous of git reset if you familiar with git.

Use console:

  1. You need to know the revision number. hg log -l 10. This command shows the last 10 commits. Find commit you are looking for. You need 4 digit number from changeset line changeset: 5888:ba6205914681

  2. Then hg strip -r 5888 --keep. This removes the record of the commit but keeps all files modified and then you could recommit them. (if you want to delete files to just remove --keep hg strip -r 5888

SELECTING with multiple WHERE conditions on same column

can't really see your table, but flag cannot be both 'Volunteer' and 'Uploaded'. If you have multiple values in a column, you can use

WHERE flag LIKE "%Volunteer%" AND flag LIKE "%UPLOADED%"

not really applicable seeing the formatted table.

How to pass all arguments passed to my bash script to a function of mine?

abc "$@" is generally the correct answer. But I was trying to pass a parameter through to an su command, and no amount of quoting could stop the error su: unrecognized option '--myoption'. What actually worked for me was passing all the arguments as a single string :

abc "$*"

My exact case (I'm sure someone else needs this) was in my .bashrc

# run all aws commands as Jenkins user
aws ()
{
    sudo su jenkins -c "aws $*"
}

Can I Set "android:layout_below" at Runtime Programmatically?

Alternatively you can use the views current layout parameters and modify them:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewToLayout.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.below_id);

How to enable Logger.debug() in Log4j

This is probably happening because your log4j configuration is set to ERROR. Look for a log4j.properties file with contents like the following:

log4j.rootLogger=ERROR, CONSOLE

# console logging
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=DEBUG
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d %-5p %-20.20t %-24c{1}: %m%n

The rootLogger is set to ERROR level here using a CONSOLE appender.

Note that some appenders like the console appender also have a Threshold property that can be used to overrule the rootLoggers level. You need to check both in this case.

How to reference a file for variables using Bash?

The script containing variables can be executed imported using bash. Consider the script-variable.sh

#!/bin/sh
scr-var=value

Consider the actual script where the variable will be used :

 #!/bin/sh
 bash path/to/script-variable.sh
 echo "$scr-var"

How can I close a Twitter Bootstrap popover with a click from anywhere (else) on the page?

An even easier solution, just iterate through all popovers and hide if not this.

$(document).on('click', '.popup-marker', function() {
    $(this).popover('toggle')
})

$(document).bind('click touchstart', function(e) {
    var target = $(e.target)[0];
    $('.popup-marker').each(function () {
        // hide any open popovers except for the one we've clicked
        if (!$(this).is(target)) {
            $(this).popover('hide');
        }
    });
});

Free Barcode API for .NET

I do recommend BarcodeLibrary

Here is a small piece of code of how to use it.

        BarcodeLib.Barcode barcode = new BarcodeLib.Barcode()
        {
            IncludeLabel = true,
            Alignment = AlignmentPositions.CENTER,
            Width = 300,
            Height = 100,
            RotateFlipType = RotateFlipType.RotateNoneFlipNone,
            BackColor = Color.White,
            ForeColor = Color.Black,
        };

        Image img = barcode.Encode(TYPE.CODE128B, "123456789");

How do I get the App version and build number using Swift?

if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
        lblVersion.text = "Version \(version)"

    }

foreach loop in angularjs

In Angular 7 the for loop is like below

var values = [
        {
            "name":"Thomas",
            "password":"thomas"
        },
        { 
            "name":"linda",
            "password":"linda"
        }];

for (let item of values)
{
}

How do I use IValidatableObject?

First off, thanks to @paper1337 for pointing me to the right resources...I'm not registered so I can't vote him up, please do so if anybody else reads this.

Here's how to accomplish what I was trying to do.

Validatable class:

public class ValidateMe : IValidatableObject
{
    [Required]
    public bool Enable { get; set; }

    [Range(1, 5)]
    public int Prop1 { get; set; }

    [Range(1, 5)]
    public int Prop2 { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var results = new List<ValidationResult>();
        if (this.Enable)
        {
            Validator.TryValidateProperty(this.Prop1,
                new ValidationContext(this, null, null) { MemberName = "Prop1" },
                results);
            Validator.TryValidateProperty(this.Prop2,
                new ValidationContext(this, null, null) { MemberName = "Prop2" },
                results);

            // some other random test
            if (this.Prop1 > this.Prop2)
            {
                results.Add(new ValidationResult("Prop1 must be larger than Prop2"));
            }
        }
        return results;
    }
}

Using Validator.TryValidateProperty() will add to the results collection if there are failed validations. If there is not a failed validation then nothing will be add to the result collection which is an indication of success.

Doing the validation:

    public void DoValidation()
    {
        var toValidate = new ValidateMe()
        {
            Enable = true,
            Prop1 = 1,
            Prop2 = 2
        };

        bool validateAllProperties = false;

        var results = new List<ValidationResult>();

        bool isValid = Validator.TryValidateObject(
            toValidate,
            new ValidationContext(toValidate, null, null),
            results,
            validateAllProperties);
    }

It is important to set validateAllProperties to false for this method to work. When validateAllProperties is false only properties with a [Required] attribute are checked. This allows the IValidatableObject.Validate() method handle the conditional validations.

Replacing Numpy elements if condition is met

The quickest (and most flexible) way is to use np.where, which chooses between two arrays according to a mask(array of true and false values):

import numpy as np
a = np.random.randint(0, 5, size=(5, 4))
b = np.where(a<3,0,1)
print('a:',a)
print()
print('b:',b)

which will produce:

a: [[1 4 0 1]
 [1 3 2 4]
 [1 0 2 1]
 [3 1 0 0]
 [1 4 0 1]]

b: [[0 1 0 0]
 [0 1 0 1]
 [0 0 0 0]
 [1 0 0 0]
 [0 1 0 0]]

Why ModelState.IsValid always return false in mvc

As Brad Wilson states in his answer here:

ModelState.IsValid tells you if any model errors have been added to ModelState.

The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.

Try using :-

if (!ModelState.IsValid)
{
    var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));

    // Breakpoint, Log or examine the list with Exceptions.
}

If it helps catching you the error. Courtesy this and this

Remove Project from Android Studio

Easiest way to do this is close the project. Using file explorer head to the location of that project and delete.

Alot of processes, even simply deleting can be annoying to figure out in studio. Most deleting options a good work around is to delete using file explorer. This is a part of the process tht works for deleting modules as well. Which u will prob find is painful as well

ASP.Net which user account running Web Service on IIS 7?

I had a ton of trouble with this and then found a great solution:

Create a file in a text editor called whoami.php with the below code as it's content, save the file and upload it to public_html (or whatever you root of your webserver directory is named). It should output a useful string that you can use to track down the user the webserver is running as, my output was "php is running as user: nt authority\iusr" which allowed me to track down the permissions I needed to modify to the user "IUSR".

<?php
  // outputs the username that owns the running php/httpd process
  // (on a system with the "whoami" executable in the path)
  echo 'php is running as user: ' . exec('whoami');
?>

sqldeveloper error message: Network adapter could not establish the connection error

I just created a local connection by breaking my head for hours. So thought of helping you guys.

  • Step 1: Check your file name listener.ora located at

    C:\app\\product\12.1.0\dbhome_3\NETWORK\ADMIN

    Check your HOSTNAME, PORT AND SERVICE and give the same while creating new database connection.

  • Step 2: if this doesnt work, try these combinations give PORT:1521 and SID: orcl give PORT: and SID: orcl give PORT:1521 and SID: pdborcl give PORT:1521 and

    SID: admin

If you get the error as "wrong username and password" :
Make sure you are giving correct username and password

if still it doesnt work try this: Username :system Password: .

Hope it helps!!!!

How can I determine browser window size on server side C#

Here's an Ajax, asxh handler and session variables approach:

Handler:

using System;
using System.Web;

public class windowSize : IHttpHandler , System.Web.SessionState.IRequiresSessionState  {

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "application/json";

        var json = new System.Web.Script.Serialization.JavaScriptSerializer();
        var output = json.Serialize(new { isFirst = context.Session["BrowserWidth"] == null });
        context.Response.Write(output);

        context.Session["BrowserWidth"] =  context.Request.QueryString["Width"]; 
        context.Session["BrowserHeight"] = context.Request.QueryString["Height"];
    }

    public bool IsReusable
    {
        get { throw new NotImplementedException(); }
    }
}

Javascript:

window.onresize = function (event) {
    SetWidthHeight();
}
function SetWidthHeight() {
    var height = $(window).height();
    var width = $(window).width();
    $.ajax({
        url: "windowSize.ashx",
        data: {
            'Height': height,
            'Width': width
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (data) {     
        if (data.isFirst) {
            window.location.reload();
        };
    }).fail(function (xhr) {
        alert("Problem to retrieve browser size.");
    });

}
$(function () {
    SetWidthHeight();
});

On aspx file:

...
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/BrowserWindowSize.js"></script>
...
<asp:Label ID="lblDim" runat="server" Text=""></asp:Label>
...

Code behind:

protected void Page_Load(object sender, EventArgs e)
  {
      if (Session["BrowserWidth"] != null)
      {
          // Do all code here to avoid double execution first time
          // ....
          lblDim.Text = "Width: " + Session["BrowserWidth"] + " Height: " + Session["BrowserHeight"];
      }
  }

Source: https://techbrij.com/browser-height-width-server-responsive-design-asp-net

How to determine if a String has non-alphanumeric characters?

You can use isLetter(char c) static method of Character class in Java.lang .

public boolean isAlpha(String s) {
    char[] charArr = s.toCharArray();

    for(char c : charArr) {
        if(!Character.isLetter(c)) {
            return false;
        }
    }
    return true;
}

What are the differences between normal and slim package of jquery?

The short answer taken from the announcement of jQuery 3.0 Final Release :

Along with the regular version of jQuery that includes the ajax and effects modules, we’re releasing a “slim” version that excludes these modules. All in all, it excludes ajax, effects, and currently deprecated code.

The file size (gzipped) is about 6k smaller, 23.6k vs 30k.

Windows batch: call more than one command in a FOR loop?

Using & is fine for short commands, but that single line can get very long very quick. When that happens, switch to multi-line syntax.

FOR /r %%X IN (*.txt) DO (
    ECHO %%X
    DEL %%X
)

Placement of ( and ) matters. The round brackets after DO must be placed on the same line, otherwise the batch file will be incorrect.

See if /?|find /V "" for details.

How to get ID of clicked element with jQuery

Your IDs are #1, and cycle just wants a number passed to it. You need to remove the # before calling cycle.

$('a.pagerlink').click(function() { 
    var id = $(this).attr('id');
    $container.cycle(id.replace('#', '')); 
    return false; 
});

Also, IDs shouldn't contain the # character, it's invalid (numeric IDs are also invalid). I suggest changing the ID to something like pager_1.

<a href="#" id="pager_1" class="pagerlink" >link</a>

$('a.pagerlink').click(function() { 
    var id = $(this).attr('id');
    $container.cycle(id.replace('pager_', '')); 
    return false; 
});

Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

Adapted from Timmmm to PYQT5

from PyQt5.QtGui import QPixmap
from PyQt5.QtGui import QResizeEvent
from PyQt5.QtWidgets import QLabel


class Label(QLabel):

    def __init__(self):
        super(Label, self).__init__()
        self.pixmap_width: int = 1
        self.pixmapHeight: int = 1

    def setPixmap(self, pm: QPixmap) -> None:
        self.pixmap_width = pm.width()
        self.pixmapHeight = pm.height()

        self.updateMargins()
        super(Label, self).setPixmap(pm)

    def resizeEvent(self, a0: QResizeEvent) -> None:
        self.updateMargins()
        super(Label, self).resizeEvent(a0)

    def updateMargins(self):
        if self.pixmap() is None:
            return
        pixmapWidth = self.pixmap().width()
        pixmapHeight = self.pixmap().height()
        if pixmapWidth <= 0 or pixmapHeight <= 0:
            return
        w, h = self.width(), self.height()
        if w <= 0 or h <= 0:
            return

        if w * pixmapHeight > h * pixmapWidth:
            m = int((w - (pixmapWidth * h / pixmapHeight)) / 2)
            self.setContentsMargins(m, 0, m, 0)
        else:
            m = int((h - (pixmapHeight * w / pixmapWidth)) / 2)
            self.setContentsMargins(0, m, 0, m)

AngularJS : Custom filters and ng-repeat

If you want to run some custom filter logic you can create a function which takes the array element as an argument and returns true or false based on whether it should be in the search results. Then pass it to the filter instruction just like you do with the search object, for example:

JS:

$scope.filterFn = function(car)
{
    // Do some tests

    if(car.carDetails.doors > 2)
    {
        return true; // this will be listed in the results
    }

    return false; // otherwise it won't be within the results
};

HTML:

...
<article data-ng-repeat="result in results | filter:search | filter:filterFn" class="result">
...

As you can see you can chain many filters together, so adding your custom filter function doesn't force you to remove the previous filter using the search object (they will work together seamlessly).

JTable won't show column headers

The main difference between this answer and the accepted answer is the use of setViewportView() instead of add().

How to put JTable in JScrollPane using Eclipse IDE:

  1. Create JScrollPane container via Design tab.
  2. Stretch JScrollPane to desired size (applies to Absolute Layout).
  3. Drag and drop JTable component on top of JScrollPane (Viewport area).

In Structure > Components, table should be a child of scrollPane. enter image description here

The generated code would be something like this:

JScrollPane scrollPane = new JScrollPane();
...

JTable table = new JTable();
scrollPane.setViewportView(table);

SQL Column definition : default value and not null redundant?

I would say not.

If the column does accept null values, then there's nothing to stop you inserting a null value into the field. As far as I'm aware, the default value only applies on creation of a new row.

With not null set, then you can't insert a null value into the field as it'll throw an error.

Think of it as a fail safe mechanism to prevent nulls.

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

You have to add one jar : jackson-annotations-2.1.2.jar You can download it from here and add it to the class path If you are using the gradle then add the following dependency.

compile 'com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:2.5.2'

How to solve could not create the virtual machine error of Java Virtual Machine Launcher?

I had the same issue today when running the ancient software Dundjinni, a mapping tool, on Windows 10. (Dundjinni requires a rather old installation of Java; I haven’t tried updating Java, for fear the programme will fail.) My method was to simply run Dundjinni in administrator mode. Here is how:

Click Start or press the Start key, navigate down to the software, rightclick the programme, choose More, then choose Run as administrator. Note that this option is not available if you simply type the name of the software.

enter image description here

JavaScript Editor Plugin for Eclipse

In 2015 I would go with:

  • For small scripts: The js editor + jsHint plugin
  • For large code bases: TypeScript Eclipse plugin, or a similar transpiled language... I only know that TypeScript works well in Eclipse.

Of course you may want to keep JS for easy project setup and to avoid the transpilation process... there is no ultimate solution.

Or just wait for ECMA6, 7, ... :)

How to close IPython Notebook properly?

First step is to save all open notebooks. And then think about shutting down your running Jupyter Notebook. You can use this simple command:

$ jupyter notebook stop 
Shutting down server on port 8888 ...

Which also takes the port number as argument and you can shut down the jupyter notebook gracefully.

For eg:

jupyter notebook stop 8889 
Shutting down server on port 8889 ...

Additionally to know your current jupyter instance running, check below command:

shell> jupyter notebook list 
Currently running servers:
http://localhost:8888/?token=ef12021898c435f865ec706de98632 :: /Users/username/jupyter-notebooks [/code]

Oracle JDBC ojdbc6 Jar as a Maven Dependency

I followed below command it worked:

mvn install:install-file -Dfile=E:\JAVA\Spring\ojdbc14-10.2.0.4.0.jar\ojdbc14-10.2.0.4.0.jar -DgroupId=com.oracle -DartifactId=ojdbc14 -Dversion=10.2.0.4.0 -Dpackaging=jar

After installation check that jar is installed correctly on your M2_repo.

What is the equivalent of Java's final in C#?

What everyone here is missing is Java's guarantee of definite assignment for final member variables.

For a class C with final member variable V, every possible execution path through every constructor of C must assign V exactly once - failing to assign V or assigning V two or more times will result in an error.

C#'s readonly keyword has no such guarantee - the compiler is more than happy to leave readonly members unassigned or allow you to assign them multiple times within a constructor.

So, final and readonly (at least with respect to member variables) are definitely not equivalent - final is much more strict.

How to execute cmd commands via Java

The code you posted starts three different processes each with it's own command. To open a command prompt and then run a command try the following (never tried it myself):

try {
    // Execute command
    String command = "cmd /c start cmd.exe";
    Process child = Runtime.getRuntime().exec(command);

    // Get output stream to write from it
    OutputStream out = child.getOutputStream();

    out.write("cd C:/ /r/n".getBytes());
    out.flush();
    out.write("dir /r/n".getBytes());
    out.close();
} catch (IOException e) {
}

Python print statement “Syntax Error: invalid syntax”

Use print("use this bracket -sample text")

In Python 3 print "Hello world" gives invalid syntax error.

To display string content in Python3 have to use this ("Hello world") brackets.

Javascript parse float is ignoring the decimals after my comma

In my case, I already had a period(.) and also a comma(,), so what worked for me was to replace the comma(,) with an empty string like below:

parseFloat('3,000.78'.replace(',', '')) 

This is assuming that the amount from the existing database is 3,000.78. The results are: 3000.78 without the initial comma(,).

Check if Nullable Guid is empty in c#

You should use the HasValue property:

SomeProperty.HasValue

For example:

if (SomeProperty.HasValue)
{
    // Do Something
}
else
{
    // Do Something Else
}

FYI

public Nullable<System.Guid> SomeProperty { get; set; }

is equivalent to:

public System.Guid? SomeProperty { get; set; }

The MSDN Reference: http://msdn.microsoft.com/en-us/library/sksw8094.aspx

How to copy Docker images from one host to another without using a repository

I assume you need to save couchdb-cartridge which has an image id of 7ebc8510bc2c:

stratos@Dev-PC:~$ docker images
REPOSITORY                             TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
couchdb-cartridge                      latest              7ebc8510bc2c        17 hours ago        1.102 GB
192.168.57.30:5042/couchdb-cartridge   latest              7ebc8510bc2c        17 hours ago        1.102 GB
ubuntu                                 14.04               53bf7a53e890        3 days ago          221.3 MB

Save the archiveName image to a tar file. I will use the /media/sf_docker_vm/ to save the image.

stratos@Dev-PC:~$ docker save imageID > /media/sf_docker_vm/archiveName.tar

Copy the archiveName.tar file to your new Docker instance using whatever method works in your environment, for example FTP, SCP, etc.

Run the docker load command on your new Docker instance and specify the location of the image tar file.

stratos@Dev-PC:~$ docker load < /media/sf_docker_vm/archiveName.tar

Finally, run the docker images command to check that the image is now available.

stratos@Dev-PC:~$ docker images
REPOSITORY                             TAG        IMAGE ID         CREATED             VIRTUAL SIZE
couchdb-cartridge                      latest     7ebc8510bc2c     17 hours ago        1.102 GB
192.168.57.30:5042/couchdb-cartridge   latest     bc8510bc2c       17 hours ago        1.102 GB
ubuntu                                 14.04      4d2eab1c0b9a     3 days ago          221.3 MB

Please find this detailed post.

How do I get the full path to a Perl script that is executing?

You could use FindBin, Cwd, File::Basename, or a combination of them. They're all in the base distribution of Perl IIRC.

I used Cwd in the past:

Cwd:

use Cwd qw(abs_path);
my $path = abs_path($0);
print "$path\n";

Gradle Build Android Project "Could not resolve all dependencies" error

If you are running on headless CI and are installing the Android SDK through command line, make sure to include the m2repository packages in the --filter argument:

android update sdk --no-ui --filter platform-tools,build-tools-19.0.1,android-19,extra-android-support,extra-android-m2repository,extra-google-m2repository

Update

As of Android SDK Manager rev. 22.6.4 this does not work anymore. Try this instead:

android list sdk --all

You will get a list of all available SDK packages. Look up the numerical values of the components from the first command above ("Google Repository" and others you might be missing).

Install the packages using their numerical values:

android update sdk --no-ui --all --filter <num>

Update #2 (Sept 2017)

With the "new" Android SDK tools that were released earlier this year, the android command is now deprecated, and similar functionality has been moved to a new tool called sdkmanager:

List installed components:

sdkmanager --list

Update installed components:

sdkmanager --update

Install a new component (e.g. build tools version 26.0.0):

sdkmanager 'build-tools;26.0.0'

Using setImageDrawable dynamically to set image in an ImageView

You can also use something like:

imageView.setImageDrawable(ActivityCompat.getDrawable(getContext(), R.drawable.generatedID));

or using Picasso:

Picasso.with(getContext()).load(R.drawable.generatedId).into(imageView);

Can we open pdf file using UIWebView on iOS?

use this for open pdf file in webview

NSString *path = [[NSBundle mainBundle] pathForResource:@"mypdf" ofType:@"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
UIWebView *webView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
[[webView scrollView] setContentOffset:CGPointMake(0,500) animated:YES];
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.scrollTo(0.0, 50.0)"]];
[webView loadRequest:request];
[self.view addSubview:webView];
[webView release];

An array of List in c#

simple approach:

        List<int>[] a = new List<int>[100];
        for (int i = 0; i < a.Length; i++)
        {
            a[i] = new List<int>();
        }

or LINQ approach

        var b = Enumerable.Range(0,100).Select((i)=>new List<int>()).ToArray();

TERM environment variable not set

Using a terminal command i.e. "clear", in a script called from cron (no terminal) will trigger this error message. In your particular script, the smbmount command expects a terminal in which case the work-arounds above are appropriate.

iPhone X / 8 / 8 Plus CSS media queries

It seems that the most accurate (and seamless) method of adding the padding for iPhone X/8 using env()...

padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);

Here's a link describing this:

https://css-tricks.com/the-notch-and-css/

Git resolve conflict using --ours/--theirs for all files

git diff --name-only --diff-filter=U | xargs git checkout --theirs

Seems to do the job. Note that you have to be cd'ed to the root directory of the git repo to achieve this.

Best JavaScript compressor

In searching silver bullet, found this question. For Ruby on Rails http://github.com/sstephenson/sprockets

Getting index value on razor foreach

 @{int i = 0;}
 @foreach(var myItem in Model.Members)
 {
     <span>@i</span>
     @{i++;
      }
 }

// Use @{i++ to increment value}

What is the Ruby <=> (spaceship) operator?

Perl was likely the first language to use it. Groovy is another language that supports it. Basically instead of returning 1 (true) or 0 (false) depending on whether the arguments are equal or unequal, the spaceship operator will return 1, 0, or -1 depending on the value of the left argument relative to the right argument.

a <=> b :=
  if a < b then return -1
  if a = b then return  0
  if a > b then return  1
  if a and b are not comparable then return nil

It's useful for sorting an array.

Throw away local commits in Git

Use any number of times, to revert back to the last commit without deleting any files that you have recently created.

git reset --soft HEAD~1

Then use

git reset HEAD <name-of-file/files*>

to unstage, or untrack.

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

I resolved by replacing the corrupted jar files.

But to find those corrupted jar files, I have to run my application in three IDE- 1) Intellij Idea 2)NetBeans 3) Eclipse.

Netbeans given me information for maximum number of corrupted jar. In Netbeans along with the run, I use the build option(after right clicking on project) to know more about corrupted jars.

It took me more than 15 hours to find out the root cause for these errors. Hope it help anyone.

Set database from SINGLE USER mode to MULTI USER

You couldn't do that becouse database in single mode. Above all right but you should know that: when you opened the sql management studio it doesn't know any user on the database but when you click the database it consider you the single user and your command not working. Just do that: Close management studio and re open it. new query window without selecting any database write the command script.

USE [master];
GO
ALTER DATABASE [tuncayoto] SET MULTI_USER WITH NO_WAIT;
GO 

make f5 wolla everything ok !

How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

Use Paulo Freitas suggestion instead.


Until Laravel fixes this, you can run a standard database query after the Schema::create have been run.

    Schema::create("users", function($table){
        $table->increments('id');
        $table->string('email', 255);
        $table->string('given_name', 100);
        $table->string('family_name', 100);
        $table->timestamp('joined');
        $table->enum('gender', ['male', 'female', 'unisex'])->default('unisex');
        $table->string('timezone', 30)->default('UTC');
        $table->text('about');
    });
    DB::statement("ALTER TABLE ".DB::getTablePrefix()."users CHANGE joined joined TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL");

It worked wonders for me.

How to return first 5 objects of Array in Swift?

For getting the first 5 elements of an array, all you need to do is slice the array in question. In Swift, you do it like this: array[0..<5].

To make picking the N first elements of an array a bit more functional and generalizable, you could create an extension method for doing it. For instance:

extension Array {
    func takeElements(var elementCount: Int) -> Array {
        if (elementCount > count) {
            elementCount = count
        }
        return Array(self[0..<elementCount])
    }
}

Pandas sort by group aggregate and column

One way to do this is to insert a dummy column with the sums in order to sort:

In [10]: sum_B_over_A = df.groupby('A').sum().B

In [11]: sum_B_over_A
Out[11]: 
A
bar    0.253652
baz   -2.829711
foo    0.551376
Name: B

in [12]: df['sum_B_over_A'] = df.A.apply(sum_B_over_A.get_value)

In [13]: df
Out[13]: 
     A         B      C  sum_B_over_A
0  foo  1.624345  False      0.551376
1  bar -0.611756   True      0.253652
2  baz -0.528172  False     -2.829711
3  foo -1.072969   True      0.551376
4  bar  0.865408  False      0.253652
5  baz -2.301539   True     -2.829711

In [14]: df.sort(['sum_B_over_A', 'A', 'B'])
Out[14]: 
     A         B      C   sum_B_over_A
5  baz -2.301539   True      -2.829711
2  baz -0.528172  False      -2.829711
1  bar -0.611756   True       0.253652
4  bar  0.865408  False       0.253652
3  foo -1.072969   True       0.551376
0  foo  1.624345  False       0.551376

and maybe you would drop the dummy row:

In [15]: df.sort(['sum_B_over_A', 'A', 'B']).drop('sum_B_over_A', axis=1)
Out[15]: 
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

Selenium WebDriver and DropDown Boxes

You could try this:

IWebElement dropDownListBox = driver.findElement(By.Id("selection"));
SelectElement clickThis = new SelectElement(dropDownListBox);
clickThis.SelectByText("Germany");

How can I add or update a query string parameter?

Java script code to find a specific query string and replace its value *

('input.letter').click(function () {
                //0- prepare values
                var qsTargeted = 'letter=' + this.value; //"letter=A";
                var windowUrl = '';
                var qskey = qsTargeted.split('=')[0];
                var qsvalue = qsTargeted.split('=')[1];
                //1- get row url
                var originalURL = window.location.href;
                //2- get query string part, and url
                if (originalURL.split('?').length > 1) //qs is exists
                {
                    windowUrl = originalURL.split('?')[0];
                    var qs = originalURL.split('?')[1];
                    //3- get list of query strings
                    var qsArray = qs.split('&');
                    var flag = false;
                    //4- try to find query string key
                    for (var i = 0; i < qsArray.length; i++) {
                        if (qsArray[i].split('=').length > 0) {
                            if (qskey == qsArray[i].split('=')[0]) {
                                //exists key
                                qsArray[i] = qskey + '=' + qsvalue;
                                flag = true;
                                break;
                            }
                        }
                    }
                    if (!flag)//   //5- if exists modify,else add
                    {
                        qsArray.push(qsTargeted);
                    }
                    var finalQs = qsArray.join('&');
                    //6- prepare final url
                    window.location = windowUrl + '?' + finalQs;
                }
                else {
                    //6- prepare final url
                    //add query string
                    window.location = originalURL + '?' + qsTargeted;
                }
            })
        });

How to Lock Android App's Orientation to Portrait in Phones and Landscape in Tablets?

Set the Screen orientation to portrait in Manifest file under the activity Tag.

Browser Caching of CSS files

Your file will probably be cached - but it depends...

Different browsers have slightly different behaviors - most noticeably when dealing with ambiguous/limited caching headers emanating from the server. If you send a clear signal, the browsers obey, virtually all of the time.

The greatest variance by far, is in the default caching configuration of different web servers and application servers.

Some (e.g. Apache) are likely to serve known static file types with HTTP headers encouraging the browser to cache them, while other servers may send no-cache commands with every response - regardless of filetype.

...

So, first off, read some of the excellent HTTP caching tutorials out there. HTTP Caching & Cache-Busting for Content Publishers was a real eye opener for me :-)

Next install and fiddle around with Firebug and the Live HTTP Headers add-on , to find out which headers your server is actually sending.

Then read your web server docs to find out how to tweak them to perfection (or talk your sysadmin into doing it for you).

...

As to what happens when the browser is restarted, it depends on the browser and the user configuration.

As a rule of thumb, expect the browser to be more likely to check in with the server after each restart, to see if anything has changed (see If-Last-Modified and If-None-Match).

If you configure your server correctly, it should be able to return a super-short 304 Not Modified (costing very little bandwidth) and after that the browser will use the cache as normal.

IPC performance: Named Pipe vs Socket

I would suggest you take the easy path first, carefully isolating the IPC mechanism so that you can change from socket to pipe, but I would definitely go with socket first. You should be sure IPC performance is a problem before preemptively optimizing.

And if you get in trouble because of IPC speed, I think you should consider switching to shared memory rather than going to pipe.

If you want to do some transfer speed testing, you should try socat, which is a very versatile program that allows you to create almost any kind of tunnel.

calling java methods in javascript code

When it is on server side, use web services - maybe RESTful with JSON.

  • create a web service (for example with Tomcat)
  • call its URL from JavaScript (for example with JQuery or dojo)

When Java code is in applet you can use JavaScript bridge. The bridge between the Java and JavaScript programming languages, known informally as LiveConnect, is implemented in Java plugin. Formerly Mozilla-specific LiveConnect functionality, such as the ability to call static Java methods, instantiate new Java objects and reference third-party packages from JavaScript, is now available in all browsers.

Below is example from documentation. Look at methodReturningString.

Java code:

public class MethodInvocation extends Applet {
    public void noArgMethod() { ... }
    public void someMethod(String arg) { ... }
    public void someMethod(int arg) { ... }
    public int  methodReturningInt() { return 5; }
    public String methodReturningString() { return "Hello"; }
    public OtherClass methodReturningObject() { return new OtherClass(); }
}

public class OtherClass {
    public void anotherMethod();
}

Web page and JavaScript code:

<applet id="app"
        archive="examples.jar"
        code="MethodInvocation" ...>
</applet>
<script language="javascript">
    app.noArgMethod();
    app.someMethod("Hello");
    app.someMethod(5);
    var five = app.methodReturningInt();
    var hello = app.methodReturningString();
    app.methodReturningObject().anotherMethod();
</script>

Updating .class file in jar

An alternative is not to replace the .class file in the jar file. Instead put it into a new jar file and ensure that it appears earlier on your classpath than the original jar file.

Not sure I would recommend this for production software but for development it is quick and easy.

no matching function for call to ' '

You are passing pointers (Complex*) when your function takes references (const Complex&). A reference and a pointer are entirely different things. When a function expects a reference argument, you need to pass it the object directly. The reference only means that the object is not copied.

To get an object to pass to your function, you would need to dereference your pointers:

Complex::distanta(*firstComplexNumber, *secondComplexNumber);

Or get your function to take pointer arguments.

However, I wouldn't really suggest either of the above solutions. Since you don't need dynamic allocation here (and you are leaking memory because you don't delete what you have newed), you're better off not using pointers in the first place:

Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);
Complex::distanta(firstComplexNumber, secondComplexNumber);

Maven with Eclipse Juno

You should be able to install m2e (maven project for eclipse) using the Help -> Install New Software dialog. On that dialog open the Juno site (http://download.eclipse.org/releases/juno) and expand the Collaboration group (or type m2e into the filter). Select the two m2e options and follow the installation dialog

Using % for host when creating a MySQL user

As @nos pointed out in the comments of the currently accepted answer to this question, the accepted answer is incorrect.

Yes, there IS a difference between using % and localhost for the user account host when connecting via a socket connect instead of a standard TCP/IP connect.

A host value of % does not include localhost for sockets and thus must be specified if you want to connect using that method.

Compare two data.frames to find the rows in data.frame 1 that are not present in data.frame 2

sqldf provides a nice solution

a1 <- data.frame(a = 1:5, b=letters[1:5])
a2 <- data.frame(a = 1:3, b=letters[1:3])

require(sqldf)

a1NotIna2 <- sqldf('SELECT * FROM a1 EXCEPT SELECT * FROM a2')

And the rows which are in both data frames:

a1Ina2 <- sqldf('SELECT * FROM a1 INTERSECT SELECT * FROM a2')

The new version of dplyr has a function, anti_join, for exactly these kinds of comparisons

require(dplyr) 
anti_join(a1,a2)

And semi_join to filter rows in a1 that are also in a2

semi_join(a1,a2)

How to print full stack trace in exception?

I usually use the .ToString() method on exceptions to present the full exception information (including the inner stack trace) in text:

catch (MyCustomException ex)
{
    Debug.WriteLine(ex.ToString());
}

Sample output:

ConsoleApplication1.MyCustomException: some message .... ---> System.Exception: Oh noes!
   at ConsoleApplication1.SomeObject.OtherMethod() in C:\ConsoleApplication1\SomeObject.cs:line 24
   at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 14
   --- End of inner exception stack trace ---
   at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 18
   at ConsoleApplication1.Program.DoSomething() in C:\ConsoleApplication1\Program.cs:line 23
   at ConsoleApplication1.Program.Main(String[] args) in C:\ConsoleApplication1\Program.cs:line 13

How to initialize a struct in accordance with C programming language standards

You can do it with a compound literal. According to that page, it works in C99 (which also counts as ANSI C).

MY_TYPE a;

a = (MY_TYPE) { .flag = true, .value = 123, .stuff = 0.456 };
...
a = (MY_TYPE) { .value = 234, .stuff = 1.234, .flag = false };

The designations in the initializers are optional; you could also write:

a = (MY_TYPE) { true,  123, 0.456 };
...
a = (MY_TYPE) { false, 234, 1.234 };

Django 1.7 - "No migrations to apply" when run migrate after makemigrations

This is a very confusing topic. django stores all applied migrations in a table called django_migrations. perform this sql ( i am using postgres . so in query tool section)

select * from django_migrations where app='your appname'  (app in which u have issue with).

This will list all applied migrations for that app.
Go to your app/migration folder and check all migrations . find the migration file associated with your error . file where your table was created or column added or modified.
look for the id of this migration file in django_migrations table( select * from django_migrations where app='your app') .

Then do :

delete from django_migrations where id='id of your migration';

delete multiple id's if you have multiple migrations file associated with your issue.

now reapply migrate

Python manage.py migrate yourappname

second option

  1. Drop tables in your app where you have issue.

  2. delete all migrations for that app from app/migrations folder.(don't delete init.py from that folder).

  3. now run

    python manage.py makemigrations appname

  4. now run

python manage.py migrate appname

Add tooltip to font awesome icon

Simply with native html & css :

<div class="tooltip">Hover over me
  <span class="tooltiptext">Tooltip text</span>
</div>

/* Tooltip container */
.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black; /* If you want dots under the hoverable text */
}

/* Tooltip text */
.tooltip .tooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: #555;
  color: #fff;
  text-align: center;
  padding: 5px 0;
  border-radius: 6px;

  /* Position the tooltip text */
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  margin-left: -60px;

  /* Fade in tooltip */
  opacity: 0;
  transition: opacity 0.3s;
}

/* Tooltip arrow */
.tooltip .tooltiptext::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}

/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
  visibility: visible;
  opacity: 1;
}

Here is the source of the example from w3schools

Mergesort with Python

def merge(arr, p, q, r):
    left = arr[p:q + 1]
    right = arr[q + 1:r + 1]
    left.append(float('inf'))
    right.append(float('inf'))
    i = j = 0
    for k in range(p, r + 1):
        if left[i] <= right[j]:
            arr[k] = left[i]
            i += 1
        else:
            arr[k] = right[j]
            j += 1


def init_func(function):
    def wrapper(*args):
        a = []
        if len(args) == 1:
            a = args[0] + []
            function(a, 0, len(a) - 1)
        else:
            function(*args)
        return a

    return wrapper


@init_func
def merge_sort(arr, p, r):
    if p < r:
        q = (p + r) // 2
        merge_sort(arr, p, q)
        merge_sort(arr, q + 1, r)
        merge(arr, p, q, r)
if __name__ == "__main__":
    test = [5, 4, 3, 2, 1]
    print(merge_sort(test))

Result would be

[1, 2, 3, 4, 5]

How to convert array into comma separated string in javascript

Use the join method from the Array type.

a.value = [a, b, c, d, e, f];
var stringValueYouWant = a.join();

The join method will return a string that is the concatenation of all the array elements. It will use the first parameter you pass as a separator - if you don't use one, it will use the default separator, which is the comma.

How do I format date and time on ssrs report?

I am using this

=Format(Now(), "dd/MM/yyyy hh:mm tt")

convert from Color to brush

you can use this:

new SolidBrush(color)

where color is something like this:

Color.Red

or

Color.FromArgb(36,97,121))

or ...

How to determine the IP address of a Solaris system

The following shell script gives a nice tabular result of interfaces and IP addresses (excluding the loopback interface) It has been tested on a Solaris box

/usr/sbin/ifconfig -a | awk '/flags/ {printf $1" "} /inet/ {print $2}' | grep -v lo

ce0: 10.106.106.108
ce0:1: 10.106.106.23
ce0:2: 10.106.106.96
ce1: 10.106.106.109

SQL to Query text in access with an apostrophe in it

How about more simply: Select * from tblStudents where [name] = replace(YourName,"'","''")

What is a constant reference? (not a reference to a constant)

The statement icr=y; does not make the reference refer to y; it assigns the value of y to the variable that icr refers to, i.

References are inherently const, that is you can't change what they refer to. There are 'const references' which are really 'references to const', that is you can't change the value of the object they refer to. They are declared const int& or int const& rather than int& const though.

#include errors detected in vscode

The error message "Please update your includePath" does not necessarily mean there is actually a problem with the includePath. The problem may be that VSCode is using the wrong compiler or wrong IntelliSense mode. I have written instructions in this answer on how to troubleshoot and align your VSCode C++ configuration with your compiler and project.

How to change font in ipython notebook

You can hover to .ipython folder (i.e. you can type $ ipython locate in your terminal/bash OR CMD.exe Prompt from your Anaconda Navigator to see where is your ipython is located)

Then, in .ipython, you will see profile_default directory which is the default one. This directory will have static/custom/custom.css file located.

You can now apply change to this custom.css file. There are a lot of styles in the custom.css file that you can use or search for. For example, you can see this link (which is my own customize custom.css file)

Basically, this custom.css file apply changes to your browser. You can use inspect elements in your ipython notebook to see which elements you want to change. Then, you can changes to the custom.css file. For example, you can add these chunk to change font in .CodeMirror pre to type Monaco

.CodeMirror pre {font-family: Monaco; font-size: 9pt;}

Note that now for Jupyter notebook version >= 4.1, the custom css file is moved to ~/.jupyter/custom/custom.css instead.

String comparison in Python: is vs. ==

For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x==y is also True.

Not always. NaN is a counterexample. But usually, identity (is) implies equality (==). The converse is not true: Two distinct objects can have the same value.

Also, is it generally considered better to just use '==' by default, even when comparing int or Boolean values?

You use == when comparing values and is when comparing identities.

When comparing ints (or immutable types in general), you pretty much always want the former. There's an optimization that allows small integers to be compared with is, but don't rely on it.

For boolean values, you shouldn't be doing comparisons at all. Instead of:

if x == True:
    # do something

write:

if x:
    # do something

For comparing against None, is None is preferred over == None.

I've always liked to use 'is' because I find it more aesthetically pleasing and pythonic (which is how I fell into this trap...), but I wonder if it's intended to just be reserved for when you care about finding two objects with the same id.

Yes, that's exactly what it's for.

How to download a Nuget package without nuget.exe or Visual Studio extension?

Based on Xavier's answer, I wrote a Google chrome extension NuTake to add links to the Nuget.org package pages.

Why does this "Slow network detected..." log appear in Chrome?

Go to the Font's stylesheet.css and add font-display: block; in all @font-face { }

This Stackoverflow Answer helped me..

Below is the Summary of the answer

If you can access to css of this extension, simply add font-display:block; on font-face definition or send feedback to developer of this extension:)

@font-face {
  font-family: ExampleFont;
  src: url(/path/to/fonts/examplefont.woff) format('woff'),
       url(/path/to/fonts/examplefont.eot) format('eot');
  font-weight: 400;
  font-style: normal;
  font-display: block;
}

How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

I use serializable classes for the WCF communication between different modules. Below is an example of serializable class which serves as DataContract as well. My approach is to use the power of LINQ to convert the Dictionary into out-of-the-box serializable List<> of KeyValuePair<>:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.Xml.Serialization;

    namespace MyFirm.Common.Data
    {
        [DataContract]
        [Serializable]
        public class SerializableClassX
        {
            // since the Dictionary<> class is not serializable,
            // we convert it to the List<KeyValuePair<>>
            [XmlIgnore]
            public Dictionary<string, int> DictionaryX 
            {
                get
                {
                    return  SerializableList == null ? 
                            null :
                            SerializableList.ToDictionary(item => item.Key, item => item.Value);
                }

                set
                {
                    SerializableList =  value == null ?
                                        null :
                                        value.ToList();
                }
            }

            [DataMember]
            [XmlArray("SerializableList")]
            [XmlArrayItem("Pair")]
            public List<KeyValuePair<string, int>> SerializableList { get; set; }
        }
    }

The usage is straightforward - I assign a dictionary to my data object's dictionary field - DictionaryX. The serialization is supported inside the SerializableClassX by conversion of the assigned dictionary into the serializable List<> of KeyValuePair<>:

    // create my data object
    SerializableClassX SerializableObj = new SerializableClassX(param);

    // this will call the DictionaryX.set and convert the '
    // new Dictionary into SerializableList
    SerializableObj.DictionaryX = new Dictionary<string, int>
    {
        {"Key1", 1},
        {"Key2", 2},
    };

Jquery- Get the value of first td in table

$(this).parent().siblings(":first").text()

parent gives you the <td> around the link,

siblings gives all the <td> tags in that <tr>,

:first gives the first matched element in the set.

text() gives the contents of the tag.

Determining type of an object in ruby

I would say "Yes". As "Matz" had said something like this in one of his talks, "Ruby objects have no types." Not all of it but the part that he is trying to get across to us. Why would anyone have said "Everything is an Object" then? To add he said "Data has Types not objects".

So we might enjoy this.

https://www.youtube.com/watch?v=1l3U1X3z0CE

But Ruby doesn't care to much about the type of object just the class. We use classes not types. All data then has a class.

12345.class

'my string'.class

They may also have ancestors

Object.ancestors

They also have meta classes but I'll save you the details on that.

Once you know the class then you'll be able to lookup what methods you may use for it. That's where the "data type" is needed. If you really want to get into details the look up...

"The Ruby Object Model"

This is the term used for how Ruby handles objects. It's all internal so you don't really see much of this but it's nice to know. But that's another topic.

Yes! The class is the data type. Objects have classes and data has types. So if you know about data bases then you know there are only a finite set of types.

text blocks numbers

How do you post to an iframe?

An iframe is used to embed another document inside a html page.

If the form is to be submitted to an iframe within the form page, then it can be easily acheived using the target attribute of the tag.

Set the target attribute of the form to the name of the iframe tag.

<form action="action" method="post" target="output_frame">
    <!-- input elements here --> 
</form>
<iframe name="output_frame" src="" id="output_frame" width="XX" height="YY">
</iframe>           

Advanced iframe target use
This property can also be used to produce an ajax like experience, especially in cases like file upload, in which case where it becomes mandatory to submit the form, in order to upload the files

The iframe can be set to a width and height of 0, and the form can be submitted with the target set to the iframe, and a loading dialog opened before submitting the form. So, it mocks a ajax control as the control still remains on the input form jsp, with the loading dialog open.

Exmaple

<script>
$( "#uploadDialog" ).dialog({ autoOpen: false, modal: true, closeOnEscape: false,                 
            open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); } });

function startUpload()
{            
    $("#uploadDialog").dialog("open");
}

function stopUpload()
{            
    $("#uploadDialog").dialog("close");
}
</script>

<div id="uploadDialog" title="Please Wait!!!">
            <center>
            <img src="/imagePath/loading.gif" width="100" height="100"/>
            <br/>
            Loading Details...
            </center>
 </div>

<FORM  ENCTYPE="multipart/form-data" ACTION="Action" METHOD="POST" target="upload_target" onsubmit="startUpload()"> 
<!-- input file elements here--> 
</FORM>

<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;" onload="stopUpload()">   
        </iframe>

Command line for looking at specific port

Here is the easy solution of port finding...

In cmd:

netstat -na | find "8080"

In bash:

netstat -na | grep "8080"

In PowerShell:

netstat -na | Select-String "8080"

How to check identical array in most efficient way?

You could compare String representations so:

array1.toString() == array2.toString()
array1.toString() !== array3.toString()

but that would also make

array4 = ['1',2,3,4,5]

equal to array1 if that matters to you

Keyboard shortcut to change font size in Eclipse?

Windows > Preferences > General > Appearance > Colors and Fonts

Then, to change Java editor font: Java > Java Editor Text Font > EDIT

There it is.

Compare two objects' properties to find differences?

Yes. Use Reflection. With Reflection, you can do things like:

//given object of some type
object myObjectFromSomewhere;
Type myObjOriginalType = myObjectFromSomewhere.GetType();
PropertyInfo[] myProps = myObjOriginalType.GetProperties();

And then you can use the resulting PropertyInfo classes to compare all manner of things.

How to set a variable to current date and date-1 in linux?

You can also use the shorter format

From the man page:

%F     full date; same as %Y-%m-%d

Example:

#!/bin/bash
date_today=$(date +%F)
date_dir=$(date +%F -d yesterday)

What is the purpose of "&&" in a shell command?

&& lets you do something based on whether the previous command completed successfully - that's why you tend to see it chained as do_something && do_something_else_that_depended_on_something.

the getSource() and getActionCommand()

I use getActionCommand() to hear buttons. I apply the setActionCommand() to each button so that I can hear whenever an event is execute with event.getActionCommand("The setActionCommand() value of the button").

I use getSource() for JRadioButtons for example. I write methods that returns each JRadioButton so in my Listener Class I can specify an action each time a new JRadioButton is pressed. So for example:

public class SeleccionListener implements ActionListener, FocusListener {}

So with this I can hear button events and radioButtons events. The following are examples of how I listen each one:

public void actionPerformed(ActionEvent event) {
    if (event.getActionCommand().equals(GUISeleccion.BOTON_ACEPTAR)) {
        System.out.println("Aceptar pressed");
    }

In this case GUISeleccion.BOTON_ACEPTAR is a "public static final String" which is used in JButtonAceptar.setActionCommand(BOTON_ACEPTAR).

public void focusGained(FocusEvent focusEvent) {
    if (focusEvent.getSource().equals(guiSeleccion.getJrbDat())){
        System.out.println("Data radio button");
    }

In this one, I get the source of any JRadioButton that is focused when the user hits it. guiSeleccion.getJrbDat() returns the reference to the JRadioButton that is in the class GUISeleccion (this is a Frame)

jQuery add text to span within a div

Careful - append() will append HTML, and you may run into cross-site-scripting problems if you use it all the time and a user makes you append('<script>alert("Hello")</script>').

Use text() to replace element content with text, or append(document.createTextNode(x)) to append a text node.

SQL Server: Get table primary key using sql query

select * 
from sysobjects 
where xtype='pk' and 
   parent_obj in (select id from sysobjects where name='tablename')

this will work in sql 2005

pyplot scatter plot marker size

This can be a somewhat confusing way of defining the size but you are basically specifying the area of the marker. This means, to double the width (or height) of the marker you need to increase s by a factor of 4. [because A = WH => (2W)(2H)=4A]

There is a reason, however, that the size of markers is defined in this way. Because of the scaling of area as the square of width, doubling the width actually appears to increase the size by more than a factor 2 (in fact it increases it by a factor of 4). To see this consider the following two examples and the output they produce.

# doubling the width of markers
x = [0,2,4,6,8,10]
y = [0]*len(x)
s = [20*4**n for n in range(len(x))]
plt.scatter(x,y,s=s)
plt.show()

gives

enter image description here

Notice how the size increases very quickly. If instead we have

# doubling the area of markers
x = [0,2,4,6,8,10]
y = [0]*len(x)
s = [20*2**n for n in range(len(x))]
plt.scatter(x,y,s=s)
plt.show()

gives

enter image description here

Now the apparent size of the markers increases roughly linearly in an intuitive fashion.

As for the exact meaning of what a 'point' is, it is fairly arbitrary for plotting purposes, you can just scale all of your sizes by a constant until they look reasonable.

Hope this helps!

Edit: (In response to comment from @Emma)

It's probably confusing wording on my part. The question asked about doubling the width of a circle so in the first picture for each circle (as we move from left to right) it's width is double the previous one so for the area this is an exponential with base 4. Similarly the second example each circle has area double the last one which gives an exponential with base 2.

However it is the second example (where we are scaling area) that doubling area appears to make the circle twice as big to the eye. Thus if we want a circle to appear a factor of n bigger we would increase the area by a factor n not the radius so the apparent size scales linearly with the area.

Edit to visualize the comment by @TomaszGandor:

This is what it looks like for different functions of the marker size:

Exponential, Square, or Linear size

x = [0,2,4,6,8,10,12,14,16,18]
s_exp = [20*2**n for n in range(len(x))]
s_square = [20*n**2 for n in range(len(x))]
s_linear = [20*n for n in range(len(x))]
plt.scatter(x,[1]*len(x),s=s_exp, label='$s=2^n$', lw=1)
plt.scatter(x,[0]*len(x),s=s_square, label='$s=n^2$')
plt.scatter(x,[-1]*len(x),s=s_linear, label='$s=n$')
plt.ylim(-1.5,1.5)
plt.legend(loc='center left', bbox_to_anchor=(1.1, 0.5), labelspacing=3)
plt.show()

How do you Change a Package's Log Level using Log4j?

Which app server are you using? Each one puts its logging config in a different place, though most nowadays use Commons-Logging as a wrapper around either Log4J or java.util.logging.

Using Tomcat as an example, this document explains your options for configuring logging using either option. In either case you need to find or create a config file that defines the log level for each package and each place the logging system will output log info (typically console, file, or db).

In the case of log4j this would be the log4j.properties file, and if you follow the directions in the link above your file will start out looking like:

log4j.rootLogger=DEBUG, R 
log4j.appender.R=org.apache.log4j.RollingFileAppender 
log4j.appender.R.File=${catalina.home}/logs/tomcat.log 
log4j.appender.R.MaxFileSize=10MB 
log4j.appender.R.MaxBackupIndex=10 
log4j.appender.R.layout=org.apache.log4j.PatternLayout 
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

Simplest would be to change the line:

log4j.rootLogger=DEBUG, R

To something like:

log4j.rootLogger=WARN, R

But if you still want your own DEBUG level output from your own classes add a line that says:

log4j.category.com.mypackage=DEBUG

Reading up a bit on Log4J and Commons-Logging will help you understand all this.

How should I load files into my Java application?

What are you loading the files for - configuration or data (like an input file) or as a resource?

  • If as a resource, follow the suggestion and example given by Will and Justin
  • If configuration, then you can use a ResourceBundle or Spring (if your configuration is more complex).
  • If you need to read a file in order to process the data inside, this code snippet may help BufferedReader file = new BufferedReader(new FileReader(filename)) and then read each line of the file using file.readLine(); Don't forget to close the file.

Is there a way to access an iteration-counter in Java's for-each loop?

There is a "variant" to pax' answer... ;-)

int i = -1;
for(String s : stringArray) {
    doSomethingWith(s, ++i);
}

Good examples using java.util.logging

Should declare logger like this:

private final static Logger LOGGER = Logger.getLogger(MyClass.class.getName());

so if you refactor your class name it follows.

I wrote an article about java logger with examples here.

Extracting the last n characters from a string in R

str = 'This is an example'
n = 7
result = substr(str,(nchar(str)+1)-n,nchar(str))
print(result)

> [1] "example"
> 

Grant execute permission for a user on all stored procedures in database?

use below code , change proper database name and user name and then take that output and execute in SSMS. FOR SQL 2005 ABOVE

USE <database_name> 
select 'GRANT EXECUTE ON ['+name+'] TO [userName]  '  
from sys.objects  
where type ='P' 
and is_ms_shipped = 0  

How to convert Observable<any> to array[]

//Component. home.ts :

  contacts:IContacts[];


ionViewDidLoad() {
this.rest.getContacts()
.subscribe( res=> this.contacts= res as IContacts[]) ;

// reorderArray. accepts only Arrays

    Reorder(indexes){
  reorderArray(this.contacts, indexes)
}

// Service . res.ts

getContacts(): Observable<IContacts[]> {
return this.http.get<IContacts[]>(this.apiUrl+"?results=5")

And it works fine

Case insensitive 'Contains(string)'

Just like this:

string s="AbcdEf";
if(s.ToLower().Contains("def"))
{
    Console.WriteLine("yes");
}

How to sort two lists (which reference each other) in the exact same way

One classic approach to this problem is to use the "decorate, sort, undecorate" idiom, which is especially simple using python's built-in zip function:

>>> list1 = [3,2,4,1, 1]
>>> list2 = ['three', 'two', 'four', 'one', 'one2']
>>> list1, list2 = zip(*sorted(zip(list1, list2)))
>>> list1
(1, 1, 2, 3, 4)
>>> list2 
('one', 'one2', 'two', 'three', 'four')

These of course are no longer lists, but that's easily remedied, if it matters:

>>> list1, list2 = (list(t) for t in zip(*sorted(zip(list1, list2))))
>>> list1
[1, 1, 2, 3, 4]
>>> list2
['one', 'one2', 'two', 'three', 'four']

It's worth noting that the above may sacrifice speed for terseness; the in-place version, which takes up 3 lines, is a tad faster on my machine for small lists:

>>> %timeit zip(*sorted(zip(list1, list2)))
100000 loops, best of 3: 3.3 us per loop
>>> %timeit tups = zip(list1, list2); tups.sort(); zip(*tups)
100000 loops, best of 3: 2.84 us per loop

On the other hand, for larger lists, the one-line version could be faster:

>>> %timeit zip(*sorted(zip(list1, list2)))
100 loops, best of 3: 8.09 ms per loop
>>> %timeit tups = zip(list1, list2); tups.sort(); zip(*tups)
100 loops, best of 3: 8.51 ms per loop

As Quantum7 points out, JSF's suggestion is a bit faster still, but it will probably only ever be a little bit faster, because Python uses the very same DSU idiom internally for all key-based sorts. It's just happening a little closer to the bare metal. (This shows just how well optimized the zip routines are!)

I think the zip-based approach is more flexible and is a little more readable, so I prefer it.

Remove a marker from a GoogleMap

The method signature for addMarker is:

public final Marker addMarker (MarkerOptions options)

So when you add a marker to a GoogleMap by specifying the options for the marker, you should save the Marker object that is returned (instead of the MarkerOptions object that you used to create it). This object allows you to change the marker state later on. When you are finished with the marker, you can call Marker.remove() to remove it from the map.

As an aside, if you only want to hide it temporarily, you can toggle the visibility of the marker by calling Marker.setVisible(boolean).

How to create a Multidimensional ArrayList in Java?

Here an answer for those who'd like to have preinitialized lists of lists. Needs Java 8+.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

class Scratch {

  public static void main(String[] args) {
    int M = 4;
    int N = 3;

    // preinitialized array (== list of lists) of strings, sizes not fixed
    List<List<String>> listOfListsOfString = initializeListOfListsOfT(M, N, "-");
    System.out.println(listOfListsOfString);

    // preinitialized array (== list of lists) of int (primitive type), sizes not fixed
    List<List<Integer>> listOfListsOfInt = initializeListOfListsOfInt(M, N, 7);
    System.out.println(listOfListsOfInt);
  }

  public static <T> List<List<T>> initializeListOfListsOfT(int m, int n, T initValue) {
    return IntStream
        .range(0, m)
        .boxed()
        .map(i -> new ArrayList<T>(IntStream
            .range(0, n)
            .boxed()
            .map(j -> initValue)
            .collect(Collectors.toList()))
        )
        .collect(Collectors.toList());
  }

  public static List<List<Integer>> initializeListOfListsOfInt(int m, int n, int initValue) {
    return IntStream
        .range(0, m)
        .boxed()
        .map(i -> new ArrayList<>(IntStream
            .range(0, n)
            .map(j -> initValue)
            .boxed()
            .collect(Collectors.toList()))
        )
        .collect(Collectors.toList());
  }
}

Output:

[[-, -, -], [-, -, -], [-, -, -], [-, -, -]]
[[7, 7, 7], [7, 7, 7], [7, 7, 7], [7, 7, 7]]

Side note for those wondering about IntStream:

IntStream
    .range(0, m)
    .boxed()

is equivalent to

Stream
    .iterate(0, j -> j + 1)
    .limit(n)

How do I remove objects from an array in Java?

Arrgh, I can't get the code to show up correctly. Sorry, I got it working. Sorry again, I don't think I read the question properly.

String  foo[] = {"a","cc","a","dd"},
remove = "a";
boolean gaps[] = new boolean[foo.length];
int newlength = 0;

for (int c = 0; c<foo.length; c++)
{
    if (foo[c].equals(remove))
    {
        gaps[c] = true;
        newlength++;
    }
    else 
        gaps[c] = false;

    System.out.println(foo[c]);
}

String newString[] = new String[newlength];

System.out.println("");

for (int c1=0, c2=0; c1<foo.length; c1++)
{
    if (!gaps[c1])
    {
        newString[c2] = foo[c1];
        System.out.println(newString[c2]);
        c2++;
    }
}

jQuery UI autocomplete with item and id

At last i did it Thanks alot friends, and a special thanks to Mr https://stackoverflow.com/users/87015/salman-a because of his code i was able to solve it properly. finally my code is looking like this as i am using groovy grails i hope this will help somebody there.. Thanks alot

html code looks like this in my gsp page

  <input id="populate-dropdown" name="nameofClient" type="text">
  <input id="wilhaveid" name="idofclient" type="text">

script Function is like this in my gsp page

  <script>
        $( "#populate-dropdown").on('input', function() {
            $.ajax({
                url:'autoCOmp',
                data: {inputField: $("#populate-dropdown").val()},
                success: function(resp){
                    $('#populate-dropdown').autocomplete({
                        source:resp,
                        select: function (event, ui) {
                            $("#populate-dropdown").val(ui.item.label);
                            $("#wilhaveid").val(ui.item.value);
                             return false;
                        }
                    })
                }
            });
        });
    </script>

And my controller code is like this

   def autoCOmp(){
    println(params)
    def c = Client.createCriteria()
    def results = c.list {
        like("nameOfClient", params.inputField+"%")
    }

    def itemList = []
    results.each{
        itemList  << [value:it.id,label:it.nameOfClient]
    }
    println(itemList)
    render itemList as JSON
}

One more thing i have not set id field hidden because at first i was checking that i am getting the exact id , you can keep it hidden just put type=hidden instead of text for second input item in html

Thanks !

jQuery input button click event listener

First thing first, button() is a jQuery ui function to create a button widget which has nothing to do with jQuery core, it just styles the button.
So if you want to use the widget add jQuery ui's javascript and CSS files or alternatively remove it, like this:

$("#filter").click(function(){
    alert('clicked!');
});

Another thing that might have caused you the problem is if you didn't wait for the input to be rendered and wrote the code before the input. jQuery has the ready function, or it's alias $(func) which execute the callback once the DOM is ready.
Usage:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

So even if the order is this it will work:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

<input type="button" id="filter" name="filter" value="Filter" />

DEMO

Stop a gif animation onload, on mouseover start the activation

found a working solution here: https://codepen.io/hoanghals/pen/dZrWLZ

JS here:

var gifElements = document.querySelectorAll('img.gif');

for(var e in gifElements) {

var element = gifElements[e];

if(element.nodeName == 'IMG') {

    var supergif = new SuperGif({
        gif: element,
        progressbar_height: 0,
        auto_play: false,
    });

    var controlElement = document.createElement("div");
    controlElement.className = "gifcontrol loading g"+e;

    supergif.load((function(controlElement) {
        controlElement.className = "gifcontrol paused";
        var playing = false;
        controlElement.addEventListener("click", function(){
            if(playing) {
                this.pause();
                playing = false;
                controlElement.className = "gifcontrol paused";
            } else {
                this.play();
                playing = true;
                controlElement.className = "gifcontrol playing";
            }
        }.bind(this, controlElement));

    }.bind(supergif))(controlElement));

    var canvas = supergif.get_canvas();     
    controlElement.style.width = canvas.width+"px";
    controlElement.style.height = canvas.height+"px";
controlElement.style.left = canvas.offsetLeft+"px";
    var containerElement = canvas.parentNode;
    containerElement.appendChild(controlElement);

 }
}

create table in postgreSQL

-- Table: "user"

-- DROP TABLE "user";

CREATE TABLE "user"
(
  id bigserial NOT NULL,
  name text NOT NULL,
  email character varying(20) NOT NULL,
  password text NOT NULL,
  CONSTRAINT user_pkey PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE "user"
  OWNER TO postgres;

How to get Domain name from URL using jquery..?

You can use a trick, by creating a <a>-element, then setting the string to the href of that <a>-element and then you have a Location object you can get the hostname from.

You could either add a method to the String prototype:

String.prototype.toLocation = function() {
    var a = document.createElement('a');
    a.href = this;
    return a;
};

and use it like this:
"http://www.abc.com/search".toLocation().hostname

or make it a function:

function toLocation(url) {
    var a = document.createElement('a');
    a.href = url;
    return a;
};

and use it like this:
toLocation("http://www.abc.com/search").hostname

both of these will output: "www.abc.com"

If you also need the protocol, you can do something like this:

var url = "http://www.abc.com/search".toLocation();
url.protocol + "//" + url.hostname

which will output: "http://www.abc.com"

Secure Web Services: REST over HTTPS vs SOAP + WS-Security. Which is better?

I work in this space every day so I want to summarize the good comments on this in an effort to close this out:

SSL (HTTP/s) is only one layer ensuring:

  1. The server being connected to presents a certificate proving its identity (though this can be spoofed through DNS poisoning).
  2. The communications layer is encrypted (no eavesdropping).

WS-Security and related standards/implementations use PKI that:

  1. Prove the identity of the client.
  2. Prove the message was not modified in-transit (MITM).
  3. Allows the server to authenticate/authorize the client.

The last point is important for service requests when the identity of the client (caller) is paramount to knowing IF they should be authorized to receive such data from the service. Standard SSL is one-way (server) authentication and does nothing to identify the client.

Change input text border color without changing its height

Set a transparent border and then change it:

.default{
border: 2px solid transparent;
}

.new{
border: 2px solid red;
}

How can I reduce the waiting (ttfb) time

TTFB is something that happens behind the scenes. Your browser knows nothing about what happens behind the scenes.

You need to look into what queries are being run and how the website connects to the server.

This article might help understand TTFB, but otherwise you need to dig deeper into your application.

How to install iPhone application in iPhone Simulator

Select the platform to be iPhone Simulator then click Build and Go. If it builds correctly then it will launch the simulator and run. If it does not build ok then it will indicate errors at the bottom of the window on the right hand side.

If you only have the app file then you would need to manually install that into the simulator. The simulator was not designed to be used this way, but I'm sure it would be possible, even if it was incredibly difficult.

If you have the source code (.proj .m .h etc) files then it should be a simple case of build and go.

GSON - Date format

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").create();

Above format seems better to me as it has precision up to millis.

Get input type="file" value when it has multiple files selected

You use input.files property. It's a collection of File objects and each file has a name property:

onmouseout="for (var i = 0; i < this.files.length; i++) alert(this.files[i].name);"

Determining if a number is prime

C++

bool isPrime(int number){
    if (number != 2){
        if (number < 2 || number % 2 == 0) {
            return false;
        }
        for(int i=3; (i*i)<=number; i+=2){
            if(number % i == 0 ){
                return false;
            }
        }
    }
    return true;
}

Javascript

function isPrime(number)
{
    if (number !== 2) {
        if (number < 2 || number % 2 === 0) {
            return false;
        }
        for (var i=3; (i*i)<=number; i+=2)
        {
            if (number % 2 === 0){
                return false;
            }
        }
    }
    return true;
}

Python

def isPrime(number):
    if (number != 2):
        if (number < 2 or number % 2 == 0):
            return False
        i = 3
        while (i*i) <= number:
            if(number % i == 0 ):
                return False;
            i += 2
    return True;

User GETDATE() to put current date into SQL variable

Just use GetDate() not Select GetDate()

DECLARE @LastChangeDate as date 
SET @LastChangeDate = GETDATE() 

but if it's SQL Server, you can also initialize in same step as declaration...

DECLARE @LastChangeDate date = getDate()