Programs & Examples On #Mysqlconnection

Unable to connect to any of the specified mysql hosts. C# MySQL

Just ran into the same problem. Installing the .NET framework on the target machine solved the problem.

Better yet, make sure all required dependencies are present in the machine where the code will be running.

C# with MySQL INSERT parameters

I was facing very similar problem while trying to insert data using mysql-connector-net-5.1.7-noinstall and Visual Studio(2015) in Windows Form Application. I am not a C# guru. So, it takes around 2 hours to resolve everything.

The following code works lately:

string connetionString = null;
connetionString = "server=localhost;database=device_db;uid=root;pwd=123;";

using (MySqlConnection cn = new MySqlConnection(connetionString))
{
    try
    {
        string query = "INSERT INTO test_table(user_id, user_name) VALUES (?user_id,?user_name);";
        cn.Open();
        using (MySqlCommand cmd = new MySqlCommand(query, cn))
        {
            cmd.Parameters.Add("?user_id", MySqlDbType.Int32).Value = 123;
            cmd.Parameters.Add("?user_name", MySqlDbType.VarChar).Value = "Test username";
            cmd.ExecuteNonQuery();
        }
    }
    catch (MySqlException ex)
    {
        MessageBox.Show("Error in adding mysql row. Error: "+ex.Message);
    }
}

How to form a correct MySQL connection string?

try creating connection string this way:

MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "mysql7.000webhost.com";
conn_string.UserID = "a455555_test";
conn_string.Password = "a455555_me";
conn_string.Database = "xxxxxxxx";

using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
using (MySqlCommand cmd = conn.CreateCommand())
{    //watch out for this SQL injection vulnerability below
     cmd.CommandText = string.Format("INSERT Test (lat, long) VALUES ({0},{1})",
                                    OSGconv.deciLat, OSGconv.deciLon);
     conn.Open();
     cmd.ExecuteNonQuery();
}

Inserting data into a MySQL table using VB.NET

You need to use ?param instead of @param when performing queries to MySQL

 str_carSql = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (?id,?m_id,?model,?color,?ch_id,?pt_num,?code)"
        sqlCommand.Connection = SQLConnection
        sqlCommand.CommandText = str_carSql
        sqlCommand.Parameters.AddWithValue("?id", TextBox20.Text)
        sqlCommand.Parameters.AddWithValue("?m_id", TextBox20.Text)
        sqlCommand.Parameters.AddWithValue("?model", TextBox23.Text)
        sqlCommand.Parameters.AddWithValue("?color", TextBox24.Text)
        sqlCommand.Parameters.AddWithValue("?ch_id", TextBox22.Text)
        sqlCommand.Parameters.AddWithValue("?pt_num", TextBox21.Text)
        sqlCommand.Parameters.AddWithValue("?code", ComboBox1.SelectedItem)
        sqlCommand.ExecuteNonQuery()

Change the catch block to see the actual exception:

  Catch ex As Exception
         MsgBox(ex.Message)   
          Return False

    End Try

C# Collection was modified; enumeration operation may not execute

Any collection that you iterate over with foreach may not be modified during iteration.

So while you're running a foreach over rankings, you cannot modify its elements, add new ones or delete any.

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

database user does not have the permission to do select query.

you can grant the permission to the user if you have root access to mysql

http://dev.mysql.com/doc/refman/5.1/en/grant.html

Your second query is on different database on different table.

 String newSQL = "Select `Strike`,`LongShort`,`Current`,`TPLevel`,`SLLevel` from `json`.`tbl_Position` where `TradeID` = '" + i + "'";

And the user you are connecting with does not have permission to access data from this database or this particular table.

Have you consider this thing?

Reading all files in a directory, store them in objects, and send the object

This is a modern Promise version of the previous one, using a Promise.all approach to resolve all promises when all files have been read:

/**
 * Promise all
 * @author Loreto Parisi (loretoparisi at gmail dot com)
 */
function promiseAllP(items, block) {
    var promises = [];
    items.forEach(function(item,index) {
        promises.push( function(item,i) {
            return new Promise(function(resolve, reject) {
                return block.apply(this,[item,index,resolve,reject]);
            });
        }(item,index))
    });
    return Promise.all(promises);
} //promiseAll

/**
 * read files
 * @param dirname string
 * @return Promise
 * @author Loreto Parisi (loretoparisi at gmail dot com)
 * @see http://stackoverflow.com/questions/10049557/reading-all-files-in-a-directory-store-them-in-objects-and-send-the-object
 */
function readFiles(dirname) {
    return new Promise((resolve, reject) => {
        fs.readdir(dirname, function(err, filenames) {
            if (err) return reject(err);
            promiseAllP(filenames,
            (filename,index,resolve,reject) =>  {
                fs.readFile(path.resolve(dirname, filename), 'utf-8', function(err, content) {
                    if (err) return reject(err);
                    return resolve({filename: filename, contents: content});
                });
            })
            .then(results => {
                return resolve(results);
            })
            .catch(error => {
                return reject(error);
            });
        });
  });
}

How to Use It:

Just as simple as doing:

readFiles( EMAIL_ROOT + '/' + folder)
.then(files => {
    console.log( "loaded ", files.length );
    files.forEach( (item, index) => {
        console.log( "item",index, "size ", item.contents.length);
    });
})
.catch( error => {
    console.log( error );
});

Supposed that you have another list of folders you can as well iterate over this list, since the internal promise.all will resolve each of then asynchronously:

var folders=['spam','ham'];
folders.forEach( folder => {
    readFiles( EMAIL_ROOT + '/' + folder)
    .then(files => {
        console.log( "loaded ", files.length );
        files.forEach( (item, index) => {
            console.log( "item",index, "size ", item.contents.length);
        });
    })
    .catch( error => {
        console.log( error );
    });
});

How it Works

The promiseAll does the magic. It takes a function block of signature function(item,index,resolve,reject), where item is the current item in the array, index its position in the array, and resolve and reject the Promise callback functions. Each promise will be pushed in a array at the current index and with the current item as arguments through a anonymous function call:

promises.push( function(item,i) {
        return new Promise(function(resolve, reject) {
            return block.apply(this,[item,index,resolve,reject]);
        });
    }(item,index))

Then all promises will be resolved:

return Promise.all(promises);

Number to String in a formula field

i wrote a simple function for this:

Function (stringVar param)
(
    Local stringVar oneChar := '0';
    Local numberVar strLen := Length(param);
    Local numberVar index := strLen;

    oneChar = param[strLen];

    while index > 0 and oneChar = '0' do
    (
        oneChar := param[index];
        index := index - 1;
    );

    Left(param , index + 1);
)

How do I move to end of line in Vim?

The advantage of the 'End' key is it works in both normal and insert modes.

'$' works in normal/command mode only but it also works in the classic vi editor (good to know when vim is not available).

How do I open an .exe from another C++ .exe?

You are getting this error because you are not giving full path. (C:\Users...\file.exe) If you want to remove this error then either give full path or copy that application (you want to open) to the folder where your project(.exe) is present/saved.

#include <windows.h>
using namespace std;
int main()
{
  system ("start C:\\Users\\Folder\\chrome.exe https://www.stackoverflow.com"); //for opening stackoverflow through google chrome , if chorme.exe is in that folder..
  return 0;
}

Find p-value (significance) in scikit-learn LinearRegression

For a one-liner you can use the pingouin.linear_regression function (disclaimer: I am the creator of Pingouin), which works with uni/multi-variate regression using NumPy arrays or Pandas DataFrame, e.g:

import pingouin as pg
# Using a Pandas DataFrame `df`:
lm = pg.linear_regression(df[['x', 'z']], df['y'])
# Using a NumPy array:
lm = pg.linear_regression(X, y)

The output is a dataframe with the beta coefficients, standard errors, T-values, p-values and confidence intervals for each predictor, as well as the R^2 and adjusted R^2 of the fit.

onchange file input change img src and change image color

Try with this code, you will get the image preview while uploading

<input type='file' id="upload" onChange="readURL(this);"/>
<img id="img" src="#" alt="your image" />

 function readURL(input){
 var ext = input.files[0]['name'].substring(input.files[0]['name'].lastIndexOf('.') + 1).toLowerCase();
if (input.files && input.files[0] && (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg")) 
    var reader = new FileReader();
    reader.onload = function (e) {
        $('#img').attr('src', e.target.result);
    }

    reader.readAsDataURL(input.files[0]);
}else{
     $('#img').attr('src', '/assets/no_preview.png');
}
}

How do you properly determine the current script directory?

This should work in most cases:

import os,sys
dirname=os.path.dirname(os.path.realpath(sys.argv[0]))

How do I format a String in an email so Outlook will print the line breaks?

if work need to be done with formatted text with out html encoding. it can be easy achieved with following scenario that creates div element on the fly and using <pre></pre> html element to keep formatting.

var email_body = htmlEncode($("#Body").val());

 function htmlEncode(value) {
    return "<pre>" + $('<div/>').text(value).html() + "</pre>";
}

Write HTML to string

You could write your own classes with its Render method, and another attributes, to avoid a great mess if you use it a lot, and then use the HTMLWriter or the xmlwriter as well. This logic is used in the asp.net pages, you can inherit from webControl and override the render method, wich is great if you are developing server-side controls.
This could be a good example.

Regards

How do you enable mod_rewrite on any OS?

Module rewrite_module is built-in in to the server most cases

Use .htaccess

Use the Mod Rewrite Generator at http://www.generateit.net/mod-rewrite/

OAuth: how to test with local URLs?

You can also use ngrok: https://ngrok.com/. I use it all the time to have a public server running on my localhost. Hope this helps.

Another options which even provides your own custom domain for free are serveo.net and https://localtunnel.github.io/www/

How to loop through each and every row, column and cells in a GridView and get its value

foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
                String header = dataGridView1.Columns[i].HeaderText;
                //String cellText = row.Cells[i].Text;
                DataGridViewColumn column = dataGridView1.Columns[i]; // column[1] selects the required column 
                column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; // sets the AutoSizeMode of column defined in previous line
                int colWidth = column.Width; // store columns width after auto resize           
                colWidth += 50; // add 30 pixels to what 'colWidth' already is
                this.dataGridView1.Columns[i].Width = colWidth; // set the columns width to the value stored in 'colWidth'
            }
        }

display data from SQL database into php/ html table

refer to http://www.w3schools.com/php/php_mysql_select.asp . If you are a beginner and want to learn, w3schools is a good place.

<?php
    $con=mysqli_connect("localhost","root","YOUR_PHPMYADMIN_PASSWORD","hrmwaitrose");
    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

    $result = mysqli_query($con,"SELECT * FROM employee");

    while($row = mysqli_fetch_array($result))
      {
      echo $row['FirstName'] . " " . $row['LastName']; //these are the fields that you have stored in your database table employee
      echo "<br />";
      }

    mysqli_close($con);
    ?>

You can similarly echo it inside your table

<?php
 echo "<table>";
 while($row = mysqli_fetch_array($result))
          {
          echo "<tr><td>" . $row['FirstName'] . "</td><td> " . $row['LastName'] . "</td></tr>"; //these are the fields that you have stored in your database table employee
          }
 echo "</table>";
 mysqli_close($con);
?>

Xcode source automatic formatting

First, Examine XCode Preferences "Indentation" section. You can customize things quite a bit there...

For more fine grained control, refer to the XCode User Defaults document from apple. (May require a developer login to view). For example, I was able to disable the "indent on paste" by entering the following in terminal:

defaults write com.apple.XCODE PBXIndentOnPaste No

to read back your setting:

defaults read com.apple.XCODE PBXIndentOnPaste

What is the difference between a static and a non-static initialization code block

The code block with the static modifier signifies a class initializer; without the static modifier the code block is an instance initializer.

Class initializers are executed in the order they are defined (top down, just like simple variable initializers) when the class is loaded (actually, when it's resolved, but that's a technicality).

Instance initializers are executed in the order defined when the class is instantiated, immediately before the constructor code is executed, immediately after the invocation of the super constructor.

If you remove static from int a, it becomes an instance variable, which you are not able to access from the static initializer block. This will fail to compile with the error "non-static variable a cannot be referenced from a static context".

If you also remove static from the initializer block, it then becomes an instance initializer and so int a is initialized at construction.

How to find out the number of CPUs using python

If you want to know the number of physical cores (not virtual hyperthreaded cores), here is a platform independent solution:

psutil.cpu_count(logical=False)

https://github.com/giampaolo/psutil/blob/master/INSTALL.rst

Note that the default value for logical is True, so if you do want to include hyperthreaded cores you can use:

psutil.cpu_count()

This will give the same number as os.cpu_count() and multiprocessing.cpu_count(), neither of which have the logical keyword argument.

Javascript date regex DD/MM/YYYY

If you are in Javascript already, couldn't you just use Date.Parse() to validate a date instead of using regEx.

RegEx for date is actually unwieldy and hard to get right especially with leap years and all.

Scripting SQL Server permissions

Expanding on the answer provided in https://stackoverflow.com/a/1987215/275388 which fails for database/schema wide rights and database user types you can use:

SELECT
  CASE
      WHEN dp.class_desc = 'OBJECT_OR_COLUMN' THEN
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
        ' ON ' + '[' + obj_sch.name + ']' + '.' + '[' + o.name + ']' +
        ' TO ' + '[' + dpr.name + ']'
      WHEN dp.class_desc = 'DATABASE' THEN
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
        ' TO ' + '[' + dpr.name + ']'
      WHEN dp.class_desc = 'SCHEMA' THEN
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
        ' ON SCHEMA :: ' + '[' + SCHEMA_NAME(dp.major_id) + ']' +
        ' TO ' + '[' + dpr.name + ']'
      WHEN dp.class_desc = 'TYPE' THEN
        dp.state_desc + ' ' + dp.permission_name collate Latin1_General_CS_AS + 
        ' ON TYPE :: [' + s_types.name + '].[' + t.name + ']'
            + ' TO [' + dpr.name + ']'
      WHEN dp.class_desc = 'CERTIFICATE' THEN 
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
        ' TO ' + '[' + dpr.name + ']' 
      WHEN dp.class_desc = 'SYMMETRIC_KEYS' THEN 
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
      ' TO ' + '[' + dpr.name + ']' 
      ELSE 
        'ERROR: Unhandled class_desc: ' + dp.class_desc
  END
 AS GRANT_STMT
FROM sys.database_permissions AS dp 
  JOIN sys.database_principals AS dpr ON dp.grantee_principal_id=dpr.principal_id
  LEFT JOIN sys.objects AS o ON dp.major_id=o.object_id
  LEFT JOIN sys.schemas AS obj_sch ON o.schema_id = obj_sch.schema_id
  LEFT JOIN sys.types AS t ON dp.major_id = t.user_type_id
  LEFT JOIN sys.schemas AS s_types ON t.schema_id = s_types.schema_id
WHERE 
dpr.name NOT IN ('public','guest') 
--  AND o.name IN ('My_Procedure')      -- Uncomment to filter to specific object(s)
--  AND (o.name NOT IN ('My_Procedure') or o.name is null)  -- Uncomment to filter out specific object(s), but include rows with no o.name (VIEW DEFINITION etc.)
--  AND dp.permission_name='EXECUTE'    -- Uncomment to filter to just the EXECUTEs
--  AND dpr.name LIKE '%user_name%'     -- Uncomment to filter to just matching users
ORDER BY dpr.name, dp.class_desc, dp.permission_name

JavaScript: undefined !== undefined?

That's a bad practice to use the == equality operator instead of ===.

undefined === undefined // true
null == undefined // true
null === undefined // false

The object.x === undefined should return true if x is unknown property.

In chapter Bad Parts of JavaScript: The Good Parts, Crockford writes the following:

If you attempt to extract a value from an object, and if the object does not have a member with that name, it returns the undefined value instead.

In addition to undefined, JavaScript has a similar value called null. They are so similar that == thinks they are equal. That confuses some programmers into thinking that they are interchangeable, leading to code like

value = myObject[name];
if (value == null) {
    alert(name + ' not found.');
}

It is comparing the wrong value with the wrong operator. This code works because it contains two errors that cancel each other out. That is a crazy way to program. It is better written like this:

value = myObject[name];
if (value === undefined) {
    alert(name + ' not found.');
}

phantomjs not waiting for "full" page load

Another approach is to just ask PhantomJS to wait for a bit after the page has loaded before doing the render, as per the regular rasterize.js example, but with a longer timeout to allow the JavaScript to finish loading additional resources:

page.open(address, function (status) {
    if (status !== 'success') {
        console.log('Unable to load the address!');
        phantom.exit();
    } else {
        window.setTimeout(function () {
            page.render(output);
            phantom.exit();
        }, 1000); // Change timeout as required to allow sufficient time 
    }
});

What is the cause for "angular is not defined"

You have to put your script tag after the one that references Angular. Move it out of the head:

<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="main.js"></script>

The way you've set it up now, your script runs before Angular is loaded on the page.

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

Since this operator reduces comparisons to an integer expression, it provides the most general purpose way to sort ascending or descending based on multiple columns/attributes.

For example, if I have an array of objects I can do things like this:

# `sort!` modifies array in place, avoids duplicating if it's large...

# Sort by zip code, ascending
my_objects.sort! { |a, b| a.zip <=> b.zip }

# Sort by zip code, descending
my_objects.sort! { |a, b| b.zip <=> a.zip }
# ...same as...
my_objects.sort! { |a, b| -1 * (a.zip <=> b.zip) }

# Sort by last name, then first
my_objects.sort! { |a, b| 2 * (a.last <=> b.last) + (a.first <=> b.first) }

# Sort by zip, then age descending, then last name, then first
# [Notice powers of 2 make it work for > 2 columns.]
my_objects.sort! do |a, b|
      8 * (a.zip   <=> b.zip) +
     -4 * (a.age   <=> b.age) +
      2 * (a.last  <=> b.last) +
          (a.first <=> b.first)
end

This basic pattern can be generalized to sort by any number of columns, in any permutation of ascending/descending on each.

Is it possible to do a sparse checkout without checking out the whole repository first?

I'm new to git but it seems that if I do git checkout for each directory then it works. Also, the sparse-checkout file needs to have a trailing slash after every directory as indicated. Someone more experience please confirm that this will work.

Interestingly, if you checkout a directory not in the sparse-checkout file it seems to make no difference. They don't show up in git status and git read-tree -m -u HEAD doesn't cause it to be removed. git reset --hard doesn't cause the directory to be removed either. Anyone more experienced care to comment on what git thinks of directories that are checked out but which are not in the sparse checkout file?

How to use a findBy method with comparative criteria

This is an example using the Expr() Class - I needed this too some days ago and it took me some time to find out what is the exact syntax and way of usage:

/**
 * fetches Products that are more expansive than the given price
 * 
 * @param int $price
 * @return array
 */
public function findProductsExpensiveThan($price)
{
  $em = $this->getEntityManager();
  $qb = $em->createQueryBuilder();

  $q  = $qb->select(array('p'))
           ->from('YourProductBundle:Product', 'p')
           ->where(
             $qb->expr()->gt('p.price', $price)
           )
           ->orderBy('p.price', 'DESC')
           ->getQuery();

  return $q->getResult();
}

How to export settings?

Enable portable mode: https://code.visualstudio.com/docs/editor/portable

Summary: Portable Mode instructs VSC to store all its configuration and plugins in a specific directory (called data/ in Windows and Linux and code-portable-data in MacOS). At any time you could copy the data directory and copy it on another installation.

Outputting data from unit test in Python

inspect.trace will let you get local variables after an exception has been thrown. You can then wrap the unit tests with a decorator like the following one to save off those local variables for examination during the post mortem.

import random
import unittest
import inspect


def store_result(f):
    """
    Store the results of a test
    On success, store the return value.
    On failure, store the local variables where the exception was thrown.
    """
    def wrapped(self):
        if 'results' not in self.__dict__:
            self.results = {}
        # If a test throws an exception, store local variables in results:
        try:
            result = f(self)
        except Exception as e:
            self.results[f.__name__] = {'success':False, 'locals':inspect.trace()[-1][0].f_locals}
            raise e
        self.results[f.__name__] = {'success':True, 'result':result}
        return result
    return wrapped

def suite_results(suite):
    """
    Get all the results from a test suite
    """
    ans = {}
    for test in suite:
        if 'results' in test.__dict__:
            ans.update(test.results)
    return ans

# Example:
class TestSequenceFunctions(unittest.TestCase):

    def setUp(self):
        self.seq = range(10)

    @store_result
    def test_shuffle(self):
        # make sure the shuffled sequence does not lose any elements
        random.shuffle(self.seq)
        self.seq.sort()
        self.assertEqual(self.seq, range(10))
        # should raise an exception for an immutable sequence
        self.assertRaises(TypeError, random.shuffle, (1,2,3))
        return {1:2}

    @store_result
    def test_choice(self):
        element = random.choice(self.seq)
        self.assertTrue(element in self.seq)
        return {7:2}

    @store_result
    def test_sample(self):
        x = 799
        with self.assertRaises(ValueError):
            random.sample(self.seq, 20)
        for element in random.sample(self.seq, 5):
            self.assertTrue(element in self.seq)
        return {1:99999}


suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
unittest.TextTestRunner(verbosity=2).run(suite)

from pprint import pprint
pprint(suite_results(suite))

The last line will print the returned values where the test succeeded and the local variables, in this case x, when it fails:

{'test_choice': {'result': {7: 2}, 'success': True},
 'test_sample': {'locals': {'self': <__main__.TestSequenceFunctions testMethod=test_sample>,
                            'x': 799},
                 'success': False},
 'test_shuffle': {'result': {1: 2}, 'success': True}}

Har det gøy :-)

How to create a stacked bar chart for my DataFrame using seaborn?

You could use pandas plot as @Bharath suggest:

import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)

Output:

enter image description here

Updated:

from matplotlib.colors import ListedColormap df.set_index('App')\ .reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\ .T.plot(kind='bar', stacked=True, colormap=ListedColormap(sns.color_palette("GnBu", 10)), figsize=(12,6))

Updated Pandas 0.21.0+ reindex_axis is deprecated, use reindex

from matplotlib.colors import ListedColormap

df.set_index('App')\
  .reindex(df.set_index('App').sum().sort_values().index, axis=1)\
  .T.plot(kind='bar', stacked=True,
          colormap=ListedColormap(sns.color_palette("GnBu", 10)), 
          figsize=(12,6))

Output:

enter image description here

How to merge 2 List<T> and removing duplicate values from it in C#

Have you had a look at Enumerable.Union

This method excludes duplicates from the return set. This is different behavior to the Concat method, which returns all the elements in the input sequences including duplicates.

List<int> list1 = new List<int> { 1, 12, 12, 5};
List<int> list2 = new List<int> { 12, 5, 7, 9, 1 };
List<int> ulist = list1.Union(list2).ToList();

// ulist output : 1, 12, 5, 7, 9

Regex (grep) for multi-line search needed

Without the need to install the grep variant pcregrep, you can do multiline search with grep.

$ grep -Pzo "(?s)^(\s*)\N*main.*?{.*?^\1}" *.c

Explanation:

-P activate perl-regexp for grep (a powerful extension of regular expressions)

-z suppress newline at the end of line, substituting it for null character. That is, grep knows where end of line is, but sees the input as one big line.

-o print only matching. Because we're using -z, the whole file is like a single big line, so if there is a match, the entire file would be printed; this way it won't do that.

In regexp:

(?s) activate PCRE_DOTALL, which means that . finds any character or newline

\N find anything except newline, even with PCRE_DOTALL activated

.*? find . in non-greedy mode, that is, stops as soon as possible.

^ find start of line

\1 backreference to the first group (\s*). This is a try to find the same indentation of method.

As you can imagine, this search prints the main method in a C (*.c) source file.

What does "The code generator has deoptimised the styling of [some file] as it exceeds the max of "100KB"" mean?

In react/redux/webpack/babel build fixed this error by removing script tag type text/babel

got error:

<script type="text/babel" src="/js/bundle.js"></script>

no error:

<script src="/js/bundle.js"></script>

How to select the rows with maximum values in each group with dplyr?

More generally, I think you might want to get "top" of the rows that are sorted within a given group.

For the case of where a single value is max'd out, you have essentially sorted by only one column. However, it's often useful to hierarchically sort by multiple columns (for example: a date column and a time-of-day column).

# Answering the question of getting row with max "value".
df %>% 
  # Within each grouping of A and B values.
  group_by( A, B) %>% 
  # Sort rows in descending order by "value" column.
  arrange( desc(value) ) %>% 
  # Pick the top 1 value
  slice(1) %>% 
  # Remember to ungroup in case you want to do further work without grouping.
  ungroup()

# Answering an extension of the question of 
# getting row with the max value of the lowest "C".
df %>% 
  # Within each grouping of A and B values.
  group_by( A, B) %>% 
  # Sort rows in ascending order by C, and then within that by 
  # descending order by "value" column.
  arrange( C, desc(value) ) %>% 
  # Pick the one top row based on the sort
  slice(1) %>% 
  # Remember to ungroup in case you want to do further work without grouping.
  ungroup()

correct way to define class variables in Python

I think this sample explains the difference between the styles:

james@bodacious-wired:~$cat test.py 
#!/usr/bin/env python

class MyClass:
    element1 = "Hello"

    def __init__(self):
        self.element2 = "World"

obj = MyClass()

print dir(MyClass)
print "--"
print dir(obj)
print "--"
print obj.element1 
print obj.element2
print MyClass.element1 + " " + MyClass.element2
james@bodacious-wired:~$./test.py 
['__doc__', '__init__', '__module__', 'element1']
--
['__doc__', '__init__', '__module__', 'element1', 'element2']
--
Hello World
Hello
Traceback (most recent call last):
  File "./test.py", line 17, in <module>
    print MyClass.element2
AttributeError: class MyClass has no attribute 'element2'

element1 is bound to the class, element2 is bound to an instance of the class.

Python 3 - ValueError: not enough values to unpack (expected 3, got 2)

1. First should understand the error meaning

Error not enough values to unpack (expected 3, got 2) means:

a 2 part tuple, but assign to 3 values

and I have written demo code to show for you:


#!/usr/bin/python
# -*- coding: utf-8 -*-
# Function: Showing how to understand ValueError 'not enough values to unpack (expected 3, got 2)'
# Author: Crifan Li
# Update: 20191212

def notEnoughUnpack():
    """Showing how to understand python error `not enough values to unpack (expected 3, got 2)`"""
    # a dict, which single key's value is two part tuple
    valueIsTwoPartTupleDict = {
        "name1": ("lastname1", "email1"),
        "name2": ("lastname2", "email2"),
    }

    # Test case 1: got value from key
    gotLastname, gotEmail = valueIsTwoPartTupleDict["name1"] # OK
    print("gotLastname=%s, gotEmail=%s" % (gotLastname, gotEmail))
    # gotLastname, gotEmail, gotOtherSomeValue = valueIsTwoPartTupleDict["name1"] # -> ValueError not enough values to unpack (expected 3, got 2)

    # Test case 2: got from dict.items()
    for eachKey, eachValues in valueIsTwoPartTupleDict.items():
        print("eachKey=%s, eachValues=%s" % (eachKey, eachValues))
    # same as following:
    # Background knowledge: each of dict.items() return (key, values)
    # here above eachValues is a tuple of two parts
    for eachKey, (eachValuePart1, eachValuePart2) in valueIsTwoPartTupleDict.items():
        print("eachKey=%s, eachValuePart1=%s, eachValuePart2=%s" % (eachKey, eachValuePart1, eachValuePart2))
    # but following:
    for eachKey, (eachValuePart1, eachValuePart2, eachValuePart3) in valueIsTwoPartTupleDict.items(): # will -> ValueError not enough values to unpack (expected 3, got 2)
        pass

if __name__ == "__main__":
    notEnoughUnpack()

using VSCode debug effect:

notEnoughUnpack CrifanLi

2. For your code

for name, email, lastname in unpaidMembers.items():

but error ValueError: not enough values to unpack (expected 3, got 2)

means each item(a tuple value) in unpaidMembers, only have 1 parts:email, which corresponding above code

    unpaidMembers[name] = email

so should change code to:

for name, email in unpaidMembers.items():

to avoid error.

But obviously you expect extra lastname, so should change your above code to

    unpaidMembers[name] = (email, lastname)

and better change to better syntax:

for name, (email, lastname) in unpaidMembers.items():

then everything is OK and clear.

Change project name on Android Studio

Here's what I did in Android Studio Beta (0.8.14)

  1. Changed the package name manually in the manifest file
  2. Navigated to build -> source -> r -> release and drilled down until I found R.java
  3. Selected the file and pressed F6 to rename
  4. Then from the Build menu selected Make Project
  5. Clicked the first error and pressed Shift+F6 on the package name and renamed which updated all my source files
  6. Selected my project name in Android Studio, right clicked -> Refactor -> Rename and changed the name there too.
  7. Next went to app -> build.gradle and updated my applicationId
  8. Navigate to .idea -> .name file and rename your Android Studio project in there too
  9. Just to clean up I deleted the old package folder inside build -> source -> r -> release

And vola, my package name has now changed and builds successfully.

Grunt watch error - Waiting...Fatal error: watch ENOSPC

Any time you need to run sudo something ... to fix something, you should be pausing to think about what's going on. While the accepted answer here is perfectly valid, it's treating the symptom rather than the problem. Sorta the equivalent of buying bigger saddlebags to solve the problem of: error, cannot load more garbage onto pony. Pony has so much garbage already loaded, that pony is fainting with exhaustion.

An alternative (perhaps comparable to taking excess garbage off of pony and placing in the dump), is to run:

npm dedupe

Then go congratulate yourself for making pony happy.

jQuery Scroll to Div

The script below is a generic solution that works for me. It is based on ideas pulled from this and other threads.

When a link with an href attribute beginning with "#" is clicked, it scrolls the page smoothly to the indicated div. Where only the "#" is present, it scrolls smoothly to the top of the page.

$('a[href^=#]').click(function(){
    event.preventDefault();
    var target = $(this).attr('href');
    if (target == '#')
      $('html, body').animate({scrollTop : 0}, 600);
    else
      $('html, body').animate({
        scrollTop: $(target).offset().top - 100
    }, 600);
});

For example, When the code above is present, clicking a link with the tag <a href="#"> scrolls to the top of the page at speed 600. Clicking a link with the tag <a href="#mydiv"> scrolls to 100px above <div id="mydiv"> at speed 600. Feel free to change these numbers.

I hope it helps!

javascript how to create a validation error message without using alert

I would strongly suggest you start using jQuery. Your code would look like:

$(function() {
    $('form[name="myform"]').submit(function(e) {
        var username = $('form[name="myform"] input[name="username"]').val();
        if ( username == '') {
            e.preventDefault();
            $('#errors').text('*Please enter a username*');
        }
    });
});

How to align entire html body to the center?

You can try:

body{ margin:0 auto; }

Can I use if (pointer) instead of if (pointer != NULL)?

"Is it safe..?" is a question about the language standard and the generated code.

"Is is a good practice?" is a question about how well the statement is understood by any arbitrary human reader of the statement. If you are asking this question, it suggests that the "safe" version is less clear to future readers and writers.

String replacement in batch file

This works fine

@echo off    
set word=table    
set str=jump over the chair    
set rpl=%str:chair=%%word%    
echo %rpl%

How to center a View inside of an Android Layout?

I was able to center a view using

android:layout_centerHorizontal="true" 

and

android:layout_centerVertical="true" 

params.

How to get file size in Java

Did a quick google. Seems that to find the file size you do this,

long size = f.length();

The differences between the three methods you posted can be found here

getFreeSpace() and getTotalSpace() are pretty self explanatory, getUsableSpace() seems to be the space that the JVM can use, which in most cases will be the same as the amount of free space.

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

We had this on a recursive query that was dumping tons of data to the output - have you double checked everything does exit and no infinite loops exist?

Might try to narrow it down with a single page - we found ANTS to not be much help in that same case either - what we ended up doing was running the site hit a page watch the CPU - hit the next page watch CPU - very methodical and time consuming but if you cant find it with some code tracing you might be out of luck -

We were able to use IIS log files to track it to a set of pages that were suspect -

Hope that helps !

Select the top N values by group

# start with the mtcars data frame (included with your installation of R)
mtcars

# pick your 'group by' variable
gbv <- 'cyl'
# IMPORTANT NOTE: you can only include one group by variable here
# ..if you need more, the `order` function below will need
# one per inputted parameter: order( x$cyl , x$am )

# choose whether you want to find the minimum or maximum
find.maximum <- FALSE

# create a simple data frame with only two columns
x <- mtcars

# order it based on 
x <- x[ order( x[ , gbv ] , decreasing = find.maximum ) , ]

# figure out the ranks of each miles-per-gallon, within cyl columns
if ( find.maximum ){
    # note the negative sign (which changes the order of mpg)
    # *and* the `rev` function, which flips the order of the `tapply` result
    x$ranks <- unlist( rev( tapply( -x$mpg , x[ , gbv ] , rank ) ) )
} else {
    x$ranks <- unlist( tapply( x$mpg , x[ , gbv ] , rank ) )
}
# now just subset it based on the rank column
result <- x[ x$ranks <= 3 , ]

# look at your results
result

# done!

# but note only *two* values where cyl == 4 were kept,
# because there was a tie for third smallest, and the `rank` function gave both '3.5'
x[ x$ranks == 3.5 , ]

# ..if you instead wanted to keep all ties, you could change the
# tie-breaking behavior of the `rank` function.
# using the `min` *includes* all ties.  using `max` would *exclude* all ties
if ( find.maximum ){
    # note the negative sign (which changes the order of mpg)
    # *and* the `rev` function, which flips the order of the `tapply` result
    x$ranks <- unlist( rev( tapply( -x$mpg , x[ , gbv ] , rank , ties.method = 'min' ) ) )
} else {
    x$ranks <- unlist( tapply( x$mpg , x[ , gbv ] , rank , ties.method = 'min' ) )
}
# and there are even more options..
# see ?rank for more methods

# now just subset it based on the rank column
result <- x[ x$ranks <= 3 , ]

# look at your results
result
# and notice *both* cyl == 4 and ranks == 3 were included in your results
# because of the tie-breaking behavior chosen.

laravel-5 passing variable to JavaScript

Try this - https://github.com/laracasts/PHP-Vars-To-Js-Transformer Is simple way to append PHP variables to Javascript.

Declaring and using MySQL varchar variables

If you are using phpmyadmin to add new routine then don't forget to wrap your code between BEGIN and ENDenter image description here

What should I set JAVA_HOME environment variable on macOS X 10.6?

I am having MAC OS X(Sierra) 10.12.2.

I set JAVA_HOME to work on React Native(for Android apps) by following the following steps.

  • Open Terminal (Command+R, type Terminal, Hit ENTER).

  • Add the following lines to ~/.bash_profile. export JAVA_HOME=$(/usr/libexec/java_home)

  • Now run the following command. source ~/.bash_profile

  • You can check the exact value of JAVA_HOME by typing the following command. echo $JAVA_HOME

The value(output) returned will be something like below. /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home

That's it.

How to output a multiline string in Bash?

Also with indented source code you can use <<- (with a trailing dash) to ignore leading tabs (but not leading spaces).

For example this:

if [ some test ]; then
    cat <<- xx
        line1
        line2
xx
fi

Outputs indented text without the leading whitespace:

line1
line2

Android: Quit application when press back button

When you press back and then you finish your current activity(say A), you see a blank activity with your app logo(say B), this simply means that activity B which is shown after finishing A is still in backstack, and also activity A was started from activity B, so in activity, You should start activity A with flags as

Intent launchNextActivity;
launchNextActivity = new Intent(B.class, A.class);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);                  
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(launchNextActivity);

Now your activity A is top on stack with no other activities of your application on the backstack.

Now in the activity A where you want to implement onBackPressed to close the app, you may do something like this,

private Boolean exit = false;
@Override
    public void onBackPressed() {
        if (exit) {
            finish(); // finish activity
        } else {
            Toast.makeText(this, "Press Back again to Exit.",
                    Toast.LENGTH_SHORT).show();
            exit = true;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    exit = false;
                }
            }, 3 * 1000);

        }

    }

The Handler here handles accidental back presses, it simply shows a Toast, and if there is another back press within 3 seconds, it closes the application.

How to combine results of two queries into a single dataset

The problem is that unless your tables are related you can't determine how to join them, so you'd have to arbitrarily join them, resulting in a cartesian product:

select Table1.col1, Table1.col2, Table2.col3, Table2.col4
from Table1
cross join Table2

If you had, for example, the following data:

col1  col2
a     1
b     2

col3  col4
y     98
z     99

You would end up with the following:

col1  col2  col3  col4
a     1     y     98
a     1     z     99
b     2     y     98
b     2     z     99

Is this what you're looking for? If not, and you have some means of relating the tables, then you'd need to include that in joining the two tables together, e.g.:

select Table1.col1, Table1.col2, Table2.col3, Table2.col4
from Table1
inner join Table2
on Table1.JoiningField = Table2.JoiningField

That would pull things together for you into however the data is related, giving you your result.

vertical-align with Bootstrap 3

Flex behaviors are natively supported since Bootstrap 4. Add d-flex align-items-center in the row div. You no longer need to modify your CSS content.

Simple example: http://jsfiddle.net/vgks6L74/

<!-- language: html -->
<div class="row d-flex align-items-center">
  <div class="col-5 border border-dark" style="height:10em">  Big </div>
  <div class="col-2 border border-danger" style="height:3em"> Small </div>
</div>

With your example: http://jsfiddle.net/7zwtL702/

<!-- language: html -->
<div class="row d-flex align-items-center">
    <div class="col-5">
        <div class="border border-dark" style="height:10em">Big</div>
    </div>
    <div class="col-2">
        <div class="border border-danger" style="height:3em">Small</div>
   </div>
</div>

Source: Flex · Bootstrap

Printing Batch file results to a text file

You can add this piece of code to the top of your batch file:

@Echo off
SET LOGFILE=MyLogFile.log
call :Logit >> %LOGFILE% 
exit /b 0

:Logit
:: The rest of your code
:: ....

It basically redirects the output of the :Logit method to the LOGFILE. The exit command is to ensure the batch exits after executing :Logit.

Using a Python subprocess call to invoke a Python script

If 'somescript.py' isn't something you could normally execute directly from the command line (I.e., $: somescript.py works), then you can't call it directly using call.

Remember that the way Popen works is that the first argument is the program that it executes, and the rest are the arguments passed to that program. In this case, the program is actually python, not your script. So the following will work as you expect:

subprocess.call(['python', 'somescript.py', somescript_arg1, somescript_val1,...]).

This correctly calls the Python interpreter and tells it to execute your script with the given arguments.

Note that this is different from the above suggestion:

subprocess.call(['python somescript.py'])

That will try to execute the program called python somscript.py, which clearly doesn't exist.

call('python somescript.py', shell=True)

Will also work, but using strings as input to call is not cross platform, is dangerous if you aren't the one building the string, and should generally be avoided if at all possible.

Why does Eclipse automatically add appcompat v7 library support whenever I create a new project?

I'm new with Android and the project appcompat_v7 always be created when I create new Android application project makes me so uncomfortable.

This is just a walk around. Choose Project Properties -> Android then at Library box just remove appcompat_v7_x and add appcompat_v7. Now you can delete appcompat_v7_x.

Uncheck Create Activity in create project wizard doesn't work, because when creating activity by wizard the appcompat_v7_x appear again. My ADT's version is v22.6.2-1085508.
I'm sorry if my English is bad.

How do I open multiple instances of Visual Studio Code?

To open a new instance with your project loaded from terminal, just type code <directory-path>

jquery ajax get responsetext from http url

try this

alert( data['responseText'] );

VB6 IDE cannot load MSCOMCTL.OCX after update KB 2687323

For me, this solution worked like a charm: http://home.pacific.net.hk/~edx/bin/readmeocx.txt

Fix these two lines like that:

Object={F9043C88-F6F2-101A-A3C9-08002B2F49FB}#1.2#0; COMDLG32.OCX
Object={831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.0#0; MSCOMCTL.OCX

Search the files (.vbp and .frm) for lines like this:

Begin ComctlLib.ImageList ILTree
Begin ComctlLib.StatusBar StatusBar1 
Begin ComctlLib.Toolbar Toolbar1` 

The lines may be like this:

Begin MSComctlLib.ImageList ILTree 
Begin MSComctlLib.StatusBar StatusBar1
Begin MSComctlLib.Toolbar Toolbar1` 

Maximum value of maxRequestLength?

Right value is below. (Tried)

maxRequestLength="2147483647" targetFramework="4.5.2"/>

grunt: command not found when running from terminal

the key point is finding the right path where your grunt was installed. I installed grunt through npm, but my grunt path was /Users/${whoyouare}/.npm-global/lib/node_modules/grunt/bin/grunt. So after I added /Users/${whoyouare}/.npm-global/lib/node_modules/grunt/bin to ~/.bash_profile,and source ~/.bash_profile, It worked.

So the steps are as followings:

1. find the path where your grunt was installed(when you installed grunt, it told you. if you don't remember, you can install it one more time)

2. vi ~/.bash_profile

3. export PATH=$PATH:/your/path/where/grunt/was/installed

4. source ~/.bash_profile

You can refer http://www.hongkiat.com/blog/grunt-command-not-found/

Java file path in Linux

I think Todd is correct, but I think there's one other thing you should consider. You can reliably get the home directory from the JVM at runtime, and then you can create files objects relative to that location. It's not that much more trouble, and it's something you'll appreciate if you ever move to another computer or operating system.

File homedir = new File(System.getProperty("user.home"));
File fileToRead = new File(homedir, "java/ex.txt");

How to create a sticky left sidebar menu using bootstrap 3?

I used this way in my code

$(function(){
    $('.block').affix();
})

Using Git with Visual Studio

Visual Studio 2013 natively supports Git.

See the official announcement.

How do I check if a property exists on a dynamic anonymous type in c#?

None of the solutions above worked for dynamic that comes from Json, I however managed to transform one with Try catch (by @user3359453) by changing exception type thrown (KeyNotFoundException instead of RuntimeBinderException) into something that actually works...

public static bool HasProperty(dynamic obj, string name)
    {
        try
        {
            var value = obj[name];
            return true;
        }
        catch (KeyNotFoundException)
        {
            return false;
        }
    }

enter image description here

Hope this saves you some time.

How to use pull to refresh in Swift?

Pull to refresh is built in iOS. You could do this in swift like

var refreshControl = UIRefreshControl()

override func viewDidLoad() {
   super.viewDidLoad()

   refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
   refreshControl.addTarget(self, action: #selector(self.refresh(_:)), for: .valueChanged)
   tableView.addSubview(refreshControl) // not required when using UITableViewController
}

@objc func refresh(_ sender: AnyObject) {
   // Code to refresh table view  
}

At some point you could end refreshing.

refreshControl.endRefreshing()

Filter LogCat to get only the messages from My Application in Android?

If you are using Android Studio you can select the process from which you want to receive logcats. Here is the screenshot.

enter image description here

How to advance to the next form input when the current input has a value?

Needed to emulate the tab functionality a while ago, and now I've released it as a library that uses .

EmulateTab: A jQuery plugin to emulate tabbing between elements on a page.

You can see how it works in the demo.

if (myTextHasBeenFilledWithText) {
  // Tab to the next input after #my-text-input
  $("#my-text-input").emulateTab();
}

Manually type in a value in a "Select" / Drop-down HTML list?

ExtJS has a ComboBox control that can do this (and a whole host of other cool stuff!!)

EDIT: Browse all controls etc, here: http://www.sencha.com/products/js/

HTTP Status 405 - Method Not Allowed Error for Rest API

Add

@Produces({"image/jpeg,image/png"})

to

@POST
@Path("/pdf")
@Consumes({ MediaType.MULTIPART_FORM_DATA })
@Produces({"image/jpeg,image/png"})
//@Produces("text/plain")
public Response uploadPdfFile(@FormDataParam("file") InputStream fileInputStream,@FormDataParam("file") FormDataContentDisposition fileMetaData) throws Exception {
    ...
}

How can I develop for iPhone using a Windows development machine?

Visual Studio + Xamarin will do the job.

Visual Studio

Yet, I'd recommend you get a Mac and develop iOS apps in Xcode.

When in Rome, live like the Romans do.

(Excel) Conditional Formatting based on Adjacent Cell Value

I don't know if maybe it's a difference in Excel version but this question is 6 years old and the accepted answer didn't help me so this is what I figured out:

Under Conditional Formatting > Manage Rules:

  1. Make a new rule with "Use a formula to determine which cells to format"
  2. Make your rule, but put a dollar sign only in front of the letter: $A2<$B2
  3. Under "Applies to", Manually select the second column (It would not work for me if I changed the value in the box, it just kept snapping back to what was already there), so it looks like $B$2:$B$100 (assuming you have 100 rows)

This worked for me in Excel 2016.

MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in Internet Explorer

I still had an issue with it passing the format yyyy-MM-dd, but I got around it by changing the Date.cshtml:

@model DateTime?

@{
    string date = string.Empty;
    if (Model != null)
    {
        date = string.Format("{0}-{1}-{2}", Model.Value.Year, Model.Value.Month, Model.Value.Day);
    }

    @Html.TextBox(string.Empty, date, new { @class = "datefield", type = "date"  })
}

How do I set specific environment variables when debugging in Visual Studio?

In Visual Studio 2008 and Visual Studio 2005 at least, you can specify changes to environment variables in the project settings.

Open your project. Go to Project -> Properties... Under Configuration Properties -> Debugging, edit the 'Environment' value to set environment variables.

For example, if you want to add the directory "c:\foo\bin" to the path when debugging your application, set the 'Environment' value to "PATH=%PATH%;c:\foo\bin".

Here's a screenshot of the settings dialog

How to declare or mark a Java method as deprecated?

Use the annotation @Deprecated for your method, and you should also mention it in your javadocs.

Multiple distinct pages in one HTML file

Let's say you have multiple pages, with id #page1 #page2 and #page3. #page1 is the ID of your start page. The first thing you want to do is to redirect to your start page each time the webpage is loading. You do this with javascript:

document.location.hash = "#page1";

Then the next thing you want to do is place some links in your document to the different pages, like for example:

<a href="#page2">Click here to get to page 2.</a>

Then, lastly, you'd want to make sure that only the active page, or target-page is visible, and all other pages stay hidden. You do this with the following declarations in the <style> element:

<style>
#page1 {display:none}
#page1:target {display:block}
#page2 {display:none}
#page2:target {display:block}
#page3 {display:none}
#page3:target {display:block}
</style>

What is the equivalent of Java static methods in Kotlin?

If you need a function or a property to be tied to a class rather than to instances of it, you can declare it inside a companion object:

class Car(val horsepowers: Int) {
    companion object Factory {
        val cars = mutableListOf<Car>()

        fun makeCar(horsepowers: Int): Car {
            val car = Car(horsepowers)
            cars.add(car)
            return car
        }
    }
}

The companion object is a singleton, and its members can be accessed directly via the name of the containing class

val car = Car.makeCar(150)
println(Car.Factory.cars.size)

SQL Server loop - how do I loop through a set of records

this way we can iterate into table data.

DECLARE @_MinJobID INT
DECLARE @_MaxJobID INT
CREATE  TABLE #Temp (JobID INT)

INSERT INTO #Temp SELECT * FROM DBO.STRINGTOTABLE(@JobID,',')
SELECT @_MinJID = MIN(JobID),@_MaxJID = MAX(JobID)  FROM #Temp

    WHILE @_MinJID <= @_MaxJID
    BEGIN

        INSERT INTO Mytable        
        (        
            JobID,        
        )        

        VALUES        
        (        
            @_MinJobID,        
        ) 

        SET @_MinJID = @_MinJID + 1;
    END

DROP TABLE #Temp

STRINGTOTABLE is user define function which will parse comma separated data and return table. thanks

Select DISTINCT individual columns in django?

The other answers are fine, but this is a little cleaner, in that it only gives the values like you would get from a DISTINCT query, without any cruft from Django.

>>> set(ProductOrder.objects.values_list('category', flat=True))
{u'category1', u'category2', u'category3', u'category4'}

or

>>> list(set(ProductOrder.objects.values_list('category', flat=True)))
[u'category1', u'category2', u'category3', u'category4']

And, it works without PostgreSQL.

This is less efficient than using a .distinct(), presuming that DISTINCT in your database is faster than a python set, but it's great for noodling around the shell.

Proxy with urllib2

You can set proxies using environment variables.

import os
os.environ['http_proxy'] = '127.0.0.1'
os.environ['https_proxy'] = '127.0.0.1'

urllib2 will add proxy handlers automatically this way. You need to set proxies for different protocols separately otherwise they will fail (in terms of not going through proxy), see below.

For example:

proxy = urllib2.ProxyHandler({'http': '127.0.0.1'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com')
# next line will fail (will not go through the proxy) (https)
urllib2.urlopen('https://www.google.com')

Instead

proxy = urllib2.ProxyHandler({
    'http': '127.0.0.1',
    'https': '127.0.0.1'
})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
# this way both http and https requests go through the proxy
urllib2.urlopen('http://www.google.com')
urllib2.urlopen('https://www.google.com')

Convert canvas to PDF

Please see https://github.com/joshua-gould/canvas2pdf. This library creates a PDF representation of your canvas element, unlike the other proposed solutions which embed an image in a PDF document.

//Create a new PDF canvas context.
var ctx = new canvas2pdf.Context(blobStream());

//draw your canvas like you would normally
ctx.fillStyle='yellow';
ctx.fillRect(100,100,100,100);
// more canvas drawing, etc...

//convert your PDF to a Blob and save to file
ctx.stream.on('finish', function () {
    var blob = ctx.stream.toBlob('application/pdf');
    saveAs(blob, 'example.pdf', true);
});
ctx.end();

How can I read comma separated values from a text file in Java?

You may use the String.split() method:

String[] tokens = str.split(",");

After that, use Double.parseDouble() method to parse the string value to a double.

double latitude = Double.parseDouble(tokens[0]);
double longitude = Double.parseDouble(tokens[1]);

Similar parse methods exist in the other wrapper classes as well - Integer, Boolean, etc.

How to print time in format: 2009-08-10 18:17:54.811

time.h defines a strftime function which can give you a textual representation of a time_t using something like:

#include <stdio.h>
#include <time.h>
int main (void) {
    char buff[100];
    time_t now = time (0);
    strftime (buff, 100, "%Y-%m-%d %H:%M:%S.000", localtime (&now));
    printf ("%s\n", buff);
    return 0;
}

but that won't give you sub-second resolution since that's not available from a time_t. It outputs:

2010-09-09 10:08:34.000

If you're really constrained by the specs and do not want the space between the day and hour, just remove it from the format string.

What is a regex to match ONLY an empty string?

As explained in http://www.regular-expressions.info/anchors.html under the section "Strings Ending with a Line Break", \Z will generally match before the end of the last newline in strings that end in a newline. If you want to only match the end of the string, you need to use \z. The exception to this rule is Python.

In other words, to exclusively match an empty string, you need to use /\A\z/.

How to create a user in Django?

Bulk user creation with set_password

I you are creating several test users, bulk_create is much faster, but we can't use create_user with it.

set_password is another way to generate the hashed passwords:

def users_iterator():
    for i in range(nusers):
        is_superuser = (i == 0)
        user = User(
            first_name='First' + str(i),
            is_staff=is_superuser,
            is_superuser=is_superuser,
            last_name='Last' + str(i),
            username='user' + str(i),
        )
        user.set_password('asdfqwer')
        yield user

class Command(BaseCommand):
    def handle(self, **options):
        User.objects.bulk_create(iter(users_iterator()))

Question specific about password hashing: How to use Bcrypt to encrypt passwords in Django

Tested in Django 1.9.

ASP.NET set hiddenfield a value in Javascript

asp:HiddenField as:

<asp:HiddenField runat="server" ID="hfProduct" ClientIDMode="Static" />

js code:

$("#hfProduct").val("test")

and the code behind:

hfProduct.Value.ToString();

How to get process ID of background process?

An even simpler way to kill all child process of a bash script:

pkill -P $$

The -P flag works the same way with pkill and pgrep - it gets child processes, only with pkill the child processes get killed and with pgrep child PIDs are printed to stdout.

How to compile C programming in Windows 7?

If you are familiar with gcc, as you indicated in the question, you can install MinGW, which will set a linux-like compile environment in Win7. Otherwise, Visual Studio 2010 Express is the best choice.

here-document gives 'unexpected end of file' error

When I want to have docstrings for my bash functions, I use a solution similar to the suggestion of user12205 in a duplicate of this question.

See how I define USAGE for a solution that:

  • auto-formats well for me in my IDE of choice (sublime)
  • is multi-line
  • can use spaces or tabs as indentation
  • preserves indentations within the comment.
function foo {
    # Docstring
    read -r -d '' USAGE <<'    END'
        # This method prints foo to the terminal.
        #
        # Enter `foo -h` to see the docstring.
        #      It has indentations and multiple lines.
        #
        # Change the delimiter if you need hashtag for some reason.
        # This can include $$ and = and eval, but won't be evaluated
    END


    if [ "$1" = "-h" ]
    then
        echo "$USAGE" | cut -d "#" -f 2 | cut -c 2-
        return
    fi

    echo "foo"
}

So foo -h yields:

This method prints foo to the terminal.

Enter `foo -h` to see the docstring.
     It has indentations and multiple lines.

Change the delimiter if you need hashtag for some reason.
This can include $$ and = and eval, but won't be evaluated

Explanation

cut -d "#" -f 2: Retrieve the second portion of the # delimited lines. (Think a csv with "#" as the delimiter, empty first column).

cut -c 2-: Retrieve the 2nd to end character of the resultant string

Also note that if [ "$1" = "-h" ] evaluates as False if there is no first argument, w/o error, since it becomes an empty string.

Redirecting to URL in Flask

You can use like this:

import os
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
     # Redirect from here, replace your custom site url "www.google.com"
    return redirect("https://www.google.com", code=200)

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

Here is the referenced link to this code.

How can I write data attributes using Angular?

About access

<ol class="viewer-nav">
    <li *ngFor="let section of sections" 
        [attr.data-sectionvalue]="section.value"
        (click)="get_data($event)">
        {{ section.text }}
    </li>  
</ol>

And

get_data(event) {
   console.log(event.target.dataset.sectionvalue)
}

running php script (php function) in linux bash

just run in linux terminal to get phpinfo .

   php -r 'phpinfo();'

and to run file like index.php

    php -f index.php

Spring .properties file: get element as an Array

Here is an example of how you can do it in Spring 4.0+

application.properties content:

some.key=yes,no,cancel

Java Code:

@Autowire
private Environment env;

...

String[] springRocks = env.getProperty("some.key", String[].class);

SQLite - getting number of rows in a database

You can query the actual number of rows with

SELECT Count(*) FROM tblName
see https://www.w3schools.com/sql/sql_count_avg_sum.asp

How to process POST data in Node.js?

If you are using Express.js, before you can access to the req.body, you must add middleware bodyParser:

app.use(express.bodyParser());

Then you can ask for

req.body.user

How to add custom Http Header for C# Web Service Client consuming Axis 1.4 Web service

If you want to send a custom HTTP Header (not a SOAP Header) then you need to use the HttpWebRequest class the code would look like:

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("Authorization", token);

You cannot add HTTP headers using the visual studio generated proxy, which can be a real pain.

How to define a List bean in Spring?

Here is one method:

<bean id="stage1" class="Stageclass"/>
<bean id="stage2" class="Stageclass"/>

<bean id="stages" class="java.util.ArrayList">
    <constructor-arg>
        <list>
            <ref bean="stage1" />
            <ref bean="stage2" />                
        </list>
    </constructor-arg>
</bean>

Is it possible to set transparency in CSS3 box-shadow?

I suppose rgba() would work here. After all, browser support for both box-shadow and rgba() is roughly the same.

/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);

_x000D_
_x000D_
div {_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    line-height: 50px;_x000D_
    text-align: center;_x000D_
    color: white;_x000D_
    background-color: red;_x000D_
    margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
  box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
_x000D_
_x000D_

Query to check index on a table

Here is what I used for TSQL which took care of the problem that my table name could contain the schema name and possibly the database name:

DECLARE @THETABLE varchar(100);
SET @THETABLE = 'theschema.thetable';
select i.*
  from sys.indexes i
 where i.object_id = OBJECT_ID(@THETABLE)
   and i.name is not NULL;

The use case for this is that I wanted the list of indexes for a named table so I could write a procedure that would dynamically compress all indexes on a table.

A tool to convert MATLAB code to Python

There's also oct2py which can call .m files within python

https://pypi.python.org/pypi/oct2py

It requires GNU Octave, which is highly compatible with MATLAB.

https://www.gnu.org/software/octave/

Binary Search Tree - Java Implementation


Here is the complete Implementation of Binary Search Tree In Java insert,search,countNodes,traversal,delete,empty,maximum & minimum node,find parent node,print all leaf node, get level,get height, get depth,print left view, mirror view


import java.util.NoSuchElementException;
import java.util.Scanner;

import org.junit.experimental.max.MaxCore;

class BSTNode {

    BSTNode left = null;
    BSTNode rigth = null;
    int data = 0;

    public BSTNode() {
        super();
    }

    public BSTNode(int data) {
        this.left = null;
        this.rigth = null;
        this.data = data;
    }

    @Override
    public String toString() {
        return "BSTNode [left=" + left + ", rigth=" + rigth + ", data=" + data + "]";
    }

}


class BinarySearchTree {

    BSTNode root = null;

    public BinarySearchTree() {

    }

    public void insert(int data) {
        BSTNode node = new BSTNode(data);
        if (root == null) {
            root = node;
            return;
        }

        BSTNode currentNode = root;
        BSTNode parentNode = null;

        while (true) {
            parentNode = currentNode;
            if (currentNode.data == data)
                throw new IllegalArgumentException("Duplicates nodes note allowed in Binary Search Tree");

            if (currentNode.data > data) {
                currentNode = currentNode.left;
                if (currentNode == null) {
                    parentNode.left = node;
                    return;
                }
            } else {
                currentNode = currentNode.rigth;
                if (currentNode == null) {
                    parentNode.rigth = node;
                    return;
                }
            }
        }
    }

    public int countNodes() {
        return countNodes(root);
    }

    private int countNodes(BSTNode node) {
        if (node == null) {
            return 0;
        } else {
            int count = 1;
            count += countNodes(node.left);
            count += countNodes(node.rigth);
            return count;
        }
    }

    public boolean searchNode(int data) {
        if (empty())
            return empty();
        return searchNode(data, root);
    }

    public boolean searchNode(int data, BSTNode node) {
        if (node != null) {
            if (node.data == data)
                return true;
            else if (node.data > data)
                return searchNode(data, node.left);
            else if (node.data < data)
                return searchNode(data, node.rigth);
        }
        return false;
    }

    public boolean delete(int data) {
        if (empty())
            throw new NoSuchElementException("Tree is Empty");

        BSTNode currentNode = root;
        BSTNode parentNode = root;
        boolean isLeftChild = false;

        while (currentNode.data != data) {
            parentNode = currentNode;
            if (currentNode.data > data) {
                isLeftChild = true;
                currentNode = currentNode.left;
            } else if (currentNode.data < data) {
                isLeftChild = false;
                currentNode = currentNode.rigth;
            }
            if (currentNode == null)
                return false;
        }

        // CASE 1: node with no child
        if (currentNode.left == null && currentNode.rigth == null) {
            if (currentNode == root)
                root = null;
            if (isLeftChild)
                parentNode.left = null;
            else
                parentNode.rigth = null;
        }

        // CASE 2: if node with only one child
        else if (currentNode.left != null && currentNode.rigth == null) {
            if (root == currentNode) {
                root = currentNode.left;
            }
            if (isLeftChild)
                parentNode.left = currentNode.left;
            else
                parentNode.rigth = currentNode.left;
        } else if (currentNode.rigth != null && currentNode.left == null) {
            if (root == currentNode)
                root = currentNode.rigth;
            if (isLeftChild)
                parentNode.left = currentNode.rigth;
            else
                parentNode.rigth = currentNode.rigth;
        }

        // CASE 3: node with two child
        else if (currentNode.left != null && currentNode.rigth != null) {

            // Now we have to find minimum element in rigth sub tree
            // that is called successor
            BSTNode successor = getSuccessor(currentNode);
            if (currentNode == root)
                root = successor;
            if (isLeftChild)
                parentNode.left = successor;
            else
                parentNode.rigth = successor;
            successor.left = currentNode.left;
        }

        return true;
    }

    private BSTNode getSuccessor(BSTNode deleteNode) {

        BSTNode successor = null;
        BSTNode parentSuccessor = null;
        BSTNode currentNode = deleteNode.left;

        while (currentNode != null) {
            parentSuccessor = successor;
            successor = currentNode;
            currentNode = currentNode.left;
        }

        if (successor != deleteNode.rigth) {
            parentSuccessor.left = successor.left;
            successor.rigth = deleteNode.rigth;
        }

        return successor;
    }

    public int nodeWithMinimumValue() {
        return nodeWithMinimumValue(root);
    }

    private int nodeWithMinimumValue(BSTNode node) {
        if (node.left != null)
            return nodeWithMinimumValue(node.left);
        return node.data;
    }

    public int nodewithMaximumValue() {
        return nodewithMaximumValue(root);
    }

    private int nodewithMaximumValue(BSTNode node) {
        if (node.rigth != null)
            return nodewithMaximumValue(node.rigth);
        return node.data;
    }

    public int parent(int data) {
        return parent(root, data);
    }

    private int parent(BSTNode node, int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        if (root.data == data)
            throw new IllegalArgumentException("No Parent node found");

        BSTNode parent = null;
        BSTNode current = node;

        while (current.data != data) {
            parent = current;
            if (current.data > data)
                current = current.left;
            else
                current = current.rigth;
            if (current == null)
                throw new IllegalArgumentException(data + " is not a node in tree");
        }
        return parent.data;
    }

    public int sibling(int data) {
        return sibling(root, data);
    }

    private int sibling(BSTNode node, int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        if (root.data == data)
            throw new IllegalArgumentException("No Parent node found");

        BSTNode cureent = node;
        BSTNode parent = null;
        boolean isLeft = false;

        while (cureent.data != data) {
            parent = cureent;
            if (cureent.data > data) {
                cureent = cureent.left;
                isLeft = true;
            } else {
                cureent = cureent.rigth;
                isLeft = false;
            }
            if (cureent == null)
                throw new IllegalArgumentException("No Parent node found");
        }
        if (isLeft) {
            if (parent.rigth != null) {
                return parent.rigth.data;
            } else
                throw new IllegalArgumentException("No Sibling is there");
        } else {
            if (parent.left != null)
                return parent.left.data;
            else
                throw new IllegalArgumentException("No Sibling is there");
        }
    }

    public void leafNodes() {
        if (empty())
            throw new IllegalArgumentException("Empty");
        leafNode(root);
    }

    private void leafNode(BSTNode node) {
        if (node == null)
            return;
        if (node.rigth == null && node.left == null)
            System.out.print(node.data + " ");
        leafNode(node.left);
        leafNode(node.rigth);
    }

    public int level(int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        return level(root, data, 1);
    }

    private int level(BSTNode node, int data, int level) {
        if (node == null)
            return 0;
        if (node.data == data)
            return level;
        int result = level(node.left, data, level + 1);
        if (result != 0)
            return result;
        result = level(node.rigth, data, level + 1);
        return result;
    }

    public int depth() {
        return depth(root);
    }

    private int depth(BSTNode node) {
        if (node == null)
            return 0;
        else
            return 1 + Math.max(depth(node.left), depth(node.rigth));
    }

    public int height() {
        return height(root);
    }

    private int height(BSTNode node) {
        if (node == null)
            return 0;
        else
            return 1 + Math.max(height(node.left), height(node.rigth));
    }

    public void leftView() {
        leftView(root);
    }

    private void leftView(BSTNode node) {
        if (node == null)
            return;
        int height = height(node);

        for (int i = 1; i <= height; i++) {
            printLeftView(node, i);
        }
    }

    private boolean printLeftView(BSTNode node, int level) {
        if (node == null)
            return false;

        if (level == 1) {
            System.out.print(node.data + " ");
            return true;
        } else {
            boolean left = printLeftView(node.left, level - 1);
            if (left)
                return true;
            else
                return printLeftView(node.rigth, level - 1);
        }
    }

    public void mirroeView() {
        BSTNode node = mirroeView(root);
        preorder(node);
        System.out.println();
        inorder(node);
        System.out.println();
        postorder(node);
        System.out.println();
    }

    private BSTNode mirroeView(BSTNode node) {
        if (node == null || (node.left == null && node.rigth == null))
            return node;

        BSTNode temp = node.left;
        node.left = node.rigth;
        node.rigth = temp;

        mirroeView(node.left);
        mirroeView(node.rigth);
        return node;
    }

    public void preorder() {
        preorder(root);
    }

    private void preorder(BSTNode node) {
        if (node != null) {
            System.out.print(node.data + " ");
            preorder(node.left);
            preorder(node.rigth);
        }
    }

    public void inorder() {
        inorder(root);
    }

    private void inorder(BSTNode node) {
        if (node != null) {
            inorder(node.left);
            System.out.print(node.data + " ");
            inorder(node.rigth);
        }
    }

    public void postorder() {
        postorder(root);
    }

    private void postorder(BSTNode node) {
        if (node != null) {
            postorder(node.left);
            postorder(node.rigth);
            System.out.print(node.data + " ");
        }
    }

    public boolean empty() {
        return root == null;
    }

}

public class BinarySearchTreeTest {
    public static void main(String[] l) {
        System.out.println("Weleome to Binary Search Tree");
        Scanner scanner = new Scanner(System.in);
        boolean yes = true;
        BinarySearchTree tree = new BinarySearchTree();
        do {
            System.out.println("\n1. Insert");
            System.out.println("2. Search Node");
            System.out.println("3. Count Node");
            System.out.println("4. Empty Status");
            System.out.println("5. Delete Node");
            System.out.println("6. Node with Minimum Value");
            System.out.println("7. Node with Maximum Value");
            System.out.println("8. Find Parent node");
            System.out.println("9. Count no of links");
            System.out.println("10. Get the sibling of any node");
            System.out.println("11. Print all the leaf node");
            System.out.println("12. Get the level of node");
            System.out.println("13. Depth of the tree");
            System.out.println("14. Height of Binary Tree");
            System.out.println("15. Left View");
            System.out.println("16. Mirror Image of Binary Tree");
            System.out.println("Enter Your Choice :: ");
            int choice = scanner.nextInt();
            switch (choice) {
            case 1:
                try {
                    System.out.println("Enter Value");
                    tree.insert(scanner.nextInt());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 2:
                System.out.println("Enter the node");
                System.out.println(tree.searchNode(scanner.nextInt()));
                break;

            case 3:
                System.out.println(tree.countNodes());
                break;

            case 4:
                System.out.println(tree.empty());
                break;

            case 5:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.delete(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }

            case 6:
                try {
                    System.out.println(tree.nodeWithMinimumValue());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 7:
                try {
                    System.out.println(tree.nodewithMaximumValue());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 8:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.parent(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 9:
                try {
                    System.out.println(tree.countNodes() - 1);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 10:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.sibling(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 11:
                try {
                    tree.leafNodes();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }

            case 12:
                try {
                    System.out.println("Enter the node");
                    System.out.println("Level is : " + tree.level(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 13:
                try {
                    System.out.println(tree.depth());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 14:
                try {
                    System.out.println(tree.height());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 15:
                try {
                    tree.leftView();
                    System.out.println();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 16:
                try {
                    tree.mirroeView();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            default:
                break;
            }
            tree.preorder();
            System.out.println();
            tree.inorder();
            System.out.println();
            tree.postorder();
        } while (yes);
        scanner.close();
    }
}

How do I set session timeout of greater than 30 minutes

Setting the timeout in the web.xml is the correct way to set the timeout.

How can I make a weak protocol reference in 'pure' Swift (without @objc)

Supplemental Answer

I was always confused about whether delegates should be weak or not. Recently I've learned more about delegates and when to use weak references, so let me add some supplemental points here for the sake of future viewers.

  • The purpose of using the weak keyword is to avoid strong reference cycles (retain cycles). Strong reference cycles happen when two class instances have strong references to each other. Their reference counts never go to zero so they never get deallocated.

  • You only need to use weak if the delegate is a class. Swift structs and enums are value types (their values are copied when a new instance is made), not reference types, so they don't make strong reference cycles.

  • weak references are always optional (otherwise you would used unowned) and always use var (not let) so that the optional can be set to nil when it is deallocated.

  • A parent class should naturally have a strong reference to its child classes and thus not use the weak keyword. When a child wants a reference to its parent, though, it should make it a weak reference by using the weak keyword.

  • weak should be used when you want a reference to a class that you don't own, not just for a child referencing its parent. When two non-hierarchical classes need to reference each other, choose one to be weak. The one you choose depends on the situation. See the answers to this question for more on this.

  • As a general rule, delegates should be marked as weak because most delegates are referencing classes that they do not own. This is definitely true when a child is using a delegate to communicate with a parent. Using a weak reference for the delegate is what the documentation recommends. (But see this, too.)

  • Protocols can be used for both reference types (classes) and value types (structs, enums). So in the likely case that you need to make a delegate weak, you have to make it an object-only protocol. The way to do that is to add AnyObject to the protocol's inheritance list. (In the past you did this using the class keyword, but AnyObject is preferred now.)

    protocol MyClassDelegate: AnyObject {
        // ...
    }
    
    class SomeClass {
        weak var delegate: MyClassDelegate?
    }
    

Further Study

Reading the following articles is what helped me to understand this much better. They also discuss related issues like the unowned keyword and the strong reference cycles that happen with closures.

Related

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize

in case some one still get this kind of message. Its happen because you add JVM argument when running maven project. Because it is related with maven you can check your pom.xml file on your project.

find this line <argLine>...</argLine>, on my project I also have argument below

<argLine>-Xmx1024m -XX:MaxPermSize=512m -XX:+TieredCompilation -XX:TieredStopAtLevel=1</argLine>

you should replace MaxPermSize argument as -Xms123m -Xmx123m, since MaxPermSize is already deprecated and wont take any effect on your JVM config :

<argLine>-Xms512m -Xmx512m  -XX:+TieredCompilation -XX:TieredStopAtLevel=1</argLine>

How to use Simple Ajax Beginform in Asp.net MVC 4?

All This Work :)

Model

  public partial class ClientMessage
    {
        public int IdCon { get; set; } 
        public string Name { get; set; }
        public string Email { get; set; }  
    }

Controller

   public class TestAjaxBeginFormController : Controller{  

 projectNameEntities db = new projectNameEntities();

        public ActionResult Index(){  
            return View();
        }

        [HttpPost] 
        public ActionResult GetClientMessages(ClientMessage Vm) {
            var model = db.ClientMessages.Where(x => x.Name.Contains(Vm.Name));
            return PartialView("_PartialView", model);
        } 
}

View index.cshtml

@model  projectName.Models.ClientMessage 
@{ 
    Layout = null;
}

<script src="~/Scripts/jquery-1.9.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script>
    //\\\\\\\ JS  retrun message SucccessPost or FailPost
    function SuccessMessage() {
        alert("Succcess Post");
    }
    function FailMessage() {
        alert("Fail Post");
    } 
</script>

<h1>Page Index</h1> 

@using (Ajax.BeginForm("GetClientMessages", "TestAjaxBeginForm", null , new AjaxOptions
{
    HttpMethod = "POST",
    OnSuccess = "SuccessMessage",
    OnFailure = "FailMessage" ,
    UpdateTargetId = "resultTarget"  
}, new { id = "MyNewNameId" })) // set new Id name for  Form
{
    @Html.AntiForgeryToken()

    @Html.EditorFor(x => x.Name) 
     <input type="submit" value="Search" /> 

}


<div id="resultTarget">  </div>

View _PartialView.cshtml

@model  IEnumerable<projectName.Models.ClientMessage >
<table> 

@foreach (var item in Model) { 

    <tr> 
        <td>@Html.DisplayFor(modelItem => item.IdCon)</td>
        <td>@Html.DisplayFor(modelItem => item.Name)</td>
        <td>@Html.DisplayFor(modelItem => item.Email)</td>
    </tr>

}

</table>

How to use ESLint with Jest

ESLint supports this as of version >= 4:

/*
.eslintrc.js
*/
const ERROR = 2;
const WARN = 1;

module.exports = {
  extends: "eslint:recommended",
  env: {
    es6: true
  },
  overrides: [
    {
      files: [
        "**/*.test.js"
      ],
      env: {
        jest: true // now **/*.test.js files' env has both es6 *and* jest
      },
      // Can't extend in overrides: https://github.com/eslint/eslint/issues/8813
      // "extends": ["plugin:jest/recommended"]
      plugins: ["jest"],
      rules: {
        "jest/no-disabled-tests": "warn",
        "jest/no-focused-tests": "error",
        "jest/no-identical-title": "error",
        "jest/prefer-to-have-length": "warn",
        "jest/valid-expect": "error"
      }
    }
  ],
};

Here is a workaround (from another answer on here, vote it up!) for the "extend in overrides" limitation of eslint config :

overrides: [
  Object.assign(
    {
      files: [ '**/*.test.js' ],
      env: { jest: true },
      plugins: [ 'jest' ],
    },
    require('eslint-plugin-jest').configs.recommended
  )
]

From https://github.com/eslint/eslint/issues/8813#issuecomment-320448724

Failed Apache2 start, no error log

If we have no entries in log files then we can try to debug apache2 using this command:

$ apache2 -S

or

$ apache2 -e debug

Possible output:

[Fri Apr 05 04:04:59.682880 2019] [core:warn] [pid 11086] AH00111: Config variable ${APACHE_RUN_DIR} is not defined
apache2: Syntax error on line 80 of /etc/apache2/apache2.conf: DefaultRuntimeDir must be a valid directory, absolute or relative to ServerRoot

On Selenium WebDriver how to get Text from Span Tag

String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']/div[1]/span));

kk.getText().toString();

System.out.println(+kk.getText().toString());

Create SQL identity as primary key?

This is similar to the scripts we generate on our team. Create the table first, then apply pk/fk and other constraints.

CREATE TABLE [dbo].[ImagenesUsuario] (
    [idImagen] [int] IDENTITY (1, 1) NOT NULL
)

ALTER TABLE [dbo].[ImagenesUsuario] ADD 
    CONSTRAINT [PK_ImagenesUsuario] PRIMARY KEY  CLUSTERED 
    (
        [idImagen]
    )  ON [PRIMARY] 

setting request headers in selenium

check this out: chrome_options = Options()

chrome_options.add_argument('--headless')
chrome_options.add_argument('user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"')

Problem solved!

How to do the Recursive SELECT query in MySQL?

leftclickben answer worked for me, but I wanted a path from a given node back up the tree to the root, and these seemed to be going the other way, down the tree. So, I had to flip some of the fields around and renamed for clarity, and this works for me, in case this is what anyone else wants too--

item | parent
-------------
1    | null
2    | 1
3    | 1
4    | 2
5    | 4
6    | 3

and

select t.item_id as item, @pv:=t.parent as parent
from (select * from item_tree order by item_id desc) t
join
(select @pv:=6)tmp
where t.item_id=@pv;

gives:

item | parent
-------------
6    | 3
3    | 1
1    | null

how to save and read array of array in NSUserdefaults in swift?

Here is:

var array : [String] = ["One", "Two", "Three"]
let userDefault = UserDefaults.standard
// set
userDefault.set(array, forKey: "array")
// retrieve 
if let fetchArray = userDefault.array(forKey: "array") as? [String] {
    // code 
}

Create a jTDS connection string

SQLServer runs the default instance over port 1433. If you specify the port as port 1433, SQLServer will only look for the default instance. The name of the default instance was created at setup and usually is SQLEXPRESSxxx_xx_ENU.

The instance name also matches the folder name created in Program Files -> Microsoft SQL Server. So if you look there and see one folder named SQLEXPRESSxxx_xx_ENU it is the default instance.

Folders named MSSQL12.myInstanceName (for SQLServer 2012) are named instances in SQL Server and are not accessed via port 1433.

So if your program is accessing a default instance in the database, specify port 1433, and you may not need to specify the instance name.

If your program is accessing a named instance (not the default instance) in the database DO NOT specify the port but you must specify the instance name.

I hope this clarifies some of the confusion emanating from the errors above.

Display all post meta keys and meta values of the same post ID in wordpress

$myvals = get_post_meta( get_the_ID());
foreach($myvals as $key=>$val){
  foreach($val as $vals){
    if ($key=='Youtube'){
       echo $vals 
    }
   }
 }

Key = Youtube videos all meta keys for youtube videos and value

Calculating Covariance with Python and Numpy

Thanks to unutbu for the explanation. By default numpy.cov calculates the sample covariance. To obtain the population covariance you can specify normalisation by the total N samples like this:

Covariance = numpy.cov(a, b, bias=True)[0][1]
print(Covariance)

or like this:

Covariance = numpy.cov(a, b, ddof=0)[0][1]
print(Covariance)

Function to Calculate Median in SQL Server

In a UDF, write:

 Select Top 1 medianSortColumn from Table T
  Where (Select Count(*) from Table
         Where MedianSortColumn <
           (Select Count(*) From Table) / 2)
  Order By medianSortColumn

Postgres: How to do Composite keys?

Your compound PRIMARY KEY specification already does what you want. Omit the line that's giving you a syntax error, and omit the redundant CONSTRAINT (already implied), too:

 CREATE TABLE tags
      (
               question_id INTEGER NOT NULL,
               tag_id SERIAL NOT NULL,
               tag1 VARCHAR(20),
               tag2 VARCHAR(20),
               tag3 VARCHAR(20),
               PRIMARY KEY(question_id, tag_id)
      );

NOTICE:  CREATE TABLE will create implicit sequence "tags_tag_id_seq" for serial column "tags.tag_id"
    NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "tags_pkey" for table "tags"
    CREATE TABLE
    pg=> \d tags
                                         Table "public.tags"
       Column    |         Type          |                       Modifiers       
    -------------+-----------------------+-------------------------------------------------------
     question_id | integer               | not null
     tag_id      | integer               | not null default nextval('tags_tag_id_seq'::regclass)
     tag1        | character varying(20) |
     tag2        | character varying(20) |
     tag3        | character varying(20) |
    Indexes:
        "tags_pkey" PRIMARY KEY, btree (question_id, tag_id)

Correct MySQL configuration for Ruby on Rails Database.yml file

You also can do like this:

default: &default
  adapter: mysql2
  encoding: utf8
  username: root
  password:
  host: 127.0.0.1
  port: 3306

development:
  <<: *default
  database: development_db_name

test:
  <<: *default
  database: test_db_name

production:
  <<: *default
  database: production_db_name

jquery: change the URL address without redirecting?

NOTE: history.pushState() is now supported - see other answers.

You cannot change the whole url without redirecting, what you can do instead is change the hash.

The hash is the part of the url that goes after the # symbol. That was initially intended to direct you (locally) to sections of your HTML document, but you can read and modify it through javascript to use it somewhat like a global variable.


If applied well, this technique is useful in two ways:

  1. the browser history will remember each different step you took (since the url+hash changed)
  2. you can have an address which links not only to a particular html document, but also gives your javascript a clue about what to do. That means you end up pointing to a state inside your web app.

To change the hash you can do:

document.location.hash = "show_picture";

To watch for hash changes you have to do something like:

window.onhashchange = function(){
    var what_to_do = document.location.hash;    
    if (what_to_do=="#show_picture")
        show_picture();
}

Of course the hash is just a string, so you can do pretty much what you like with it. For example you can put a whole object there if you use JSON to stringify it.

There are very good JQuery libraries to do advanced things with that.

How to restart Jenkins manually?

jenkins_url/restart is the safest way of doing it.

For service- Service Jenkins restart.

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

I solved this problem by adding following code into my /etc/my.cnf file -

enter image description here

[client]
default-character-set=utf8

[mysql]
default-character-set=utf8


[mysqld]
collation-server = utf8_unicode_ci
character-set-server = utf8

After saving that,I went into my system settings and stopped MYSQL server and started again, and it worked.

What's the CMake syntax to set and use variables?

When writing CMake scripts there is a lot you need to know about the syntax and how to use variables in CMake.

The Syntax

Strings using set():

  • set(MyString "Some Text")
  • set(MyStringWithVar "Some other Text: ${MyString}")
  • set(MyStringWithQuot "Some quote: \"${MyStringWithVar}\"")

Or with string():

  • string(APPEND MyStringWithContent " ${MyString}")

Lists using set():

  • set(MyList "a" "b" "c")
  • set(MyList ${MyList} "d")

Or better with list():

  • list(APPEND MyList "a" "b" "c")
  • list(APPEND MyList "d")

Lists of File Names:

  • set(MySourcesList "File.name" "File with Space.name")
  • list(APPEND MySourcesList "File.name" "File with Space.name")
  • add_excutable(MyExeTarget ${MySourcesList})

The Documentation

The Scope or "What value does my variable have?"

First there are the "Normal Variables" and things you need to know about their scope:

  • Normal variables are visible to the CMakeLists.txt they are set in and everything called from there (add_subdirectory(), include(), macro() and function()).
  • The add_subdirectory() and function() commands are special, because they open-up their own scope.
    • Meaning variables set(...) there are only visible there and they make a copy of all normal variables of the scope level they are called from (called parent scope).
    • So if you are in a sub-directory or a function you can modify an already existing variable in the parent scope with set(... PARENT_SCOPE)
    • You can make use of this e.g. in functions by passing the variable name as a function parameter. An example would be function(xyz _resultVar) is setting set(${_resultVar} 1 PARENT_SCOPE)
  • On the other hand everything you set in include() or macro() scripts will modify variables directly in the scope of where they are called from.

Second there is the "Global Variables Cache". Things you need to know about the Cache:

  • If no normal variable with the given name is defined in the current scope, CMake will look for a matching Cache entry.
  • Cache values are stored in the CMakeCache.txt file in your binary output directory.
  • The values in the Cache can be modified in CMake's GUI application before they are generated. Therefore they - in comparison to normal variables - have a type and a docstring. I normally don't use the GUI so I use set(... CACHE INTERNAL "") to set my global and persistant values.

    Please note that the INTERNAL cache variable type does imply FORCE

  • In a CMake script you can only change existing Cache entries if you use the set(... CACHE ... FORCE) syntax. This behavior is made use of e.g. by CMake itself, because it normally does not force Cache entries itself and therefore you can pre-define it with another value.

  • You can use the command line to set entries in the Cache with the syntax cmake -D var:type=value, just cmake -D var=value or with cmake -C CMakeInitialCache.cmake.
  • You can unset entries in the Cache with unset(... CACHE).

The Cache is global and you can set them virtually anywhere in your CMake scripts. But I would recommend you think twice about where to use Cache variables (they are global and they are persistant). I normally prefer the set_property(GLOBAL PROPERTY ...) and set_property(GLOBAL APPEND PROPERTY ...) syntax to define my own non-persistant global variables.

Variable Pitfalls and "How to debug variable changes?"

To avoid pitfalls you should know the following about variables:

  • Local variables do hide cached variables if both have the same name
  • The find_... commands - if successful - do write their results as cached variables "so that no call will search again"
  • Lists in CMake are just strings with semicolons delimiters and therefore the quotation-marks are important
    • set(MyVar a b c) is "a;b;c" and set(MyVar "a b c") is "a b c"
    • The recommendation is that you always use quotation marks with the one exception when you want to give a list as list
    • Generally prefer the list() command for handling lists
  • The whole scope issue described above. Especially it's recommended to use functions() instead of macros() because you don't want your local variables to show up in the parent scope.
  • A lot of variables used by CMake are set with the project() and enable_language() calls. So it could get important to set some variables before those commands are used.
  • Environment variables may differ from where CMake generated the make environment and when the the make files are put to use.
    • A change in an environment variable does not re-trigger the generation process.
    • Especially a generated IDE environment may differ from your command line, so it's recommended to transfer your environment variables into something that is cached.

Sometimes only debugging variables helps. The following may help you:

  • Simply use old printf debugging style by using the message() command. There also some ready to use modules shipped with CMake itself: CMakePrintHelpers.cmake, CMakePrintSystemInformation.cmake
  • Look into CMakeCache.txt file in your binary output directory. This file is even generated if the actual generation of your make environment fails.
  • Use variable_watch() to see where your variables are read/written/removed.
  • Look into the directory properties CACHE_VARIABLES and VARIABLES
  • Call cmake --trace ... to see the CMake's complete parsing process. That's sort of the last reserve, because it generates a lot of output.

Special Syntax

  • Environment Variables
    • You can can read $ENV{...} and write set(ENV{...} ...) environment variables
  • Generator Expressions
    • Generator expressions $<...> are only evaluated when CMake's generator writes the make environment (it comparison to normal variables that are replaced "in-place" by the parser)
    • Very handy e.g. in compiler/linker command lines and in multi-configuration environments
  • References
    • With ${${...}} you can give variable names in a variable and reference its content.
    • Often used when giving a variable name as function/macro parameter.
  • Constant Values (see if() command)
    • With if(MyVariable) you can directly check a variable for true/false (no need here for the enclosing ${...})
    • True if the constant is 1, ON, YES, TRUE, Y, or a non-zero number.
    • False if the constant is 0, OFF, NO, FALSE, N, IGNORE, NOTFOUND, the empty string, or ends in the suffix -NOTFOUND.
    • This syntax is often use for something like if(MSVC), but it can be confusing for someone who does not know this syntax shortcut.
  • Recursive substitutions
    • You can construct variable names using variables. After CMake has substituted the variables, it will check again if the result is a variable itself. This is very powerful feature used in CMake itself e.g. as sort of a template set(CMAKE_${lang}_COMPILER ...)
    • But be aware this can give you a headache in if() commands. Here is an example where CMAKE_CXX_COMPILER_ID is "MSVC" and MSVC is "1":
      • if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") is true, because it evaluates to if("1" STREQUAL "1")
      • if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") is false, because it evaluates to if("MSVC" STREQUAL "1")
      • So the best solution here would be - see above - to directly check for if(MSVC)
    • The good news is that this was fixed in CMake 3.1 with the introduction of policy CMP0054. I would recommend to always set cmake_policy(SET CMP0054 NEW) to "only interpret if() arguments as variables or keywords when unquoted."
  • The option() command
    • Mainly just cached strings that only can be ON or OFF and they allow some special handling like e.g. dependencies
    • But be aware, don't mistake the option with the set command. The value given to option is really only the "initial value" (transferred once to the cache during the first configuration step) and is afterwards meant to be changed by the user through CMake's GUI.

References

What is the best way to iterate over a dictionary?

I appreciate this question has already had a lot of responses but I wanted to throw in a little research.

Iterating over a dictionary can be rather slow when compared with iterating over something like an array. In my tests an iteration over an array took 0.015003 seconds whereas an iteration over a dictionary (with the same number of elements) took 0.0365073 seconds that's 2.4 times as long! Although I have seen much bigger differences. For comparison a List was somewhere in between at 0.00215043 seconds.

However, that is like comparing apples and oranges. My point is that iterating over dictionaries is slow.

Dictionaries are optimised for lookups, so with that in mind I've created two methods. One simply does a foreach, the other iterates the keys then looks up.

public static string Normal(Dictionary<string, string> dictionary)
{
    string value;
    int count = 0;
    foreach (var kvp in dictionary)
    {
        value = kvp.Value;
        count++;
    }

    return "Normal";
}

This one loads the keys and iterates over them instead (I did also try pulling the keys into a string[] but the difference was negligible.

public static string Keys(Dictionary<string, string> dictionary)
{
    string value;
    int count = 0;
    foreach (var key in dictionary.Keys)
    {
        value = dictionary[key];
        count++;
    }

    return "Keys";
}

With this example the normal foreach test took 0.0310062 and the keys version took 0.2205441. Loading all the keys and iterating over all the lookups is clearly a LOT slower!

For a final test I've performed my iteration ten times to see if there are any benefits to using the keys here (by this point I was just curious):

Here's the RunTest method if that helps you visualise what's going on.

private static string RunTest<T>(T dictionary, Func<T, string> function)
{            
    DateTime start = DateTime.Now;
    string name = null;
    for (int i = 0; i < 10; i++)
    {
        name = function(dictionary);
    }
    DateTime end = DateTime.Now;
    var duration = end.Subtract(start);
    return string.Format("{0} took {1} seconds", name, duration.TotalSeconds);
}

Here the normal foreach run took 0.2820564 seconds (around ten times longer than a single iteration took - as you'd expect). The iteration over the keys took 2.2249449 seconds.

Edited To Add: Reading some of the other answers made me question what would happen if I used Dictionary instead of Dictionary. In this example the array took 0.0120024 seconds, the list 0.0185037 seconds and the dictionary 0.0465093 seconds. It's reasonable to expect that the data type makes a difference on how much slower the dictionary is.

What are my Conclusions?

  • Avoid iterating over a dictionary if you can, they are substantially slower than iterating over an array with the same data in it.
  • If you do choose to iterate over a dictionary don't try to be too clever, although slower you could do a lot worse than using the standard foreach method.

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:

x = ["0", "1", "2"] 
y = int(x[0]) #accessing the zeroth element

If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:

x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)

If your list elements are not strings, you'll have to convert them to strings before using str.join:

x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)

Also, as stated above, make sure that you're not returning a nested list.

How do I apply a diff patch on Windows?

For Java projects, I have used NetBeans to apply patch files. If the Java code you are patching is not already a NetBeans project, create a project for it. To create a new project:

  • Select menu File -> New Project
  • In the resulting dialog, make it a Java Application project. Give it a name in the dialog, and click Finish.
  • Right-click the name of your project, and select Properties from the context menu
  • In the resulting dialog, select Sources, and add a Source Folder. Browse to your Java source.

Now that you have a project, apply the patch:

  • Highlight your project to select it
  • From the main menu, select menu Tools -> Apply Diff Patch
  • In the resulting dialog, browse to your patch file, select it, and press the Patch button.

That's it. Your patch should be applied, and you should see a diff window showing the changes.

Html ordered list 1.1, 1.2 (Nested counters and scope) not working

After going through other answers I came up with this, just apply class nested-counter-list to root ol tag:

sass code:

ol.nested-counter-list {
  counter-reset: item;

  li {
    display: block;

    &::before {
      content: counters(item, ".") ". ";
      counter-increment: item;
      font-weight: bold;
    }
  }

  ol {
    counter-reset: item;

    & > li {
      display: block;

      &::before {
        content: counters(item, ".") " ";
        counter-increment: item;
        font-weight: bold;
      }
    }
  }
}

css code:

ol.nested-counter-list {
  counter-reset: item;
}
ol.nested-counter-list li {
  display: block;
}
ol.nested-counter-list li::before {
  content: counters(item, ".") ". ";
  counter-increment: item;
  font-weight: bold;
}
ol.nested-counter-list ol {
  counter-reset: item;
}
ol.nested-counter-list ol > li {
  display: block;
}
ol.nested-counter-list ol > li::before {
  content: counters(item, ".") " ";
  counter-increment: item;
  font-weight: bold;
}

_x000D_
_x000D_
ol.nested-counter-list {
  counter-reset: item;
}

ol.nested-counter-list li {
  display: block;
}

ol.nested-counter-list li::before {
  content: counters(item, ".") ". ";
  counter-increment: item;
  font-weight: bold;
}

ol.nested-counter-list ol {
  counter-reset: item;
}

ol.nested-counter-list ol>li {
  display: block;
}

ol.nested-counter-list ol>li::before {
  content: counters(item, ".") " ";
  counter-increment: item;
  font-weight: bold;
}
_x000D_
<ol class="nested-counter-list">
  <li>one</li>
  <li>two
    <ol>
      <li>two.one</li>
      <li>two.two</li>
      <li>two.three</li>
    </ol>
  </li>
  <li>three
    <ol>
      <li>three.one</li>
      <li>three.two
        <ol>
          <li>three.two.one</li>
          <li>three.two.two</li>
        </ol>
      </li>
    </ol>
  </li>
  <li>four</li>
</ol>
_x000D_
_x000D_
_x000D_

And if you need trailing . at the end of the nested list's counters use this:

_x000D_
_x000D_
ol.nested-counter-list {
  counter-reset: item;
}

ol.nested-counter-list li {
  display: block;
}

ol.nested-counter-list li::before {
  content: counters(item, ".") ". ";
  counter-increment: item;
  font-weight: bold;
}

ol.nested-counter-list ol {
  counter-reset: item;
}
_x000D_
<ol class="nested-counter-list">
  <li>one</li>
  <li>two
    <ol>
      <li>two.one</li>
      <li>two.two</li>
      <li>two.three</li>
    </ol>
  </li>
  <li>three
    <ol>
      <li>three.one</li>
      <li>three.two
        <ol>
          <li>three.two.one</li>
          <li>three.two.two</li>
        </ol>
      </li>
    </ol>
  </li>
  <li>four</li>
</ol>
_x000D_
_x000D_
_x000D_

An internal error occurred during: "Updating Maven Project". java.lang.NullPointerException

I had the same issue ... solution at the end !

here the eclipse log:

java.lang.NullPointerException
    at com.google.appengine.eclipse.wtp.maven.GaeRuntimeManager.getGaeRuntime(GaeRuntimeManager.java:85)
    at com.google.appengine.eclipse.wtp.maven.GaeRuntimeManager.ensureGaeRuntimeWithSdk(GaeRuntimeManager.java:55)
    at com.google.appengine.eclipse.wtp.maven.GaeFacetManager.addGaeFacet(GaeFacetManager.java:59)
    at com.google.appengine.eclipse.wtp.maven.GaeProjectConfigurator.configure(GaeProjectConfigurator.java:46)

... it comes from "appengine maven wtp plugin" that try to get the type of GAE runtime, but seems to be null here (... getRuntimeType() --> NPE):

see class com.google.appengine.eclipse.wtp.maven/GaeRuntimeManager.java

  private static IRuntime getGaeRuntime(String sdkVersion) {
    IRuntime[] runtimes = ServerCore.getRuntimes();
    for (IRuntime runtime : runtimes) {
      if (runtime != null &&  **runtime.getRuntimeType()**.equals(GAE_RUNTIME_TYPE)) {

So, if you check in eclipse, Google App Engine is visible , but when you select it you'll see that no SDK is associated ... preference/Server/Runtime environments

SOLUTION: in red on the screenshot ;-)

C# Copy a file to another location with a different name

You can use the Copy method in the System.IO.File class.

What is the best way to test for an empty string with jquery-out-of-the-box?

Try executing this in your browser console or in a node.js repl.

var string = ' ';
string ? true : false;
//-> true

string = '';
string ? true : false;
//-> false

Therefore, a simple branching construct will suffice for the test.

if(string) {
    // string is not empty
}

PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

Find the ANDROID_HOME path values from environment variable. In my case it is like C:\Users\RuwanPr\AppData\Local\Android\Sdk. If this value not found please add ANDROID_HOME value as your sdk path. (To go to environment variable right click on my computer -> Properties -> Advance System Settings -> Environment Variable ) Then open cmd on windows and go to sdk folder and then go to tools folder Type emulator -list-avds in comd. It will shows avd name list. Then type emulator -avd avd-name. Ex - think avd-name shows as J2_Api_22 emulator -avd J2_Api_22

How to render a DateTime object in a Twig template

Although you can use the

{{ game.gameDate|date('Y-m-d') }}

approach, keep in mind that this version does not honor the user locale, which should not be a problem with a site used by only users of one nationality. International users should display the game date totally different, like extending the \DateTime class, and adding a __toString() method to it that checks the locale and acts accordingly.

Edit:

As pointed out by @Nic in a comment, if you use the Intl extension of Twig, you will have a localizeddate filter available, which shows the date in the user’s locale. This way you can drop my previous idea of extending \DateTime.

Notepad++ Regular expression find and delete a line

Provide the following in the search dialog:

Find What: ^$\r\n
Replace With: (Leave it empty)

Click Replace All

Call int() function on every list element?

Thought I'd consolidate the answers and show some timeit results.

Python 2 sucks pretty bad at this, but map is a bit faster than comprehension.

Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> setup = """import random
random.seed(10)
l = [str(random.randint(0, 99)) for i in range(100)]"""
>>> timeit.timeit('[int(v) for v in l]', setup)
116.25092001434314
>>> timeit.timeit('map(int, l)', setup)
106.66044823117454

Python 3 is over 4x faster by itself, but converting the map generator object to a list is still faster than comprehension, and creating the list by unpacking the map generator (thanks Artem!) is slightly faster still.

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> setup = """import random
random.seed(10)
l = [str(random.randint(0, 99)) for i in range(100)]"""
>>> timeit.timeit('[int(v) for v in l]', setup)
25.133059591551955
>>> timeit.timeit('list(map(int, l))', setup)
19.705547827217515
>>> timeit.timeit('[*map(int, l)]', setup)
19.45838406513076

Note: In Python 3, 4 elements seems to be the crossover point (3 in Python 2) where comprehension is slightly faster, though unpacking the generator is still faster than either for lists with more than 1 element.

How do I run Java .class files?

To run Java class file from the command line, the syntax is:

java -classpath /path/to/jars <packageName>.<MainClassName>

where packageName (usually starts with either com or org) is the folder name where your class file is present.

For example if your main class name is App and Java package name of your app is com.foo.app, then your class file needs to be in com/foo/app folder (separate folder for each dot), so you run your app as:

$ java com.foo.app.App

Note: $ is indicating shell prompt, ignore it when typing

If your class doesn't have any package name defined, simply run as: java App.

If you've any other jar dependencies, make sure you specified your classpath parameter either with -cp/-classpath or using CLASSPATH variable which points to the folder with your jar/war/ear/zip/class files. So on Linux you can prefix the command with: CLASSPATH=/path/to/jars, on Windows you need to add the folder into system variable. If not set, the user class path consists of the current directory (.).


Practical example

Given we've created sample project using Maven as:

$ mvn archetype:generate -DgroupId=com.foo.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false 

and we've compiled our project by mvn compile in our my-app/ dir, it'll generate our class file is in target/classes/com/foo/app/App.class.

To run it, we can either specify class path via -cp or going to it directly, check examples below:

$ find . -name "*.class"
./target/classes/com/foo/app/App.class
$ CLASSPATH=target/classes/ java com.foo.app.App
Hello World!
$ java -cp target/classes com.foo.app.App
Hello World!
$ java -classpath .:/path/to/other-jars:target/classes com.foo.app.App
Hello World!
$ cd target/classes && java com.foo.app.App
Hello World!

To double check your class and package name, you can use Java class file disassembler tool, e.g.:

$ javap target/classes/com/foo/app/App.class
Compiled from "App.java"
public class com.foo.app.App {
  public com.foo.app.App();
  public static void main(java.lang.String[]);
}

Note: javap won't work if the compiled file has been obfuscated.

SQL server ignore case in a where expression

I found another solution elsewhere; that is, to use

upper(@yourString)

but everyone here is saying that, in SQL Server, it doesn't matter because it's ignoring case anyway? I'm pretty sure our database is case-sensitive.

Chrome Dev Tools - Modify javascript and reload

Yes, just open the "Source" Tab in the dev-tools and navigate to the script you want to change . Make your adjustments directly in the dev tools window and then hit ctrl+s to save the script - know the new js will be used until you refresh the whole page.

Why can templates only be implemented in the header file?

Just to add something noteworthy here. One can define methods of a templated class just fine in the implementation file when they are not function templates.


myQueue.hpp:

template <class T> 
class QueueA {
    int size;
    ...
public:
    template <class T> T dequeue() {
       // implementation here
    }

    bool isEmpty();

    ...
}    

myQueue.cpp:

// implementation of regular methods goes like this:
template <class T> bool QueueA<T>::isEmpty() {
    return this->size == 0;
}


main()
{
    QueueA<char> Q;

    ...
}

Attach a body onload event with JS

Cross browser window.load event

function load(){}

window[ addEventListener ? 'addEventListener' : 'attachEvent' ]( addEventListener ? 'load' : 'onload', load )

Binding a generic list to a repeater - ASP.NET

You may want to create a subRepeater.

<asp:Repeater ID="SubRepeater" runat="server" DataSource='<%# Eval("Fields") %>'>
  <ItemTemplate>
    <span><%# Eval("Name") %></span>
  </ItemTemplate>
</asp:Repeater>

You can also cast your fields

<%# ((ArrayFields)Container.DataItem).Fields[0].Name %>

Finally you could do a little CSV Function and write out your fields with a function

<%# GetAsCsv(((ArrayFields)Container.DataItem).Fields) %>

public string GetAsCsv(IEnumerable<Fields> fields)
{
  var builder = new StringBuilder();
  foreach(var f in fields)
  {
    builder.Append(f);
    builder.Append(",");
  }
  builder.Remove(builder.Length - 1);
  return builder.ToString();
}

How can I center an image in Bootstrap?

Three ways to align img in the center of its parent.

  1. img is an inline element, text-center aligns inline elements in the center of its container should the container be a block element.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
  <div class="row">_x000D_
    <div class="col text-center">_x000D_
      <img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  1. mx-auto centers block elements. In order to so, change display of the img from inline to block with d-block class.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
  <div class="row">_x000D_
    <div class="col">_x000D_
      <img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid d-block mx-auto">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  1. Use d-flex and justify-content-center on its parent.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
  <div class="row">_x000D_
    <div class="col d-flex justify-content-center">_x000D_
      <img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What does .pack() do?

The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.

From Java tutorial

You should also refer to Javadocs any time you need additional information on any Java API

JQuery / JavaScript - trigger button click from another button click event

By using JavaScript: document.getElementById("myBtn").click();

127 Return code from $?

If the IBM mainframe JCL has some extra characters or numbers at the end of the name of unix script being called then it can throw such error.

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

The second step of mongo installation is

echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list

Instead of this command do it manually

  1. cd /etc/apt/
  2. nano sources.list
  3. Write it deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4 multiverse

And save the file,

Continue all process as in installation docs

It works for me:

Why can't I do <img src="C:/localfile.jpg">?

If you're deploying a local website just for yourself or certain clients, you can get around this by running mklink /D MyImages "C:/MyImages" in the website root directory as an admin in cmd. Then in the html, do <img src="MyImages/whatever.jpg"> and the symbolic link established by mklink will connect the relative src link with the link on your C drive. It solved this issue for me, so it may help others who come to this question.

(Obviously this won't work for public websites since you can't run cmd commands on people's computers easily)

Is it possible to view RabbitMQ message contents directly from the command line?

You should enable the management plugin.

rabbitmq-plugins enable rabbitmq_management

See here:

http://www.rabbitmq.com/plugins.html

And here for the specifics of management.

http://www.rabbitmq.com/management.html

Finally once set up you will need to follow the instructions below to install and use the rabbitmqadmin tool. Which can be used to fully interact with the system. http://www.rabbitmq.com/management-cli.html

For example:

rabbitmqadmin get queue=<QueueName> requeue=false

will give you the first message off the queue.

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.`

For me the issue got resolved by doing the following:

Navigated to Tool --> Options --> Project and Solutions --> Web Projects

I could find the first check box "Use the 64 bit version of IIS Express of web sites and projects" was unchecked.

Selecting this check box helped me in launching the WCF Client.

VS Version : VS2019

How to select where ID in Array Rails ActiveRecord without exception

If it is just avoiding the exception you are worried about, the "find_all_by.." family of functions works without throwing exceptions.

Comment.find_all_by_id([2, 3, 5])

will work even if some of the ids don't exist. This works in the

user.comments.find_all_by_id(potentially_nonexistent_ids)

case as well.

Update: Rails 4

Comment.where(id: [2, 3, 5])

Using the rJava package on Win7 64 bit with R

I solved the issue by uninstalling apparently redundant Java software from my windows 7 x64 machine. I achieved this by first uninstalling all Java applications and then installing a fresh Java version. (Later I pointed R 3.4.3 x86_64-w64-mingw32 to the Java path, just to mention though I don't think this was the real issue.) Today only Java 8 Update 161 (64-bit) 8.0.1610.12 was left then. After this, install.packages("rJava"); library(rJava) did work perfectly.

How can I convert a Timestamp into either Date or DateTime object?

You can also get DateTime object from timestamp, including your current daylight saving time:

public DateTime getDateTimeFromTimestamp(Long value) {
    TimeZone timeZone = TimeZone.getDefault();
    long offset = timeZone.getOffset(value);
    if (offset < 0) {
        value -= offset;
    } else {
        value += offset;
    }
    return new DateTime(value);
}    

notifyDataSetChange not working from custom adapter

My case was different but it might be the same case for others

for those who still couldn't find a solution and tried everything above, if you're using the adapter inside fragment then the reason it's not working fragment could be recreating so the adapter is recreating everytime the fragment recreate

you should verify if the adapter and objects list are null before initializing

_x000D_
_x000D_
if(adapter == null){_x000D_
  adapter = new CustomListAdapter(...);_x000D_
}_x000D_
..._x000D_
_x000D_
if(objects == null){_x000D_
  objects = new ArrayList<>();_x000D_
}
_x000D_
_x000D_
_x000D_

Replace negative values in an numpy array

Here's a way to do it in Python without NumPy. Create a function that returns what you want and use a list comprehension, or the map function.

>>> a = [1, 2, 3, -4, 5]

>>> def zero_if_negative(x):
...   if x < 0:
...     return 0
...   return x
...

>>> [zero_if_negative(x) for x in a]
[1, 2, 3, 0, 5]

>>> map(zero_if_negative, a)
[1, 2, 3, 0, 5]

"Press Any Key to Continue" function in C

Use getch():

printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getch();

Windows alternative should be _getch().

If you're using Windows, this should be the full example:

#include <conio.h>
#include <ctype.h>

int main( void )
{
    printf("Let the Battle Begin!\n");
    printf("Press Any Key to Continue\n");
    _getch();
}

P.S. as @Rörd noted, if you're on POSIX system, you need to make sure that curses library is setup right.

Difference between int32, int, int32_t, int8 and int8_t

The _t data types are typedef types in the stdint.h header, while int is an in built fundamental data type. This make the _t available only if stdint.h exists. int on the other hand is guaranteed to exist.

How to check the version of scipy

From the python command prompt:

import scipy
print scipy.__version__

In python 3 you'll need to change it to:

print (scipy.__version__)

Using Python String Formatting with Lists

The same as @neobot's answer but a little more modern and succinct.

>>> l = range(5)
>>> " & ".join(["{}"]*len(l)).format(*l)
'0 & 1 & 2 & 3 & 4'

Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7

This is what worked for me: Using Gradle 4.8.1

buildscript {
    ext.kotlin_version = '1.1.1' 
repositories {
    jcenter()
    google()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.1.0'}
}
allprojects {
    repositories {
        mavenLocal()
        jcenter()
        google()
        maven {
            url "$rootDir/../node_modules/react-native/android"
        }
    maven {
            url 'https://dl.bintray.com/kotlin/kotlin-dev/'
    }
  }
}   

What is a Python egg?

Python eggs are a way of bundling additional information with a Python project, that allows the project's dependencies to be checked and satisfied at runtime, as well as allowing projects to provide plugins for other projects. There are several binary formats that embody eggs, but the most common is '.egg' zipfile format, because it's a convenient one for distributing projects. All of the formats support including package-specific data, project-wide metadata, C extensions, and Python code.

The easiest way to install and use Python eggs is to use the "Easy Install" Python package manager, which will find, download, build, and install eggs for you; all you do is tell it the name (and optionally, version) of the Python project(s) you want to use.

Python eggs can be used with Python 2.3 and up, and can be built using the setuptools package (see the Python Subversion sandbox for source code, or the EasyInstall page for current installation instructions).

The primary benefits of Python Eggs are:

  • They enable tools like the "Easy Install" Python package manager

  • .egg files are a "zero installation" format for a Python package; no build or install step is required, just put them on PYTHONPATH or sys.path and use them (may require the runtime installed if C extensions or data files are used)

  • They can include package metadata, such as the other eggs they depend on

  • They allow "namespace packages" (packages that just contain other packages) to be split into separate distributions (e.g. zope., twisted., peak.* packages can be distributed as separate eggs, unlike normal packages which must always be placed under the same parent directory. This allows what are now huge monolithic packages to be distributed as separate components.)

  • They allow applications or libraries to specify the needed version of a library, so that you can e.g. require("Twisted-Internet>=2.0") before doing an import twisted.internet.

  • They're a great format for distributing extensions or plugins to extensible applications and frameworks (such as Trac, which uses eggs for plugins as of 0.9b1), because the egg runtime provides simple APIs to locate eggs and find their advertised entry points (similar to Eclipse's "extension point" concept).

There are also other benefits that may come from having a standardized format, similar to the benefits of Java's "jar" format.

Turn off warnings and errors on PHP and MySQL

PHP error_reporting reference:

// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

Sleep/Wait command in Batch

Ok, yup you use the timeout command to sleep. But to do the whole process silently, it's not possible with cmd/batch. One of the ways is to create a VBScript that will run the Batch File without opening/showing any window. And here is the script:

Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "PATH OF BATCH FILE WITH QUOTATION MARKS" & Chr(34), 0
Set WshShell = Nothing

Copy and paste the above code on notepad and save it as Anyname.**vbs ** An example of the *"PATH OF BATCH FILE WITH QUOTATION MARKS" * might be: "C:\ExampleFolder\MyBatchFile.bat"

How Can I Resolve:"can not open 'git-upload-pack' " error in eclipse?

to fix SSL issue you can also try doing this.

Download the NetworkSolutionsDVServerCA2.crt from the bitbucket server and add it to the ca-bundle.crt

ca-bundle.crt needs to be copied from the git install directory and copied to your home directory

cp -r git/mingw64/ssl/certs/ca-bundle.crt ~/

then do this. this worked for me cat NetworkSolutionsDVServerCA2.crt >> ca-bundle.crt

git config --global http.sslCAInfo ~/ca-bundle.crt

git config --global http.sslverify true

Sending data back to the Main Activity in Android

Call the child activity Intent using the startActivityForResult() method call

There is an example of this here: http://developer.android.com/training/notepad/notepad-ex2.html

and in the "Returning a Result from a Screen" of this: http://developer.android.com/guide/faq/commontasks.html#opennewscreen

How can I shrink the drawable on a button?

Using Kotlin Extension

val drawable = ContextCompat.getDrawable(context, R.drawable.my_icon)
// or resources.getDrawable(R.drawable.my_icon, theme)
val sizePx = 25
drawable?.setBounds(0, 0, sizePx, sizePx)
//                            (left,     top,  right, bottom)
my_button.setCompoundDrawables(drawable, null, null, null)

I suggest creating an extension function on TextView (Button extends it) for easy reuse.

button.leftDrawable(R.drawable.my_icon, 25)

// Button extends TextView
fun TextView.leftDrawable(@DrawableRes id: Int = 0, @DimenRes sizeRes: Int) {
    val drawable = ContextCompat.getDrawable(context, id)
    val size = context.resources.getDimensionPixelSize(sizeRes)
    drawable?.setBounds(0, 0, size, size)
    this.setCompoundDrawables(drawable, null, null, null)
}

How to Read from a Text File, Character by Character in C++

Assuming that temp is a char and textFile is a std::fstream derivative...

The syntax you're looking for is

textFile.get( temp );

Download a file with Android, and showing the progress in a ProgressDialog

Permissions

  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission 
   android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Using HttpURLConnection

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class DownloadFileUseHttpURLConnection extends Activity {

ProgressBar pb;
Dialog dialog;
int downloadedSize = 0;
int totalSize = 0;
TextView cur_val;
String dwnload_file_path =  
"http://coderzheaven.com/sample_folder/sample_file.png";
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button b = (Button) findViewById(R.id.b1);
    b.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
             showProgress(dwnload_file_path);

                new Thread(new Runnable() {
                    public void run() {
                         downloadFile();
                    }
                  }).start();
        }
    });
}

void downloadFile(){

    try {
        URL url = new URL(dwnload_file_path);
        HttpURLConnection urlConnection = (HttpURLConnection)   
 url.openConnection();

        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);

        //connect
        urlConnection.connect();

        //set the path where we want to save the file           
        File SDCardRoot = Environment.getExternalStorageDirectory(); 
        //create a new file, to save the downloaded file 
        File file = new File(SDCardRoot,"downloaded_file.png");

        FileOutputStream fileOutput = new FileOutputStream(file);

        //Stream used for reading the data from the internet
        InputStream inputStream = urlConnection.getInputStream();

        //this is the total size of the file which we are downloading
        totalSize = urlConnection.getContentLength();

        runOnUiThread(new Runnable() {
            public void run() {
                pb.setMax(totalSize);
            }               
        });

        //create a buffer...
        byte[] buffer = new byte[1024];
        int bufferLength = 0;

        while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
            fileOutput.write(buffer, 0, bufferLength);
            downloadedSize += bufferLength;
            // update the progressbar //
            runOnUiThread(new Runnable() {
                public void run() {
                    pb.setProgress(downloadedSize);
                    float per = ((float)downloadedSize/totalSize) *     
                    100;
                    cur_val.setText("Downloaded " + downloadedSize +  

                    "KB / " + totalSize + "KB (" + (int)per + "%)" );
                }
            });
        }
        //close the output stream when complete //
        fileOutput.close();
        runOnUiThread(new Runnable() {
            public void run() {
                // pb.dismiss(); // if you want close it..
            }
        });         

    } catch (final MalformedURLException e) {
        showError("Error : MalformedURLException " + e);        
        e.printStackTrace();
    } catch (final IOException e) {
        showError("Error : IOException " + e);          
        e.printStackTrace();
    }
    catch (final Exception e) {
        showError("Error : Please check your internet connection " +  
e);
    }       
}

void showError(final String err){
    runOnUiThread(new Runnable() {
        public void run() {
            Toast.makeText(DownloadFileDemo1.this, err,  
      Toast.LENGTH_LONG).show();
        }
    });
}

void showProgress(String file_path){
    dialog = new Dialog(DownloadFileDemo1.this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.myprogressdialog);
    dialog.setTitle("Download Progress");

    TextView text = (TextView) dialog.findViewById(R.id.tv1);
    text.setText("Downloading file from ... " + file_path);
    cur_val = (TextView) dialog.findViewById(R.id.cur_pg_tv);
    cur_val.setText("Starting download...");
    dialog.show();

     pb = (ProgressBar)dialog.findViewById(R.id.progress_bar);
     pb.setProgress(0);
            pb.setProgressDrawable(
      getResources().getDrawable(R.drawable.green_progress));  
  }
}

Make iframe automatically adjust height according to the contents without using scrollbar?

I did it with AngularJS. Angular doesn't have an ng-load, but a 3rd party module was made; install with bower below, or find it here: https://github.com/andrefarzat/ng-load

Get the ngLoad directive: bower install ng-load --save

Setup your iframe:

<iframe id="CreditReportFrame" src="about:blank" frameborder="0" scrolling="no" ng-load="resizeIframe($event)" seamless></iframe>

Controller resizeIframe function:

$scope.resizeIframe = function (event) {
    console.log("iframe loaded!");
    var iframe = event.target;
    iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
};

IntelliJ how to zoom in / out

You need to look for the Increase Font Size and Decrease Font Size options on the Keymap menu, you can see the options on my screenshot. You will find the Keymap menu under Preferences > Keymap.

font size settings

Assigning on those will have the expected effect for font zoom.

Are the shift operators (<<, >>) arithmetic or logical in C?

GCC does

  1. for -ve - > Arithmetic Shift

  2. For +ve -> Logical Shift

What are enums and why are they useful?

Why use any programming language feature? The reason we have languages at all is for

  1. Programmers to efficiently and correctly express algorithms in a form computers can use.
  2. Maintainers to understand algorithms others have written and correctly make changes.

Enums improve both likelihood of correctness and readability without writing a lot of boilerplate. If you are willing to write boilerplate, then you can "simulate" enums:

public class Color {
    private Color() {} // Prevent others from making colors.
    public static final Color RED = new Color();
    public static final Color AMBER = new Color();
    public static final Color GREEN = new Color();
}

Now you can write:

Color trafficLightColor = Color.RED;

The boilerplate above has much the same effect as

public enum Color { RED, AMBER, GREEN };

Both provide the same level of checking help from the compiler. Boilerplate is just more typing. But saving a lot of typing makes the programmer more efficient (see 1), so it's a worthwhile feature.

It's worthwhile for at least one more reason, too:

Switch statements

One thing that the static final enum simulation above does not give you is nice switch cases. For enum types, the Java switch uses the type of its variable to infer the scope of enum cases, so for the enum Color above you merely need to say:

Color color = ... ;
switch (color) {
    case RED:
        ...
        break;
}

Note it's not Color.RED in the cases. If you don't use enum, the only way to use named quantities with switch is something like:

public Class Color {
    public static final int RED = 0;
    public static final int AMBER = 1;
    public static final int GREEN = 2;
}

But now a variable to hold a color must have type int. The nice compiler checking of the enum and the static final simulation is gone. Not happy.

A compromise is to use a scalar-valued member in the simulation:

public class Color {
    public static final int RED_TAG = 1;
    public static final int AMBER_TAG = 2;
    public static final int GREEN_TAG = 3;

    public final int tag;

    private Color(int tag) { this.tag = tag; } 
    public static final Color RED = new Color(RED_TAG);
    public static final Color AMBER = new Color(AMBER_TAG);
    public static final Color GREEN = new Color(GREEN_TAG);
}

Now:

Color color = ... ;
switch (color.tag) {
    case Color.RED_TAG:
        ...
        break;
}

But note, even more boilerplate!

Using an enum as a singleton

From the boilerplate above you can see why an enum provides a way to implement a singleton. Instead of writing:

public class SingletonClass {
    public static final void INSTANCE = new SingletonClass();
    private SingletonClass() {}

    // all the methods and instance data for the class here
}

and then accessing it with

SingletonClass.INSTANCE

we can just say

public enum SingletonClass {
    INSTANCE;

    // all the methods and instance data for the class here
}

which gives us the same thing. We can get away with this because Java enums are implemented as full classes with only a little syntactic sugar sprinkled over the top. This is again less boilerplate, but it's non-obvious unless the idiom is familiar to you. I also dislike the fact that you get the various enum functions even though they don't make much sense for the singleton: ord and values, etc. (There's actually a trickier simulation where Color extends Integer that will work with switch, but it's so tricky that it even more clearly shows why enum is a better idea.)

Thread safety

Thread safety is a potential problem only when singletons are created lazily with no locking.

public class SingletonClass {
    private static SingletonClass INSTANCE;
    private SingletonClass() {}
    public SingletonClass getInstance() {
        if (INSTANCE == null) INSTANCE = new SingletonClass();
        return INSTANCE;
    }

    // all the methods and instance data for the class here
}

If many threads call getInstance simultaneously while INSTANCE is still null, any number of instances can be created. This is bad. The only solution is to add synchronized access to protect the variable INSTANCE.

However, the static final code above does not have this problem. It creates the instance eagerly at class load time. Class loading is synchronized.

The enum singleton is effectively lazy because it's not initialized until first use. Java initialization is also synchronized, so multiple threads can't initialize more than one instance of INSTANCE. You're getting a lazily initialized singleton with very little code. The only negative is the the rather obscure syntax. You need to know the idiom or thoroughly understand how class loading and initialization work to know what's happening.

How to inspect Javascript Objects

How about alert(JSON.stringify(object)) with a modern browser?

In case of TypeError: Converting circular structure to JSON, here are more options: How to serialize DOM node to JSON even if there are circular references?

The documentation: JSON.stringify() provides info on formatting or prettifying the output.

How to 'insert if not exists' in MySQL?

Update or insert without known primary key

If you already have a unique or primary key, the other answers with either INSERT INTO ... ON DUPLICATE KEY UPDATE ... or REPLACE INTO ... should work fine (note that replace into deletes if exists and then inserts - thus does not partially update existing values).

But if you have the values for some_column_id and some_type, the combination of which are known to be unique. And you want to update some_value if exists, or insert if not exists. And you want to do it in just one query (to avoid using a transaction). This might be a solution:

INSERT INTO my_table (id, some_column_id, some_type, some_value)
SELECT t.id, t.some_column_id, t.some_type, t.some_value
FROM (
    SELECT id, some_column_id, some_type, some_value
    FROM my_table
    WHERE some_column_id = ? AND some_type = ?
    UNION ALL
    SELECT s.id, s.some_column_id, s.some_type, s.some_value
    FROM (SELECT NULL AS id, ? AS some_column_id, ? AS some_type, ? AS some_value) AS s
) AS t
LIMIT 1
ON DUPLICATE KEY UPDATE
some_value = ?

Basically, the query executes this way (less complicated than it may look):

  • Select an existing row via the WHERE clause match.
  • Union that result with a potential new row (table s), where the column values are explicitly given (s.id is NULL, so it will generate a new auto-increment identifier).
  • If an existing row is found, then the potential new row from table s is discarded (due to LIMIT 1 on table t), and it will always trigger an ON DUPLICATE KEY which will UPDATE the some_value column.
  • If an existing row is not found, then the potential new row is inserted (as given by table s).

Note: Every table in a relational database should have at least a primary auto-increment id column. If you don't have this, add it, even when you don't need it at first sight. It is definitely needed for this "trick".

JQuery Datatables : Cannot read property 'aDataSort' of undefined

For me, the bug was in DataTables itself; The code for sorting in DataTables 1.10.9 will not check for bounds; thus if you use something like

order: [[1, 'asc']]

with an empty table, there is no row idx 1 -> this exception ensures. This happened as the data for the table was being fetched asynchronously. Initially, on page loading the dataTable gets initialized without data. It should be updated later as soon as the result data is fetched.

My solution:

// add within function _fnStringToCss( s ) in datatables.js
// directly after this line
// srcCol = nestedSort[i][0];

if(srcCol >= aoColumns.length) {
    continue;
}

// this line follows:
// aDataSort = aoColumns[ srcCol ].aDataSort;

How to use a calculated column to calculate another column in the same view

You could use a nested query:

Select
  ColumnA,
  ColumnB,
  calccolumn1,
  calccolumn1 / ColumnC as calccolumn2
From (
  Select
    ColumnA,
    ColumnB,
    ColumnC,
    ColumnA + ColumnB As calccolumn1
  from t42
);

With a row with values 3, 4, 5 that gives:

   COLUMNA    COLUMNB CALCCOLUMN1 CALCCOLUMN2
---------- ---------- ----------- -----------
         3          4           7         1.4

You can also just repeat the first calculation, unless it's really doing something expensive (via a function call, say):

Select
  ColumnA,
  ColumnB,
  ColumnA + ColumnB As calccolumn1,
  (ColumnA + ColumnB) / ColumnC As calccolumn2
from t42; 

   COLUMNA    COLUMNB CALCCOLUMN1 CALCCOLUMN2
---------- ---------- ----------- -----------
         3          4           7         1.4 

How do I concatenate or merge arrays in Swift?

Swift 4.X

easiest way I know is to just use the + sign

var Array1 = ["Item 1", "Item 2"]
var Array2 = ["Thing 1", "Thing 2"]

var Array3 = Array1 + Array2

// Array 3 will just be them combined :)

XAMPP, Apache - Error: Apache shutdown unexpectedly

My problem was that in httpd.conf the DocumentRoot and <Directory> entries were pointing to non-existing folders.

For example, the 'original' httpd.conf had the following entries:

DocumentRoot "c:/Apache24/htdocs"
<Directory "c:/Apache24/htdocs">

If you've installed in C:\xampp then you need to change those entries to match, i.e.

DocumentRoot "c:/xampp/htdocs"
<Directory "c:/xampp/htdocs">

What is the best way to prevent session hijacking?

Let us consider that during the login phase the client and server can agree on a secret salt value. Thereafter the server provides a count value with each update and expects the client to respond with the hash of the (secret salt + count). The potential hijacker does not have any way to obtain this secret salt value and thus cannot generate the next hash.

Get random item from array

If you don't mind picking the same item again at some other time:

$items[rand(0, count($items) - 1)];

mysql: get record count between two date-time

for speed you can do this

WHERE date(created_at) ='2019-10-21'

Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

What worked for me after following all your workarounds was to call the API:

 <script async defer src="https://maps.googleapis.com/maps/api/js?key=you_API_KEY&callback=initMap&libraries=places"
            type="text/javascript"></script>

before my : <div id="map"></div>

I am using .ASP NET (MVC)

NSDate get year/month/day

Try this . . .

Code snippet:

 NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
 int year = [components year];
 int month = [components month];
 int day = [components day];

It gives current year, month, date

Convert timestamp in milliseconds to string formatted time in Java

    long hours = TimeUnit.MILLISECONDS.toHours(timeInMilliseconds);
    long minutes = TimeUnit.MILLISECONDS.toMinutes(timeInMilliseconds - TimeUnit.HOURS.toMillis(hours));
    long seconds = TimeUnit.MILLISECONDS
            .toSeconds(timeInMilliseconds - TimeUnit.HOURS.toMillis(hours) - TimeUnit.MINUTES.toMillis(minutes));
    long milliseconds = timeInMilliseconds - TimeUnit.HOURS.toMillis(hours)
            - TimeUnit.MINUTES.toMillis(minutes) - TimeUnit.SECONDS.toMillis(seconds);
    return String.format("%02d:%02d:%02d:%d", hours, minutes, seconds, milliseconds);

Iterate through a C array

It depends. If it's a dynamically allocated array, that is, you created it calling malloc, then as others suggest you must either save the size of the array/number of elements somewhere or have a sentinel (a struct with a special value, that will be the last one).

If it's a static array, you can sizeof it's size/the size of one element. For example:

int array[10], array_size;
...
array_size = sizeof(array)/sizeof(int);

Note that, unless it's global, this only works in the scope where you initialized the array, because if you past it to another function it gets decayed to a pointer.

Hope it helps.

Properties file in python (similar to Java Properties)

This is what I'm doing in my project: I just create another .py file called properties.py which includes all common variables/properties I used in the project, and in any file need to refer to these variables, put

from properties import *(or anything you need)

Used this method to keep svn peace when I was changing dev locations frequently and some common variables were quite relative to local environment. Works fine for me but not sure this method would be suggested for formal dev environment etc.

iOS change navigation bar title font and color

This one for alternative to Swift 4 (already answer by @Josh):

let titleTextAttributed: [NSAttributedStringKey: Any] = [.foregroundColor: UIColor.red, .font: UIFont(name: "AvenirNext-Regular", size: 20) as Any]
navigationController?.navigationBar.titleTextAttributes = titleTextAttributed

Convert date time string to epoch in Bash

A lot of these answers overly complicated and also missing how to use variables. This is how you would do it more simply on standard Linux system (as previously mentioned the date command would have to be adjusted for Mac Users) :

Sample script:

#!/bin/bash
orig="Apr 28 07:50:01"
epoch=$(date -d "${orig}" +"%s")
epoch_to_date=$(date -d @$epoch +%Y%m%d_%H%M%S)    

echo "RESULTS:"
echo "original = $orig"
echo "epoch conv = $epoch"
echo "epoch to human readable time stamp = $epoch_to_date"

Results in :

RESULTS:
original = Apr 28 07:50:01
epoch conv = 1524916201 
epoch to human readable time stamp = 20180428_075001

Or as a function :

# -- Converts from human to epoch or epoch to human, specifically "Apr 28 07:50:01" human.
#    typeset now=$(date +"%s")
#    typeset now_human_date=$(convert_cron_time "human" "$now")

function convert_cron_time() {
    case "${1,,}" in
        epoch)
            # human to epoch (eg. "Apr 28 07:50:01" to 1524916201)
            echo $(date -d "${2}" +"%s")
            ;;
        human)
            # epoch to human (eg. 1524916201 to "Apr 28 07:50:01")
            echo $(date -d "@${2}" +"%b %d %H:%M:%S")
            ;;
    esac
}

Howto? Parameters and LIKE statement SQL

you have to do:

LIKE '%' + @param + '%'

JSON find in JavaScript

General Solution

We use object-scan for a lot of data processing. It has some nice properties, especially traversing in delete safe order. Here is how one could implement find, delete and replace for your question.

_x000D_
_x000D_
// const objectScan = require('object-scan');

const tool = (() => {
  const scanner = objectScan(['[*]'], {
    abort: true,
    rtn: 'bool',
    filterFn: ({
      value, parent, property, context
    }) => {
      if (value.id === context.id) {
        context.fn({ value, parent, property });
        return true;
      }
      return false;
    }
  });
  return {
    add: (data, id, obj) => scanner(data, { id, fn: ({ parent, property }) => parent.splice(property + 1, 0, obj) }),
    del: (data, id) => scanner(data, { id, fn: ({ parent, property }) => parent.splice(property, 1) }),
    mod: (data, id, prop, v = undefined) => scanner(data, {
      id,
      fn: ({ value }) => {
        if (value !== undefined) {
          value[prop] = v;
        } else {
          delete value[prop];
        }
      }
    })
  };
})();

// -------------------------------

const data = [ { id: 'one', pId: 'foo1', cId: 'bar1' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ];
const toAdd = { id: 'two', pId: 'foo2', cId: 'bar2' };

const exec = (fn) => {
  console.log('---------------');
  console.log(fn.toString());
  console.log(fn());
  console.log(data);
};

exec(() => tool.add(data, 'one', toAdd));
exec(() => tool.mod(data, 'one', 'pId', 'zzz'));
exec(() => tool.mod(data, 'one', 'other', 'test'));
exec(() => tool.mod(data, 'one', 'gone', 'delete me'));
exec(() => tool.mod(data, 'one', 'gone'));
exec(() => tool.del(data, 'three'));

// => ---------------
// => () => tool.add(data, 'one', toAdd)
// => true
// => [ { id: 'one', pId: 'foo1', cId: 'bar1' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'pId', 'zzz')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'other', 'test')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'gone', 'delete me')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: 'delete me' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'gone')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: undefined }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.del(data, 'three')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: undefined }, { id: 'two', pId: 'foo2', cId: 'bar2' } ]
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
_x000D_
_x000D_

Disclaimer: I'm the author of object-scan

Print a list of space-separated elements in Python 3

Joining elements in a list space separated:

word = ["test", "crust", "must", "fest"]
word.reverse()
joined_string = ""
for w in word:
   joined_string = w + joined_string + " "
print(joined_string.rstrim())

How to add a reference programmatically

Browsing the registry for guids or using paths, which method is best. If browsing the registry is no longer necessary, won't it be the better way to use guids? Office is not always installed in the same directory. The installation path can be manually altered. Also the version number is a part of the path. I could have never predicted that Microsoft would ever add '(x86)' to 'Program Files' before the introduction of 64 bits processors. If possible I would try to avoid using a path.

The code below is derived from Siddharth Rout's answer, with an additional function to list all the references that are used in the active workbook. What if I open my workbook in a later version of Excel? Will the workbook still work without adapting the VBA code? I have already checked that the guids for office 2003 and 2010 are identical. Let's hope that Microsoft doesn't change guids in future versions.

The arguments 0,0 (from .AddFromGuid) should use the latest version of a reference (which I have not been able to test).

What are your thoughts? Of course we cannot predict the future but what can we do to make our code version proof?

Sub AddReferences(wbk As Workbook)
    ' Run DebugPrintExistingRefs in the immediate pane, to show guids of existing references
    AddRef wbk, "{00025E01-0000-0000-C000-000000000046}", "DAO"
    AddRef wbk, "{00020905-0000-0000-C000-000000000046}", "Word"
    AddRef wbk, "{91493440-5A91-11CF-8700-00AA0060263B}", "PowerPoint"
End Sub

Sub AddRef(wbk As Workbook, sGuid As String, sRefName As String)
    Dim i As Integer
    On Error GoTo EH
    With wbk.VBProject.References
        For i = 1 To .Count
            If .Item(i).Name = sRefName Then
               Exit For
            End If
        Next i
        If i > .Count Then
           .AddFromGuid sGuid, 0, 0 ' 0,0 should pick the latest version installed on the computer
        End If
    End With
EX: Exit Sub
EH: MsgBox "Error in 'AddRef'" & vbCrLf & vbCrLf & err.Description
    Resume EX
    Resume ' debug code
End Sub

Public Sub DebugPrintExistingRefs()
    Dim i As Integer
    With Application.ThisWorkbook.VBProject.References
        For i = 1 To .Count
            Debug.Print "    AddRef wbk, """ & .Item(i).GUID & """, """ & .Item(i).Name & """"
        Next i
    End With
End Sub

The code above does not need the reference to the "Microsoft Visual Basic for Applications Extensibility" object anymore.

Can I apply a CSS style to an element name?

This is the perfect job for the query selector...

var Set1=document.querySelectorAll('input[type=button]');  // by type

var Set2=document.querySelectorAll('input[name=goButton]'); // by name

var Set3=document.querySelectorAll('input[value=Go]'); // by value

You can then loop through these collections to operate on elements found.

Multiple line comment in Python

Try this

'''
This is a multiline
comment. I can type here whatever I want.
'''

Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.

On the other hand, if you say this behavior must be documented in the official docs to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.

In any case your editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to an editor that does.

Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.

Not only should the editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.

Why is the parent div height zero when it has floated children

Content that is floating does not influence the height of its container. The element contains no content that isn't floating (so nothing stops the height of the container being 0, as if it were empty).

Setting overflow: hidden on the container will avoid that by establishing a new block formatting context. See methods for containing floats for other techniques and containing floats for an explanation about why CSS was designed this way.

CSS Background image not loading

here is another image url result..working fine...i'm just put only a image path..please check it..

Fiddel:http://jsfiddle.net/287Kw/

body 
{
background-image: url('http://www.birds.com/wp-content/uploads/home/bird4.jpg');
padding-left: 11em;
padding-right: 20em;
font-family:
Georgia, "Times New Roman",
Times, serif; 
color: red;


}

How do I convert a Swift Array to a String?

for any Element type

extension Array {

    func joined(glue:()->Element)->[Element]{
        var result:[Element] = [];
        result.reserveCapacity(count * 2);
        let last = count - 1;
        for (ix,item) in enumerated() {
            result.append(item);
            guard ix < last else{ continue }
            result.append(glue());
        }
        return result;
    }
}

How to install trusted CA certificate on Android device?

What I did to beable to use startssl certificates was quite easy. (on my rooted phone)

I copied /system/etc/security/cacerts.bks to my sdcard

Downloaded http://www.startssl.com/certs/ca.crt and http://www.startssl.com/certs/sub.class1.server.ca.crt

Went to portecle.sourceforge.net and ran portecle directly from the webpage.

Opened my cacerts.bks file from my sdcard (entered nothing when asked for a password)

Choose import in portacle and opened sub.class1.server.ca.crt, im my case it allready had the ca.crt but maybe you need to install that too.

Saved the keystore and copied it baxck to /system/etc/security/cacerts.bks (I made a backup of that file first just in case)

Rebooted my phone and now I can vist my site thats using a startssl certificate without errors.

Remove accents/diacritics in a string in JavaScript

thanks to all
I use this version and say why (because I misses those explanations at the begining, so I try to help the next reader if he is as dull as me ...)

Remark : I wanted an efficient solution, so :

  • only one regexp compilation (if needed)
  • only one string scan for each string
  • an efficient way to find the translated characters etc ...

My version is :
(there is no new technical trick inside it, only some selected ones + explanations why)

makeSortString = (function() {
    var translate_re = /[¹²³áàâãäåaaaÀÁÂÃÄÅAAAÆccç©CCÇÐÐèéê?ëeeeeeÈÊË?EEEEE€gGiìíîïìiiiÌÍÎÏ?ÌIIIlLnnñNNÑòóôõöoooøÒÓÔÕÖOOOØŒr®Ršs?ߊS?ùúûüuuuuÙÚÛÜUUUUýÿÝŸžzzŽZZ]/g;
    var translate = {
"¹":"1","²":"2","³":"3","á":"a","à":"a","â":"a","ã":"a","ä":"a","å":"a","a":"a","a":"a","a":"a","À":"a","Á":"a","Â":"a","Ã":"a","Ä":"a","Å":"a","A":"a","A":"a",
"A":"a","Æ":"a","c":"c","c":"c","ç":"c","©":"c","C":"c","C":"c","Ç":"c","Ð":"d","Ð":"d","è":"e","é":"e","ê":"e","?":"e","ë":"e","e":"e","e":"e","e":"e","e":"e",
"e":"e","È":"e","Ê":"e","Ë":"e","?":"e","E":"e","E":"e","E":"e","E":"e","E":"e","€":"e","g":"g","G":"g","i":"i","ì":"i","í":"i","î":"i","ï":"i","ì":"i","i":"i",
"i":"i","i":"i","Ì":"i","Í":"i","Î":"i","Ï":"i","?":"i","Ì":"i","I":"i","I":"i","I":"i","l":"l","L":"l","n":"n","n":"n","ñ":"n","N":"n","N":"n","Ñ":"n","ò":"o",
"ó":"o","ô":"o","õ":"o","ö":"o","o":"o","o":"o","o":"o","ø":"o","Ò":"o","Ó":"o","Ô":"o","Õ":"o","Ö":"o","O":"o","O":"o","O":"o","Ø":"o","Œ":"o","r":"r","®":"r",
"R":"r","š":"s","s":"s","?":"s","ß":"s","Š":"s","S":"s","?":"s","ù":"u","ú":"u","û":"u","ü":"u","u":"u","u":"u","u":"u","u":"u","Ù":"u","Ú":"u","Û":"u","Ü":"u",
"U":"u","U":"u","U":"u","U":"u","ý":"y","ÿ":"y","Ý":"y","Ÿ":"y","ž":"z","z":"z","z":"z","Ž":"z","Z":"z","Z":"z"
    };
    return function(s) {
        return(s.replace(translate_re, function(match){return translate[match];}) );
    }
})();

and I use it this way :

var without_accents = makeSortString("wïthêüÄTrèsBïgüeAk100t");
// I let you guess the result,
// no I was kidding you : I give you the result : witheuatresbigueak100t

Comments :

  • Tthe instruction inside it is done once (after, makeSortString != undefined)
  • function(){...} is stored once in makeSortString, so the "big" translate_re and translate objects are stored once
  • When you call makeSortString('something') it call directly the inside function which calls only s.replace(...) : it is efficient
  • s.replace uses regexp (the special syntax of var translate_re= .... is in fact equivalent to var translate_re = new RegExp("[¹....Z]","g"); but the compilation of the regexp is done once for all, and the scan of the s String is done one for a call of the function (not for every character as it would be in a loop)
  • For each character found s.replace calls function(match) where parameter match contains the character found, and it call the corresponding translated character (translate[match])
  • Translate[match] is probably efficient too as the javascript translate object is probably implemented by javascript with a hashtab or something equivalent and allow the program to find the translated character almost directly and not for instance through a loop on a array of all characters to find the right one (which would be awfully unefficient).

Big-oh vs big-theta

Because my keyboard has an O key.
It does not have a T or an O key.

I suspect most people are similarly lazy and use O when they mean T because it's easier to type.

'invalid value encountered in double_scalars' warning, possibly numpy

I encount this while I was calculating np.var(np.array([])). np.var will divide size of the array which is zero in this case.

Is there a C++ gdb GUI for Linux?

As someone familiar with Visual Studio, I've looked at several open source IDE's to replace it, and KDevelop comes the closest IMO to being something that a Visual C++ person can just sit down and start using. When you run the project in debugging mode, it uses gdb but kdevelop pretty much handles the whole thing so that you don't have to know it's gdb; you're just single stepping or assigning watches to variables.

It still isn't as good as the Visual Studio Debugger, unfortunately.

MySQL compare now() (only date, not time) with a datetime field

Compare date only instead of date + time (NOW) with:

CURDATE()