Programs & Examples On #Hexagonal tiles

Tessellating tiles for use as 2d-histogram bins, game boards, etc.

How is AngularJS different from jQuery

Jquery :-

jQuery is a lightweight and feature-rich JavaScript Library that helps web developers
by simplifying the usage of client-side scripting for web applications using JavaScript.
It extensively simplifies using JavaScript on a website and it’s lightweight as well as fast.

So, using jQuery, we can:

easily manipulate the contents of a webpage
apply styles to make UI more attractive
easy DOM traversal
effects and animation
simple to make AJAX calls and
utilities and much more… 

AngularJS :-

AngularJS is a product by none other the Search Engine Giant Google and it’s an open source
MVC-based framework(considered to be the best and only next generation framework). AngularJS
is a great tool for building highly rich client-side web applications.

As being a framework, it dictates us to follow some rules and a structured approach. It’s
not just a JavaScript library but a framework that is perfectly designed (framework tools
are designed to work together in a truly interconnected way).

In comparison of features jQuery Vs AngularJS, AngularJS simply offers more features:

Two-Way data binding
REST friendly
MVC-based Pattern
Deep Linking
Template
Form Validation
Dependency Injection
Localization
Full Testing Environment
Server Communication

How to find if directory exists in Python

#You can also check it get help for you

if not os.path.isdir('mydir'):
    print('new directry has been created')
    os.system('mkdir mydir')

Simplest way to restart service on a remote computer

I believe PowerShell now trumps the "sc" command in terms of simplicity:

Restart-Service "servicename"

How to check if a number is a power of 2

bool isPowerOfTwo(int x_)
{
  register int bitpos, bitpos2;
  asm ("bsrl %1,%0": "+r" (bitpos):"rm" (x_));
  asm ("bsfl %1,%0": "+r" (bitpos2):"rm" (x_));
  return bitpos > 0 && bitpos == bitpos2;
}

Can we use join for two different database tables?

You could use Synonyms part in the database.

enter image description here

Then in view wizard from Synonyms tab find your saved synonyms and add to view and set inner join simply. enter image description here

Undefined reference to `pow' and `floor'

For the benefit of anyone reading this later, you need to link against it as Fred said:

gcc fib.c -lm -o fibo

One good way to find out what library you need to link is by checking the man page if one exists. For example, man pow and man floor will both tell you:

Link with -lm.

An explanation for linking math library in C programming - Linking in C

Add one day to date in javascript

Just for the sake of adding functions to the Date prototype:

In a mutable fashion / style:

Date.prototype.addDays = function(n) {
   this.setDate(this.getDate() + n);
};

// Can call it tomorrow if you want
Date.prototype.nextDay = function() {
   this.addDays(1);
};

Date.prototype.addMonths = function(n) {
   this.setMonth(this.getMonth() + n);
};

Date.prototype.addYears = function(n) {
   this.setFullYear(this.getFullYear() + n);
}

// etc...

var currentDate = new Date();
currentDate.nextDay();

Is there any way to call a function periodically in JavaScript?

Old question but.. I also needed a periodical task runner and wrote TaskTimer. This is also useful when you need to run multiple tasks on different intervals.

// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);

// Add task(s) based on tick intervals.
timer.add({
    id: 'job1',       // unique id of the task
    tickInterval: 5,    // run every 5 ticks (5 x interval = 5000 ms)
    totalRuns: 10,      // run 10 times only. (set to 0 for unlimited times)
    callback(task) {
        // code to be executed on each run
        console.log(task.id + ' task has run ' + task.currentRuns + ' times.');
    }
});

// Start the timer
timer.start();

TaskTimer works both in browser and Node. See documentation for all features.

JQuery $.ajax() post - data in a java servlet

You don't want a string, you really want a JS map of key value pairs. E.g., change:

 data: myDataVar.toString(),

with:

var myKeyVals = { A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }



var saveData = $.ajax({
      type: 'POST',
      url: "someaction.do?action=saveData",
      data: myKeyVals,
      dataType: "text",
      success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });

jQuery understands key value pairs like that, it does NOT understand a big string. It passes it simply as a string.

UPDATE: Code fixed.

Programmatically extract contents of InstallShield setup.exe

The free and open-source program called cabextract will list and extract the contents of not just .cab-files, but Macrovision's archives too:

% cabextract /tmp/QLWREL.EXE
Extracting cabinet: /tmp/QLWREL.EXE
  extracting ikernel.dll
  extracting IsProBENT.tlb
  ....
  extracting IScript.dll
  extracting iKernel.rgs

All done, no errors.

MySQL foreach alternative for procedure

Here's the mysql reference for cursors. So I'm guessing it's something like this:

  DECLARE done INT DEFAULT 0;
  DECLARE products_id INT;
  DECLARE result varchar(4000);
  DECLARE cur1 CURSOR FOR SELECT products_id FROM sets_products WHERE set_id = 1;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

  OPEN cur1;

  REPEAT
    FETCH cur1 INTO products_id;
    IF NOT done THEN
      CALL generate_parameter_list(@product_id, @result);
      SET param = param + "," + result; -- not sure on this syntax
    END IF;
  UNTIL done END REPEAT;

  CLOSE cur1;

  -- now trim off the trailing , if desired

Spring schemaLocation fails when there is no internet connection

Just make sure the relevant spring jar file are in your runtime classpath. In my case this we were missing spring-tx-4.3.4.RELEASE.jar from runtime classpath. After adding this jar, the issue was resolved.

MySQL integer field is returned as string in PHP

You can do this with...

  1. mysql_fetch_field()
  2. mysqli_result::fetch_field_direct or
  3. PDOStatement::getColumnMeta()

...depending on the extension you want to use. The first is not recommended because the mysql extension is deprecated. The third is still experimental.

The comments at these hyperlinks do a good job of explaining how to set your type from a plain old string to its original type in the database.

Some frameworks also abstract this (CodeIgniter provides $this->db->field_data()).

You could also do guesswork--like looping through your resulting rows and using is_numeric() on each. Something like:

foreach($result as &$row){
 foreach($row as &$value){
  if(is_numeric($value)){
   $value = (int) $value;
  }       
 }       
}

This would turn anything that looks like a number into one...definitely not perfect.

Python MySQLdb TypeError: not all arguments converted during string formatting

The accepted answer by @kevinsa5 is correct, but you might be thinking "I swear this code used to work and now it doesn't," and you would be right.

There was an API change in the MySQLdb library between 1.2.3 and 1.2.5. The 1.2.3 versions supported

cursor.execute("SELECT * FROM foo WHERE bar = %s", 'baz')

but the 1.2.5 versions require

cursor.execute("SELECT * FROM foo WHERE bar = %s", ['baz'])

as the other answers state. I can't find the change in the changelogs, and it's possible the earlier behavior was considered a bug.

The Ubuntu 14.04 repository has python-mysqldb 1.2.3, but Ubuntu 16.04 and later have python-mysqldb 1.3.7+.

If you're dealing with a legacy codebase that requires the old behavior but your platform is a newish Ubuntu, install MySQLdb from PyPI instead:

$ pip install MySQL-python==1.2.3

Synchronous Requests in Node.js

Though asynchronous style may be the nature of node.js and generally you should not do this, there are some times you want to do this.

I'm writing a handy script to check an API and want not to mess it up with callbacks.

Javascript cannot execute synchronous requests, but C libraries can.

https://github.com/dhruvbird/http-sync

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm

Linux Mint 19. Helped for me:

sudo apt install tk-dev

P.S. Recompile python interpreter after package install.

How to use callback with useState hook in react

With React16.x, if you want to invoke a callback function on state change using useState hook, you can use the useEffect hook attached to the state change.

import React, { useEffect } from 'react';

useEffect(() => {
  props.getChildChange(name); // using camelCase for variable name is recommended.
}, [name]); // this will call getChildChange when ever name changes.

Error handling with PHPMailer

In PHPMailer.php, there are lines as below:

echo $e->getMessage()

Just comment these lines and you will be good to go.

HTML email in outlook table width issue - content is wider than the specified table width

I guess problem is in width attributes in table and td remove 'px' for example

<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">

Should be

<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">

Image height and width not working?

You must write

<img src="theSource" style="width:30px;height:30px;" />

Inline styling will always take precedence over CSS styling. The width and height attributes are being overridden by your stylesheet, so you need to switch to this format.

Using success/error/finally/catch with Promises in AngularJS

Forget about using success and error method.

Both methods have been deprecated in angular 1.4. Basically, the reason behind the deprecation is that they are not chainable-friendly, so to speak.

With the following example, I'll try to demonstrate what I mean about success and error being not chainable-friendly. Suppose we call an API that returns a user object with an address:

User object:

{name: 'Igor', address: 'San Francisco'}

Call to the API:

$http.get('/user')
    .success(function (user) {
        return user.address;   <---  
    })                            |  // you might expect that 'obj' is equal to the
    .then(function (obj) {   ------  // address of the user, but it is NOT

        console.log(obj); // -> {name: 'Igor', address: 'San Francisco'}
    });
};

What happened?

Because success and error return the original promise, i.e. the one returned by $http.get, the object passed to the callback of the then is the whole user object, that is to say the same input to the preceding success callback.

If we had chained two then, this would have been less confusing:

$http.get('/user')
    .then(function (user) {
        return user.address;  
    })
    .then(function (obj) {  
        console.log(obj); // -> 'San Francisco'
    });
};

Why does sudo change the PATH?

# cat .bash_profile | grep PATH
PATH=$HOME/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
export PATH

# cat /etc/sudoers | grep Defaults
Defaults    requiretty
Defaults    env_reset
Defaults    env_keep = "SOME_PARAM1 SOME_PARAM2 ... PATH"

Android: disabling highlight on listView click

RoflcoptrException's answer should do the trick,but for some reason it did not work for me, So I am posting the solution which worked for me, hope it helps someone

<ListView 
android:listSelector="@android:color/transparent" 
android:cacheColorHint="@android:color/transparent"
/>

Angularjs - Pass argument to directive

You can pass arguments to your custom directive as you do with the builtin Angular-directives - by specifying an attribute on the directive-element:

angular.element(document.getElementById('wrapper'))
       .append('<directive-name title="title2"></directive-name>');

What you need to do is define the scope (including the argument(s)/parameter(s)) in the factory function of your directive. In below example the directive takes a title-parameter. You can then use it, for example in the template, using the regular Angular-way: {{title}}

app.directive('directiveName', function(){
   return {
      restrict:'E',
      scope: {
         title: '@'
      },
      template:'<div class="title"><h2>{{title}}</h2></div>'
   };
});

Depending on how/what you want to bind, you have different options:

  • = is two-way binding
  • @ simply reads the value (one-way binding)
  • & is used to bind functions

In some cases you may want use an "external" name which differs from the "internal" name. With external I mean the attribute name on the directive-element and with internal I mean the name of the variable which is used within the directive's scope.

For example if we look at above directive, you might not want to specify another, additional attribute for the title, even though you internally want to work with a title-property. Instead you want to use your directive as follows:

<directive-name="title2"></directive-name>

This can be achieved by specifying a name behind the above mentioned option in the scope definition:

scope: {
    title: '@directiveName'
}

Please also note following things:

  • The HTML5-specification says that custom attributes (this is basically what is all over the place in Angular applications) should be prefixed with data-. Angular supports this by stripping the data--prefix from any attributes. So in above example you could specify the attribute on the element (data-title="title2") and internally everything would be the same.
  • Attributes on elements are always in the form of <div data-my-attribute="..." /> while in code (e.g. properties on scope object) they are in the form of myAttribute. I lost lots of time before I realized this.
  • For another approach to exchanging/sharing data between different Angular components (controllers, directives), you might want to have a look at services or directive controllers.
  • You can find more information on the Angular homepage (directives)

Inserting values to SQLite table in Android

public class TestingData extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    SQLiteDatabase db;
    db = openOrCreateDatabase(
        "TestingData.db"
        , SQLiteDatabase.CREATE_IF_NECESSARY
        , null
        );
 }

}

then see this link link

Laravel 5 Failed opening required bootstrap/../vendor/autoload.php

I encountered the same problem. It occurred because composer was not able to install the dependencies specified in composer.json file. try running

composer install 

If this does not solve the problem, make sure the following php modules are installed php-mbstring php-dom

To install this extensions run the following in terminal

sudo apt-get install php-mbstring php-dom

once the installation is complete

try running the command in your project root folder

composer install 

Simple IEnumerator use (with example)

I'd do something like:

private IEnumerable<string> DoWork(IEnumerable<string> data)
{
    List<string> newData = new List<string>();
    foreach(string item in data)
    {
        newData.Add(item + "roxxors");
    }
    return newData;
}

Simple stuff :)

Angular2 module has no exported member

For my case, I restarted the server and it worked.

Counting inversions in an array

The number of inversions in an array is half the total distance elements must be moved in order to sort the array. Therefore, it can be computed by sorting the array, maintaining the resulting permutation p[i], and then computing the sum of abs(p[i]-i)/2. This takes O(n log n) time, which is optimal.

An alternative method is given at http://mathworld.wolfram.com/PermutationInversion.html. This method is equivalent to the sum of max(0, p[i]-i), which is equal to the sum of abs(p[i]-i])/2 since the total distance elements move left is equal to the total distance elements move to the right.

EDIT: This method is wrong (see comments), and there is unfortunately no way to fix it while preserving the character of the method.

Converting Symbols, Accent Letters to English Alphabet

Following Class does the trick:

org.apache.lucene.analysis.miscellaneous.ASCIIFoldingFilter

Fatal error: Class 'SoapClient' not found

To install SOAP in PHP5.6 run following in your Ubuntu 14.04 terminal:

sudo apt-get install php5.6-soap
service php5.6-fpm restart
service apache2 restart

See if SOAP was enabled:

php -m

(You should see SOAP between returned text.)

Accessing the last entry in a Map

move does not make sense for a hashmap since its a dictionary with a hashcode for bucketing based on key and then a linked list for colliding hashcodes resolved via equals. Use a TreeMap for sorted maps and then pass in a custom comparator.

What is the difference between 'typedef' and 'using' in C++11?

They are largely the same, except that:

The alias declaration is compatible with templates, whereas the C style typedef is not.

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

I had the same problem when my network config was incorrect and DNS was not resolving. In other words the issue could arise when there is no Network Access.

How to upgrade Git to latest version on macOS?

You need to adjust shell path , the path will be set in either .bashrc or .bash_profile in your home directory, more likely .bash_profile.

So add into the path similar to the below and keep what you already have in the path, each segment is separated by a colon:

export PATH="/usr/local/bin:/usr/bin/git:/usr/bin:/usr/local/sbin:$PATH"

Make child visible outside an overflow:hidden parent

For others, if clearfix does not solve this for you, add margins to the non-floated sibling that is/are the same as the width(s) of the floated sibling(s).

Assigning default values to shell variables with a single command in bash

see here under 3.5.3(shell parameter expansion)

so in your case

${VARIABLE:-default}

How to get Printer Info in .NET?

As an alternative to WMI you can get fast accurate results by tapping in to WinSpool.drv (i.e. Windows API) - you can get all the details on the interfaces, structs & constants from pinvoke.net, or I've put the code together at http://delradiesdev.blogspot.com/2012/02/accessing-printer-status-using-winspool.html

What is a good practice to check if an environmental variable exists or not?

To be on the safe side use

os.getenv('FOO') or 'bar'

A corner case with the above answers is when the environment variable is set but is empty

For this special case you get

print(os.getenv('FOO', 'bar'))
# prints new line - though you expected `bar`

or

if "FOO" in os.environ:
    print("FOO is here")
# prints FOO is here - however its not

To avoid this just use or

os.getenv('FOO') or 'bar'

Then you get

print(os.getenv('FOO') or 'bar')
# bar

When do we have empty environment variables?

You forgot to set the value in the .env file

# .env
FOO=

or exported as

$ export FOO=

or forgot to set it in settings.py

# settings.py
os.environ['FOO'] = ''

Update: if in doubt, check out these one-liners

>>> import os; os.environ['FOO'] = ''; print(os.getenv('FOO', 'bar'))

$ FOO= python -c "import os; print(os.getenv('FOO', 'bar'))"

Get unique values from arraylist in java

    public static List getUniqueValues(List input) {
      return new ArrayList<>(new LinkedHashSet<>(incoming));
    }

dont forget to implement your equals method first

What's the PowerShell syntax for multiple values in a switch statement?

A slight modification to derekerdmann's post to meet the original request using regex's alternation operator "|"(pipe).

It's also slightly easier for regex newbies to understand and read.

Note that while using regex, if you don't put the start of string character "^"(caret/circumflex) and/or end of string character "$"(dollar) then you may get unexpected/unintuitive behavior (like matching "yesterday" or "why").

Putting grouping characters "()"(parentheses) around the options reduces the need to put start and end of string characters for each option. Without them, you'll get possibly unexpected behavior if you're not savvy with regex. Of course, if you're not processing user input, but rather some set of known strings, it will be more readable without grouping and start and end of string characters.

switch -regex ($someString) #many have noted ToLower() here is redundant
{
        #processing user input
    "^(y|yes|indubitably)$" { "You entered Yes." }

        # not processing user input
    "y|yes|indubitably" { "Yes was the selected string" } 
    default { "You entered No." } 
}

Html.Textbox VS Html.TextboxFor

IMO the main difference is that Textbox is not strongly typed. TextboxFor take a lambda as a parameter that tell the helper the with element of the model to use in a typed view.

You can do the same things with both, but you should use typed views and TextboxFor when possible.

When is JavaScript synchronous?

"I have been under the impression for that JavaScript was always asynchronous"

You can use JavaScript in a synchronous way, or an asynchronous way. In fact JavaScript has really good asynchronous support. For example I might have code that requires a database request. I can then run other code, not dependent on that request, while I wait for that request to complete. This asynchronous coding is supported with promises, async/await, etc. But if you don't need a nice way to handle long waits then just use JS synchronously.

What do we mean by 'asynchronous'. Well it does not mean multi-threaded, but rather describes a non-dependent relationship. Check out this image from this popular answer:

         A-Start ------------------------------------------ A-End   
           | B-Start -----------------------------------------|--- B-End   
           |    |      C-Start ------------------- C-End      |      |   
           |    |       |                           |         |      |
           V    V       V                           V         V      V      
1 thread->|<-A-|<--B---|<-C-|-A-|-C-|--A--|-B-|--C-->|---A---->|--B-->| 

We see that a single threaded application can have async behavior. The work in function A is not dependent on function B completing, and so while function A began before function B, function A is able to complete at a later time and on the same thread.

So, just because JavaScript executes one command at a time, on a single thread, it does not then follow that JavaScript can only be used as a synchronous language.

"Is there a good reference anywhere about when it will be synchronous and when it will be asynchronous"

I'm wondering if this is the heart of your question. I take it that you mean how do you know if some code you are calling is async or sync. That is, will the rest of your code run off and do something while you wait for some result? Your first check should be the documentation for whichever library you are using. Node methods, for example, have clear names like readFileSync. If the documentation is no good there is a lot of help here on SO. EG:

How to know if a function is async?

Best way to list files in Java, sorted by Date Modified?

public String[] getDirectoryList(String path) {
    String[] dirListing = null;
    File dir = new File(path);
    dirListing = dir.list();

    Arrays.sort(dirListing, 0, dirListing.length);
    return dirListing;
}

Using % for host when creating a MySQL user

Let's just test.

Connect as superuser, and then:

SHOW VARIABLES LIKE "%version%"; 
+-------------------------+------------------------------+ 
| Variable_name           | Value                        | 
+-------------------------+------------------------------+ 
| version                 | 10.0.23-MariaDB-0+deb8u1-log | 

and then

USE mysql;

Setup

Create a user foo with password bar for testing:

CREATE USER foo@'%' IDENTIFIED BY 'bar'; FLUSH PRIVILEGES;

Connect

To connect to the Unix Domain Socket (i.e. the I/O pipe that is named by the filesystem entry /var/run/mysqld/mysqld.sock or some such), run this on the command line (use the --protocol option to make doubly sure)

mysql -pbar -ufoo
mysql -pbar -ufoo --protocol=SOCKET

One expects that the above matches "user comes from localhost" but certainly not "user comes from 127.0.0.1".

To connect to the server from "127.0.0.1" instead, run this on the command line

mysql -pbar -ufoo --bind-address=127.0.0.1 --protocol=TCP

If you leave out --protocol=TCP, the mysql command will still try to use the Unix domain socket. You can also say:

mysql -pbar -ufoo --bind-address=127.0.0.1 --host=127.0.0.1

The two connection attempts in one line:

export MYSQL_PWD=bar; \
mysql -ufoo --protocol=SOCKET --execute="SELECT 1"; \
mysql -ufoo --bind-address=127.0.0.1 --host=127.0.0.1 --execute="SELECT 1"

(the password is set in the environment so that it is passed to the mysql process)

Verification In Case Of Doubt

To really check whether the connection goes via a TCP/IP socket or a Unix Domain socket

  1. get the PID of the mysql client process by examining the output of ps faux
  2. run lsof -n -p<yourpid>.

You will see something like:

mysql [PID] quux 3u IPv4 [code] 0t0 TCP 127.0.0.1:[port]->127.0.0.1:mysql (ESTABLISHED)

or

mysql [PID] quux 3u unix [code] 0t0 [code] socket

So:

Case 0: Host = '10.10.10.10' (null test)

update user set host='10.10.10.10' where user='foo'; flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: FAILURE

Case 1: Host = '%'

update user set host='%' where user='foo'; flush privileges;
  • Connect using socket: OK
  • Connect from 127.0.0.1: OK

Case 2: Host = 'localhost'

update user set host='localhost' where user='foo';flush privileges;

Behaviour varies and this apparently depends on skip-name-resolve. If set, causes lines with localhost to be ignored according to the log. The following can be seen in the error log: "'user' entry 'root@localhost' ignored in --skip-name-resolve mode.". This means no connecting through the Unix Domain Socket. But this is empirically not the case. localhost now means ONLY the Unix Domain Socket, and no longer matched 127.0.0.1.

skip-name-resolve is off:

  • Connect using socket: OK
  • Connect from 127.0.0.1: OK

skip-name-resolve is on:

  • Connect using socket: OK
  • Connect from 127.0.0.1: FAILURE

Case 3: Host = '127.0.0.1'

update user set host='127.0.0.1' where user='foo';flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: OK

Case 4: Host = ''

update user set host='' where user='foo';flush privileges;
  • Connect using socket: OK
  • Connect from 127.0.0.1: OK

(According to MySQL 5.7: 6.2.4 Access Control, Stage 1: Connection Verification, The empty string '' also means “any host” but sorts after '%'. )

Case 5: Host = '192.168.0.1' (extra test)

('192.168.0.1' is one of my machine's IP addresses, change appropriately in your case)

update user set host='192.168.0.1' where user='foo';flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: FAILURE

but

  • Connect using mysql -pbar -ufoo -h192.168.0.1: OK (!)

The latter because this is actually TCP connection coming from 192.168.0.1, as revealed by lsof:

TCP 192.168.0.1:37059->192.168.0.1:mysql (ESTABLISHED)

Edge Case A: Host = '0.0.0.0'

update user set host='0.0.0.0' where user='foo';flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: FAILURE

Edge Case B: Host = '255.255.255.255'

update user set host='255.255.255.255' where user='foo';flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: FAILURE

Edge Case C: Host = '127.0.0.2'

(127.0.0.2 is perfectly valid loopback address equivalent to 127.0.0.1 as defined in RFC6890)

update user set host='127.0.0.2' where user='foo';flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: FAILURE

Interestingly:

  • mysql -pbar -ufoo -h127.0.0.2 connects from 127.0.0.1 and is FAILURE
  • mysql -pbar -ufoo -h127.0.0.2 --bind-address=127.0.0.2 is OK

Cleanup

delete from user where user='foo';flush privileges;

Addendum

To see what is actually in the mysql.user table, which is one of the permission tables, use:

SELECT SUBSTR(password,1,6) as password, user, host,
Super_priv AS su,
Grant_priv as gr,
CONCAT(Select_priv, Lock_tables_priv) AS selock,
CONCAT(Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv) AS modif,
CONCAT(References_priv, Index_priv, Alter_priv) AS ria,
CONCAT(Create_tmp_table_priv, Create_view_priv, Show_view_priv) AS views,
CONCAT(Create_routine_priv, Alter_routine_priv, Execute_priv, Event_priv, Trigger_priv) AS funcs,
CONCAT(Repl_slave_priv, Repl_client_priv) AS replic,
CONCAT(Shutdown_priv, Process_priv, File_priv, Show_db_priv, Reload_priv, Create_user_priv) AS admin
FROM user ORDER BY user, host;

this gives:

+----------+----------+-----------+----+----+--------+-------+-----+-------+-------+--------+--------+
    | password | user     | host      | su | gr | selock | modif | ria | views | funcs | replic | admin  |
    +----------+----------+-----------+----+----+--------+-------+-----+-------+-------+--------+--------+
    | *E8D46   | foo      |           | N  | N  | NN     | NNNNN | NNN | NNN   | NNNNN | NN     | NNNNNN |

Similarly for table mysql.db:

SELECT host,db,user, 
       Grant_priv as gr,
       CONCAT(Select_priv, Lock_tables_priv) AS selock, 
       CONCAT(Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv) AS modif, 
       CONCAT(References_priv, Index_priv, Alter_priv) AS ria, 
       CONCAT(Create_tmp_table_priv, Create_view_priv, Show_view_priv) AS views, 
       CONCAT(Create_routine_priv, Alter_routine_priv, Execute_priv) AS funcs 
       FROM db ORDER BY user, db, host;

How can I copy the output of a command directly into my clipboard?

I usually run this command when I have to copy my ssh-key:

cat ~/.ssh/id_rsa.pub | pbcopy

ctrl+v anywhere else.

Updates were rejected because the tip of your current branch is behind its remote counterpart

Me help next:

git stash
git pull origin master
git apply
git commit -m "some comment"
git push

How to force a component's re-rendering in Angular 2?

ChangeDetectorRef.detectChanges() is usually the most focused way of doing this. ApplicationRef.tick() is usually too much of a sledgehammer approach.

To use ChangeDetectorRef.detectChanges(), you'll need this at the top of your component:

import {  ChangeDetectorRef } from '@angular/core';

... then, usually you alias that when you inject it in your constructor like this:

constructor( private cdr: ChangeDetectorRef ) { ... }

Then, in the appropriate place, you call it like this:

this.cdr.detectChanges();

Where you call ChangeDetectorRef.detectChanges() can be highly significant. You need to completely understand the life cycle and exactly how your application is functioning and rendering its components. There's no substitute here for completely doing your homework and making sure you understand the Angular lifecycle inside out. Then, once you understand that, you can use ChangeDetectorRef.detectChanges() appropriately (sometimes it's very easy to understand where you should use it, other times it can be very complex).

Wait for all promises to resolve

You can use "await" in an "async function".

app.controller('MainCtrl', async function($scope, $q, $timeout) {
  ...
  var all = await $q.all([one.promise, two.promise, three.promise]); 
  ...
}

NOTE: I'm not 100% sure you can call an async function from a non-async function and have the right results.

That said this wouldn't ever be used on a website. But for load-testing/integration test...maybe.

Example code:

_x000D_
_x000D_
async function waitForIt(printMe) {_x000D_
  console.log(printMe);_x000D_
  console.log("..."+await req());_x000D_
  console.log("Legendary!")_x000D_
}_x000D_
_x000D_
function req() {_x000D_
  _x000D_
  var promise = new Promise(resolve => {_x000D_
    setTimeout(() => {_x000D_
      resolve("DARY!");_x000D_
    }, 2000);_x000D_
    _x000D_
  });_x000D_
_x000D_
    return promise;_x000D_
}_x000D_
_x000D_
waitForIt("Legen-Wait For It");
_x000D_
_x000D_
_x000D_

How to replicate vector in c?

A lot of C projects end up implementing a vector-like API. Dynamic arrays are such a common need, that it's nice to abstract away the memory management as much as possible. A typical C implementation might look something like:

typedef struct dynamic_array_struct
{
  int* data;
  size_t capacity; /* total capacity */
  size_t size; /* number of elements in vector */
} vector;

Then they would have various API function calls which operate on the vector:

int vector_init(vector* v, size_t init_capacity)
{
  v->data = malloc(init_capacity * sizeof(int));
  if (!v->data) return -1;

  v->size = 0;
  v->capacity = init_capacity;

  return 0; /* success */
}

Then of course, you need functions for push_back, insert, resize, etc, which would call realloc if size exceeds capacity.

vector_resize(vector* v, size_t new_size);

vector_push_back(vector* v, int element);

Usually, when a reallocation is needed, capacity is doubled to avoid reallocating all the time. This is usually the same strategy employed internally by std::vector, except typically std::vector won't call realloc because of C++ object construction/destruction. Rather, std::vector might allocate a new buffer, and then copy construct/move construct the objects (using placement new) into the new buffer.

An actual vector implementation in C might use void* pointers as elements rather than int, so the code is more generic. Anyway, this sort of thing is implemented in a lot of C projects. See http://codingrecipes.com/implementation-of-a-vector-data-structure-in-c for an example vector implementation in C.

Convert Text to Date?

This code is working for me

Dim N As Long, r As Range
N = Cells(Rows.Count, "B").End(xlUp).Row
For i = 1 To N
    Set r = Cells(i, "B")
    r.Value = CDate(r.Value)
Next i

Try it changing the columns to suit your sheet

Find if listA contains any elements not in listB

listA.Any(_ => listB.Contains(_))

:)

How do I show a console output/window in a forms application?

Why not just leave it as a Window Forms app, and create a simple form to mimic the Console. The form can be made to look just like the black-screened Console, and have it respond directly to key press. Then, in the program.cs file, you decide whether you need to Run the main form or the ConsoleForm. For example, I use this approach to capture the command line arguments in the program.cs file. I create the ConsoleForm, initially hide it, then pass the command line strings to an AddCommand function in it, which displays the allowed commands. Finally, if the user gave the -h or -? command, I call the .Show on the ConsoleForm and when the user hits any key on it, I shut down the program. If the user doesn't give the -? command, I close the hidden ConsoleForm and Run the main form.

Export HTML table to pdf using jspdf

Here is working example:

in head

<script type="text/javascript" src="jspdf.debug.js"></script>

script:

<script type="text/javascript">
        function demoFromHTML() {
            var pdf = new jsPDF('p', 'pt', 'letter');
            // source can be HTML-formatted string, or a reference
            // to an actual DOM element from which the text will be scraped.
            source = $('#customers')[0];

            // we support special element handlers. Register them with jQuery-style 
            // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
            // There is no support for any other type of selectors 
            // (class, of compound) at this time.
            specialElementHandlers = {
                // element with id of "bypass" - jQuery style selector
                '#bypassme': function(element, renderer) {
                    // true = "handled elsewhere, bypass text extraction"
                    return true
                }
            };
            margins = {
                top: 80,
                bottom: 60,
                left: 40,
                width: 522
            };
            // all coords and widths are in jsPDF instance's declared units
            // 'inches' in this case
            pdf.fromHTML(
                    source, // HTML string or DOM elem ref.
                    margins.left, // x coord
                    margins.top, {// y coord
                        'width': margins.width, // max width of content on PDF
                        'elementHandlers': specialElementHandlers
                    },
            function(dispose) {
                // dispose: object with X, Y of the last line add to the PDF 
                //          this allow the insertion of new lines after html
                pdf.save('Test.pdf');
            }
            , margins);
        }
    </script>

and table:

<div id="customers">
        <table id="tab_customers" class="table table-striped" >
            <colgroup>
                <col width="20%">
                <col width="20%">
                <col width="20%">
                <col width="20%">
            </colgroup>
            <thead>         
                <tr class='warning'>
                    <th>Country</th>
                    <th>Population</th>
                    <th>Date</th>
                    <th>Age</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Chinna</td>
                    <td>1,363,480,000</td>
                    <td>March 24, 2014</td>
                    <td>19.1</td>
                </tr>
                <tr>
                    <td>India</td>
                    <td>1,241,900,000</td>
                    <td>March 24, 2014</td>
                    <td>17.4</td>
                </tr>
                <tr>
                    <td>United States</td>
                    <td>317,746,000</td>
                    <td>March 24, 2014</td>
                    <td>4.44</td>
                </tr>
                <tr>
                    <td>Indonesia</td>
                    <td>249,866,000</td>
                    <td>July 1, 2013</td>
                    <td>3.49</td>
                </tr>
                <tr>
                    <td>Brazil</td>
                    <td>201,032,714</td>
                    <td>July 1, 2013</td>
                    <td>2.81</td>
                </tr>
            </tbody>
        </table> 
    </div>

and button to run:

<button onclick="javascript:demoFromHTML()">PDF</button>

and working example online:

tabel to pdf jspdf

or try this: HTML Table Export

Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space

For anyone still strugging (like me...) after the above more expert replies, this works in Visual Studio 2019:

outputString = Regex.Replace(inputString, @"\W", "_");

Remember to add

using System.Text.RegularExpressions;

Use HTML5 to resize an image before upload

If some of you, like me, encounter orientation problems I have combined the solutions here with a exif orientation fix

https://gist.github.com/SagiMedina/f00a57de4e211456225d3114fd10b0d0

Why does range(start, end) not include end?

Consider the code

for i in range(10):
    print "You'll see this 10 times", i

The idea is that you get a list of length y-x, which you can (as you see above) iterate over.

Read up on the python docs for range - they consider for-loop iteration the primary usecase.

Format / Suppress Scientific Notation from Python Pandas Aggregation Results

Here is another way of doing it, similar to Dan Allan's answer but without the lambda function:

>>> pd.options.display.float_format = '{:.2f}'.format
>>> Series(np.random.randn(3))
0    0.41
1    0.99
2    0.10

or

>>> pd.set_option('display.float_format', '{:.2f}'.format)

How to use sessions in an ASP.NET MVC 4 application?

Due to the stateless nature of the web, sessions are also an extremely useful way of persisting objects across requests by serialising them and storing them in a session.

A perfect use case of this could be if you need to access regular information across your application, to save additional database calls on each request, this data can be stored in an object and unserialised on each request, like so:

Our reusable, serializable object:

[Serializable]
public class UserProfileSessionData
{
    public int UserId { get; set; }

    public string EmailAddress { get; set; }

    public string FullName { get; set; }
}

Use case:

public class LoginController : Controller {

    [HttpPost]
    public ActionResult Login(LoginModel model)
    {
        if (ModelState.IsValid)
        {
            var profileData = new UserProfileSessionData {
                UserId = model.UserId,
                EmailAddress = model.EmailAddress,
                FullName = model.FullName
            }

            this.Session["UserProfile"] = profileData;
        }
    }

    public ActionResult LoggedInStatusMessage()
    {
        var profileData = this.Session["UserProfile"] as UserProfileSessionData;

        /* From here you could output profileData.FullName to a view and
        save yourself unnecessary database calls */
    }

}

Once this object has been serialised, we can use it across all controllers without needing to create it or query the database for the data contained within it again.

Inject your session object using Dependency Injection

In a ideal world you would 'program to an interface, not implementation' and inject your serializable session object into your controller using your Inversion of Control container of choice, like so (this example uses StructureMap as it's the one I'm most familiar with).

public class WebsiteRegistry : Registry
{
    public WebsiteRegistry()
    {
        this.For<IUserProfileSessionData>().HybridHttpOrThreadLocalScoped().Use(() => GetUserProfileFromSession());   
    }

    public static IUserProfileSessionData GetUserProfileFromSession()
    {
        var session = HttpContext.Current.Session;
        if (session["UserProfile"] != null)
        {
            return session["UserProfile"] as IUserProfileSessionData;
        }

        /* Create new empty session object */
        session["UserProfile"] = new UserProfileSessionData();

        return session["UserProfile"] as IUserProfileSessionData;
    }
}

You would then register this in your Global.asax.cs file.

For those that aren't familiar with injecting session objects, you can find a more in-depth blog post about the subject here.

A word of warning:

It's worth noting that sessions should be kept to a minimum, large sessions can start to cause performance issues.

It's also recommended to not store any sensitive data in them (passwords, etc).

The import android.support cannot be resolved

This issue may also occur if you have multiple versions of the same support library android-support-v4.jar. If your project is using other library projects that contain different-2 versions of the support library. To resolve the issue keep the same version of support library at each place.

How can I check if a Perl module is installed on my system from the command line?

For example, to check if the DBI module is installed or not, use

perl -e 'use DBI;'

You will see error if not installed. (from http://www.linuxask.com)

Uses of content-disposition in an HTTP response header

Refer to RFC 6266 (Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)) http://tools.ietf.org/html/rfc6266

How to format numbers as currency string?

Short and fast solution (works everywhere!)

(12345.67).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');  // 12,345.67

The idea behind this solution is replacing matched sections with first match and comma, i.e. '$&,'. The matching is done using lookahead approach. You may read the expression as "match a number if it is followed by a sequence of three number sets (one or more) and a dot".

TESTS:

1        --> "1.00"
12       --> "12.00"
123      --> "123.00"
1234     --> "1,234.00"
12345    --> "12,345.00"
123456   --> "123,456.00"
1234567  --> "1,234,567.00"
12345.67 --> "12,345.67"

DEMO: http://jsfiddle.net/hAfMM/9571/


Extended short solution

You can also extend the prototype of Number object to add additional support of any number of decimals [0 .. n] and the size of number groups [0 .. x]:

/**
 * Number.prototype.format(n, x)
 * 
 * @param integer n: length of decimal
 * @param integer x: length of sections
 */
Number.prototype.format = function(n, x) {
    var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\.' : '$') + ')';
    return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$&,');
};

1234..format();           // "1,234"
12345..format(2);         // "12,345.00"
123456.7.format(3, 2);    // "12,34,56.700"
123456.789.format(2, 4);  // "12,3456.79"

DEMO / TESTS: http://jsfiddle.net/hAfMM/435/


Super extended short solution

In this super extended version you may set different delimiter types:

/**
 * Number.prototype.format(n, x, s, c)
 * 
 * @param integer n: length of decimal
 * @param integer x: length of whole part
 * @param mixed   s: sections delimiter
 * @param mixed   c: decimal delimiter
 */
Number.prototype.format = function(n, x, s, c) {
    var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')',
        num = this.toFixed(Math.max(0, ~~n));

    return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));
};

12345678.9.format(2, 3, '.', ',');  // "12.345.678,90"
123456.789.format(4, 4, ' ', ':');  // "12 3456:7890"
12345678.9.format(0, 3, '-');       // "12-345-679"

DEMO / TESTS: http://jsfiddle.net/hAfMM/612/

Generate Java class from JSON?

You could also try GSON library. Its quite powerful it can create JSON from collections, custom objects and works also vice versa. Its released under Apache Licence 2.0 so you can use it also commercially.

http://code.google.com/p/google-gson/

Auto populate columns in one sheet from another sheet

If I understood you right you want to have sheet1!A1 in sheet2!A1, sheet1!A2 in sheet2!A2,...right?

It might not be the best way but you may type the following

=IF(sheet1!A1<>"",sheet1!A1,"")

and drag it down to the maximum number of rows you expect.

How to check if another instance of my shell script is running

pidof wasn't working for me so I searched some more and came across pgrep

for pid in $(pgrep -f my_script.sh); do
    if [ $pid != $$ ]; then
        echo "[$(date)] : my_script.sh : Process is already running with PID $pid"
        exit 1
    else
      echo "Running with PID $pid"
    fi  
done

Taken in part from answers above and https://askubuntu.com/a/803106/802276

Convert String to Carbon

You were almost there.

Remove protected $dates = ['license_expire']

and then change your LicenseExpire accessor to:

public function getLicenseExpireAttribute($date)
{
    return Carbon::parse($date);
}

This way it will return a Carbon instance no matter what. So for your form you would just have $employee->license_expire->format('Y-m-d') (or whatever format is required) and diffForHumans() should work on your home page as well.

Hope this helps!

Find the most popular element in int[] array

Try this answer. First, the data:

int[] a = {1,2,3,4,5,6,7,7,7,7};

Here, we build a map counting the number of times each number appears:

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i : a) {
    Integer count = map.get(i);
    map.put(i, count != null ? count+1 : 1);
}

Now, we find the number with the maximum frequency and return it:

Integer popular = Collections.max(map.entrySet(),
    new Comparator<Map.Entry<Integer, Integer>>() {
    @Override
    public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
        return o1.getValue().compareTo(o2.getValue());
    }
}).getKey();

As you can see, the most popular number is seven:

System.out.println(popular);
> 7

EDIT

Here's my answer without using maps, lists, etc. and using only arrays; although I'm sorting the array in-place. It's O(n log n) complexity, better than the O(n^2) accepted solution.

public int findPopular(int[] a) {

    if (a == null || a.length == 0)
        return 0;

    Arrays.sort(a);

    int previous = a[0];
    int popular = a[0];
    int count = 1;
    int maxCount = 1;

    for (int i = 1; i < a.length; i++) {
        if (a[i] == previous)
            count++;
        else {
            if (count > maxCount) {
                popular = a[i-1];
                maxCount = count;
            }
            previous = a[i];
            count = 1;
        }
    }

    return count > maxCount ? a[a.length-1] : popular;

}

Update React component every second

i myself like setTimeout more that setInterval but didn't find a solution in class based component .you could use sth like this in class based components:

class based component and setInterval:

_x000D_
_x000D_
class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      date: new Date()
    };
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      this.state.date.toLocaleTimeString()
    );
  }
}

ReactDOM.render( 
  <Clock / > ,
  document.getElementById('app')
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app" />
_x000D_
_x000D_
_x000D_

function based component and setInterval:

https://codesandbox.io/s/sweet-diffie-wsu1t?file=/src/index.js

function based component and setTimeout:

https://codesandbox.io/s/youthful-lovelace-xw46p

Class Not Found Exception when running JUnit test

These steps worked for me.

  • Delete the content of local Maven repository.
  • run mvn clean install in the command line. (cd to the pom directory).
  • Build Project in Eclipse.

Error "The input device is not a TTY"

I believe you need to be in a TTY for docker to be able to allocate a TTY (the -t option). Jenkins executes its jobs not in a TTY.

Having said that, the script you are running within Jenkins you may also want to run locally. In that case it can be really convenient to have a TTY allocated so you can send signals like ctrl+c when running it locally.

To fix this make your script optionally use the -t option, like so:

test -t 1 && USE_TTY="-t" 
docker run ${USE_TTY} ...

Python: Removing spaces from list objects

List comprehension [num.strip() for num in hello] is the fastest.

>>> import timeit
>>> hello = ['999 ',' 666 ']

>>> t1 = lambda: map(str.strip, hello)
>>> timeit.timeit(t1)
1.825870468015296

>>> t2 = lambda: list(map(str.strip, hello))
>>> timeit.timeit(t2)
2.2825958750515269

>>> t3 = lambda: [num.strip() for num in hello]
>>> timeit.timeit(t3)
1.4320335103944899

>>> t4 = lambda: [num.replace(' ', '') for num in hello]
>>> timeit.timeit(t4)
1.7670568718943969

AngularJS sorting by property

according to http://docs.angularjs.org/api/ng.filter:orderBy , orderBy sorts an array. In your case you're passing an object, so You'll have to implement Your own sorting function.

or pass an array -

$scope.testData = {
    C: {name:"CData", order: 1},
    B: {name:"BData", order: 2},
    A: {name:"AData", order: 3},
}

take a look at http://jsfiddle.net/qaK56/

Add padding to HTML text input field

you can solve this, taking the input tag inside a div, then put the padding property on div tag. This work's for me...

Like this:

<div class="paded">
    <input type="text" />
</div>

and css:

.paded{
    padding-right: 20px;
}

How to get cookie expiration date / creation date from javascript?

If you are using Chrome you can goto the "Resources" tab and find the item "Cookies" in the left sidebar. From there select the domain you are checking the set cookie for and it will give you a list of cookies associated with that domain, along with their expiration date.

How to make a link open multiple pages when clicked

You might want to arrange your HTML so that the user can still open all of the links even if JavaScript isn’t enabled. (We call this progressive enhancement.) If so, something like this might work well:

HTML

<ul class="yourlinks">
    <li><a href="http://www.google.com/"></li>
    <li><a href="http://www.yahoo.com/"></li>
</ul>

jQuery

$(function() { // On DOM content ready...
    var urls = [];

    $('.yourlinks a').each(function() {
        urls.push(this.href); // Store the URLs from the links...
    });

    var multilink = $('<a href="#">Click here</a>'); // Create a new link...
    multilink.click(function() {
        for (var i in urls) {
            window.open(urls[i]); // ...that opens each stored link in its own window when clicked...
        }
    });

    $('.yourlinks').replaceWith(multilink); // ...and replace the original HTML links with the new link.
});

This code assumes you’ll only want to use one “multilink” like this per page. (I’ve also not tested it, so it’s probably riddled with errors.)

MySQL: Enable LOAD DATA LOCAL INFILE

in case your flavor of mysql on ubuntu does NOT under any circumstances work and you still get the 1148 error, you can run the load data infile command via command line

open a terminal window

run mysql -u YOURUSERNAME -p --local-infile YOURDBNAME

you will be requested to insert mysqluser password

you will be running MySQLMonitor and your command prompt will be mysql>

run your load data infile command (dont forget to end with a semicolon ; )

like this:

load data local infile '/home/tony/Desktop/2013Mini.csv' into table Reading_Table FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';

Getting key with maximum value in dictionary?

Much simpler to understand approach:

dict = { 'a':302, 'e':53, 'g':302, 'h':100 }
max_value_keys = [key for key in dict.keys() if dict[key] == max(dict.values())]
print(max_value_keys) # prints a list of keys with max value

Output: ['a', 'g']

Now you can choose only one key:

maximum = dict[max_value_keys[0]]

How do I vertically align text in a div?

CSS:

.vertical {
   display: table-caption;
}

Add this class to the element that contains the things you want to align vertically

Android Studio Emulator and "Process finished with exit code 0"

Docker installation selected Hyper-V on windows by default. Deselect the Hyper-v b

This worked for me.

enter image description here

Where does System.Diagnostics.Debug.Write output appear?

The solution for my case is:

  1. Right click the output window;
  2. Check the 'Program Output'

How to set session attribute in java?

By default session object is available on jsp page(implicit object). It will not available in normal POJO java class. You can get the reference of HttpSession object on Servelt by using HttpServletRequest

HttpSession s=request.getSession()
s.setAttribute("name","value");

You can get session on an ActionSupport based Action POJO class as follows

 ActionContext ctx= ActionContext.getContext();
   Map m=ctx.getSession();
   m.put("name", value);

look at: http://ohmjavaclasses.blogspot.com/2011/12/access-session-in-action-class-struts2.html

struct.error: unpack requires a string argument of length 4

By default, on many platforms the short will be aligned to an offset at a multiple of 2, so there will be a padding byte added after the char.

To disable this, use: struct.unpack("=BH", data). This will use standard alignment, which doesn't add padding:

>>> struct.calcsize('=BH')
3

The = character will use native byte ordering. You can also use < or > instead of = to force little-endian or big-endian byte ordering, respectively.

Remote desktop connection protocol error 0x112f

If anyone comes to this thread and has this issue when you remote to a VMware VM with windows 10 1903, disabling 3d in the graphics card worked for me.

Add values to app.config and retrieve them

Are you missing the reference to System.Configuration.dll? ConfigurationManager class lies there.

EDIT: The System.Configuration namespace has classes in mscorlib.dll, system.dll and in system.configuration.dll. Your project always include the mscorlib.dll and system.dll references, but system.configuration.dll must be added to most project types, as it's not there by default...

How to set String's font size, style in Java using the Font class?

Look here http://docs.oracle.com/javase/6/docs/api/java/awt/Font.html#deriveFont%28float%29

JComponent has a setFont() method. You will control the font there, not on the String.

Such as

JButton b = new JButton();
b.setFont(b.getFont().deriveFont(18.0f));

How to insert table values from one database to another database?

Mostly we need this type of query in migration script

INSERT INTO  db1.table1(col1,col2,col3,col4)
SELECT col5,col6,col7,col8
  FROM db1.table2

In this query column count must be same in both table

how do I query sql for a latest record date for each user

I used this way to take the last record for each user that I have on my table. It was a query to get last location for salesman as per recent time detected on PDA devices.

CREATE FUNCTION dbo.UsersLocation()
RETURNS TABLE
AS
RETURN
Select GS.UserID, MAX(GS.UTCDateTime) 'LastDate'
From USERGPS GS
where year(GS.UTCDateTime) = YEAR(GETDATE()) 
Group By GS.UserID
GO
select  gs.UserID, sl.LastDate, gs.Latitude , gs.Longitude
        from USERGPS gs
        inner join USER s on gs.SalesManNo = s.SalesmanNo 
        inner join dbo.UsersLocation() sl on gs.UserID= sl.UserID and gs.UTCDateTime = sl.LastDate 
        order by LastDate desc

Object reference not set to an instance of an object.

I know this was posted about a year ago, but this is for users for future reference.

I came across similar issue. In my case (i will try to be brief, please do let me know if you would like more detail), i was trying to check if a string was empty or not (string is the subject of an email). It always returned the same error message no matter what i did. I knew i was doing it right but it still kept throwing the same error message. Then it dawned in me that, i was checking if the subject (string) of an email (instance/object), what if the email(instance) was already a null at the first place. How could i check for a subject of an email, if the email is already a null..i checked if the the email was empty, it worked fine.

while checking for the subject(string) i used IsNullorWhiteSpace(), IsNullOrEmpty() methods.

if (email == null)
{     
     break;    
}
else
{    
     // your code here    
}

"No such file or directory" but it exists

I had this issue and the reason was EOL in some editors such as Notepad++. You can check it in Edit menu/EOL conversion. Unix(LF) should be selected. I hope it would be useful.

add onclick function to a submit button

html:

<form method="post" name="form1" id="form1">    
    <input id="submit" name="submit" type="submit" value="Submit" onclick="eatFood();" />
</form>

Javascript: to submit the form using javascript

function eatFood() {
document.getElementById('form1').submit();
}

to show onclick message

function eatFood() {
alert('Form has been submitted');
}

"register" keyword in C?

Microsoft's Visual C++ compiler ignores the register keyword when global register-allocation optimization (the /Oe compiler flag) is enabled.

See register Keyword on MSDN.

Python list of dictionaries search

people = [
{'name': "Tom", 'age': 10},
{'name': "Mark", 'age': 5},
{'name': "Pam", 'age': 7}
]

def search(name):
    for p in people:
        if p['name'] == name:
            return p

search("Pam")

Where is the web server root directory in WAMP?

To check what is your root directory go to httpd.conf file of apache and search for "DocumentRoot".The location following it is your root directory

Why is the console window closing immediately once displayed my output?

The program immediately closes because there's nothing stopping it from closing. Insert a breakpoint at return 0; or add Console.Read(); before return 0; to prevent the program from closing.

Change the Right Margin of a View Programmatically?

Update: Android KTX

The Core KTX module provides extensions for common libraries that are part of the Android framework, androidx.core.view among them.

dependencies {
    implementation "androidx.core:core-ktx:{latest-version}"
}

The following extension functions are handy to deal with margins:

Note: they are all extension functions of MarginLayoutParams, so first you need to get and cast the layoutParams of your view:

val params = (myView.layoutParams as ViewGroup.MarginLayoutParams)

Sets the margins of all axes in the ViewGroup's MarginLayoutParams. (The dimension has to be provided in pixels, see the last section if you want to work with dp)

inline fun MarginLayoutParams.setMargins(@Px size: Int): Unit
// E.g. 16px margins
params.setMargins(16)

Updates the margins in the ViewGroup's ViewGroup.MarginLayoutParams.

inline fun MarginLayoutParams.updateMargins(
    @Px left: Int = leftMargin, 
    @Px top: Int = topMargin, 
    @Px right: Int = rightMargin, 
    @Px bottom: Int = bottomMargin
): Unit
// Example: 8px left margin 
params.updateMargins(left = 8)

Updates the relative margins in the ViewGroup's MarginLayoutParams (start/end instead of left/right).

inline fun MarginLayoutParams.updateMarginsRelative(
    @Px start: Int = marginStart, 
    @Px top: Int = topMargin, 
    @Px end: Int = marginEnd, 
    @Px bottom: Int = bottomMargin
): Unit
// E.g: 8px start margin 
params.updateMargins(start = 8)

The following extension properties are handy to get the current margins:

inline val View.marginBottom: Int
inline val View.marginEnd: Int
inline val View.marginLeft: Int
inline val View.marginRight: Int
inline val View.marginStart: Int
inline val View.marginTop: Int
// E.g: get margin bottom
val bottomPx = myView1.marginBottom
  • Using dp instead of px:

If you want to work with dp (density-independent pixels) instead of px, you will need to convert them first. You can easily do that with the following extension property:

val Int.px: Int
    get() = (this * Resources.getSystem().displayMetrics.density).toInt()

Then you can call the previous extension functions like:

params.updateMargins(start = 16.px, end = 16.px, top = 8.px, bottom = 8.px)
val bottomDp = myView1.marginBottom.dp

Old answer:

In Kotlin you can declare an extension function like:

fun View.setMargins(
    leftMarginDp: Int? = null,
    topMarginDp: Int? = null,
    rightMarginDp: Int? = null,
    bottomMarginDp: Int? = null
) {
    if (layoutParams is ViewGroup.MarginLayoutParams) {
        val params = layoutParams as ViewGroup.MarginLayoutParams
        leftMarginDp?.run { params.leftMargin = this.dpToPx(context) }
        topMarginDp?.run { params.topMargin = this.dpToPx(context) }
        rightMarginDp?.run { params.rightMargin = this.dpToPx(context) }
        bottomMarginDp?.run { params.bottomMargin = this.dpToPx(context) }
        requestLayout()
    }
}

fun Int.dpToPx(context: Context): Int {
    val metrics = context.resources.displayMetrics
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), metrics).toInt()
}

Then you can call it like:

myView1.setMargins(8, 16, 34, 42)

Or:

myView2.setMargins(topMarginDp = 8) 

Use 'class' or 'typename' for template parameters?

In response to Mike B, I prefer to use 'class' as, within a template, 'typename' has an overloaded meaning, but 'class' does not. Take this checked integer type example:

template <class IntegerType>
class smart_integer {
public: 
    typedef integer_traits<Integer> traits;
    IntegerType operator+=(IntegerType value){
        typedef typename traits::larger_integer_t larger_t;
        larger_t interm = larger_t(myValue) + larger_t(value); 
        if(interm > traits::max() || interm < traits::min())
            throw overflow();
        myValue = IntegerType(interm);
    }
}

larger_integer_t is a dependent name, so it requires 'typename' to preceed it so that the parser can recognize that larger_integer_t is a type. class, on the otherhand, has no such overloaded meaning.

That... or I'm just lazy at heart. I type 'class' far more often than 'typename', and thus find it much easier to type. Or it could be a sign that I write too much OO code.

How to label each equation in align environment?

The answers seem a bit dated, they don't work for me. What did work was

\begin{align}
1+1=2     \tag{xyz}
\end{align}

reference

How to plot a histogram using Matplotlib in Python with a list of data?

Though the question appears to be demanding plotting a histogram using matplotlib.hist() function, it can arguably be not done using the same as the latter part of the question demands to use the given probabilities as the y-values of bars and given names(strings) as the x-values.

I'm assuming a sample list of names corresponding to given probabilities to draw the plot. A simple bar plot serves the purpose here for the given problem. The following code can be used:

import matplotlib.pyplot as plt
probability = [0.3602150537634409, 0.42028985507246375, 
  0.373117033603708, 0.36813186813186816, 0.32517482517482516, 
  0.4175257731958763, 0.41025641025641024, 0.39408866995073893, 
  0.4143222506393862, 0.34, 0.391025641025641, 0.3130841121495327, 
  0.35398230088495575]
names = ['name1', 'name2', 'name3', 'name4', 'name5', 'name6', 'name7', 'name8', 'name9',
'name10', 'name11', 'name12', 'name13'] #sample names
plt.bar(names, probability)
plt.xticks(names)
plt.yticks(probability) #This may be included or excluded as per need
plt.xlabel('Names')
plt.ylabel('Probability')

How to get the path of a running JAR file?

I'm surprised to see that none recently proposed to use Path. Here follows a citation: "The Path class includes various methods that can be used to obtain information about the path, access elements of the path, convert the path to other forms, or extract portions of a path"

Thus, a good alternative is to get the Path objest as:

Path path = Paths.get(Test.class.getProtectionDomain().getCodeSource().getLocation().toURI());

MySQL Calculate Percentage

try this

   SELECT group_name, employees, surveys, COUNT( surveys ) AS test1, 
        concat(round(( surveys/employees * 100 ),2),'%') AS percentage
    FROM a_test
    GROUP BY employees

DEMO HERE

Selecting multiple items in ListView

Step 1: setAdapter to your listview.

 listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, GENRES)); 

Step 2: set choice mode for listview .The second line of below code represents which checkbox should be checked.

listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setItemChecked(2, true);

listView.setOnItemClickListener(this);



 private static  String[] GENRES = new String[] {
        "Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
        "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
    };

Step 3: Checked views are returned in SparseBooleanArray, so you might use the below code to get key or values.The below sample are simply displayed selected names in a single String.

@Override
    public void onItemClick(AdapterView<?> adapter, View arg1, int arg2, long arg3)
    {

    SparseBooleanArray sp=getListView().getCheckedItemPositions();

    String str="";
    for(int i=0;i<sp.size();i++)
    {
        str+=GENRES[sp.keyAt(i)]+",";
    }
    Toast.makeText(this, ""+str, Toast.LENGTH_SHORT).show();

    }

multiple classes on single element html

It's a good practice if you need them. It's also a good practice is they make sense, so future coders can understand what you're doing.

But generally, no it's not a good practice to attach 10 class names to an object because most likely whatever you're using them for, you could accomplish the same thing with far fewer classes. Probably just 1 or 2.

To qualify that statement, javascript plugins and scripts may append far more classnames to do whatever it is they're going to do. Modernizr for example appends anywhere from 5 - 25 classes to your body tag, and there's a very good reason for it. jQuery UI appends lots of classnames when you use one of the widgets in that library.

.NET Format a string with fixed spaces

it seems like you want something like this, that will place you string at a fixed point in a string of constant length:

Dim totallength As Integer = 100
Dim leftbuffer as Integer = 5
Dim mystring As String = "string goes here"
Dim Formatted_String as String = mystring.PadLeft(leftbuffer + mystring.Length, "-") + String.Empty.PadRight(totallength - (mystring.Length + leftbuffer), "-")

note that this will have problems if mystring.length + leftbuffer exceeds totallength

What is Dispatcher Servlet in Spring?

We can say like DispatcherServlet taking care of everything in Spring MVC.

At web container start up:

  1. DispatcherServlet will be loaded and initialized by calling init() method
  2. init() of DispatcherServlet will try to identify the Spring Configuration Document with naming conventions like "servlet_name-servlet.xml" then all beans can be identified.

Example:

public class DispatcherServlet extends HttpServlet {

    ApplicationContext ctx = null;

    public void init(ServletConfig cfg){
        // 1. try to get the spring configuration document with default naming conventions
        String xml = "servlet_name" + "-servlet.xml";

        //if it was found then creates the ApplicationContext object
        ctx = new XmlWebApplicationContext(xml);
    }
    ...
}

So, in generally DispatcherServlet capture request URI and hand over to HandlerMapping. HandlerMapping search mapping bean with method of controller, where controller returning logical name(view). Then this logical name is send to DispatcherServlet by HandlerMapping. Then DispatcherServlet tell ViewResolver to give full location of view by appending prefix and suffix, then DispatcherServlet give view to the client.

Compare 2 JSON objects

Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).

You need to do a deep equals.

From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.

Object.extend(Object, {
   deepEquals: function(o1, o2) {
     var k1 = Object.keys(o1).sort();
     var k2 = Object.keys(o2).sort();
     if (k1.length != k2.length) return false;
     return k1.zip(k2, function(keyPair) {
       if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
         return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
       } else {
         return o1[keyPair[0]] == o2[keyPair[1]];
       }
     }).all();
   }
});

Usage:

var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);

if (Object.deepEquals(anObj, anotherObj))
   ...

Set HTTP header for one request

Try this, perhaps it works ;)

.factory('authInterceptor', function($location, $q, $window) {


return {
    request: function(config) {
      config.headers = config.headers || {};

      config.headers.Authorization = 'xxxx-xxxx';

      return config;
    }
  };
})

.config(function($httpProvider) {
  $httpProvider.interceptors.push('authInterceptor');
})

And make sure your back end works too, try this. I'm using RESTful CodeIgniter.

class App extends REST_Controller {
    var $authorization = null;

    public function __construct()
    {
        parent::__construct();
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
        if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {
            die();
        }

        if(!$this->input->get_request_header('Authorization')){
            $this->response(null, 400);    
        }

        $this->authorization = $this->input->get_request_header('Authorization');
    }

}

Uploading file using POST request in Node.js

 const remoteReq = request({
    method: 'POST',
    uri: 'http://host.com/api/upload',
    headers: {
      'Authorization': 'Bearer ' + req.query.token,
      'Content-Type': req.headers['content-type'] || 'multipart/form-data;'
    }
  })
  req.pipe(remoteReq);
  remoteReq.pipe(res);

Why am I getting a "401 Unauthorized" error in Maven?

As stated in @John's answer, the fact that there is already a 0.1.2-SNAPSHOT, interfered with my new non-SNAPSHOT version 0.1.2. Since the 401 Unauthorized error is nebulous and unhelpful--and is normally associated to user/pass problems--it's no surprise that I was unable to figure this out on my own.

Changing the version to 0.1.3 brings me back to my original error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-install-plugin:2.4:install (default-install) on project xbnjava: Failed to install artifact com.github.aliteralmind:xbnjava:jar:0.1.3: R:\jeffy\programming\build\xbnjava-0.1.3\download\xbnjava-0.1.3-all.jar (The system cannot find the path specified) -> [Help 1].

A sonatype support person also recommended that I remove the <parent> block from my POM (it's only there because it's in the one from ez-vcard, which is what I started with) and replace my <distributionManagement> block with

<distributionManagement>
  <snapshotRepository>
    <id>ossrh</id>
    <url>https://oss.sonatype.org/content/repositories/snapshots</url>
  </snapshotRepository>
  <repository>
    <id>ossrh</id>
    <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
  </repository>
</distributionManagement>
and then make sure that lines up with what's in your settings.xml:
<settings>
  <servers>
    <server>
      <id>ossrh</id>
      <username>your-jira-id</username>
      <password>your-jira-pwd</password>
    </server>
  </servers>
</settings>

After doing this, running mvn deploy actually uploaded one of my jars for the very first time!!!

Output:

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building XBN-Java 0.1.3
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- build-helper-maven-plugin:1.8:attach-artifact (attach-artifacts) @ xbnjava ---
[INFO]
[INFO] --- maven-install-plugin:2.4:install (default-install) @ xbnjava ---
[INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\pom.xml to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.3\xbnjava-0.1.3.pom
[INFO] Installing R:\jeffy\programming\build\xbnjava-0.1.3\download\xbnjava-0.1.3.jar to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.3\xbnjava-0.1.3.jar
[INFO]
[INFO] --- maven-deploy-plugin:2.7:deploy (default-deploy) @ xbnjava ---
Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.3/xbnjava-0.1.3.pom
2/6 KB
4/6 KB
6/6 KB

Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.3/xbnjava-0.1.3.pom (6 KB at 4.6 KB/sec)
Downloading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml
310/310 B

Downloaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml (310 B at 1.6 KB/sec)
Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml
310/310 B

Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml (310 B at 1.4 KB/sec)
Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.3/xbnjava-0.1.3.jar
2/630 KB
4/630 KB
6/630 KB
8/630 KB
10/630 KB
12/630 KB
14/630 KB
...
618/630 KB
620/630 KB
622/630 KB
624/630 KB
626/630 KB
628/630 KB
630/630 KB

(Success portion:)

Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.3/xbnjava-0.1.3.jar (630 KB at 474.7 KB/sec)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.632 s
[INFO] Finished at: 2014-07-18T15:09:25-04:00
[INFO] Final Memory: 6M/19M
[INFO] ------------------------------------------------------------------------

Here's the full updated POM:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.github.aliteralmind</groupId>
  <artifactId>xbnjava</artifactId>
  <packaging>pom</packaging>
  <version>0.1.3</version>
  <name>XBN-Java</name>
  <url>https://github.com/aliteralmind/xbnjava</url>
  <inceptionYear>2014</inceptionYear>
  <organization>
     <name>Jeff Epstein</name>
  </organization>
  <description>XBN-Java is a collection of generically-useful backend (server side, non-GUI) programming utilities, featuring RegexReplacer and FilteredLineIterator. XBN-Java is the foundation of Codelet (http://codelet.aliteralmind.com).</description>

  <licenses>
     <license>
        <name>Lesser General Public License (LGPL) version 3.0</name>
        <url>https://www.gnu.org/licenses/lgpl-3.0.txt</url>
     </license>
     <license>
        <name>Apache Software License (ASL) version 2.0</name>
        <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
     </license>
  </licenses>

  <developers>
     <developer>
        <name>Jeff Epstein</name>
        <email>[email protected]</email>
        <roles>
           <role>Lead Developer</role>
        </roles>
     </developer>
  </developers>

  <issueManagement>
     <system>GitHub Issue Tracker</system>
     <url>https://github.com/aliteralmind/xbnjava/issues</url>
  </issueManagement>

  <distributionManagement>
    <snapshotRepository>
      <id>ossrh</id>
      <url>https://oss.sonatype.org/content/repositories/snapshots</url>
    </snapshotRepository>
    <repository>
      <id>ossrh</id>
      <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
    </repository>
  </distributionManagement>

  <scm>
     <connection>scm:git:[email protected]:aliteralmind/xbnjava.git</connection>
     <url>scm:git:[email protected]:aliteralmind/xbnjava.git</url>
     <developerConnection>scm:git:[email protected]:aliteralmind/xbnjava.git</developerConnection>
  </scm>

  <properties>
     <java.version>1.7</java.version>
     <jarprefix>R:\jeffy\programming\build\/${project.artifactId}-${project.version}/download/${project.artifactId}-${project.version}</jarprefix>
  </properties>
  <build>
     <plugins>
        <plugin>
           <groupId>org.codehaus.mojo</groupId>
           <artifactId>build-helper-maven-plugin</artifactId>
           <version>1.8</version>
           <executions>
              <execution>
                 <id>attach-artifacts</id>
                 <phase>package</phase>
                 <goals>
                    <goal>attach-artifact</goal>
                 </goals>
                 <configuration>
                    <artifacts>
                       <artifact>
                          <file>${jarprefix}.jar</file>
                          <type>jar</type>
                       </artifact>
                    </artifacts>
                 </configuration>
              </execution>
           </executions>
        </plugin>
     </plugins>
  </build>

  <profiles>
     <!--
     This profile will sign the JAR file, sources file, and javadocs file using the GPG key on the local machine.
     See: https://docs.sonatype.org/display/Repository/How+To+Generate+PGP+Signatures+With+Maven
     -->
     <profile>
        <id>release-sign-artifacts</id>
        <activation>
           <property>
              <name>release</name>
              <value>true</value>
           </property>
        </activation>
     </profile>
  </profiles>
</project>

That's one big Maven problem out of the way. Only 627 more to go.

How to close existing connections to a DB

in restore wizard click "close existing connections to destination database"

in Detach Database wizard click "Drop connection" item.

jQuery Mobile: document ready vs. page events

This is the correct way:

To execute code that will only be available to the index page, we could use this syntax:

$(document).on('pageinit', "#index",  function() {
    ...
});

SQL Server: converting UniqueIdentifier to string in a case statement

I think I found the answer:

convert(nvarchar(50), RequestID)

Here's the link where I found this info:

http://msdn.microsoft.com/en-us/library/ms187928.aspx

Replace line break characters with <br /> in ASP.NET MVC Razor view

I prefer this method as it doesn't require manually emitting markup. I use this because I'm rendering Razor Pages to strings and sending them out via email, which is an environment where the white-space styling won't always work.

public static IHtmlContent RenderNewlines<TModel>(this IHtmlHelper<TModel> html, string content)
{
    if (string.IsNullOrEmpty(content) || html is null)
    {
        return null;
    }

    TagBuilder brTag = new TagBuilder("br");
    IHtmlContent br = brTag.RenderSelfClosingTag();
    HtmlContentBuilder htmlContent = new HtmlContentBuilder();

    // JAS: On the off chance a browser is using LF instead of CRLF we strip out CR before splitting on LF.
    string lfContent = content.Replace("\r", string.Empty, StringComparison.InvariantCulture);
    string[] lines = lfContent.Split('\n', StringSplitOptions.None);
    foreach(string line in lines)
    {
        _ = htmlContent.Append(line);
        _ = htmlContent.AppendHtml(br);
    }

    return htmlContent;
}

What is the height of iPhone's onscreen keyboard?

I can't find latest answer, so I check it all with simulator.(iOS 11.0)


Device | Screen Height | Portrait | Landscape

iPhone 4s | 480.0 | 216.0 | 162.0

iPhone 5, iPhone 5s, iPhone SE | 568.0 | 216.0 | 162.0

iPhone 6, iPhone 6s, iPhone 7, iPhone 8, iPhone X | 667.0 | 216.0 | 162.0

iPhone 6 plus, iPhone 7 plus, iPhone 8 plus | 736.0 | 226.0 | 162.0

iPad 5th generation, iPad Air, iPad Air 2, iPad Pro 9.7, iPad Pro 10.5, iPad Pro 12.9 | 1024.0 | 265.0 | 353.0


Thanks!

How to get request URL in Spring Boot RestController

If you don't want any dependency on Spring's HATEOAS or javax.* namespace, use ServletUriComponentsBuilder to get URI of current request:

import org.springframework.web.util.UriComponentsBuilder;

ServletUriComponentsBuilder.fromCurrentRequest();
ServletUriComponentsBuilder.fromCurrentRequestUri();

Getting list of tables, and fields in each, in a database

This will get you all the user created tables:

select * from sysobjects where xtype='U'

To get the cols:

Select * from Information_Schema.Columns Where Table_Name = 'Insert Table Name Here'

Also, I find http://www.sqlservercentral.com/ to be a pretty good db resource.

Difference between size and length methods?

size() is a method specified in java.util.Collection, which is then inherited by every data structure in the standard library. length is a field on any array (arrays are objects, you just don't see the class normally), and length() is a method on java.lang.String, which is just a thin wrapper on a char[] anyway.

Perhaps by design, Strings are immutable, and all of the top-level Collection subclasses are mutable. So where you see "length" you know that's constant, and where you see "size" it isn't.

Where can I find a list of Mac virtual key codes?

The more canonical reference is in <HIToolbox/Events.h>:

/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h

In newer Versions of MacOS the "Events.h" moved to here:

/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h

How do I truncate a .NET string?

You can create a Truncate extension method that compares the max length relative to the string length and calls Substring if needed.

If you want null handling behavior that parallels that of Substring, don't include a null check. That way, just as str.Substring(0, 10) throws a NullReferenceException if str is null, so will str.Truncate(10).

public static class StringExtensions
{
    public static string Truncate(this string value, int maxLength) =>
        value.Length <= maxLength ? value : value.Substring(0, maxLength); 
}

Interface defining a constructor signature?

I was looking back at this question and I thought to myself, maybe we are aproaching this problem the wrong way. Interfaces might not be the way to go when it concerns defining a constructor with certain parameters... but an (abstract) base class is.

If you create a base class with a constructor on there that accepts the parameters you need, every class that derrives from it needs to supply them.

public abstract class Foo
{
  protected Foo(SomeParameter x)
  {
    this.X = x;
  }

  public SomeParameter X { get; private set }
}

public class Bar : Foo // Bar inherits from Foo
{
  public Bar() 
    : base(new SomeParameter("etc...")) // Bar will need to supply the constructor param
  {
  }
}

TypeError: object of type 'int' has no len() error assistance needed

May be it is the problem of using len() for an integer value. does not posses the len attribute in Python.

Error as:I will give u an example:

number= 1
print(len(num))

Instead of use ths,

data = [1,2,3,4]
print(len(data))

How do multiple clients connect simultaneously to one port, say 80, on a server?

Normally, for every connecting client the server forks a child process that communicates with the client (TCP). The parent server hands off to the child process an established socket that communicates back to the client.

When you send the data to a socket from your child server, the TCP stack in the OS creates a packet going back to the client and sets the "from port" to 80.

Jquery Value match Regex

Change it to this:

var email = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;

This is a regular expression literal that is passed the i flag which means to be case insensitive.

Keep in mind that email address validation is hard (there is a 4 or 5 page regular expression at the end of Mastering Regular Expressions demonstrating this) and your expression certainly will not capture all valid e-mail addresses.

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

If you use vagrant, try this:

First remove config.php in current/vendor.

Run these command:

php artisan config:clear
php artisan clear-compiled
php artisan optimize

NOT RUN php artisan config:cache.

Hope this help.

How can I generate a tsconfig.json file?

You need to have typescript library installed and then you can use

npx tsc --init 

If the response is error TS5023: Unknown compiler option 'init'. that means the library is not installed

yarn add --dev typescript

and run npx command again

PHP random string generator

Here is another solution.

function genRandomString($length = 10)
{
    if($length < 1)
        $length = 1;
    return substr(preg_replace("/[^A-Za-z0-9]/", '', base64_encode(openssl_random_pseudo_bytes($length * 2))), 0, $length);
}

PS. I am using PHP 7.2 on Ubuntu.

How to revert to origin's master branch's version of file

Assuming you did not commit the file, or add it to the index, then:

git checkout -- filename

Assuming you added it to the index, but did not commit it, then:

git reset HEAD filename
git checkout -- filename

Assuming you did commit it, then:

git checkout origin/master filename

Assuming you want to blow away all commits from your branch (VERY DESTRUCTIVE):

git reset --hard origin/master

Android Studio Checkout Github Error "CreateProcess=2" (Windows)

I encountered a similar error with RubyMine 2016.3 recently, wherein any attempts at checkout or export to Github were met with "Cannot run program 'C:\Program Files (x86)\Git\cmd\git.exe': CreateProcess error=2, The system cannot find the file specified"

As an alternative solution for this problem, other than editing the Path system variable, you can try searching through the program files of Android Studio for a git.xml file and editing the myPathToGit option to match the actual location of git.exe on your computer. This is how I fixed this similar issue in RubyMine.

Posting this solution here for the sake of posterity.

What is the purpose of Looper and how to use it?

I will try to explain the purpose of looper class as simple as possible. With a normal thread of Java when the run method completes the execution we say the thread has done it's job and thread lives no longer after that. what if we want to execute more tasks throughout our program with that same thread which is not living anymore? Oh there is a problem now right? Yes because we want to execute more tasks but the thread in not alive anymore. It is where the Looper comes in to rescue us. Looper as the name suggests loops. Looper is nothing more than an infinite loop inside your thread. So, it keeps the thread alive for an infinite time until we explicitly calls quit() method. Calling quit() method on the infinitely alive thread will make the condition false in the infinite loop inside the thread thus, infinite loop will exit. so, the thread will die or will no longer be alive. And it's critical to call the quit() method on our Thread to which looper is attached otherwise they will be there in your system just like Zombies. So, for example if we want to create a background thread to do some multiple tasks over it. we will create a simple Java's thread and will use Looper class to prepare a looper and attach the prepared looper with that thread so that our thread can live as longer as we want them because we can always call quit() anytime whenever we want to terminate our thread. So our the looper will keep our thread alive thus we will be able to execute multiple tasks with the same thread and when we are done we will call quit() to terminate the thread. What if we want our Main thread or UI thread to display the results computed by the background thread or non-UI thread on some UI elements? for that purpose there comes in the concept of Handlers; via handlers we can do inter-process communication or say via handlers two threads can communicate with each other. So, the main thread will have an associated Handler and Background thread will communicate with Main Thread via that handler to get the task done of displaying the results computed by it on some UI elements on Main thread. I know I am explaining only theory here but try to understand the concept because understanding the concept in depth is very important. And I am posting a link below which will take you to a small video series about Looper, Handler and HandlerThread and I will highly recommend watching it and all these concepts will get cleared with examples there.

https://www.youtube.com/watch?v=rfLMwbOKLRk&list=PL6nth5sRD25hVezlyqlBO9dafKMc5fAU2&index=1

reading from app.config file

ConfigurationSettings.AppSettings is deprecated, see here:

http://msdn.microsoft.com/en-us/library/system.configuration.configurationsettings.appsettings.aspx

That said, it should still work.

Just a suggestion, but have you confirmed that your application configuration is the one your executable is using?

Try attaching a debugger and checking the following value:

AppDomain.CurrentDomain.SetupInformation.ConfigurationFile

And then opening the configuration file and verifying the section is there as you expected.

AngularJS : Factory and Service?

$provide service

They are technically the same thing, it's actually a different notation of using the provider function of the $provide service.

  • If you're using a class: you could use the service notation.
  • If you're using an object: you could use the factory notation.

The only difference between the service and the factory notation is that the service is new-ed and the factory is not. But for everything else they both look, smell and behave the same. Again, it's just a shorthand for the $provide.provider function.

// Factory

angular.module('myApp').factory('myFactory', function() {

  var _myPrivateValue = 123;

  return {
    privateValue: function() { return _myPrivateValue; }
  };

});

// Service

function MyService() {
  this._myPrivateValue = 123;
}

MyService.prototype.privateValue = function() {
  return this._myPrivateValue;
};

angular.module('myApp').service('MyService', MyService);

How to navigate to to different directories in the terminal (mac)?

To check that the file you're trying to open actually exists, you can change directories in terminal using cd. To change to ~/Desktop/sass/css: cd ~/Desktop/sass/css. To see what files are in the directory: ls.

If you want information about either of those commands, use the man page: man cd or man ls, for example.

Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.

On Mac OS X, you can also use open to open a finder window: open . will open the current directory in finder. (open ~/Desktop/sass/css will open the ~/Desktop/sass/css).

How to check command line parameter in ".bat" file?

In addition to the other answers, which I subscribe, you may consider using the /I switch of the IF command.

... the /I switch, if specified, says to do case insensitive string compares.

it may be of help if you want to give case insensitive flexibility to your users to specify the parameters.

IF /I "%1"=="-b" GOTO SPECIFIC

How to sort an array of associative arrays by value of a given key in PHP?

//Just in one line custom function
function cmp($a, $b)
{
return (float) $a['price'] < (float)$b['price'];
}
@uasort($inventory, "cmp");
print_r($inventory);

//result

Array
(
[2] => Array
    (
        [type] => pork
        [price] => 5.43
    )

[0] => Array
    (
        [type] => fruit
        [price] => 3.5
    )

[1] => Array
    (
        [type] => milk
        [price] => 2.9
    )

)

Anchor links in Angularjs?

You could try to use anchorScroll.

Example

So the controller would be:

app.controller('MainCtrl', function($scope, $location, $anchorScroll, $routeParams) {
  $scope.scrollTo = function(id) {
     $location.hash(id);
     $anchorScroll();
  }
});

And the view:

<a href="" ng-click="scrollTo('foo')">Scroll to #foo</a>

...and no secret for the anchor id:

<div id="foo">
  This is #foo
</div>

Get SELECT's value and text in jQuery

$("#yourdropdownid option:selected").text(); // selected option text
$("#yourdropdownid").val(); // selected option value

Best way to implement keyboard shortcuts in a Windows Forms application?

From the main Form, you have to:

  • Be sure you set KeyPreview to true( TRUE by default)
  • Add MainForm_KeyDown(..) - by which you can set here any shortcuts you want.

Additionally,I have found this on google and I wanted to share this to those who are still searching for answers. (for global)

I think you have to be using user32.dll

protected override void WndProc(ref Message m)
{
    base.WndProc(ref m);

    if (m.Msg == 0x0312)
    {
        /* Note that the three lines below are not needed if you only want to register one hotkey.
         * The below lines are useful in case you want to register multiple keys, which you can use a switch with the id as argument, or if you want to know which key/modifier was pressed for some particular reason. */

        Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF);                  // The key of the hotkey that was pressed.
        KeyModifier modifier = (KeyModifier)((int)m.LParam & 0xFFFF);       // The modifier of the hotkey that was pressed.
        int id = m.WParam.ToInt32();                                        // The id of the hotkey that was pressed.


        MessageBox.Show("Hotkey has been pressed!");
        // do something
    }
}

Further read this http://www.fluxbytes.com/csharp/how-to-register-a-global-hotkey-for-your-application-in-c/

Enabling HTTPS on express.js

Including Points:

  1. SSL setup
    1. In config/local.js
    2. In config/env/production.js

HTTP and WS handling

  1. The app must run on HTTP in development so we can easily debug our app.
  2. The app must run on HTTPS in production for security concern.
  3. App production HTTP request should always redirect to https.

SSL configuration

In Sailsjs there are two ways to configure all the stuff, first is to configure in config folder with each one has their separate files (like database connection regarding settings lies within connections.js ). And second is configure on environment base file structure, each environment files presents in config/env folder and each file contains settings for particular env.

Sails first looks in config/env folder and then look forward to config/ *.js

Now lets setup ssl in config/local.js.

var local = {
   port: process.env.PORT || 1337,
   environment: process.env.NODE_ENV || 'development'
};

if (process.env.NODE_ENV == 'production') {
    local.ssl = {
        secureProtocol: 'SSLv23_method',
        secureOptions: require('constants').SSL_OP_NO_SSLv3,
        ca: require('fs').readFileSync(__dirname + '/path/to/ca.crt','ascii'),
        key: require('fs').readFileSync(__dirname + '/path/to/jsbot.key','ascii'),
        cert: require('fs').readFileSync(__dirname + '/path/to/jsbot.crt','ascii')
    };
    local.port = 443; // This port should be different than your default port
}

module.exports = local;

Alternative you can add this in config/env/production.js too. (This snippet also show how to handle multiple CARoot certi)

Or in production.js

module.exports = {
    port: 443,
    ssl: {
        secureProtocol: 'SSLv23_method',
        secureOptions: require('constants').SSL_OP_NO_SSLv3,
        ca: [
            require('fs').readFileSync(__dirname + '/path/to/AddTrustExternalCARoot.crt', 'ascii'),
            require('fs').readFileSync(__dirname + '/path/to/COMODORSAAddTrustCA.crt', 'ascii'),
            require('fs').readFileSync(__dirname + '/path/to/COMODORSADomainValidationSecureServerCA.crt', 'ascii')
        ],
        key: require('fs').readFileSync(__dirname + '/path/to/jsbot.key', 'ascii'),
        cert: require('fs').readFileSync(__dirname + '/path/to/jsbot.crt', 'ascii')
    }
};

http/https & ws/wss redirection

Here ws is Web Socket and wss represent Secure Web Socket, as we set up ssl then now http and ws both requests become secure and transform to https and wss respectively.

There are many source from our app will receive request like any blog post, social media post but our server runs only on https so when any request come from http it gives “This site can’t be reached” error in client browser. And we loss our website traffic. So we must redirect http request to https, same rules allow for websocket otherwise socket will fails.

So we need to run same server on port 80 (http), and divert all request to port 443(https). Sails first compile config/bootstrap.js file before lifting server. Here we can start our express server on port 80.

In config/bootstrap.js (Create http server and redirect all request to https)

module.exports.bootstrap = function(cb) {
    var express = require("express"),
        app = express();

    app.get('*', function(req, res) {  
        if (req.isSocket) 
            return res.redirect('wss://' + req.headers.host + req.url)  

        return res.redirect('https://' + req.headers.host + req.url)  
    }).listen(80);
    cb();
};

Now you can visit http://www.yourdomain.com, it will redirect to https://www.yourdomain.com

Where does the iPhone Simulator store its data?

For iOS 8

To locate the Documents folder, you can write a file in the Documents folder:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:@"Words.txt"];
NSString *content = @"Apple";
[content writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];

say, in didFinishLaunchingWithOptions.

Then you can open a Terminal and find the folder:

$ find ~/Library -name Words.txt

excel vba getting the row,cell value from selection.address

Is this what you are looking for ?

Sub getRowCol()

    Range("A1").Select ' example

    Dim col, row
    col = Split(Selection.Address, "$")(1)
    row = Split(Selection.Address, "$")(2)

    MsgBox "Column is : " & col
    MsgBox "Row is : " & row

End Sub

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

Good tutorial for using HTML5 History API (Pushstate?)

I've written a very simple router abstraction on top of History.js, called StateRouter.js. It's in very early stages of development, but I am using it as the routing solution in a single-page application I'm writing. Like you, I found History.js very hard to grasp, especially as I'm quite new to JavaScript, until I understood that you really need (or should have) a routing abstraction on top of it, as it solves a low-level problem.

This simple example code should demonstrate how it's used:

var router = new staterouter.Router();
// Configure routes
router
  .route('/', getHome)
  .route('/persons', getPersons)
  .route('/persons/:id', getPerson);
// Perform routing of the current state
router.perform();

Here's a little fiddle I've concocted in order to demonstrate its usage.

Visual Studio 2015 or 2017 does not discover unit tests

I had the same issue. The unit test template of Visual Studio 2015 (Update 3) generates a class with TestContext property defined as follow:

    private TestContext testContextInstance;

    /// <summary>
    ///Gets or sets the test context which provides
    ///information about and functionality for the current test run.
    ///</summary>
    public TestContext TestContext
    {
        get
        {
            return testContextInstance;
        }
        set
        {
            testContextInstance = value;
        }
    }

After changing it to a public field (ungly) the test runner could discover the test.

public TestContext TestContext;

Very strange behaviour, but it was the cause of the issue in my case.

How to convert answer into two decimal point

If you just want to print a decimal number with 2 digits after decimal point in specific format no matter of locals use something like this

dim d as double = 1.23456789
dim s as string = d.Tostring("0.##", New System.Globalization.CultureInfo("en-US"))

CodeIgniter activerecord, retrieve last insert id?

$this->db->insert_id();

Returns the insert ID number when performing database inserts

Query Helper Methods for codeigniter-3

Add an incremental number in a field in INSERT INTO SELECT query in SQL Server

You can use the row_number() function for this.

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

If you want to start with the maximum already in the table then do:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

Finally, you can just make the sequence column an auto-incrementing identity column. This saves the need to increment it each time:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .
)

Getting Current date, time , day in laravel

use DateTime;

$now = new DateTime();

What's the difference between deadlock and livelock?

DEADLOCK Deadlock is a condition in which a task waits indefinitely for conditions that can never be satisfied - task claims exclusive control over shared resources - task holds resources while waiting for other resources to be released - tasks cannot be forced to relinguish resources - a circular waiting condition exists

LIVELOCK Livelock conditions can arise when two or more tasks depend on and use the some resource causing a circular dependency condition where those tasks continue running forever, thus blocking all lower priority level tasks from running (these lower priority tasks experience a condition called starvation)

SQL SELECT everything after a certain character

Try this in MySQL.

right(field,((CHAR_LENGTH(field))-(InStr(field,','))))

DateTimePicker: pick both date and time

Unfortunately, this is one of the many misnomers in the framework, or at best a violation of SRP.

To use the DateTimePicker for times, set the Format property to either Time or Custom (Use Custom if you want to control the format of the time using the CustomFormat property). Then set the ShowUpDown property to true.

Although a user may set the date and time together manually, they cannot use the GUI to set both.

Casting interfaces for deserialization in JSON.NET

@SamualDavis provided a great solution in a related question, which I'll summarize here.

If you have to deserialize a JSON stream into a concrete class that has interface properties, you can include the concrete classes as parameters to a constructor for the class! The NewtonSoft deserializer is smart enough to figure out that it needs to use those concrete classes to deserialize the properties.

Here is an example:

public class Visit : IVisit
{
    /// <summary>
    /// This constructor is required for the JSON deserializer to be able
    /// to identify concrete classes to use when deserializing the interface properties.
    /// </summary>
    public Visit(MyLocation location, Guest guest)
    {
        Location = location;
        Guest = guest;
    }
    public long VisitId { get; set; }
    public ILocation Location { get;  set; }
    public DateTime VisitDate { get; set; }
    public IGuest Guest { get; set; }
}

Is the practice of returning a C++ reference variable evil?

About horrible code:

int& getTheValue()
{
   return *new int;
}

So, indeed, memory pointer lost after return. But if you use shared_ptr like that:

int& getTheValue()
{
   std::shared_ptr<int> p(new int);
   return *p->get();
}

Memory not lost after return and will be freed after assignment.

How to delete a folder and all contents using a bat file in windows?

@RD /S /Q "D:\PHP_Projects\testproject\Release\testfolder"

Explanation:

Removes (deletes) a directory.

RMDIR [/S] [/Q] [drive:]path RD [/S] [/Q] [drive:]path

/S      Removes all directories and files in the specified directory
        in addition to the directory itself.  Used to remove a directory
        tree.

/Q      Quiet mode, do not ask if ok to remove a directory tree with /S

Notice: Array to string conversion in

Even simpler:

$get = @mysql_query("SELECT money FROM players WHERE username = '" . $_SESSION['username'] . "'");

note the quotes around username in the $_SESSION reference.

How to resolve javax.mail.AuthenticationFailedException issue?

When you are trying to sign in to your Google Account from your new device or application you have to unlock the CAPTCHA. To unlock the CAPTCHA go to https://www.google.com/accounts/DisplayUnlockCaptcha and then enter image description here

And also make sure to allow less secure apps on enter image description here

How to change the order of DataFrame columns?

This question has been answered before but reindex_axis is deprecated now so I would suggest to use:

df = df.reindex(sorted(df.columns), axis=1)

For those who want to specify the order they want instead of just sorting them, here's the solution spelled out:

df = df.reindex(['the','order','you','want'], axis=1)

Now, how you want to sort the list of column names is really not a pandas question, that's a Python list manipulation question. There are many ways of doing that, and I think this answer has a very neat way of doing it.

HTML - how to make an entire DIV a hyperlink?

This is a late answer, but this question appears highly on search results so it's worth answering properly.

Basically, you shouldn't be trying to make a div clickable, but rather make an anchor div-like by giving the <a> tag a display: block CSS attribute.

That way, your HTML remains semantically valid and you can inherit the typical browser behaviours for hyperlinks. It also works even if javascript is disabled / js resources don't load.

500 internal server error, how to debug

You can turn on your PHP errors with error_reporting:

error_reporting(E_ALL);
ini_set('display_errors', 'on');

Edit: It's possible that even after putting this, errors still don't show up. This can be caused if there is a fatal error in the script. From PHP Runtime Configuration:

Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.

You should set display_errors = 1 in your php.ini file and restart the server.

Reading CSV file and storing values into an array

If you need to skip (head-)lines and/or columns, you can use this to create a 2-dimensional array:

    var lines = File.ReadAllLines(path).Select(a => a.Split(';'));
    var csv = (from line in lines               
               select (from col in line
               select col).Skip(1).ToArray() // skip the first column
              ).Skip(2).ToArray(); // skip 2 headlines

This is quite useful if you need to shape the data before you process it further (assuming the first 2 lines consist of the headline, and the first column is a row title - which you don't need to have in the array because you just want to regard the data).

N.B. You can easily get the headlines and the 1st column by using the following code:

    var coltitle = (from line in lines 
                    select line.Skip(1).ToArray() // skip 1st column
                   ).Skip(1).Take(1).FirstOrDefault().ToArray(); // take the 2nd row
    var rowtitle = (from line in lines select line[0] // take 1st column
                   ).Skip(2).ToArray(); // skip 2 headlines

This code example assumes the following structure of your *.csv file:

CSV Matrix

Note: If you need to skip empty rows - which can by handy sometimes, you can do so by inserting

    where line.Any(a=>!string.IsNullOrWhiteSpace(a))

between the from and the select statement in the LINQ code examples above.

Padding characters in printf

There's no way to pad with anything but spaces using printf. You can use sed:

printf "%-50s@%s\n" $PROC_NAME [UP] | sed -e 's/ /-/g' -e 's/@/ /' -e 's/-/ /'

javax.xml.bind.UnmarshalException: unexpected element. Expected elements are (none)

Alternatively if you want to persist in using the DocumentType class. Then you could just add the following annotation on top of your DocumentType class.

    @XmlRootElement(name="document")

Note: the String value "document" refers to the name of the root tag of the xml message.

Get a resource using getResource()

if you are calling from static method, use :

TestGameTable.class.getClassLoader().getResource("dice.jpg");

curl posting with header application/x-www-form-urlencoded

 $curl = curl_init();
 curl_setopt_array($curl, array(
            CURLOPT_URL => "http://example.com",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "value1=111&value2=222",
            CURLOPT_HTTPHEADER => array(
                "cache-control: no-cache",
                "content-type: application/x-www-form-urlencoded"
            ),
        ));
 $response = curl_exec($curl);
 $err = curl_error($curl);

 curl_close($curl);

 if (!$err)
 {
      var_dump($response);
 }

How to scroll table's "tbody" independent of "thead"?

thead {
  position: fixed;
  height: 10px; /* This is whatever height you want */
}
  tbody {
  position: fixed;
  margin-top: 10px; /* This has to match the height of thead */
  height: 300px; /* This is whatever height you want */
}

Counting DISTINCT over multiple columns

You can just use the Count Function Twice.

In this case, it would be:

SELECT COUNT (DISTINCT DocumentId), COUNT (DISTINCT DocumentSessionId) 
FROM DocumentOutputItems

Why not use tables for layout in HTML?

  • 508 Compliance - the ability for a screenreader to make sense of your markup.
  • Waiting for render - tables don't render in the browser until it gets to the end of the </table> element.

How do I send an HTML Form in an Email .. not just MAILTO

> 2020 Answer = The Easy Way using Google Apps Script (5 Mins)

We had a similar challenge to solve yesterday, and we solved it using a Google Apps Script!

Send Email From an HTML Form Without a Backend (Server) via Google!

The solution takes 5 mins to implement and I've documented with step-by-step instructions: https://github.com/nelsonic/html-form-send-email-via-google-script-without-server

Brief Overview

A. Using the sample script, deploy a Google App Script

Deploy the sample script as a Google Spreadsheet APP Script: google-script-just-email.js

3-script-editor-showing-script

remember to set the TO_ADDRESS in the script to where ever you want the emails to be sent.
and copy the APP URL so you can use it in the next step when you publish the script.

B. Create your HTML Form and Set the action to the App URL

Using the sample html file: index.html create a basic form.

7-html-form

remember to paste your APP URL into the form action in the HTML form.

C. Test the HTML Form in your Browser

Open the HTML Form in your Browser, Input some data & submit it!

html form

Submit the form. You should see a confirmation that it was sent: form sent

Open the inbox for the email address you set (above)

email received

Done.

Everything about this is customisable, you can easily style/theme the form with your favourite CSS Library and Store the submitted data in a Google Spreadsheet for quick analysis.
The complete instructions are available on GitHub:
https://github.com/nelsonic/html-form-send-email-via-google-script-without-server

Python object.__repr__(self) should be an expression?

It should be a Python expression that, when eval'd, creates an object with the exact same properties as this one. For example, if you have a Fraction class that contains two integers, a numerator and denominator, your __repr__() method would look like this:

# in the definition of Fraction class
def __repr__(self):
    return "Fraction(%d, %d)" % (self.numerator, self.denominator)

Assuming that the constructor takes those two values.

python for increment inner loop

I read all the above answers and those are actually good.

look at this code:

for i in range(1, 4):
    print("Before change:", i)
    i = 20 # changing i variable
    print("After change:", i) # this line will always print 20

When we execute above code the output is like below,

Before Change: 1
After change: 20
Before Change: 2
After change: 20
Before Change: 3
After change: 20

in python for loop is not trying to increase i value. for loop is just assign values to i which we gave. Using range(4) what we are doing is we give the values to for loop which need assign to the i.

You can use while loop instead of for loop to do same thing what you want,

i = 0
while i < 6:
    print(i)
    j = 0
    while j < 5:
        i += 2 # to increase `i` by 2

This will give,

0
2
4

Thank you !

Collections.emptyList() returns a List<Object>?

You want to use:

Collections.<String>emptyList();

If you look at the source for what emptyList does you see that it actually just does a

return (List<T>)EMPTY_LIST;

Get current date/time in seconds

_x000D_
_x000D_
// The Current Unix Timestamp_x000D_
// 1443535752 seconds since Jan 01 1970. (UTC)_x000D_
_x000D_
// Current time in seconds_x000D_
console.log(Math.floor(new Date().valueOf() / 1000));  // 1443535752_x000D_
console.log(Math.floor(Date.now() / 1000));            // 1443535752_x000D_
console.log(Math.floor(new Date().getTime() / 1000));  // 1443535752
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

jQuery

_x000D_
_x000D_
console.log(Math.floor($.now() / 1000));               // 1443535752
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

VHDL - How should I create a clock in a testbench?

How to use a clock and do assertions

This example shows how to generate a clock, and give inputs and assert outputs for every cycle. A simple counter is tested here.

The key idea is that the process blocks run in parallel, so the clock is generated in parallel with the inputs and assertions.

library ieee;
use ieee.std_logic_1164.all;

entity counter_tb is
end counter_tb;

architecture behav of counter_tb is
    constant width : natural := 2;
    constant clk_period : time := 1 ns;

    signal clk : std_logic := '0';
    signal data : std_logic_vector(width-1 downto 0);
    signal count : std_logic_vector(width-1 downto 0);

    type io_t is record
        load : std_logic;
        data : std_logic_vector(width-1 downto 0);
        count : std_logic_vector(width-1 downto 0);
    end record;
    type ios_t is array (natural range <>) of io_t;
    constant ios : ios_t := (
        ('1', "00", "00"),
        ('0', "UU", "01"),
        ('0', "UU", "10"),
        ('0', "UU", "11"),

        ('1', "10", "10"),
        ('0', "UU", "11"),
        ('0', "UU", "00"),
        ('0', "UU", "01")
    );
begin
    counter_0: entity work.counter port map (clk, load, data, count);

    process
    begin
        for i in ios'range loop
            load <= ios(i).load;
            data <= ios(i).data;
            wait until falling_edge(clk);
            assert count = ios(i).count;
        end loop;
        wait;
    end process;

    process
    begin
        for i in 1 to 2 * ios'length loop
            wait for clk_period / 2;
            clk <= not clk;
        end loop;
        wait;
    end process;
end behav;

The counter would look like this:

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all; -- unsigned

entity counter is
    generic (
        width : in natural := 2
    );
    port (
        clk, load : in std_logic;
        data : in std_logic_vector(width-1 downto 0);
        count : out std_logic_vector(width-1 downto 0)
    );
end entity counter;

architecture rtl of counter is
    signal cnt : unsigned(width-1 downto 0);
begin
    process(clk) is
    begin
        if rising_edge(clk) then
            if load = '1' then
                cnt <= unsigned(data);
            else
                cnt <= cnt + 1;
            end if;
        end if;
    end process;
    count <= std_logic_vector(cnt);
end architecture rtl;

Related: https://electronics.stackexchange.com/questions/148320/proper-clock-generation-for-vhdl-testbenches

How to convert a Title to a URL slug in jQuery?

Well, after reading the answers, I came up with this one.

    const generateSlug = (text) => text.toLowerCase().trim().replace(/[^\w- ]+/g, '').replace(/ /g, '-').replace(/[-]+/g, '-');

Append text to input field

_x000D_
_x000D_
    $('#input-field-id').val($('#input-field-id').val() + 'more text');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<input id="input-field-id" />
_x000D_
_x000D_
_x000D_

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES) Symfony2

In your app/config/parameters.yml

# This file is auto-generated during the composer install
parameters:
    database_driver: pdo_mysql
    database_host: 127.0.0.1
    database_port: 3306
    database_name: symfony
    database_user: root
    database_password: "your_password"
    mailer_transport: smtp
    mailer_host: 127.0.0.1
    mailer_user: null
    mailer_password: null
    locale: en
    secret: ThisTokenIsNotSoSecretChangeIt

The value of database_password should be within double or single quotes as in: "your_password" or 'your_password'.

I have seen most of users experiencing this error because they are using password with leading zero or numeric values.

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

Sometimes this issue comes because the java.version which you have mentioned in POM.xml is not the one installed in your machine.

<properties>
    <java.version>1.7</java.version>
</properties>

Ensure you exactly mention the same version in your pom.xml as the jdk and jre version present in your machine.

How to SELECT by MAX(date)?

Workaround but working solution

Only if ID is autoincrement, you can search for the maximum id instead of the max date. So, by the ID you can find all others fields.

select *
from table
where id IN ( 
              select max(id)
              from table
              group by #MY_FIELD#
              )

Counting the number of non-NaN elements in a numpy ndarray in Python

To determine if the array is sparse, it may help to get a proportion of nan values

np.isnan(ndarr).sum() / ndarr.size

If that proportion exceeds a threshold, then use a sparse array, e.g. - https://sparse.pydata.org/en/latest/

What's the most efficient way to check if a record exists in Oracle?

select decode(count(*), 0, 'N', 'Y') rec_exists 
      from sales 
      where sales_type = 'Accessories'; 

How can I read a text file in Android?

Try this code

public static String pathRoot = "/sdcard/system/temp/";
public static String readFromFile(Context contect, String nameFile) {
    String aBuffer = "";
    try {
        File myFile = new File(pathRoot + nameFile);
        FileInputStream fIn = new FileInputStream(myFile);
        BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
        String aDataRow = "";
        while ((aDataRow = myReader.readLine()) != null) {
            aBuffer += aDataRow;
        }
        myReader.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return aBuffer;
}

How to open google chrome from terminal?

Use command

google-chrome-stable

We can also use command

google-chrome

To open terminal but in my case when I make an interrupt ctrl + c then it get closed so I would recommend to use google-chrome-stable instead of google-chrome

Extract matrix column values by matrix column name

Yes. But place your "test" after the comma if you want the column...

> A <- matrix(sample(1:12,12,T),ncol=4)

> rownames(A) <- letters[1:3]

> colnames(A) <- letters[11:14]
> A[,"l"]
 a  b  c 
 6 10  1 

see also help(Extract)

Adding System.Web.Script reference in class library

You need to add a reference to System.Web.Extensions.dll in project for System.Web.Script.Serialization error.

How to add minutes to current time in swift

Swift 3:

let minutes: TimeInterval = 1 * 60
let nowPlusOne = Date() + minutes

Get name of currently executing test in JUnit 4

JUnit 5 and higher

In JUnit 5 you can inject TestInfo which simplifies test meta data providing to test methods. For example:

@Test
@DisplayName("This is my test")
@Tag("It is my tag")
void test1(TestInfo testInfo) {
    assertEquals("This is my test", testInfo.getDisplayName());
    assertTrue(testInfo.getTags().contains("It is my tag"));
}

See more: JUnit 5 User guide, TestInfo javadoc.

Add swipe to delete UITableViewCell

Xcode asks for UIContextualAction, here what worked for me for the updated version:

For Trailing Swipe Actions:->

 func delete(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
        let company = companies[indexPath.row]
        let action = UIContextualAction(style: .destructive, title: "Delete") { (action, view, _) in
           // Perform Delete Action
        }
        return action
    }
    
    func edit(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
        let action  = UIContextualAction(style: .normal, title: "Edit") { (action, view, escaping) in
            // Perform Edit Action
        }
        return action
    }
    
    override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let delete = self.delete(forRowAtIndexPath: indexPath)
        let edit = self.edit(forRowAtIndexPath: indexPath)
        let swipe = UISwipeActionsConfiguration(actions: [delete, edit])
        return swipe
    }

For Leading Swipe Actions:->

 func delete(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
        let company = companies[indexPath.row]
        let action = UIContextualAction(style: .destructive, title: "Delete") { (action, view, _) in
           // Perform Delete Action
        }
        return action
    }
    
    func edit(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
        let action  = UIContextualAction(style: .normal, title: "Edit") { (action, view, escaping) in
            // Perform Edit Action
        }
        return action
    }
    
    override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let delete = self.delete(forRowAtIndexPath: indexPath)
        let edit = self.edit(forRowAtIndexPath: indexPath)
        let swipe = UISwipeActionsConfiguration(actions: [delete, edit])
        return swipe
    }

Return true for canEditRowAt for tableView Delegate:->

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

How to check if a file exists in Go?

The example by user11617 is incorrect; it will report that the file exists even in cases where it does not, but there was an error of some other sort.

The signature should be Exists(string) (bool, error). And then, as it happens, the call sites are no better.

The code he wrote would better as:

func Exists(name string) bool {
    _, err := os.Stat(name)
    return !os.IsNotExist(err)
}

But I suggest this instead:

func Exists(name string) (bool, error) {
  _, err := os.Stat(name)
  if os.IsNotExist(err) {
    return false, nil
  }
  return err != nil, err
}

Force update of an Android app when a new version is available

try this: First you need to make a request call to the playstore link, fetch current version from there and then compare it with your current version.

String currentVersion, latestVersion;
Dialog dialog;
private void getCurrentVersion(){
 PackageManager pm = this.getPackageManager();
        PackageInfo pInfo = null;

        try {
            pInfo =  pm.getPackageInfo(this.getPackageName(),0);

        } catch (PackageManager.NameNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        currentVersion = pInfo.versionName;

   new GetLatestVersion().execute();

}

private class GetLatestVersion extends AsyncTask<String, String, JSONObject> {

        private ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected JSONObject doInBackground(String... params) {
            try {
//It retrieves the latest version by scraping the content of current version from play store at runtime
                Document doc = Jsoup.connect(urlOfAppFromPlayStore).get();
                latestVersion = doc.getElementsByClass("htlgb").get(6).text();

            }catch (Exception e){
                e.printStackTrace();

            }

            return new JSONObject();
        }

        @Override
        protected void onPostExecute(JSONObject jsonObject) {
            if(latestVersion!=null) {
                if (!currentVersion.equalsIgnoreCase(latestVersion)){
                   if(!isFinishing()){ //This would help to prevent Error : BinderProxy@45d459c0 is not valid; is your activity running? error
                    showUpdateDialog();
                    }
                }
            }
            else
                background.start();
            super.onPostExecute(jsonObject);
        }
    }

private void showUpdateDialog(){
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("A New Update is Available");
        builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse
                        ("market://details?id=yourAppPackageName")));
                dialog.dismiss();
            }
        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                background.start();
            }
        });

        builder.setCancelable(false);
        dialog = builder.show();
    }

c++ bool question

Yes that is correct. "Boolean variables only have two possible values: true (1) and false (0)." cpp tutorial on boolean values

PHP unable to load php_curl.dll extension

You are loading .dll so your OS has to be windows.

First check which php.ini file you are using by running phpinfo()

Then check where your extensions folder is by checking extension_dir attribute in that file.

Next make sure that php_curl.dll is present in that folder. If not copy it over.

Restart apache and check if it works.

Since you installed packages individually, also do this:

Copy the dll file from php_installation_folder/extensions to apache_installation_folder/bin

Passing an integer by reference in Python

class PassByReference:
    def Change(self, var):
        self.a = var
        print(self.a)
s=PassByReference()
s.Change(5)     

hadoop No FileSystem for scheme: file

This is not related to Flink, but I've found this issue in Flink also.

For people using Flink, you need to download Pre-bundled Hadoop and put it inside /opt/flink/lib.

LISTAGG in Oracle to return distinct values

select col1, listaggr(col2,',') within group(Order by col2) from table group by col1 meaning aggregate the strings (col2) into list keeping the order n then afterwards deal with the duplicates as group by col1 meaning merge col1 duplicates in 1 group. perhaps this looks clean and simple as it should be and if in case you want col3 as well just you need to add one more listagg() that is select col1, listaggr(col2,',') within group(Order by col2),listaggr(col3,',') within group(order by col3) from table group by col1

How to save the output of a console.log(object) to a file?

right click on console.. click save as.. its this simple.. you'll get an output text file

How to replace all dots in a string using JavaScript

I add double backslash to the dot to make it work. Cheer.

var st = "okay.this.is.a.string";
var Re = new RegExp("\\.","g");
st = st.replace(Re," ");
alert(st);

How to undo the last commit in git

Try simply to reset last commit using --soft flag

git reset --soft HEAD~1

Note :

For Windows, wrap the HEAD parts in quotes like git reset --soft "HEAD~1"

How do I setup the InternetExplorerDriver so it works

If you are using RemoteDriver things are different. From http://element34.ca/blog/iedriverserver-webdriver-and-python :

You will need to start the server using a line like

java -jar selenium-server-standalone-2.26.0.jar -Dwebdriver.ie.driver=C:\Temp\IEDriverServer.exe

I found that if the IEDriverServer.exe was in C:\Windows\System32\ or its subfolders, it couldn't be found automatically (even though System32 was in the %PATH%) or explicitly using the -D flag.