Programs & Examples On #String decoding

Spring @Transactional read-only propagation

It seem to ignore the settings for the current active transaction, it only apply settings to a new transaction:

org.springframework.transaction.PlatformTransactionManager
TransactionStatus getTransaction(TransactionDefinition definition)
                         throws TransactionException
Return a currently active transaction or create a new one, according to the specified propagation behavior.
Note that parameters like isolation level or timeout will only be applied to new transactions, and thus be ignored when participating in active ones.
Furthermore, not all transaction definition settings will be supported by every transaction manager: A proper transaction manager implementation should throw an exception when unsupported settings are encountered.
An exception to the above rule is the read-only flag, which should be ignored if no explicit read-only mode is supported. Essentially, the read-only flag is just a hint for potential optimization.

Simple Java Client/Server Program

There is a fundamental concept of IP routing: You must have a unique IP address if you want your machine to be reachable via the Internet. This is called a "Public IP Address". "www.whatismyipaddress.com" will give you this. If your server is behind some default gateway, IP packets would reach you via that router. You can not be reached via your private IP address from the outside world. You should note that private IP addresses of client and server may be same as long as their corresponding default gateways have different addresses (that's why IPv4 is still in effect) I guess you're trying to ping from your private address of your client to the public IP address of the server (provided by whatismyipaddress.com). This is not feasible. In order to achieve this, a mapping from private to public address is required, a process called Network Address Translation or NAT in short. This is configured in Firewall or Router. You can create your own private network (say via wifi). In this case, since your client and server would be on the same logical network, no private to public address translation would be required and hence you can communicate using your private IP addresses only.

Can a CSS class inherit one or more other classes?

I ran into this same problem and ended up using a JQuery solution to make it seem like a class can inherit other classes.

<script>
    $(function(){
            $(".composite").addClass("something else");
        });
</script>

This will find all elements with the class "composite" and add the classes "something" and "else" to the elements. So something like <div class="composite">...</div> will end up like so:
<div class="composite something else">...</div>

passing 2 $index values within nested ng-repeat

What about using this syntax (take a look in this plunker). I just discovered this and it's pretty awesome.

ng-repeat="(key,value) in data"

Example:

<div ng-repeat="(indexX,object) in data">
    <div ng-repeat="(indexY,value) in object">
       {{indexX}} - {{indexY}} - {{value}}
    </div>
</div>

With this syntax you can give your own name to $index and differentiate the two indexes.

"VT-x is not available" when I start my Virtual machine

You might try reducing your base memory under settings to around 3175MB and reduce your cores to 1. That should work given that your BIOS is set for virtualization. Use the f12 key, security, virtualization to make sure that it is enabled. If it doesn't say VT-x that is ok, it should say VT-d or the like.

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

You can put the jQuery's Ajax setup in synchronous mode by calling

jQuery.ajaxSetup({async:false});

And then perform your Ajax calls using jQuery.get( ... );

Then just turning it on again once

jQuery.ajaxSetup({async:true});

I guess it works out the same thing as suggested by @Adam, but it might be helpful to someone that does want to reconfigure their jQuery.get() or jQuery.post() to the more elaborate jQuery.ajax() syntax.

How do you create a daemon in Python?

Here's my basic 'Howdy World' Python daemon that I start with, when I'm developing a new daemon application.

#!/usr/bin/python
import time
from daemon import runner

class App():
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path =  '/tmp/foo.pid'
        self.pidfile_timeout = 5
    def run(self):
        while True:
            print("Howdy!  Gig'em!  Whoop!")
            time.sleep(10)

app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()

Note that you'll need the python-daemon library. You can install it by:

pip install python-daemon

Then just start it with ./howdy.py start, and stop it with ./howdy.py stop.

Implement Validation for WPF TextBoxes

I have implemented this validation. But you would be used code behind. It is too much easy and simplest way.

XAML: For name Validtion only enter character from A-Z and a-z.

<TextBox x:Name="first_name_texbox" PreviewTextInput="first_name_texbox_PreviewTextInput" >  </TextBox>

Code Behind.

private void first_name_texbox_PreviewTextInput ( object sender, TextCompositionEventArgs e )
{
    Regex regex = new Regex ( "[^a-zA-Z]+" );
    if ( regex.IsMatch ( first_name_texbox.Text ) )
    {
        MessageBox.Show("Invalid Input !");
    }
}

For Salary and ID validation, replace regex constructor passed value with [0-9]+. It means you can only enter number from 1 to infinite.

You can also define length with [0-9]{1,4}. It means you can only enter less then or equal to 4 digit number. This baracket means {at least,How many number}. By doing this you can define range of numbers in textbox.

May it help to others.

XAML:

Code Behind.

private void salary_texbox_PreviewTextInput ( object sender, TextCompositionEventArgs e )
{
    Regex regex = new Regex ( "[^0-9]+" );
    if ( regex.IsMatch ( salary_texbox.Text ) )
    {
        MessageBox.Show("Invalid Input !");
    }
}

SQL Developer is returning only the date, not the time. How do I fix this?

Date format can also be set by using below query :-

alter SESSION set NLS_DATE_FORMAT = 'date_format'

e.g. : alter SESSION set NLS_DATE_FORMAT = 'DD-MM-YYYY HH24:MI:SS'

PDO's query vs execute

query runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.

execute runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. execute will also perform better if you are repeating a query multiple times. Example of prepared statements:

$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories);
$sth->bindParam(':colour', $colour);
$sth->execute();
// $calories or $color do not need to be escaped or quoted since the
//    data is separated from the query

Best practice is to stick with prepared statements and execute for increased security.

See also: Are PDO prepared statements sufficient to prevent SQL injection?

How do I get extra data from intent on Android?

You can also do like this
// put value in intent

    Intent in = new Intent(MainActivity.this, Booked.class);
    in.putExtra("filter", "Booked");
    startActivity(in);

// get value from intent

    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();
    String filter = bundle.getString("filter");

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

I ran into this issue and my problem was a bit more involved... Originally I was trying to restore a SQL Server 2000 backup to SQL Server 2012. Of course this didn't work cause SQL server 2012 only supports backups from 2005 and upwards .

So, I restored the database on a SQL Server 2008 machine. Once this was done - I copied the database over to restore on SQL Server 2012 - and it failed with the following error

The media family on device 'C:\XXXXXXXXXXX.bak' is incorrectly formed. SQL Server cannot process this media family. RESTORE HEADERONLY is terminating abnormally. (Microsoft SQL Server, Error: 3241)

After a lot of research I found that I had skipped a step - I had to go back to the SQL Server 2008 machine and Right Click On the database(that I wanted to backup)> Properties > Options > Make sure compatibility level is set to SQL Server 2008. > Save

And then re-create the backup - After this I was able to restore to SQL Server 2012.

Perform Segue programmatically and pass parameters to the destination view

I understand the problem of performing the segue at one place and maintaining the state to send parameters in prepare for segue.

I figured out a way to do this. I've added a property called userInfoDict to ViewControllers using a category. and I've override perform segue with identifier too, in such a way that If the sender is self(means the controller itself). It will pass this userInfoDict to the next ViewController.

Here instead of passing the whole UserInfoDict you can also pass the specific params, as sender and override accordingly.

1 thing you need to keep in mind. don't forget to call super method in ur performSegue method.

Split string by single spaces

If strictly one space character is the delimiter, probably std::getline will be valid.
For example:

int main() {
  using namespace std;
  istringstream iss("This  is a string");
  string s;
  while ( getline( iss, s, ' ' ) ) {
    printf( "`%s'\n", s.c_str() );
  }
}

`IF` statement with 3 possible answers each based on 3 different ranges

=IF(X2>=85,0.559,IF(X2>=80,0.327,IF(X2>=75,0.255,-1)))

Explanation:

=IF(X2>=85,                  'If the value is in the highest bracket
      0.559,                 'Use the appropriate number
      IF(X2>=80,             'Otherwise, if the number is in the next highest bracket
           0.327,            'Use the appropriate number
           IF(X2>=75,        'Otherwise, if the number is in the next highest bracket
              0.255,         'Use the appropriate number
              -1             'Otherwise, we're not in any of the ranges (Error)
             )
        )
   )

What is the use of System.in.read()?

May be this example will help you.

import java.io.IOException;

public class MainClass {

    public static void main(String[] args) {
        int inChar;
        System.out.println("Enter a Character:");
        try {
            inChar = System.in.read();
            System.out.print("You entered ");
            System.out.println(inChar);
        }
        catch (IOException e){
            System.out.println("Error reading from user");
        }
    }
}

Add item to Listview control

Simple one, just do like this..

ListViewItem lvi = new ListViewItem(pet.Name);
    lvi.SubItems.Add(pet.Type);
    lvi.SubItems.Add(pet.Age);
    listView.Items.Add(lvi);

If statement within Where clause

You can't use IF like that. You can do what you want with AND and OR:

SELECT t.first_name,
       t.last_name,
       t.employid,
       t.status
  FROM employeetable t
 WHERE ((status_flag = STATUS_ACTIVE   AND t.status = 'A')
     OR (status_flag = STATUS_INACTIVE AND t.status = 'T')
     OR (source_flag = SOURCE_FUNCTION AND t.business_unit = 'production')
     OR (source_flag = SOURCE_USER     AND t.business_unit = 'users'))
   AND t.first_name LIKE firstname
   AND t.last_name  LIKE lastname
   AND t.employid   LIKE employeeid;

How to increase apache timeout directive in .htaccess?

This solution is for Litespeed Server (Apache as well)

Add the following code in .htaccess

RewriteRule .* - [E=noabort:1]
RewriteRule .* - [E=noconntimeout:1]

Litespeed reference

"Bitmap too large to be uploaded into a texture"

NOTE FOR THOSE WHO WANT TO PUT IMAGES OF SMALL SIZE:

Pilot_51's solution (moving your images to drawable-nodpi folder) works, but has another problem: It makes images TOO SMALL on screen unless the images are resized to a very large (like 2000 x 3800) resolution to fit screen -- then it makes your app heavier.

SOLUTION: put your image files in drawable-hdpi -- It worked like a charm for me.

How to get all table names from a database?

If you want to use a high-level API, that hides a lot of the JDBC complexity around database schema metadata, take a look at this article: http://www.devx.com/Java/Article/32443/1954

Is it possible to ignore one single specific line with Pylint?

import config.logging_settings # pylint: disable=W0611

That was simple and is specific for that line.

You can and should use the more readable form:

import config.logging_settings # pylint: disable=unused-import

How do I encrypt and decrypt a string in python?

Try this:

Python Cryptography Toolkit (pycrypto) is required

$ pip install pycrypto

Code:

from Crypto.Cipher import AES
from base64 import b64encode, b64decode


class Crypt:

    def __init__(self, salt='SlTKeYOpHygTYkP3'):
        self.salt = salt.encode('utf8')
        self.enc_dec_method = 'utf-8'

    def encrypt(self, str_to_enc, str_key):
        try:
            aes_obj = AES.new(str_key, AES.MODE_CFB, self.salt)
            hx_enc = aes_obj.encrypt(str_to_enc.encode('utf8'))
            mret = b64encode(hx_enc).decode(self.enc_dec_method)
            return mret
        except ValueError as value_error:
            if value_error.args[0] == 'IV must be 16 bytes long':
                raise ValueError('Encryption Error: SALT must be 16 characters long')
            elif value_error.args[0] == 'AES key must be either 16, 24, or 32 bytes long':
                raise ValueError('Encryption Error: Encryption key must be either 16, 24, or 32 characters long')
            else:
                raise ValueError(value_error)

    def decrypt(self, enc_str, str_key):
        try:
            aes_obj = AES.new(str_key.encode('utf8'), AES.MODE_CFB, self.salt)
            str_tmp = b64decode(enc_str.encode(self.enc_dec_method))
            str_dec = aes_obj.decrypt(str_tmp)
            mret = str_dec.decode(self.enc_dec_method)
            return mret
        except ValueError as value_error:
            if value_error.args[0] == 'IV must be 16 bytes long':
                raise ValueError('Decryption Error: SALT must be 16 characters long')
            elif value_error.args[0] == 'AES key must be either 16, 24, or 32 bytes long':
                raise ValueError('Decryption Error: Encryption key must be either 16, 24, or 32 characters long')
            else:
                raise ValueError(value_error)

Usage:

        test_crpt = Crypt()
        test_text = """Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum."""

        test_key = 'MyKey4TestingYnP'
        test_enc_text = test_crpt.encrypt(test_text, test_key)
        test_dec_text = test_crpt.decrypt(test_enc_text, test_key)
        print(f'Encrypted:{test_enc_text}  Decrypted:{test_dec_text}')

SQL Server stored procedure Nullable parameter

It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.

Other than that, I would suggest two things...

First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...

    ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0

Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.

operator << must take exactly one argument

I ran into this problem with templated classes. Here's a more general solution I had to use:

template class <T>
class myClass
{
    int myField;

    // Helper function accessing my fields
    void toString(std::ostream&) const;

    // Friend means operator<< can use private variables
    // It needs to be declared as a template, but T is taken
    template <class U>
    friend std::ostream& operator<<(std::ostream&, const myClass<U> &);
}

// Operator is a non-member and global, so it's not myClass<U>::operator<<()
// Because of how C++ implements templates the function must be
// fully declared in the header for the linker to resolve it :(
template <class U>
std::ostream& operator<<(std::ostream& os, const myClass<U> & obj)
{
  obj.toString(os);
  return os;
}

Now: * My toString() function can't be inline if it is going to be tucked away in cpp. * You're stuck with some code in the header, I couldn't get rid of it. * The operator will call the toString() method, it's not inlined.

The body of operator<< can be declared in the friend clause or outside the class. Both options are ugly. :(

Maybe I'm misunderstanding or missing something, but just forward-declaring the operator template doesn't link in gcc.

This works too:

template class <T>
class myClass
{
    int myField;

    // Helper function accessing my fields
    void toString(std::ostream&) const;

    // For some reason this requires using T, and not U as above
    friend std::ostream& operator<<(std::ostream&, const myClass<T> &)
    {
        obj.toString(os);
        return os;
    }
}

I think you can also avoid the templating issues forcing declarations in headers, if you use a parent class that is not templated to implement operator<<, and use a virtual toString() method.

Java OCR implementation

Just found this one (don't know it, not tested, check yourself)

Ron Cemer Java OCR


As you only need this for curiosity you could look into the source of this applet.

It does OCR of handwritten characters with a neural network

Java OCR: Handwriting Recognition

Convert base64 png data to javascript file objects

Way 1: only works for dataURL, not for other types of url.

function dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
}

//Usage example:
var file = dataURLtoFile('data:image/png;base64,......', 'a.png');
console.log(file);

Way 2: works for any type of url, (http url, dataURL, blobURL, etc...)

//return a promise that resolves with a File instance
function urltoFile(url, filename, mimeType){
    mimeType = mimeType || (url.match(/^data:([^;]+);/)||'')[1];
    return (fetch(url)
        .then(function(res){return res.arrayBuffer();})
        .then(function(buf){return new File([buf], filename, {type:mimeType});})
    );
}

//Usage example:
urltoFile('data:image/png;base64,......', 'a.png')
.then(function(file){
    console.log(file);
})

Both works in Chrome and Firefox.

Date difference in minutes in Python

In Other ways to get difference between date;

import dateutil.parser
import datetime

timeDifference = current_date - dateutil.parser.parse(last_sent_date)
time_difference_in_minutes = (int(timeDifference.days) * 24 * 60) + int((timeDifference.seconds) / 60)

Thanks

Execute an action when an item on the combobox is selected

Not an answer to the original question, but an example to the how-to-make-reusable and working custom renderers without breaking MVC :-)

// WRONG
public class DataWrapper {
   final Data data;
   final String description;
   public DataWrapper(Object data, String description) {
       this.data = data;
       this.description = description;
   }
   ....
   @Override
   public String toString() {
       return description;
   } 
}
// usage
myModel.add(new DataWrapper(data1, data1.getName());

It is wrong in a MVC environment, because it is mixing data and view: now the model doesn't contain the data but a wrapper which is introduced for view reasons. That's breaking separation of concerns and encapsulation (every class interacting with the model needs to be aware of the wrapped data).

The driving forces for breaking of rules were:

  • keep functionality of the default KeySelectionManager (which is broken by a custom renderer)
  • reuse of the wrapper class (can be applied to any data type)

As in Swing a custom renderer is the small coin designed to accomodate for custom visual representation, a default manager which can't cope is ... broken. Tweaking design just to accommodate for such a crappy default is the wrong way round, kind of upside-down. The correct is, to implement a coping manager.

While re-use is fine, doing so at the price of breaking the basic architecture is not a good bargin.

We have a problem in the presentation realm, let's solve it in the presentation realm with the elements designed to solve exactly that problem. As you might have guessed, SwingX already has such a solution :-)

In SwingX, the provider of a string representation is called StringValue, and all default renderers take such a StringValue to configure themselves:

StringValue sv = new StringValue() {
     @Override
     public String getString(Object value) {
        if (value instanceof Data) {
            return ((Data) value).getSomeProperty();
        }
        return TO_STRING.getString(value);
     }
};
DefaultListRenderer renderer = new DefaultListRenderer(sv);

As the defaultRenderer is-a StringValue (implemented to delegate to the given), a well-behaved implementation of KeySelectionManager now can delegate to the renderer to find the appropriate item:

public BetterKeySelectionManager implements KeySelectionManager {

     @Override
     public int selectionForKey(char ch, ComboBoxModel model) {

         ....
         if (getCellRenderer() instance of StringValue) {
              String text = ((StringValue) getCellRenderer()).getString(model.getElementAt(row));
              ....
         } 
     }

}

Outlined the approach because it is easily implementable even without using SwingX, simply define implement something similar and use it:

  • some provider of a string representation
  • a custom renderer which is configurable by that provider and guarantees to use it in configuring itself
  • a well-behaved keySelectionManager with queries the renderer for its string represention

All except the string provider is reusable as-is (that is exactly one implemenation of the custom renderer and the keySelectionManager). There can be general implementations of the string provider, f.i. those formatting value or using bean properties via reflection. And all without breaking basic rules :-)

Convert number of minutes into hours & minutes using PHP

function hour_min($minutes){// Total
   if($minutes <= 0) return '00 Hours 00 Minutes';
else    
   return sprintf("%02d",floor($minutes / 60)).' Hours '.sprintf("%02d",str_pad(($minutes % 60), 2, "0", STR_PAD_LEFT)). " Minutes";
}
echo hour_min(250); //Function Call will return value : 04 Hours 10 Minutes

Php - testing if a radio button is selected and get the value

A very more efficient way to do this in php:

<form action="#" method="post">
<select name="Color">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Pink">Pink</option>
<option value="Yellow">Yellow</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
<?php
if(isset($_POST['submit'])){
$selected_val = $_POST['Color'];  // Storing Selected Value In Variable
echo "You have selected :" .$selected_val;  // Displaying Selected Value
}
?>

and for check boxes multiple choice:

<form action="#" method="post">
<select name="Color[]" multiple> // Initializing Name With An Array
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Pink">Pink</option>
<option value="Yellow">Yellow</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
<?php
if(isset($_POST['submit'])){
// As output of $_POST['Color'] is an array we have to use foreach Loop to display individual value
foreach ($_POST['Color'] as $select)
{
echo "You have selected :" .$select; // Displaying Selected Value
}
?> 

Add SUM of values of two LISTS into new LIST

If you consider your lists as numpy array, then you need to easily sum them:

import numpy as np

third = np.array(first) + np.array(second)

print third

[7, 9, 11, 13, 15]

Using group by and having clause

The semantics of Having

To better understand having, you need to see it from a theoretical point of view.

A group by is a query that takes a table and summarizes it into another table. You summarize the original table by grouping the original table into subsets (based upon the attributes that you specify in the group by). Each of these groups will yield one tuple.

The Having is simply equivalent to a WHERE clause after the group by has executed and before the select part of the query is computed.

Lets say your query is:

select a, b, count(*) 
from Table 
where c > 100 
group by a, b 
having count(*) > 10;

The evaluation of this query can be seen as the following steps:

  1. Perform the WHERE, eliminating rows that do not satisfy it.
  2. Group the table into subsets based upon the values of a and b (each tuple in each subset has the same values of a and b).
  3. Eliminate subsets that do not satisfy the HAVING condition
  4. Process each subset outputting the values as indicated in the SELECT part of the query. This creates one output tuple per subset left after step 3.

You can extend this to any complex query there Table can be any complex query that return a table (a cross product, a join, a UNION, etc).

In fact, having is syntactic sugar and does not extend the power of SQL. Any given query:

SELECT list 
FROM table
GROUP BY attrList
HAVING condition;

can be rewritten as:

SELECT list from (
   SELECT listatt 
   FROM table 
   GROUP BY attrList) as Name
WHERE condition;

The listatt is a list that includes the GROUP BY attributes and the expressions used in list and condition. It might be necessary to name some expressions in this list (with AS). For instance, the example query above can be rewritten as:

select a, b, count 
from (select a, b, count(*) as count
      from Table 
      where c > 100
      group by a, b) as someName
where count > 10;

The solution you need

Your solution seems to be correct:

SELECT s.sid, s.name
FROM Supplier s, Supplies su, Project pr
WHERE s.sid = su.sid AND su.jid = pr.jid
GROUP BY s.sid, s.name
HAVING COUNT (DISTINCT pr.jid) >= 2 

You join the three tables, then using sid as a grouping attribute (sname is functionally dependent on it, so it does not have an impact on the number of groups, but you must include it, otherwise it cannot be part of the select part of the statement). Then you are removing those that do not satisfy your condition: the satisfy pr.jid is >= 2, which is that you wanted originally.

Best solution to your problem

I personally prefer a simpler cleaner solution:

  1. You need to only group by Supplies (sid, pid, jid**, quantity) to find the sid of those that supply at least to two projects.
  2. Then join it to the Suppliers table to get the supplier same.

 SELECT sid, sname from
    (SELECT sid from supplies 
    GROUP BY sid, pid 
    HAVING count(DISTINCT jid) >= 2
    ) AS T1
NATURAL JOIN 
Supliers;

It will also be faster to execute, because the join is only done when needed, not all the times.

--dmg

How do I install a custom font on an HTML site

Yes, you can use the CSS feature named @font-face. It has only been officially approved in CSS3, but been proposed and implemented in CSS2 and has been supported in IE for quite a long time.

You declare it in the CSS like this:

 @font-face { font-family: Delicious; src: url('Delicious-Roman.otf'); } 
 @font-face { font-family: Delicious; font-weight: bold; src: url('Delicious-Bold.otf');}

Then, you can just reference it like the other standard fonts:

 h3 { font-family: Delicious, sans-serif; }

So, in this case,

<html>
   <head>
    <style>
      @font-face { font-family: JuneBug; src: url('JUNEBUG.TTF'); } 
      h1 {
         font-family: JuneBug
      }
    </style>
   </head>
   <body>
      <h1>Hey, June</h1>
   </body>
</html>

And you just need to put the JUNEBUG.TFF in the same location as the html file.

I downloaded the font from the dafont.com website:

http://www.dafont.com/junebug.font

Tar archiving that takes input from a list of files

For me on AIX, it worked as follows:

tar -L List.txt -cvf BKP.tar

How do I generate a list with a specified increment step?

Executing seq(1, 10, 1) does what 1:10 does. You can change the last parameter of seq, i.e. by, to be the step of whatever size you like.

> #a vector of even numbers
> seq(0, 10, by=2) # Explicitly specifying "by" only to increase readability 
> [1]  0  2  4  6  8 10

Querying DynamoDB by date

Approach I followed to solve this problem is by created a Global Secondary Index as below. Not sure if this is the best approach but hopefully if it is useful to someone.

Hash Key                 | Range Key
------------------------------------
Date value of CreatedAt  | CreatedAt

Limitation imposed on the HTTP API user to specify the number of days to retrieve data, defaulted to 24 hr.

This way, I can always specify the HashKey as Current date's day and RangeKey can use > and < operators while retrieving. This way the data is also spread across multiple shards.

How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

    D:\Java\jdk1.5.0_10\bin\keytool -import -file "D:\Certificates\SDS services\Dev\dev-sdsservices-was8.infavig.com.cer" -keystore "D:\Java\jdk1.5.0_10\jre\lib\security\cacerts" -alias "sds certificate"

How to run a Powershell script from the command line and pass a directory as a parameter

Change your code to the following :

Function Foo($directory)
    {
        echo $directory
    }

    if ($args.Length -eq 0)
    {
        echo "Usage: Foo <directory>"
    }
    else
    {
        Foo([string[]]$args)
    }

And then invoke it as:

powershell -ExecutionPolicy RemoteSigned -File "c:\foo.ps1" "c:\Documents and Settings" "c:\test"

Can Android Studio be used to run standard Java projects?

Tested in Android Studio 0.8.14:
I was able to get a standard project running with minimal steps in this way:

  • In an open Android Studio project, click File > New Module.
  • Click More Modules > Java Library > Next, then fill in whatever you prefer for the names.
  • A new module will appear as a folder on the same level as your "app" folder in the Project Structure. Open it and open the new Java class file.

    You can then add your code, and choose Build > Run 'YourClassName'. Presto, your code is running with no Android device!

  • what is the unsigned datatype?

    Bringing my answer from another question.

    From the C specification, section 6.7.2:

    — unsigned, or unsigned int

    Meaning that unsigned, when not specified the type, shall default to unsigned int. So writing unsigned a is the same as unsigned int a.

    Find object by its property in array of objects with AngularJS way

    The solucion that work for me is the following

    $filter('filter')(data, {'id':10}) 
    

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

    Something like this?

    <!DOCTYPE html>
    <html>
    <head>
    <style>
    form * {
      display: block;
      margin: 10px;
    }
    </style>
    <script language="Javascript" >
    function download(filename, text) {
      var pom = document.createElement('a');
      pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 
    
    encodeURIComponent(text));
      pom.setAttribute('download', filename);
    
      pom.style.display = 'none';
      document.body.appendChild(pom);
    
      pom.click();
    
      document.body.removeChild(pom);
    }
    </script>
    </head>
    <body>
    
    <form onsubmit="download(this['name'].value, this['text'].value)">
      <input type="text" name="name" value="test.txt">
      <textarea rows=3 cols=50 name="text">Please type in this box. When you 
    
    click the Download button, the contents of this box will be downloaded to 
    
    your machine at the location you specify. Pretty nifty. </textarea>
      <input type="submit" value="Download">
    </form>
    </body>
    </html>
    

    Saving awk output to variable

    I think the $() syntax is easier to read...

    variable=$(ps -ef | grep "port 10 -" | grep -v "grep port 10 -"| awk '{printf "%s", $12}')
    

    But the real issue is probably that $12 should not be qouted with ""

    Edited since the question was changed, This returns valid data, but it is not clear what the expected output of ps -ef is and what is expected in variable.

    gcloud command not found - while installing Google Cloud SDK

    $ sudo su
    $ /opt/google-appengine-sdk/bin/gcloud components update
    $ su <yourusername>
    

    How to write a simple Java program that finds the greatest common divisor between two numbers?

    One way to do it is the code below:

            int gcd = 0;
            while (gcdNum2 !=0 && gcdNum1 != 0 ) {
            if(gcdNum1 % gcdNum2 == 0){
                gcd = gcdNum2;
            }
                int aux = gcdNum2; 
                gcdNum2 = gcdNum1 % gcdNum2;
                gcdNum1 = aux;
        }
    

    You do not need recursion to do this.

    And be careful, it says that when a number is zero, then the GCD is the number that is not zero.

        while (gcdNum1 == 0) {
        gcdNum1 = 0;
    }
    

    You should modify this to fulfill the requirement.

    I am not going to tell you how to modify your code entirely, only how to calculate the gcd.

    Convert Json Array to normal Java list

    You can use a String[] instead of an ArrayList<String>:

    Hope it helps!

       private String[] getStringArray(JSONArray jsonArray) throws JSONException {
                if (jsonArray != null) {
                    String[] stringsArray = new String[jsonArray.length()];
                    for (int i = 0; i < jsonArray.length(); i++) {
                        stringsArray[i] = jsonArray.getString(i);
                    }
                    return stringsArray;
                } else
                    return null;
            }
    

    ASP.net using a form to insert data into an sql server table

    There are tons of sample code online as to how to do this.

    Here is just one example of how to do this: http://geekswithblogs.net/dotNETvinz/archive/2009/04/30/creating-a-simple-registration-form-in-asp.net.aspx

    you define the text boxes between the following tag:

    <form id="form1" runat="server"> 
    

    you create your textboxes and define them to runat="server" like so:

    <asp:TextBox ID="TxtName" runat="server"></asp:TextBox>
    

    define a button to process your logic like so (notice the onclick):

    <asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />
    

    in the code behind, you define what you want the server to do if the user clicks on the button by defining a method named

    protected void Button1_Click(object sender, EventArgs e)
    

    or you could just double click the button in the design view.

    Here is a very quick sample of code to insert into a table in the button click event (codebehind)

    protected void Button1_Click(object sender, EventArgs e)
    {
       string name = TxtName.Text; // Scrub user data
    
       string connString = ConfigurationManager.ConnectionStrings["yourconnstringInWebConfig"].ConnectionString;
       SqlConnection conn = null;
       try
       {
              conn = new SqlConnection(connString);
              conn.Open();
    
              using(SqlCommand cmd = new SqlCommand())
              {
                     cmd.Conn = conn;
                     cmd.CommandType = CommandType.Text;
                     cmd.CommandText = "INSERT INTO dummyTable(name) Values (@var)";
                     cmd.Parameters.AddWithValue("@var", name);
                     int rowsAffected = cmd.ExecuteNonQuery();
                     if(rowsAffected ==1)
                     {
                            //Success notification
                     }
                     else
                     {
                            //Error notification
                     }
              }
       }
       catch(Exception ex)
       {
              //log error 
              //display friendly error to user
       }
       finally
       {
              if(conn!=null)
              {
                     //cleanup connection i.e close 
              }
       }
    }
    

    How to Update Date and Time of Raspberry Pi With out Internet

    Thanks for the replies.
    What I did was,
    1. I install meinberg ntp software application on windows 7 pc. (softros ntp server is also possible.)
    2. change raspberry pi ntp.conf file (for auto update date and time)

    server xxx.xxx.xxx.xxx iburst
    server 1.debian.pool.ntp.org iburst
    server 2.debian.pool.ntp.org iburst
    server 3.debian.pool.ntp.org iburst
    

    3. If you want to make sure that date and time update at startup run this python script in rpi,

    import os
    
    try:
        client = ntplib.NTPClient()
        response = client.request('xxx.xxx.xxx.xxx', version=4)
        print "===================================="
        print "Offset : "+str(response.offset)
        print "Version : "+str(response.version)
        print "Date Time : "+str(ctime(response.tx_time))
        print "Leap : "+str(ntplib.leap_to_text(response.leap))
        print "Root Delay : "+str(response.root_delay)
        print "Ref Id : "+str(ntplib.ref_id_to_text(response.ref_id))
        os.system("sudo date -s '"+str(ctime(response.tx_time))+"'")
        print "===================================="
    except:
        os.system("sudo date")
        print "NTP Server Down Date Time NOT Set At The Startup"
        pass
    

    I found more info in raspberry pi forum.

    Avoiding "resource is out of sync with the filesystem"

    This happens to me all the time.

    Go to the error log, find the exception, and open a few levels until you can see something more like a root cause. Does it says "Resource is out of sync with the file system" ?

    When renaming packages, of course, Eclipse has to move files around in the file system. Apparently what happens is that it later discovers that something it thinks it needs to clean up has been renamed, can't find it, throws an exception.

    There are a couple of things you might try. First, go to Window: Preferences, Workspace, and enable "Refresh Automatically". In theory this should fix the problem, but for me, it didn't.

    Second, if you are doing a large refactoring with subpackages, do the subpackages one at a time, from the bottom up, and explicitly refresh with the file system after each subpackage is renamed.

    Third, just ignore the error: when the error dialog comes up, click Abort to preserve the partial change, instead of rolling it back. Try it again, and again, and you may find you can get through the entire operation using multiple retries.

    How do I prevent a parent's onclick event from firing when a child anchor is clicked?

    e.stopPropagation() is a correct solution, but in case you don't want to attach any event handler to your inner anchor, you can simply attach this handler to your outer div:

    e => { e.target === e.currentTarget && window.location = URL; }
    

    Comments in Markdown

    An alternative is to put comments within stylized HTML tags. This way, you can toggle their visibility as needed. For example, define a comment class in your CSS stylesheet.

    .comment { display: none; }

    Then, the following enhanced MARKDOWN

    We do <span class="comment">NOT</span> support comments

    appears as follows in a BROWSER

    We do support comments

    #1071 - Specified key was too long; max key length is 1000 bytes

    I had this issue, and solved by following:

    Cause

    There is a known bug with MySQL related to MyISAM, the UTF8 character set and indexes that you can check here.

    Resolution

    • Make sure MySQL is configured with the InnoDB storage engine.

    • Change the storage engine used by default so that new tables will always be created appropriately:

      set GLOBAL storage_engine='InnoDb';

    • For MySQL 5.6 and later, use the following:

      SET GLOBAL default_storage_engine = 'InnoDB';

    • And finally make sure that you're following the instructions provided in Migrating to MySQL.

    Reference

    How can I change from SQL Server Windows mode to mixed mode (SQL Server 2008)?

    You can do it with SQL Management Studio -

    Server Properties - Security - [Server Authentication section] you check Sql Server and Windows authentication mode

    Here is the msdn source - http://msdn.microsoft.com/en-us/library/ms188670.aspx

    How to concatenate two strings to build a complete path

    This should works for empty dir (You may need to check if the second string starts with / which should be treat as an absolute path?):

    #!/bin/bash
    
    join_path() {
        echo "${1:+$1/}$2" | sed 's#//#/#g'
    }
    
    join_path "" a.bin
    join_path "/data" a.bin
    join_path "/data/" a.bin
    

    Output:

    a.bin
    /data/a.bin
    /data/a.bin
    

    Reference: Shell Parameter Expansion

    Free c# QR-Code generator

    ZXing is an open source project that can detect and parse a number of different barcodes. It can also generate QR-codes. (Only QR-codes, though).

    There are a number of variants for different languages: ActionScript, Android (java), C++, C#, IPhone (Obj C), Java ME, Java SE, JRuby, JSP. Support for generating QR-codes comes with some of those: ActionScript, Android, C# and the Java variants.

    How can I throw a general exception in Java?

    You can define your own exception class extending java.lang.Exception (that's for a checked exception - these which must be caught), or extending java.lang.RuntimeException - these exceptions does not have to be caught.

    The other solution is to review the Java API and finding an appropriate exception describing your situation: in this particular case I think that the best one would be IllegalArgumentException.

    How to move a file?

      import os,shutil
    
      current_path = "" ## source path
    
      new_path = "" ## destination path
    
      os.chdir(current_path)
    
      for files in os.listdir():
    
            os.rename(files, new_path+'{}'.format(f))
            shutil.move(files, new_path+'{}'.format(f)) ## to move files from 
    

    different disk ex. C: --> D:

    Clear the value of bootstrap-datepicker

    I was having similar trouble and the following worked for me:

    $('#datepicker').val('').datepicker('update');
    

    Both method calls were needed, otherwise it didn't clear.

    Can you use a trailing comma in a JSON object?

    Use JSON5. Don't use JSON.

    • Objects and arrays can have trailing commas
    • Object keys can be unquoted if they're valid identifiers
    • Strings can be single-quoted
    • Strings can be split across multiple lines
    • Numbers can be hexadecimal (base 16)
    • Numbers can begin or end with a (leading or trailing) decimal point.
    • Numbers can include Infinity and -Infinity.
    • Numbers can begin with an explicit plus (+) sign.
    • Both inline (single-line) and block (multi-line) comments are allowed.

    http://json5.org/

    https://github.com/aseemk/json5

    How to write/update data into cells of existing XLSX workbook using xlsxwriter in python

    you can use this code to open (test.xlsx) file and modify A1 cell and then save it with a new name

    import openpyxl
    xfile = openpyxl.load_workbook('test.xlsx')
    
    sheet = xfile.get_sheet_by_name('Sheet1')
    sheet['A1'] = 'hello world'
    xfile.save('text2.xlsx')
    

    replace anchor text with jquery

    Try

    $("#link1").text()
    

    to access the text inside your element. The # indicates you're searching by id. You aren't looking for a child element, so you don't need children(). Instead you want to access the text inside the element your jQuery function returns.

    Google maps Marker Label with multiple characters

    As of API version 3.26.10, you can set the marker label with more than one characters. The restriction is lifted.

    Try it, it works!

    Moreover, using a MarkerLabel object instead of just a string, you can set a number of properties for the appearance, and if using a custom Icon you can set the labelOrigin property to reposition the label.

    Source: https://code.google.com/p/gmaps-api-issues/issues/detail?id=8578#c30 (also, you can report any issues regarding this at the above linked thread)

    Calling a JavaScript function named in a variable

    I'd avoid eval.

    To solve this problem, you should know these things about JavaScript.

    1. Functions are first-class objects, so they can be properties of an object (in which case they are called methods) or even elements of arrays.
    2. If you aren't choosing the object a function belongs to, it belongs to the global scope. In the browser, that means you're hanging it on the object named "window," which is where globals live.
    3. Arrays and objects are intimately related. (Rumor is they might even be the result of incest!) You can often substitute using a dot . rather than square brackets [], or vice versa.

    Your problem is a result of considering the dot manner of reference rather than the square bracket manner.

    So, why not something like,

    window["functionName"]();
    

    That's assuming your function lives in the global space. If you've namespaced, then:

    myNameSpace["functionName"]();
    

    Avoid eval, and avoid passing a string in to setTimeout and setInterval. I write a lot of JS, and I NEVER need eval. "Needing" eval comes from not knowing the language deeply enough. You need to learn about scoping, context, and syntax. If you're ever stuck with an eval, just ask--you'll learn quickly.

    Laravel Query Builder where max id

    For Laravel ^5

    Orders::max('id');
    

    I used it is short and best;

    How to switch to other branch in Source Tree to commit the code?

    Hi I'm also relatively new but I can give you basic help.

    1. To switch to another branch use "Checkout". Just click on your branch and then on the button "checkout" at the top.

    UPDATE 12.01.2016:

    The bold line is the current branch.

    You can also just double click a branch to use checkout.


    1. Your first answer I think depends on the repository you use (like github or bitbucket). Maybe the "Show hosted repository"-Button can help you (Left panel, bottom, right button = database with cog)

    And here some helpful links:

    Easy Git Guide

    Git-flow - Git branching model

    Tips on branching with sourcetree

    How can I autoformat/indent C code in vim?

    Their is a tool called indent. You can download it with apt-get install indent, then run indent my_program.c.

    How to return multiple objects from a Java method?

    While in your case, the comment may be a good way to go, in Android, you can use Pair . Simply

    return new Pair<>(yourList, yourCommaSeparatedValues);
    

    Object creation on the stack/heap?

    The two forms are the same with one exception: temporarily, the new (Object *) has an undefined value when the creation and assignment are separate. The compiler may combine them back together, since the undefined pointer is not particularly useful. This does not relate to global variables (unless the declaration is global, in which case it's still true for both forms).

    Entity Framework code first unique column

    In EF 6.2 using FluentAPI, you can use HasIndex()

    modelBuilder.Entity<User>().HasIndex(u => u.UserName).IsUnique();
    

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

    I took this from TypeScript definitions library @types:

    Let's say the repo has this structure:

    types/
    |_ dependency/
    

    ?? This requires minimum git version 2.27.0, which is likely newer than the default on most machines. More complicated procedures are available in older versions, but not covered by this guide.

    git clone --sparse --filter=blob:none --depth=1 <forkedUrl>
    git sparse-checkout add types/<type> types/<dependency type> ...
    

    This will check out the types/identity folder to your local machine.

    --sparse initializes the sparse-checkout file so the working directory starts with only the files in the root of the repository.

    --filter=blob:none will exclude files, fetching them only as needed.

    --depth=1 will further improve clone speed by truncating commit history, but it may cause issues as summarized here.

    How to use PHP's password_hash to hash and verify passwords

    I’ve built a function I use all the time for password validation and to create passwords, e.g. to store them in a MySQL database. It uses a randomly generated salt which is way more secure than using a static salt.

    function secure_password($user_pwd, $multi) {
    
    /*
        secure_password ( string $user_pwd, boolean/string $multi ) 
    
        *** Description: 
            This function verifies a password against a (database-) stored password's hash or
            returns $hash for a given password if $multi is set to either true or false
    
        *** Examples:
            // To check a password against its hash
            if(secure_password($user_password, $row['user_password'])) {
                login_function();
            } 
            // To create a password-hash
            $my_password = 'uber_sEcUrE_pass';
            $hash = secure_password($my_password, true);
            echo $hash;
    */
    
    // Set options for encryption and build unique random hash
    $crypt_options = ['cost' => 11, 'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM)];
    $hash = password_hash($user_pwd, PASSWORD_BCRYPT, $crypt_options);
    
    // If $multi is not boolean check password and return validation state true/false
    if($multi!==true && $multi!==false) {
        if (password_verify($user_pwd, $table_pwd = $multi)) {
            return true; // valid password
        } else {
            return false; // invalid password
        }
    // If $multi is boolean return $hash
    } else return $hash;
    
    }
    

    C++ initial value of reference to non-const must be an lvalue

    When you call test with &nKByte, the address-of operator creates a temporary value, and you can't normally have references to temporary values because they are, well, temporary.

    Either do not use a reference for the argument, or better yet don't use a pointer.

    How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

    If you wanted just a Date, you can do Date.strptime(invoice.date.to_s, '%s') where invoice.date comes in the form of anFixnum and then converted to a String.

    firestore: PERMISSION_DENIED: Missing or insufficient permissions

    I had this error with Firebase Admin, the solution was configure the Firebase Admin correctly following this link

    Simple GUI Java calculator

    Somewhere you have to keep track of what button had been pressed. When things happen, you need to store something in a variable so you can recall the information or it's gone forever.

    When someone pressed one of the operator buttons, don't just let them type in another value. Save the operator symbol, then let them type in another value. You could literally just have a String operator that gets the text of the operator button pressed. Then, when the equals button is pressed, you have to check to see which operator you stored. You could do this with an if/else if/else chain.

    So, in your symbol's button press event, store the symbol text in a variable, then, in the = button press event, check to see which symbol is in the variable and act accordingly.

    Alternatively, if you feel comfortable enough with enums (looks like you're just starting, so if you're not to that point yet, ignore this), you could have an enumeration of symbols that lets you check symbols easily with a switch.

    jQuery show for 5 seconds then hide

    You can use .delay() before an animation, like this:

    $("#myElem").show().delay(5000).fadeOut();
    

    If it's not an animation, use setTimeout() directly, like this:

    $("#myElem").show();
    setTimeout(function() { $("#myElem").hide(); }, 5000);
    

    You do the second because .hide() wouldn't normally be on the animation (fx) queue without a duration, it's just an instant effect.

    Or, another option is to use .delay() and .queue() yourself, like this:

    $("#myElem").show().delay(5000).queue(function(n) {
      $(this).hide(); n();
    });
    

    "React.Children.only expected to receive a single React element child" error when putting <Image> and <TouchableHighlight> in a <View>

    I had this same error, even when I only had one child under the TouchableHighlight. The issue was that I had a few others commented out but incorrectly. Make sure you are commenting out appropriately: http://wesbos.com/react-jsx-comments/

    Can I target all <H> tags with a single selector?

    You could .class all the headings in Your document if You would like to target them with a single selector, as follows,

    <h1 class="heading">...heading text...</h1>
    <h2 class="heading">...heading text...</h2>
    

    and in the css

    .heading{
        color: #Dad;
        background-color: #DadDad;
    }
    

    I am not saying this is always best practice, but it can be useful, and for targeting syntax, easier in many ways,

    so if You give all h1 through h6 the same .heading class in the html, then You can modify them for any html docs that utilize that css sheet.

    upside, more global control versus "section div article h1, etc{}",

    downside, instead of calling all the selectors in on place in the css, You will have much more typing in the html, yet I find that having a class in the html to target all headings can be beneficial, just be careful of precedence in the css, because conflicts could arise from

    Where do I put image files, css, js, etc. in Codeigniter?

    you can put the css folder inside the assest folder(you name it any name) in the directory of your project as:

    - ci_app
    - application 
    - views      
    - assets 
      - css 
        - style.css 
    

    ... when you want to load that file in a page, you can use base_url()function as this way: <head> <link rel='stylesheet' href='<?php echo base_url();?>assets/css/style.css'> </head> and you are sure to add base_url of your project in the config.php file as this:

    $config['base_url'] = 'http://localhost/ci_app';
    

    "Could not find the main class" error when running jar exported by Eclipse

    I ran into the same issues the other day and it took me days to make it work. The error message was "Could not find the main class", but I can run the executable jar exported from Eclipse in other Windows machines without any problem.

    The solution was to install both x64 and x86 version of the same version of JRE. The path environment variable was pointed to the x64 version. No idea why, but it worked for me.

    GitHub Error Message - Permission denied (publickey)

    If you are using the GitHub for Mac UI, check preferences to make sure you're logged in.

    How do I generate random integers within a specific range in Java?

    Another option is just using Apache Commons:

    import org.apache.commons.math.random.RandomData;
    import org.apache.commons.math.random.RandomDataImpl;
    
    public void method() {
        RandomData randomData = new RandomDataImpl();
        int number = randomData.nextInt(5, 10);
        // ...
     }
    

    How can I send a Firebase Cloud Messaging notification without use the Firebase Console?

    If you want to send push notifications from android check out my blog post

    Send Push Notifications from 1 android phone to another with out server.

    sending push notification is nothing but a post request to https://fcm.googleapis.com/fcm/send

    code snippet using volley:

        JSONObject json = new JSONObject();
     try {
     JSONObject userData=new JSONObject();
     userData.put("title","your title");
     userData.put("body","your body");
    
    json.put("data",userData);
    json.put("to", receiverFirebaseToken);
     }
     catch (JSONException e) {
     e.printStackTrace();
     }
    
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("https://fcm.googleapis.com/fcm/send", json, new Response.Listener<JSONObject>() {
     @Override
     public void onResponse(JSONObject response) {
    
    Log.i("onResponse", "" + response.toString());
     }
     }, new Response.ErrorListener() {
     @Override
     public void onErrorResponse(VolleyError error) {
    
    }
     }) {
     @Override
     public Map<String, String> getHeaders() throws AuthFailureError {
    
    Map<String, String> params = new HashMap<String, String>();
     params.put("Authorizationey=" + SERVER_API_KEY);
     params.put("Content-Typepplication/json");
     return params;
     }
     };
     MySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest);
    

    I suggest you all to check out my blog post for complete details.

    Why cannot cast Integer to String in java?

    No, Integer and String are different types. To convert an integer to string use: String.valueOf(integer), or Integer.toString(integer) for primitive, or Integer.toString() for the object.

    C++ Object Instantiation

    Well, the reason to use the pointer would be exactly the same that the reason to use pointers in C allocated with malloc: if you want your object to live longer than your variable!

    It is even highly recommended to NOT use the new operator if you can avoid it. Especially if you use exceptions. In general it is much safer to let the compiler free your objects.

    How to fix java.net.SocketException: Broken pipe?

    This is caused by:

    • most usually, writing to a connection when the other end has already closed it;
    • less usually, the peer closing the connection without reading all the data that is already pending at his end.

    So in both cases you have a poorly defined or implemented application protocol.

    There is a third reason which I will not document here but which involves the peer taking deliberate action to reset rather than properly close the connection.

    How do you add a timed delay to a C++ program?

    The top answer here seems to be an OS dependent answer; for a more portable solution you can write up a quick sleep function using the ctime header file (although this may be a poor implementation on my part).

    #include <iostream>
    #include <ctime>
    
    using namespace std;
    
    void sleep(float seconds){
        clock_t startClock = clock();
        float secondsAhead = seconds * CLOCKS_PER_SEC;
        // do nothing until the elapsed time has passed.
        while(clock() < startClock+secondsAhead);
        return;
    }
    int main(){
    
        cout << "Next string coming up in one second!" << endl;
        sleep(1.0);
        cout << "Hey, what did I miss?" << endl;
    
        return 0;
    }
    

    How do I unlock a SQLite database?

    I had this problem just now, using an SQLite database on a remote server, stored on an NFS mount. SQLite was unable to obtain a lock after the remote shell session I used had crashed while the database was open.

    The recipes for recovery suggested above did not work for me (including the idea to first move and then copy the database back). But after copying it to a non-NFS system, the database became usable and not data appears to have been lost.

    How can I return the difference between two lists?

    First convert list to sets.

    // create an empty set 
    Set<T> set = new HashSet<>(); 
    
    // Add each element of list into the set 
    for (T t : list) 
        set.add(t); 
    

    You can use Sets.difference(Set1, Set2), which returns extra items present in Set1.
    You can use Sets.difference(Set2, Set1), which returns extra items present in Set2.

    MySQL - UPDATE multiple rows with different values in one query

    You can use a CASE statement to handle multiple if/then scenarios:

    UPDATE table_to_update 
    SET  cod_user= CASE WHEN user_rol = 'student' THEN '622057'
                       WHEN user_rol = 'assistant' THEN '2913659'
                       WHEN user_rol = 'admin' THEN '6160230'
                   END
        ,date = '12082014'
    WHERE user_rol IN ('student','assistant','admin')
      AND cod_office = '17389551';
    

    Printf width specifier to maintain precision of floating-point value

    No, there is no such printf width specifier to print floating-point with maximum precision. Let me explain why.

    The maximum precision of float and double is variable, and dependent on the actual value of the float or double.

    Recall float and double are stored in sign.exponent.mantissa format. This means that there are many more bits used for the fractional component for small numbers than for big numbers.

    enter image description here

    For example, float can easily distinguish between 0.0 and 0.1.

    float r = 0;
    printf( "%.6f\n", r ) ; // 0.000000
    r+=0.1 ;
    printf( "%.6f\n", r ) ; // 0.100000
    

    But float has no idea of the difference between 1e27 and 1e27 + 0.1.

    r = 1e27;
    printf( "%.6f\n", r ) ; // 999999988484154753734934528.000000
    r+=0.1 ;
    printf( "%.6f\n", r ) ; // still 999999988484154753734934528.000000
    

    This is because all the precision (which is limited by the number of mantissa bits) is used up for the large part of the number, left of the decimal.

    The %.f modifier just says how many decimal values you want to print from the float number as far as formatting goes. The fact that the accuracy available depends on the size of the number is up to you as the programmer to handle. printf can't/doesn't handle that for you.

    SQL Data Reader - handling Null column values

    I think you would want to use:

    SqlReader.IsDBNull(indexFirstName)
    

    Reset ID autoincrement ? phpmyadmin

    You can also do this in phpMyAdmin without writing SQL.

    • Click on a database name in the left column.
    • Click on a table name in the left column.
    • Click the "Operations" tab at the top.
    • Under "Table options" there should be a field for AUTO_INCREMENT (only on tables that have an auto-increment field).
    • Input desired value and click the "Go" button below.

    Note: You'll see that phpMyAdmin is issuing the same SQL that is mentioned in the other answers.

    How to rsync only a specific list of files?

    None of these answers worked for me, when all I had was a list of directories. Then I stumbled upon the solution! You have to add -r to --files-from because -a will not be recursive in this scenario (who knew?!).

    rsync -aruRP --files-from=directory.list . ../new/location
    

    Convert HH:MM:SS string to seconds only in javascript

    You can do this dynamically - in case you encounter not only: HH:mm:ss, but also, mm:ss, or even ss alone.

    var str = '12:99:07';
    var times = str.split(":");
    times.reverse();
    var x = times.length, y = 0, z;
    for (var i = 0; i < x; i++) {
        z = times[i] * Math.pow(60, i);
        y += z;
    }
    console.log(y);
    

    Android: Storing username and password?

    Take a look at this this post from android-developers, that might help increasing the security on the stored data in your Android app.

    Using Cryptography to Store Credentials Safely

    plot legends without border and with white background

    Use option bty = "n" in legend to remove the box around the legend. For example:

    legend(1, 5,
           "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",
           bty = "n")
    

    How to get first object out from List<Object> using Linq

    Try this to get all the list at first, then your desired element (say the First in your case):

    var desiredElementCompoundValueList = new List<YourType>();
    dic.Values.ToList().ForEach( elem => 
    {
       desiredElementCompoundValue.Add(elem.ComponentValue("Dep"));
    });
    var x = desiredElementCompoundValueList.FirstOrDefault();
    

    To get directly the first element value without a lot of foreach iteration and variable assignment:

    var desiredCompoundValue = dic.Values.ToList().Select( elem => elem.CompoundValue("Dep")).FirstOrDefault();
    

    See the difference between the two approaches: in the first one you get the list through a ForEach, then your element. In the second you can get your value in a straight way.

    Same result, different computation ;)

    Using Notepad++ to validate XML against an XSD

    1. In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager then find Xml Tools plugin. Tick the box and click Install

      enter image description here

    2. Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now).
      Following dialog will open: enter image description here

    3. Click on .... Point to XSD file and I am pretty sure you'll be able to handle things from here.

    Hope this saves you some time.

    EDIT: Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
    In version 7.7.1 plugin manager is back under a different guise... Plugin Admin so now you can simply update notepad++ and have it back.

    enter image description here

    How to integrate SAP Crystal Reports in Visual Studio 2017

    Visual Studio 2017 is supported in Crystal Reports SP 21, which is available for download as of 1 Sep 2017.

    Pyspark: Filter dataframe based on multiple conditions

    Your logic condition is wrong. IIUC, what you want is:

    import pyspark.sql.functions as f
    
    df.filter((f.col('d')<5))\
        .filter(
            ((f.col('col1') != f.col('col3')) | 
             (f.col('col2') != f.col('col4')) & (f.col('col1') == f.col('col3')))
        )\
        .show()
    

    I broke the filter() step into 2 calls for readability, but you could equivalently do it in one line.

    Output:

    +----+----+----+----+---+
    |col1|col2|col3|col4|  d|
    +----+----+----+----+---+
    |   A|  xx|   D|  vv|  4|
    |   A|   x|   A|  xx|  3|
    |   E| xxx|   B|  vv|  3|
    |   F|xxxx|   F| vvv|  4|
    |   G| xxx|   G|  xx|  4|
    +----+----+----+----+---+
    

    how to rotate text left 90 degree and cell size is adjusted according to text in html

    Unfortunately while I thought these answers may have worked for me, I struggled with a solution, as I'm using tables inside responsive tables - where the overflow-x is played with.

    So, with that in mind, have a look at this link for a cleaner way, which doesn't have the weird width overflow issues. It worked for me in the end and was very easy to implement.

    https://css-tricks.com/rotated-table-column-headers/

    Check date with todays date

    to check if a date is today's date or not only check for dates not time included with that so make time 00:00:00 and use the code below

        Calendar c = Calendar.getInstance();
    
        // set the calendar to start of today
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
    
        Date today = c.getTime();
    
        // or as a timestamp in milliseconds
        long todayInMillis = c.getTimeInMillis();
    
    
        int dayOfMonth = 24;
        int month = 4;
        int year =2013;
    
        // reuse the calendar to set user specified date
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month - 1);
        c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        // and get that as a Date
        Date dateSpecified = c.getTime();
    
        // test your condition
        if (dateSpecified.before(today)) {
    
            Log.v(" date is previou")
        } else if (dateSpecified.equal(today)) {
    
            Log.v(" date is today ")
        } 
                 else if (dateSpecified.after(today)) {
    
            Log.v(" date is future date ")
        } 
    

    Hope it will help....

    How do I use the nohup command without getting nohup.out?

    If you have a BASH shell on your mac/linux in-front of you, you try out the below steps to understand the redirection practically :

    Create a 2 line script called zz.sh

    #!/bin/bash
    echo "Hello. This is a proper command"
    junk_errorcommand
    
    • The echo command's output goes into STDOUT filestream (file descriptor 1).
    • The error command's output goes into STDERR filestream (file descriptor 2)

    Currently, simply executing the script sends both STDOUT and STDERR to the screen.

    ./zz.sh
    

    Now start with the standard redirection :

    zz.sh > zfile.txt
    

    In the above, "echo" (STDOUT) goes into the zfile.txt. Whereas "error" (STDERR) is displayed on the screen.

    The above is the same as :

    zz.sh 1> zfile.txt
    

    Now you can try the opposite, and redirect "error" STDERR into the file. The STDOUT from "echo" command goes to the screen.

    zz.sh 2> zfile.txt
    

    Combining the above two, you get:

    zz.sh 1> zfile.txt 2>&1
    

    Explanation:

    • FIRST, send STDOUT 1 to zfile.txt
    • THEN, send STDERR 2 to STDOUT 1 itself (by using &1 pointer).
    • Therefore, both 1 and 2 goes into the same file (zfile.txt)

    Eventually, you can pack the whole thing inside nohup command & to run it in the background:

    nohup zz.sh 1> zfile.txt 2>&1&
    

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

    I also faced the same error. After a few hours I figured it out.

    I hope it helps you :

    Go to Tools ==> SDK Menager ==>Android SDK

    (Appearange&Behavior=>System settings=>Android SDK)==>SDK Tools==>Intel x86 Emulator Accelerator(install this).

    It will solve your problem.I hope it helps.

    You can look at pictures which you must install

    Split function in oracle to comma separated values with automatic sequence

    Here is how you could create such a table:

     SELECT LEVEL AS id, REGEXP_SUBSTR('A,B,C,D', '[^,]+', 1, LEVEL) AS data
       FROM dual
    CONNECT BY REGEXP_SUBSTR('A,B,C,D', '[^,]+', 1, LEVEL) IS NOT NULL;
    

    With a little bit of tweaking (i.e., replacing the , in [^,] with a variable) you could write such a function to return a table.

    Pandas: Subtracting two date columns and the result being an integer

    I feel that the overall answer does not handle if the dates 'wrap' around a year. This would be useful in understanding proximity to a date being accurate by day of year. In order to do these row operations, I did the following. (I had this used in a business setting in renewing customer subscriptions).

    def get_date_difference(row, x, y):
        try:
            # Calcuating the smallest date difference between the start and the close date
            # There's some tricky logic in here to calculate for determining date difference
            # the other way around (Dec -> Jan is 1 month rather than 11)
    
            sub_start_date = int(row[x].strftime('%j')) # day of year (1-366)
            close_date = int(row[y].strftime('%j')) # day of year (1-366)
    
            later_date_of_year = max(sub_start_date, close_date) 
            earlier_date_of_year = min(sub_start_date, close_date)
            days_diff = later_date_of_year - earlier_date_of_year
    
    # Calculates the difference going across the next year (December -> Jan)
            days_diff_reversed = (365 - later_date_of_year) + earlier_date_of_year
            return min(days_diff, days_diff_reversed)
    
        except ValueError:
            return None
    

    Then the function could be:

    dfAC_Renew['date_difference'] = dfAC_Renew.apply(get_date_difference, x = 'customer_since_date', y = 'renewal_date', axis = 1)
    

    How can I read and manipulate CSV file data in C++?

    Look at 'The Practice of Programming' (TPOP) by Kernighan & Pike. It includes an example of parsing CSV files in both C and C++. But it would be worth reading the book even if you don't use the code.

    (Previous URL: http://cm.bell-labs.com/cm/cs/tpop/)

    Pass variables between two PHP pages without using a form or the URL of page

    Have you tried adding both to $_SESSION?

    Then at the top of your page2.php just add:

    <?php
    session_start();
    

    Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

    CSS selector:

    Use a CSS selector of img[src='images/toolbar/b_edit.gif']

    This says select element(s) with img tag with attribute src having value of 'images/toolbar/b_edit.gif'


    CSS query:

    CSS query


    VBA:

    You can apply the selector with the .querySelector method of document.

    IE.document.querySelector("img[src='images/toolbar/b_edit.gif']").Click
    

    How to read a file from jar in Java?

    Check first your class loader.

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    
    if (classLoader == null) {
        classLoader = Class.class.getClassLoader();
    }
    
    classLoader.getResourceAsStream("xmlFileNameInJarFile.xml");
    
    // xml file location at xxx.jar
    // + folder
    // + folder
    // xmlFileNameInJarFile.xml
    

    How to insert a line break before an element using CSS

    assuming you want the line height to be 20 px

      .restart:before { 
         content: 'First Line';
         padding-bottom:20px;
      }
      .restart:after { 
        content: 'Second-line';
        position:absolute;
        top:40px;
      }
    

    iOS9 Untrusted Enterprise Developer with no option to trust

    Do it like this:

    Enter image description here

    Go to Settings -> General -> Profiles - tap on your Profile - tap on the Trust button.

    but iOS10 has a little change,

    Users should go to Settings - General - Device Management - tap on your Profile - tap on Trust button.

    enter image description here

    Reference: iOS10AdaptationTips

    'sprintf': double precision in C

    You need to write it like sprintf(aa, "%9.7lf", a)

    Check out http://en.wikipedia.org/wiki/Printf for some more details on format codes.

    Jquery post, response in new window

    Use the write()-Method of the Popup's document to put your markup there:

    $.post(url, function (data) {
        var w = window.open('about:blank');
        w.document.open();
        w.document.write(data);
        w.document.close();
    });
    

    Inserting HTML elements with JavaScript

    To my knowledge, which, to be fair, is fairly new and limited, the only potential issue with this technique is the fact that you are prevented from dynamically creating some table elements.

    I use a form to templating by adding "template" elements to a hidden DIV and then using cloneNode(true) to create a clone and appending it as required. Bear in ind that you do need to ensure you re-assign id's as required to prevent duplication.

    Append to the end of a Char array in C++

    If your arrays are character arrays(which seems to be the case), You need a strcat().
    Your destination array should have enough space to accommodate the appended data though.

    In C++, You are much better off using std::string and then you can use std::string::append()

    How to edit the legend entry of a chart in Excel?

    The data series names are defined by the column headers. Add the names to the column headers that you would like to use as titles for each of your data series, select all of the data (including the headers), then re-generate your graph. The names in the headers should then appear as the names in the legend for each series.

    Column headers become data series titles in graph legend

    How do I get a file's last modified time in Perl?

    I think you're looking for the stat function (perldoc -f stat)

    In particular, the 9th field (10th, index #9) of the returned list is the last modify time of the file in seconds since the epoch.

    So:

    my $last_modified = (stat($fh))[9];

    Email & Phone Validation in Swift

    File-New-File.Make a Swift class named AppExtension.Add the following.

            extension UIViewController{
                func validateEmailAndGetBoolValue(candidate: String) -> Bool {
                    let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
                    return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluateWithObject(candidate)
                }
            }
    
            Use: 
            var emailValidator:Bool?
            self.emailValidator =  self.validateEmailAndGetBoolValue(resetEmail!)
                            print("emailValidator : "+String(self.emailValidator?.boolValue))
    
            Use a loop to alternate desired results.
    
    
        OR
            extension String
            {
            //Validate Email
                var isEmail: Bool {
                    do {
                        let regex = try NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .CaseInsensitive)
                        return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil
                    } catch {
                        return false
                    }
    
                }
            }
    
            Use:
            if(resetEmail!.isEmail)
                            {
                            AppController().requestResetPassword(resetEmail!)
                            self.view.makeToast(message: "Sending OTP")
                            }
                            else
                            {
                                self.view.makeToast(message: "Please enter a valid email")
                            }
    

    Python: most idiomatic way to convert None to empty string?

    def xstr(s):
        return '' if s is None else str(s)
    

    Simplest way to detect keypresses in javascript

    There are a few ways to handle that; Vanilla JavaScript can do it quite nicely:

    function code(e) {
        e = e || window.event;
        return(e.keyCode || e.which);
    }
    window.onload = function(){
        document.onkeypress = function(e){
            var key = code(e);
            // do something with key
        };
    };
    

    Or a more structured way of handling it:

    (function(d){
        var modern = (d.addEventListener), event = function(obj, evt, fn){
            if(modern) {
                obj.addEventListener(evt, fn, false);
            } else {
                obj.attachEvent("on" + evt, fn);
            }
        }, code = function(e){
            e = e || window.event;
            return(e.keyCode || e.which);
        }, init = function(){
            event(d, "keypress", function(e){
                var key = code(e);
                // do stuff with key here
            });
        };
        if(modern) {
            d.addEventListener("DOMContentLoaded", init, false);
        } else {
            d.attachEvent("onreadystatechange", function(){
                if(d.readyState === "complete") {
                    init();
                }
            });
        }
    })(document);
    

    How to serve up images in Angular2?

    In angular only one page is requested from server, that is index.html. And index.html and assets folder are on same directory. while putting image in any component give src value like assets\image.png. This will work fine because browser will make request to server for that image and webpack will be able serve that image.

    CodeIgniter -> Get current URL relative to base url

    // For current url
    echo base_url(uri_string());
    

    JavaScript Array splice vs slice

    The difference between Slice() and Splice() javascript build-in functions is, Slice returns removed item but did not change the original array ; like,

            // (original Array)
            let array=[1,2,3,4,5] 
            let index= array.indexOf(4)
             // index=3
            let result=array.slice(index)
            // result=4  
            // after slicing=>  array =[1,2,3,4,5]  (same as original array)
    

    but in splice() case it affects original array; like,

             // (original Array)
            let array=[1,2,3,4,5] 
            let index= array.indexOf(4)
             // index=3
            let result=array.splice(index)
            // result=4  
            // after splicing array =[1,2,3,5]  (splicing affects original array)
    

    PHP Get all subdirectories of a given directory

    This is the one liner code:

     $sub_directories = array_map('basename', glob($directory_path . '/*', GLOB_ONLYDIR));
    

    Difference between <context:annotation-config> and <context:component-scan>

    <context:annotation-config> is used to activate annotations in beans already registered in the application context (no matter if they were defined with XML or by package scanning).

    <context:component-scan> can also do what <context:annotation-config> does but <context:component-scan> also scans packages to find and register beans within the application context.

    I'll use some examples to show the differences/similarities.

    Lets start with a basic setup of three beans of type A, B and C, with B and C being injected into A.

    package com.xxx;
    public class B {
      public B() {
        System.out.println("creating bean B: " + this);
      }
    }
    
    package com.xxx;
    public class C {
      public C() {
        System.out.println("creating bean C: " + this);
      }
    }
    
    package com.yyy;
    import com.xxx.B;
    import com.xxx.C;
    public class A { 
      private B bbb;
      private C ccc;
      public A() {
        System.out.println("creating bean A: " + this);
      }
      public void setBbb(B bbb) {
        System.out.println("setting A.bbb with " + bbb);
        this.bbb = bbb;
      }
      public void setCcc(C ccc) {
        System.out.println("setting A.ccc with " + ccc);
        this.ccc = ccc; 
      }
    }
    

    With the following XML configuration :

    <bean id="bBean" class="com.xxx.B" />
    <bean id="cBean" class="com.xxx.C" />
    <bean id="aBean" class="com.yyy.A">
      <property name="bbb" ref="bBean" />
      <property name="ccc" ref="cBean" />
    </bean>
    

    Loading the context produces the following output:

    creating bean B: com.xxx.B@c2ff5
    creating bean C: com.xxx.C@1e8a1f6
    creating bean A: com.yyy.A@1e152c5
    setting A.bbb with com.xxx.B@c2ff5
    setting A.ccc with com.xxx.C@1e8a1f6
    

    OK, this is the expected output. But this is "old style" Spring. Now we have annotations so lets use those to simplify the XML.

    First, lets autowire the bbb and ccc properties on bean A like so:

    package com.yyy;
    import org.springframework.beans.factory.annotation.Autowired;
    import com.xxx.B;
    import com.xxx.C;
    public class A { 
      private B bbb;
      private C ccc;
      public A() {
        System.out.println("creating bean A: " + this);
      }
      @Autowired
      public void setBbb(B bbb) {
        System.out.println("setting A.bbb with " + bbb);
        this.bbb = bbb;
      }
      @Autowired
      public void setCcc(C ccc) {
        System.out.println("setting A.ccc with " + ccc);
        this.ccc = ccc;
      }
    }
    

    This allows me to remove the following rows from the XML:

    <property name="bbb" ref="bBean" />
    <property name="ccc" ref="cBean" />
    

    My XML is now simplified to this:

    <bean id="bBean" class="com.xxx.B" />
    <bean id="cBean" class="com.xxx.C" />
    <bean id="aBean" class="com.yyy.A" />
    

    When I load the context I get the following output:

    creating bean B: com.xxx.B@5e5a50
    creating bean C: com.xxx.C@54a328
    creating bean A: com.yyy.A@a3d4cf
    

    OK, this is wrong! What happened? Why aren't my properties autowired?

    Well, annotations are a nice feature but by themselves they do nothing whatsoever. They just annotate stuff. You need a processing tool to find the annotations and do something with them.

    <context:annotation-config> to the rescue. This activates the actions for the annotations that it finds on the beans defined in the same application context where itself is defined.

    If I change my XML to this:

    <context:annotation-config />
    <bean id="bBean" class="com.xxx.B" />
    <bean id="cBean" class="com.xxx.C" />
    <bean id="aBean" class="com.yyy.A" />
    

    when I load the application context I get the proper result:

    creating bean B: com.xxx.B@15663a2
    creating bean C: com.xxx.C@cd5f8b
    creating bean A: com.yyy.A@157aa53
    setting A.bbb with com.xxx.B@15663a2
    setting A.ccc with com.xxx.C@cd5f8b
    

    OK, this is nice, but I've removed two rows from the XML and added one. That's not a very big difference. The idea with annotations is that it's supposed to remove the XML.

    So let's remove the XML definitions and replace them all with annotations:

    package com.xxx;
    import org.springframework.stereotype.Component;
    @Component
    public class B {
      public B() {
        System.out.println("creating bean B: " + this);
      }
    }
    
    package com.xxx;
    import org.springframework.stereotype.Component;
    @Component
    public class C {
      public C() {
        System.out.println("creating bean C: " + this);
      }
    }
    
    package com.yyy;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import com.xxx.B;
    import com.xxx.C;
    @Component
    public class A { 
      private B bbb;
      private C ccc;
      public A() {
        System.out.println("creating bean A: " + this);
      }
      @Autowired
      public void setBbb(B bbb) {
        System.out.println("setting A.bbb with " + bbb);
        this.bbb = bbb;
      }
      @Autowired
      public void setCcc(C ccc) {
        System.out.println("setting A.ccc with " + ccc);
        this.ccc = ccc;
      }
    }
    

    While in the XML we only keep this:

    <context:annotation-config />
    

    We load the context and the result is... Nothing. No beans are created, no beans are autowired. Nothing!

    That's because, as I said in the first paragraph, the <context:annotation-config /> only works on beans registered within the application context. Because I removed the XML configuration for the three beans there is no bean created and <context:annotation-config /> has no "targets" to work on.

    But that won't be a problem for <context:component-scan> which can scan a package for "targets" to work on. Let's change the content of the XML config into the following entry:

    <context:component-scan base-package="com.xxx" />
    

    When I load the context I get the following output:

    creating bean B: com.xxx.B@1be0f0a
    creating bean C: com.xxx.C@80d1ff
    

    Hmmmm... something is missing. Why?

    If you look closelly at the classes, class A has package com.yyy but I've specified in the <context:component-scan> to use package com.xxx so this completely missed my A class and only picked up B and C which are on the com.xxx package.

    To fix this, I add this other package also:

    <context:component-scan base-package="com.xxx,com.yyy" />
    

    and now we get the expected result:

    creating bean B: com.xxx.B@cd5f8b
    creating bean C: com.xxx.C@15ac3c9
    creating bean A: com.yyy.A@ec4a87
    setting A.bbb with com.xxx.B@cd5f8b
    setting A.ccc with com.xxx.C@15ac3c9
    

    And that's it! Now you don't have XML definitions anymore, you have annotations.

    As a final example, keeping the annotated classes A, B and C and adding the following to the XML, what will we get after loading the context?

    <context:component-scan base-package="com.xxx" />
    <bean id="aBean" class="com.yyy.A" />
    

    We still get the correct result:

    creating bean B: com.xxx.B@157aa53
    creating bean C: com.xxx.C@ec4a87
    creating bean A: com.yyy.A@1d64c37
    setting A.bbb with com.xxx.B@157aa53
    setting A.ccc with com.xxx.C@ec4a87
    

    Even if the bean for class A isn't obtained by scanning, the processing tools are still applied by <context:component-scan> on all beans registered in the application context, even for A which was manually registered in the XML.

    But what if we have the following XML, will we get duplicated beans because we've specified both <context:annotation-config /> and <context:component-scan>?

    <context:annotation-config />
    <context:component-scan base-package="com.xxx" />
    <bean id="aBean" class="com.yyy.A" />
    

    No, no duplications, We again get the expected result:

    creating bean B: com.xxx.B@157aa53
    creating bean C: com.xxx.C@ec4a87
    creating bean A: com.yyy.A@1d64c37
    setting A.bbb with com.xxx.B@157aa53
    setting A.ccc with com.xxx.C@ec4a87
    

    That's because both tags register the same processing tools (<context:annotation-config /> can be omitted if <context:component-scan> is specified) but Spring takes care of running them only once.

    Even if you register the processing tools yourself multiple times, Spring will still make sure they do their magic only once; this XML:

    <context:annotation-config />
    <context:component-scan base-package="com.xxx" />
    <bean id="aBean" class="com.yyy.A" />
    <bean id="bla" class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
    <bean id="bla1" class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
    <bean id="bla2" class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
    <bean id="bla3" class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
    

    will still generate the following result:

    creating bean B: com.xxx.B@157aa53
    creating bean C: com.xxx.C@ec4a87
    creating bean A: com.yyy.A@25d2b2
    setting A.bbb with com.xxx.B@157aa53
    setting A.ccc with com.xxx.C@ec4a87
    

    OK, that about raps it up.

    I hope this information along with the responses from @Tomasz Nurkiewicz and @Sean Patrick Floyd are all you need to understand how <context:annotation-config> and <context:component-scan> work.

    psql: server closed the connection unexepectedly

    If you are using Docker make sure you are not using the same port in another service, in my case i was mistakenly using the same port for both PostgreSQL and Redis.

    How can I truncate a double to only two decimal places in Java?

          double value = 3.4555;
          String value1 =  String.format("% .3f", value) ;
          String value2 = value1.substring(0, value1.length() - 1);
          System.out.println(value2);         
          double doublevalue= Double.valueOf(value2);
          System.out.println(doublevalue);
    

    Jackson Vs. Gson

    Jackson and Gson are the most complete Java JSON packages regarding actual data binding support; many other packages only provide primitive Map/List (or equivalent tree model) binding. Both have complete support for generic types, as well, as enough configurability for many common use cases.

    Since I am more familiar with Jackson, here are some aspects where I think Jackson has more complete support than Gson (apologies if I miss a Gson feature):

    • Extensive annotation support; including full inheritance, and advanced "mix-in" annotations (associate annotations with a class for cases where you can not directly add them)
    • Streaming (incremental) reading, writing, for ultra-high performance (or memory-limited) use cases; can mix with data binding (bind sub-trees) -- EDIT: latest versions of Gson also include streaming reader
    • Tree model (DOM-like access); can convert between various models (tree <-> java object <-> stream)
    • Can use any constructors (or static factory methods), not just default constructor
    • Field and getter/setter access (earlier gson versions only used fields, this may have changed)
    • Out-of-box JAX-RS support
    • Interoperability: can also use JAXB annotations, has support/work-arounds for common packages (joda, ibatis, cglib), JVM languages (groovy, clojure, scala)
    • Ability to force static (declared) type handling for output
    • Support for deserializing polymorphic types (Jackson 1.5) -- can serialize AND deserialize things like List correctly (with additional type information)
    • Integrated support for binary content (base64 to/from JSON Strings)

    How to render a DateTime object in a Twig template

    Dont forget

    @ORM\HasLifecycleCallbacks()

    Entity :

    /**
         * Set gameDate
         *
         * @ORM\PrePersist
         */
        public function setGameDate()
        {
            $this->dateCreated = new \DateTime();
    
            return $this;
        }
    

    View:

    {{ item.gameDate|date('Y-m-d H:i:s') }}
    

    >> Output 2013-09-18 16:14:20

    Properties private set;

    This is one possible solution although not very clean:

    1. Make the property you need to expose to BAL & DAL internal
    2. Mark BAL.dll & DAL.dll Internal Visible in assemblyinfo.cs

    public class Person
    {
        public Person(int id)
        {
             this.Id=id;
        }
    
        public string Name { get;  set; }
        public int Id { get; internal set; }
        public int Age { get; set; }
    }
    

    AssemblyInfo.cs for Entities.dll

    [assembly: InternalsVisibleTo("DAL"), InternalsVisibleTo("BAL")]
    

    That way all your internals will be visible to DAL & BAL. This may not be desirable but I'm just suggesting one possible solution.

    Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

    I just ran into this annoying problem today. We use SmartAssembly to pack/obfuscate our .NET assemblies, but suddenly the final product wasn't working on our test systems. I didn't even think I had .NET 4.5, but apparently something installed it about a month ago.

    I uninstalled 4.5 and reinstalled 4.0, and now everything is working again. Not too impressed with having blown an afternoon on this.

    How to count the occurrence of certain item in an ndarray?

    If you know exactly which number you're looking for, you can use the following;

    lst = np.array([1,1,2,3,3,6,6,6,3,2,1])
    (lst == 2).sum()
    

    returns how many times 2 is occurred in your array.

    Spring - @Transactional - What happens in background?

    It may be late but I came across something which explains your concern related to proxy (only 'external' method calls coming in through the proxy will be intercepted) nicely.

    For example, you have a class that looks like this

    @Component("mySubordinate")
    public class CoreBusinessSubordinate {
    
        public void doSomethingBig() {
            System.out.println("I did something small");
        }
    
        public void doSomethingSmall(int x){
            System.out.println("I also do something small but with an int");    
      }
    }
    

    and you have an aspect, that looks like this:

    @Component
    @Aspect
    public class CrossCuttingConcern {
    
        @Before("execution(* com.intertech.CoreBusinessSubordinate.*(..))")
        public void doCrossCutStuff(){
            System.out.println("Doing the cross cutting concern now");
        }
    }
    

    When you execute it like this:

     @Service
    public class CoreBusinessKickOff {
    
        @Autowired
        CoreBusinessSubordinate subordinate;
    
        // getter/setters
    
        public void kickOff() {
           System.out.println("I do something big");
           subordinate.doSomethingBig();
           subordinate.doSomethingSmall(4);
       }
    

    }

    Results of calling kickOff above given code above.

    I do something big
    Doing the cross cutting concern now
    I did something small
    Doing the cross cutting concern now
    I also do something small but with an int
    

    but when you change your code to

    @Component("mySubordinate")
    public class CoreBusinessSubordinate {
    
        public void doSomethingBig() {
            System.out.println("I did something small");
            doSomethingSmall(4);
        }
    
        public void doSomethingSmall(int x){
           System.out.println("I also do something small but with an int");    
       }
    }
    
    
    public void kickOff() {
      System.out.println("I do something big");
       subordinate.doSomethingBig();
       //subordinate.doSomethingSmall(4);
    }
    

    You see, the method internally calls another method so it won't be intercepted and the output would look like this:

    I do something big
    Doing the cross cutting concern now
    I did something small
    I also do something small but with an int
    

    You can by-pass this by doing that

    public void doSomethingBig() {
        System.out.println("I did something small");
        //doSomethingSmall(4);
        ((CoreBusinessSubordinate) AopContext.currentProxy()).doSomethingSmall(4);
    }
    

    Code snippets taken from: https://www.intertech.com/Blog/secrets-of-the-spring-aop-proxy/

    Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL?

    All of these are kinds of indices.

    primary: must be unique, is an index, is (likely) the physical index, can be only one per table.

    unique: as it says. You can't have more than one row with a tuple of this value. Note that since a unique key can be over more than one column, this doesn't necessarily mean that each individual column in the index is unique, but that each combination of values across these columns is unique.

    index: if it's not primary or unique, it doesn't constrain values inserted into the table, but it does allow them to be looked up more efficiently.

    fulltext: a more specialized form of indexing that allows full text search. Think of it as (essentially) creating an "index" for each "word" in the specified column.

    How to access full source of old commit in BitBucket?

    I know it's too late, but with API 2.0 you can do

    from command line with:

    curl https://api.bitbucket.org/2.0/repositories/<user>/<repo>/filehistory/<branch>/<path_file>
    

    or in php with:

    $data = json_decode(file_get_contents("https://api.bitbucket.org/2.0/repositories/<user>/<repo>/filehistory/<branch>/<path_file>", true));
    

    then you have the history of your file (from the most recent commit to the oldest one):

    {
    "pagelen": 50,
    "values": [
        {
          "links": {
            "self": {
              "href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/src/<hash>/<path_file>"
            },
            "meta": {
              "href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/src/<HEAD>/<path_file>?format=meta"
            },
            "history": {
              "href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/filehistory/<HEAD>/<path_file>"
            }
          },
          "commit": {
            "hash": "<HEAD>",
            "type": "commit",
            "links": {
              "self": {
                "href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/commit/<HEAD>"
              },
              "html": {
                "href": "https://bitbucket.org/<user>/<repo>/commits/<HEAD>"
              }
            }
          },
          "attributes": [],
          "path": "<path_file>",
          "type": "commit_file",
          "size": 31
        },
        {
          "links": {
            "self": {
              "href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/src/<HEAD~1>/<path_file>"
            },
            "meta": {
              "href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/src/<HEAD~1>/<path_file>?format=meta"
            },
            "history": {
              "href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/filehistory/<HEAD~1>/<path_file>"
            }
          },
          "commit": {
            "hash": "<HEAD~1>",
            "type": "commit",
            "links": {
              "self": {
                "href": "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/commit/<HEAD~1>"
              },
              "html": {
                "href": "https://bitbucket.org/<user>/<repo>/commits/<HEAD~1>"
              }
            }
          },
          "attributes": [],
          "path": "<path_file>",
          "type": "commit_file",
          "size": 20
        }
      ],
      "page": 1
    }
    

    where values > links > self provides the file at the moment in the history which you can retrieve it with curl <link> or file_get_contents(<link>).

    Eventually, from the command line you can filter with:

     curl https://api.bitbucket.org/2.0/repositories/<user>/<repo>/filehistory/<branch>/<path_file>?fields=values.links.self
    

    in php, just make a foreach loop on the array $data.

    Note: if <path_file> has a / you have to convert it in %2F.

    See the doc here: https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Busername%7D/%7Brepo_slug%7D/filehistory/%7Bnode%7D/%7Bpath%7D

    sqlalchemy: how to join several tables by one query?

    Expanding on Abdul's answer, you can obtain a KeyedTuple instead of a discrete collection of rows by joining the columns:

    q = Session.query(*User.__table__.columns + Document.__table__.columns).\
            select_from(User).\
            join(Document, User.email == Document.author).\
            filter(User.email == 'someemail').all()
    

    How to get started with Windows 7 gadgets

    Here's an MSDN article on Vista Gadgets. Some preliminary documentation on 7 gadgets, and changes. I think the only major changes are that Gadgets don't reside in the Sidebar anymore, and as such "dock/undock events" are now backwards-compatibility cludges that really shouldn't be used.

    Best way to get started is probably to just tweak an existing gadget. There's an example gadget in the above link, or you could pick a different one out on your own.

    Gadgets are written in HTML, CSS, and some IE scripting language (generally Javascript, but I believe VBScript also works). For really fancy things you might need to create an ActiveX object, so C#/C++ for COM could be useful to know.

    Gadgets are packaged as ".gadget" files, which are just renamed Zip archives that contain a gadget manifest (gadget.xml) in their top level.

    How to get the current user in ASP.NET MVC

    If any one still reading this then, to access in cshtml file I used in following way.

    <li>Hello @User.Identity.Name</li>
    

    What does "<>" mean in Oracle

    It (<>) is a function that is used to compare values in database table.

    != (Not equal to) functions the same as the <> (Not equal to) comparison operator.

    Node.js - Find home directory in platform agnostic way

    os.homedir() was added by this PR and is part of the public 4.0.0 release of nodejs.


    Example usage:

    const os = require('os');
    
    console.log(os.homedir());
    

    Making a Simple Ajax call to controller in asp.net mvc

    It's for your UPDATE question.

    Since you cannot have two methods with the same name and signature you have to use the ActionName attribute:

    UPDATE:

    [HttpGet]
    public ActionResult FirstAjax()
    {
        Some Code--Some Code---Some Code
        return View();
    }
    
    [HttpPost]
    [ActionName("FirstAjax")]
    public ActionResult FirstAjaxPost()
    {
        Some Code--Some Code---Some Code
        return View();
    }
    

    And please refer this link for further reference of how a method becomes an action. Very good reference though.

    Printing long int value in C

    Use printf("%ld",a);

    Have a look at format specifiers for printf

    Difference between Destroy and Delete

    delete will only delete current object record from db but not its associated children records from db.

    destroy will delete current object record from db and also its associated children record from db.

    Their use really matters:

    If your multiple parent objects share common children objects, then calling destroy on specific parent object will delete children objects which are shared among other multiple parents.

    How to make inactive content inside a div?

    if you want to hide a whole div from the view in another screen size. You can follow bellow code as an example.

    div.disabled{
      display: none;
    }
    

    Reload a DIV without reloading the whole page

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js" />
    
    <div class="View"><?php include 'Small.php'; ?></div>
    
    <script type="text/javascript">
    $(document).ready(function() {
    $('.View').load('Small.php');
    var auto_refresh = setInterval(
        function ()
        {
            $('.View').load('Small.php').fadeIn("slow");
        }, 15000); // refresh every 15000 milliseconds
            $.ajaxSetup({ cache: true });
        });
    </script>
    

    Regular expression to match standard 10 digit phone number

    Adding up an example using above mentioned solutions on jsfiddle. I have modified the code a bit as per my clients requirement. Hope this also helps someone.

    /^\s*(?:\+?(\d{1,3}))?[- (]*(\d{3})[- )]*(\d{3})[- ]*(\d{4})(?: *[x/#]{1}(\d+))?\s*$/
    

    See Example Here

    Reading a huge .csv file

    For someone who lands to this question. Using pandas with ‘chunksize’ and ‘usecols’ helped me to read a huge zip file faster than the other proposed options.

    import pandas as pd
    
    sample_cols_to_keep =['col_1', 'col_2', 'col_3', 'col_4','col_5']
    
    # First setup dataframe iterator, ‘usecols’ parameter filters the columns, and 'chunksize' sets the number of rows per chunk in the csv. (you can change these parameters as you wish)
    df_iter = pd.read_csv('../data/huge_csv_file.csv.gz', compression='gzip', chunksize=20000, usecols=sample_cols_to_keep) 
    
    # this list will store the filtered dataframes for later concatenation 
    df_lst = [] 
    
    # Iterate over the file based on the criteria and append to the list
    for df_ in df_iter: 
            tmp_df = (df_.rename(columns={col: col.lower() for col in df_.columns}) # filter eg. rows where 'col_1' value grater than one
                                      .pipe(lambda x:  x[x.col_1 > 0] ))
            df_lst += [tmp_df.copy()] 
    
    # And finally combine filtered df_lst into the final lareger output say 'df_final' dataframe 
    df_final = pd.concat(df_lst)
    

    Could not load file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies

    I got this after downgrading a project from .net 4.5 to .net 3.5.

    To resolve I had to go in to the project - properties - settings window and delete all my settings, save the project, exit and restart visual studio, go back into project - properties -settings window and re-enter all my settings and their default values

    How do I print bytes as hexadecimal?

    Well you can convert one byte (unsigned char) at a time into a array like so

    char buffer [17];
    buffer[16] = 0;
    for(j = 0; j < 8; j++)
        sprintf(&buffer[2*j], "%02X", data[j]);
    

    Remove Elements from a HashSet while Iterating

    Like timber said - "Java 8 Collection has a nice method called removeIf that makes things easier and safer"

    Here is the code that solve your problem:

    set.removeIf((Integer element) -> {
        return (element % 2 == 0);
    });
    

    Now your set contains only odd values.

    Simplest way to wait some asynchronous tasks complete, in Javascript?

    Use Promises.

    var mongoose = require('mongoose');
    
    mongoose.connect('your MongoDB connection string');
    var conn = mongoose.connection;
    
    var promises = ['aaa', 'bbb', 'ccc'].map(function(name) {
      return new Promise(function(resolve, reject) {
        var collection = conn.collection(name);
        collection.drop(function(err) {
          if (err) { return reject(err); }
          console.log('dropped ' + name);
          resolve();
        });
      });
    });
    
    Promise.all(promises)
    .then(function() { console.log('all dropped)'); })
    .catch(console.error);
    

    This drops each collection, printing “dropped” after each one, and then prints “all dropped” when complete. If an error occurs, it is displayed to stderr.


    Previous answer (this pre-dates Node’s native support for Promises):

    Use Q promises or Bluebird promises.

    With Q:

    var Q = require('q');
    var mongoose = require('mongoose');
    
    mongoose.connect('your MongoDB connection string');
    var conn = mongoose.connection;
    
    var promises = ['aaa','bbb','ccc'].map(function(name){
        var collection = conn.collection(name);
        return Q.ninvoke(collection, 'drop')
          .then(function() { console.log('dropped ' + name); });
    });
    
    Q.all(promises)
    .then(function() { console.log('all dropped'); })
    .fail(console.error);
    

    With Bluebird:

    var Promise = require('bluebird');
    var mongoose = Promise.promisifyAll(require('mongoose'));
    
    mongoose.connect('your MongoDB connection string');
    var conn = mongoose.connection;
    
    var promises = ['aaa', 'bbb', 'ccc'].map(function(name) {
      return conn.collection(name).dropAsync().then(function() {
        console.log('dropped ' + name);
      });
    });
    
    Promise.all(promises)
    .then(function() { console.log('all dropped'); })
    .error(console.error);
    

    Get column value length, not column max length of value

    LENGTH() does return the string length (just verified). I suppose that your data is padded with blanks - try

    SELECT typ, LENGTH(TRIM(t1.typ))
    FROM AUTA_VIEW t1;
    

    instead.

    As OraNob mentioned, another cause could be that CHAR is used in which case LENGTH() would also return the column width, not the string length. However, the TRIM() approach also works in this case.

    Equivalent of Math.Min & Math.Max for Dates?

    How about:

    public static T Min<T>(params T[] values)
    {
        if (values == null) throw new ArgumentNullException("values");
        var comparer = Comparer<T>.Default;
        switch(values.Length) {
            case 0: throw new ArgumentException();
            case 1: return values[0];
            case 2: return comparer.Compare(values[0],values[1]) < 0
                   ? values[0] : values[1];
            default:
                T best = values[0];
                for (int i = 1; i < values.Length; i++)
                {
                    if (comparer.Compare(values[i], best) < 0)
                    {
                        best = values[i];
                    }
                }
                return best;
        }        
    }
    // overload for the common "2" case...
    public static T Min<T>(T x, T y)
    {
        return Comparer<T>.Default.Compare(x, y) < 0 ? x : y;
    }
    

    Works with any type that supports IComparable<T> or IComparable.

    Actually, with LINQ, another alternative is:

    var min = new[] {x,y,z}.Min();
    

    Dump all tables in CSV format using 'mysqldump'

    It looks like others had this problem also, and there is a simple Python script now, for converting output of mysqldump into CSV files.

    wget https://raw.githubusercontent.com/jamesmishra/mysqldump-to-csv/master/mysqldump_to_csv.py
    mysqldump -u username -p --host=rdshostname database table | python mysqldump_to_csv.py > table.csv
    

    ERROR : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

    If you're working with an x64 server, keep in mind that there are different ODBC settings for x86 and x64 applications. The "Data Sources (ODBC)" tool in the Administrative Tools list takes you to the x64 version. To view/edit the x86 ODBC settings, you'll need to run that version of the tool manually:

    %windir%\SysWOW64\odbcad32.exe (%windir% is usually C:\Windows)
    

    When your app runs as x64, it will use the x64 data sources, and when it runs as x86, it will use those data sources instead.

    Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

    No previous single solution worked for me, I had to mix them and got the issue fixed also on older devices (iphone 3).

    First, I had to wrap the html content into an outer div:

    <html>
      <body>
        <div id="wrapper">... old html goes here ...</div>
      </body>
    </html>
    

    Then I had to apply overflow hidden to the wrapper, because overflow-x was not working:

      #wrapper {
        overflow: hidden;
      }
    

    and this fixed the issue.

    How to display text in pygame?

    When displaying I sometimes make a new file called Funk. This will have the font, size etc. This is the code for the class:

    import pygame
    
    def text_to_screen(screen, text, x, y, size = 50,
                color = (200, 000, 000), font_type = 'data/fonts/orecrusherexpand.ttf'):
        try:
    
            text = str(text)
            font = pygame.font.Font(font_type, size)
            text = font.render(text, True, color)
            screen.blit(text, (x, y))
    
        except Exception, e:
            print 'Font Error, saw it coming'
            raise e
    

    Then when that has been imported when I want to display text taht updates E.G score I do:

    Funk.text_to_screen(screen, 'Text {0}'.format(score), xpos, ypos)
    

    If it is just normal text that isn't being updated:

    Funk.text_to_screen(screen, 'Text', xpos, ypos)
    

    You may notice {0} on the first example. That is because when .format(whatever) is used that is what will be updated. If you have something like Score then target score you'd do {0} for score then {1} for target score then .format(score, targetscore)

    Count occurrences of a char in a string using Bash

    you can for example remove all other chars and count the whats remains, like:

    var="text,text,text,text"
    res="${var//[^,]}"
    echo "$res"
    echo "${#res}"
    

    will print

    ,,,
    3
    

    or

    tr -dc ',' <<<"$var" | awk '{ print length; }'
    

    or

    tr -dc ',' <<<"$var" | wc -c    #works, but i don't like wc.. ;)
    

    or

    awk -F, '{print NF-1}' <<<"$var"
    

    or

    grep -o ',' <<<"$var" | grep -c .
    

    or

    perl -nle 'print s/,//g' <<<"$var"
    

    How to get the home directory in Python?

    I know this is an old thread, but I recently needed this for a large scale project (Python 3.8). It had to work on any mainstream OS, so therefore I went with the solution @Max wrote in the comments.

    Code:

    import os
    print(os.path.expanduser("~"))
    

    Output Windows:

    PS C:\Python> & C:/Python38/python.exe c:/Python/test.py
    C:\Users\mXXXXX
    

    Output Linux (Ubuntu):

    rxxx@xx:/mnt/c/Python$ python3 test.py
    /home/rxxx
    

    I also tested it on Python 2.7.17 and that works too.

    React eslint error missing in props validation

    For me, upgrading eslint-plugin-react to the latest version 7.21.5 fixed this

    How to apply !important using .css()?

    Here is what I did after encountering this problem...

    var origStyleContent = jQuery('#logo-example').attr('style');
    jQuery('#logo-example').attr('style', origStyleContent + ';width:150px !important');
    

    How to upload files to server using Putty (ssh)

    Use WinSCP for file transfer over SSH, putty is only for SSH commands.

    Converting int to bytes in Python 3

    The documentation says:

    bytes(int) -> bytes object of size given by the parameter
                  initialized with null bytes
    

    The sequence:

    b'3\r\n'
    

    It is the character '3' (decimal 51) the character '\r' (13) and '\n' (10).

    Therefore, the way would treat it as such, for example:

    >>> bytes([51, 13, 10])
    b'3\r\n'
    
    >>> bytes('3', 'utf8') + b'\r\n'
    b'3\r\n'
    
    >>> n = 3
    >>> bytes(str(n), 'ascii') + b'\r\n'
    b'3\r\n'
    

    Tested on IPython 1.1.0 & Python 3.2.3

    Checking if a collection is null or empty in Groovy

    !members.find()
    

    I think now the best way to solve this issue is code above. It works since Groovy 1.8.1 http://docs.groovy-lang.org/docs/next/html/groovy-jdk/java/util/Collection.html#find(). Examples:

    def lst1 = []
    assert !lst1.find()
    
    def lst2 = [null]
    assert !lst2.find()
    
    def lst3 = [null,2,null]
    assert lst3.find()
    
    def lst4 = [null,null,null]
    assert !lst4.find()
    
    def lst5 = [null, 0, 0.0, false, '', [], 42, 43]
    assert lst5.find() == 42
    
    def lst6 = null; 
    assert !lst6.find()
    

    Remove a modified file from pull request

    Removing a file from pull request but not from your local repository.

    1. Go to your branch from where you created the request use the following commands

    git checkout -- c:\temp..... next git checkout origin/master -- c:\temp... u replace origin/master with any other branch. Next git commit -m c:\temp..... Next git push origin

    Note : no single quote or double quotes for the filepath

    Binding to static property

    Another solution is to create a normal class which implements PropertyChanger like this

    public class ViewProps : PropertyChanger
    {
        private string _MyValue = string.Empty;
        public string MyValue
        {
            get { 
                return _MyValue
            }
            set
            {
                if (_MyValue == value)
                {
                    return;
                }
                SetProperty(ref _MyValue, value);
            }
        }
    }
    

    Then create a static instance of the class somewhere you wont

    public class MyClass
    {
        private static ViewProps _ViewProps = null;
        public static ViewProps ViewProps
        {
            get
            {
                if (_ViewProps == null)
                {
                    _ViewProps = new ViewProps();
                }
                return _ViewProps;
            }
        }
    }
    

    And now use it as static property

    <TextBlock  Text="{x:Bind local:MyClass.ViewProps.MyValue, Mode=OneWay}"  />
    

    And here is PropertyChanger implementation if necessary

    public abstract class PropertyChanger : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
        {
            if (object.Equals(storage, value)) return false;
    
            storage = value;
            OnPropertyChanged(propertyName);
            return true;
        }
    
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    

    How to run a cronjob every X minutes?

    In a crontab file, the fields are:

    • minute of the hour.
    • hour of the day.
    • day of the month.
    • month of the year.
    • day of the week.

    So:

    10 * * * * blah
    

    means execute blah at 10 minutes past every hour.

    If you want every five minutes, use either:

    */5 * * * * blah
    

    meaning every minute but only every fifth one, or:

    0,5,10,15,20,25,30,35,40,45,50,55 * * * * blah
    

    for older cron executables that don't understand the */x notation.

    If it still seems to be not working after that, change the command to something like:

    date >>/tmp/debug_cron_pax.txt
    

    and monitor that file to ensure something's being written every five minutes. If so, there's something wrong with your PHP scripts. If not, there's something wrong with your cron daemon.

    Return HTTP status code 201 in flask

    You can read about it here.

    return render_template('page.html'), 201
    

    How to order by with union in SQL?

    If I want the sort to be applied to only one of the UNION if use Union all:

    Select id,name,age
    From Student
    Where age < 15
    Union all
    Select id,name,age
    From 
    (
    Select id,name,age
    From Student
    Where Name like "%a%"
    Order by name
    )
    

    dplyr mutate with conditional values

    With dplyr 0.7.2, you can use the very useful case_when function :

    x=read.table(
     text="V1 V2 V3 V4
     1  1  2  3  5
     2  2  4  4  1
     3  1  4  1  1
     4  4  5  1  3
     5  5  5  5  4")
    x$V5 = case_when(x$V1==1 & x$V2!=4 ~ 1,
                     x$V2==4 & x$V3!=1 ~ 2,
                     TRUE ~ 0)
    

    Expressed with dplyr::mutate, it gives:

    x = x %>% mutate(
         V5 = case_when(
             V1==1 & V2!=4 ~ 1,
             V2==4 & V3!=1 ~ 2,
             TRUE ~ 0
         )
    )
    

    Please note that NA are not treated specially, as it can be misleading. The function will return NA only when no condition is matched. If you put a line with TRUE ~ ..., like I did in my example, the return value will then never be NA.

    Therefore, you have to expressively tell case_when to put NA where it belongs by adding a statement like is.na(x$V1) | is.na(x$V3) ~ NA_integer_. Hint: the dplyr::coalesce() function can be really useful here sometimes!

    Moreover, please note that NA alone will usually not work, you have to put special NA values : NA_integer_, NA_character_ or NA_real_.

    How to convert a DataFrame back to normal RDD in pyspark?

    @dapangmao's answer works, but it doesn't give the regular spark RDD, it returns a Row object. If you want to have the regular RDD format.

    Try this:

    rdd = df.rdd.map(tuple)
    

    or

    rdd = df.rdd.map(list)
    

    Clear data in MySQL table with PHP?

    MySQLI example where $con is the database connection variable and table name is: mytable.

    mysqli_query($con,'TRUNCATE TABLE mytable');
    

    MySQL select where column is not empty

    Surprisingly(as nobody else mentioned it before) found that the condition below does the job:

    WHERE ORD(field_to_check) > 0 
    

    when we need to exclude both null and empty values. Is anybody aware of downsides of the approach?

    Oracle SQL - select within a select (on the same table!)

    Basically, all you have to do is

    select ..., (select ... from ... where ...) as ..., ..., from ... where ...
    

    For exemple. You can insert the (select ... from ... where) wherever you want it will be replaced by the corresponding data.

    I know that the others exemple (even if each of them are really great :) ) are a bit complicated to understand for the newbies (like me :p) so i hope this "simple" exemple will help some of you guys :)

    Easy way to add drop down menu with 1 - 100 without doing 100 different options?

    In Html5, you can now use

    <form>
    <input type="number" min="1" max="100">
    </form>
    

    How to Bulk Insert from XLSX file extension?

    you can save the xlsx file as a tab-delimited text file and do

    BULK INSERT TableName
            FROM 'C:\SomeDirectory\my table.txt'
                WITH
        (
                    FIELDTERMINATOR = '\t',
                    ROWTERMINATOR = '\n'
        )
    GO
    

    PHP script to loop through all of the files in a directory?

    You can use the DirectoryIterator. Example from php Manual:

    <?php
    $dir = new DirectoryIterator(dirname(__FILE__));
    foreach ($dir as $fileinfo) {
        if (!$fileinfo->isDot()) {
            var_dump($fileinfo->getFilename());
        }
    }
    ?>
    

    Inserting line breaks into PDF

    $pdf->SetY($Y_Fields_Name_position);
    $pdf->SetX(#);
    $pdf->MultiCell($height,$width,"Line1 \nLine2 \nLine3",1,'C',1);
    

    In every Column, before you set the X Position indicate first the Y position, so it became like this

    Column 1

    $pdf->SetY($Y_Fields_Name_position);
    $pdf->SetX(#);
    $pdf->MultiCell($height,$width,"Line1 \nLine2 \nLine3",1,'C',1);
    

    Column 2

    $pdf->SetY($Y_Fields_Name_position);
    $pdf->SetX(#);
    $pdf->MultiCell($height,$width,"Line1 \nLine2 \nLine3",1,'C',1);
    

    UIImage resize (Scale proportion)

    This change worked for me:

    // The size returned by CGImageGetWidth(imgRef) & CGImageGetHeight(imgRef) is incorrect as it doesn't respect the image orientation!
    // CGImageRef imgRef = [image CGImage];
    // CGFloat width = CGImageGetWidth(imgRef);
    // CGFloat height = CGImageGetHeight(imgRef);
    //
    // This returns the actual width and height of the photo (and hence solves the problem
    CGFloat width = image.size.width; 
    CGFloat height = image.size.height;
    CGRect bounds = CGRectMake(0, 0, width, height);
    

    How can I plot a histogram such that the heights of the bars sum to 1 in matplotlib?

    I know this answer is too late considering the question is dated 2010 but I came across this question as I was facing a similar problem myself. As already stated in the answer, normed=True means that the total area under the histogram is equal to 1 but the sum of heights is not equal to 1. However, I wanted to, for convenience of physical interpretation of a histogram, make one with sum of heights equal to 1.

    I found a hint in the following question - Python: Histogram with area normalized to something other than 1

    But I was not able to find a way of making bars mimic the histtype="step" feature hist(). This diverted me to : Matplotlib - Stepped histogram with already binned data

    If the community finds it acceptable I should like to put forth a solution which synthesises ideas from both the above posts.

    import matplotlib.pyplot as plt
    
    # Let X be the array whose histogram needs to be plotted.
    nx, xbins, ptchs = plt.hist(X, bins=20)
    plt.clf() # Get rid of this histogram since not the one we want.
    
    nx_frac = nx/float(len(nx)) # Each bin divided by total number of objects.
    width = xbins[1] - xbins[0] # Width of each bin.
    x = np.ravel(zip(xbins[:-1], xbins[:-1]+width))
    y = np.ravel(zip(nx_frac,nx_frac))
    
    plt.plot(x,y,linestyle="dashed",label="MyLabel")
    #... Further formatting.
    

    This has worked wonderfully for me though in some cases I have noticed that the left most "bar" or the right most "bar" of the histogram does not close down by touching the lowest point of the Y-axis. In such a case adding an element 0 at the begging or the end of y achieved the necessary result.

    Just thought I'd share my experience. Thank you.

    Handling identity columns in an "Insert Into TABLE Values()" statement?

    By default, if you have an identity column, you do not need to specify it in the VALUES section. If your table is:

    ID    NAME    ADDRESS
    

    Then you can do:

    INSERT INTO MyTbl VALUES ('Joe', '123 State Street, Boston, MA')
    

    This will auto-generate the ID for you, and you don't have to think about it at all. If you SET IDENTITY_INSERT MyTbl ON, you can assign a value to the ID column.

    Can (domain name) subdomains have an underscore "_" in it?

    Most answers given here are false. It is perfectly legal to have an underscore in a domain name. Let me quote the standard, RFC 2181, section 11, "Name syntax":

    The DNS itself places only one restriction on the particular labels that can be used to identify resource records. That one restriction relates to the length of the label and the full name. [...] Implementations of the DNS protocols must not place any restrictions on the labels that can be used. In particular, DNS servers must not refuse to serve a zone because it contains labels that might not be acceptable to some DNS client programs.

    See also the original DNS specification, RFC 1034, section 3.5 "Preferred name syntax" but read it carefully.

    Domains with underscores are very common in the wild. Check _jabber._tcp.gmail.com or _sip._udp.apnic.net.

    Other RFC mentioned here deal with different things. The original question was for domain names. If the question is for host names (or for URLs, which include a host name), then this is different, the relevant standard is RFC 1123, section 2.1 "Host Names and Numbers" which limits host names to letters-digits-hyphen.

    SQL: Combine Select count(*) from multiple tables

    SELECT 
    (select count(*) from foo1 where ID = '00123244552000258')
    +
    (select count(*) from foo2 where ID = '00123244552000258')
    +
    (select count(*) from foo3 where ID = '00123244552000258')
    

    This is an easy way.

    Playing HTML5 video on fullscreen in android webview

    Tested on Android 9.0 version

    None of the answers worked for me . This is the final thing worked

    import android.annotation.SuppressLint;
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.webkit.WebChromeClient;
    import android.webkit.WebSettings;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;
    import android.widget.FrameLayout;
    import android.widget.ProgressBar;
    
    public class MainActivity extends AppCompatActivity {
    
        WebView mWebView;
    
    
        @SuppressLint("SetJavaScriptEnabled")
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
    
            mWebView = (WebView) findViewById(R.id.webView);
    
    
            mWebView.setWebViewClient(new WebViewClient());
            mWebView.setWebChromeClient(new MyChrome());
            WebSettings webSettings = mWebView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webSettings.setAllowFileAccess(true);
            webSettings.setAppCacheEnabled(true);
    
           if (savedInstanceState == null) {
              mWebView.loadUrl("https://www.youtube.com/");
           }
    
        }
    
    
        private class MyChrome extends WebChromeClient {
    
            private View mCustomView;
            private WebChromeClient.CustomViewCallback mCustomViewCallback;
            protected FrameLayout mFullscreenContainer;
            private int mOriginalOrientation;
            private int mOriginalSystemUiVisibility;
    
            MyChrome() {}
    
            public Bitmap getDefaultVideoPoster()
            {
                if (mCustomView == null) {
                    return null;
                }
                return BitmapFactory.decodeResource(getApplicationContext().getResources(), 2130837573);
            }
    
            public void onHideCustomView()
            {
                ((FrameLayout)getWindow().getDecorView()).removeView(this.mCustomView);
                this.mCustomView = null;
                getWindow().getDecorView().setSystemUiVisibility(this.mOriginalSystemUiVisibility);
                setRequestedOrientation(this.mOriginalOrientation);
                this.mCustomViewCallback.onCustomViewHidden();
                this.mCustomViewCallback = null;
            }
    
            public void onShowCustomView(View paramView, WebChromeClient.CustomViewCallback paramCustomViewCallback)
            {
                if (this.mCustomView != null)
                {
                    onHideCustomView();
                    return;
                }
                this.mCustomView = paramView;
                this.mOriginalSystemUiVisibility = getWindow().getDecorView().getSystemUiVisibility();
                this.mOriginalOrientation = getRequestedOrientation();
                this.mCustomViewCallback = paramCustomViewCallback;
                ((FrameLayout)getWindow().getDecorView()).addView(this.mCustomView, new FrameLayout.LayoutParams(-1, -1));
                getWindow().getDecorView().setSystemUiVisibility(3846 | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            }
        }
    
     @Override
        protected void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            mWebView.saveState(outState);
        }
    
        @Override
        protected void onRestoreInstanceState(Bundle savedInstanceState) {
            super.onRestoreInstanceState(savedInstanceState);
            mWebView.restoreState(savedInstanceState);
        }
    }
    

    In AndroidManifest.xml

    <activity
      android:name=".MainActivity"
      android:configChanges="orientation|screenSize" />
    

    Source Monster Techno

    Write Base64-encoded image to file

    Try this:

    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.net.URL;
    import javax.imageio.ImageIO;
    
    public class WriteImage 
    {   
        public static void main( String[] args )
        {
            BufferedImage image = null;
            try {
    
                URL url = new URL("URL_IMAGE");
                image = ImageIO.read(url);
    
                ImageIO.write(image, "jpg",new File("C:\\out.jpg"));
                ImageIO.write(image, "gif",new File("C:\\out.gif"));
                ImageIO.write(image, "png",new File("C:\\out.png"));
    
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("Done");
        }
    }
    

    Overlapping Views in Android

    Android handles transparency across views and drawables (including PNG images) natively, so the scenario you describe (a partially transparent ImageView in front of a Gallery) is certainly possible.

    If you're having problems it may be related to either the layout or your image. I've replicated the layout you describe and successfully achieved the effect you're after. Here's the exact layout I used.

    <RelativeLayout 
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/gallerylayout"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent">
      <Gallery
        android:id="@+id/overview"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
      />
      <ImageView
        android:id="@+id/navigmaske"
        android:background="#0000"      
        android:src="@drawable/navigmask"
        android:scaleType="fitXY"
        android:layout_alignTop="@id/overview"
        android:layout_alignBottom="@id/overview"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
      />
    </RelativeLayout>
    

    Note that I've changed the parent RelativeLayout to a height and width of fill_parent as is generally what you want for a main Activity. Then I've aligned the top and bottom of the ImageView to the top and bottom of the Gallery to ensure it's centered in front of it.

    I've also explicitly set the background of the ImageView to be transparent.

    As for the image drawable itself, if you put the PNG file somewhere for me to look at I can use it in my project and see if it's responsible.

    jquery animate .css

    The example from jQuery's website animates size AND font but you could easily modify it to fit your needs

    $("#go").click(function(){
      $("#block").animate({ 
        width: "70%",
        opacity: 0.4,
        marginLeft: "0.6in",
        fontSize: "3em", 
        borderWidth: "10px"
      }, 1500 );
    

    http://api.jquery.com/animate/

    libaio.so.1: cannot open shared object file

    It looks like a 32/64 bit mismatch. The ldd output shows that mainly libraries from /lib64 are chosen. That would indicate that you have installed a 64 bit version of the Oracle client and have created a 64 bit executable. But libaio.so is probably a 32 bit library and cannot be used for your application.

    So you either need a 64 bit version of libaio or you create a 32 bit version of your application.