Programs & Examples On #Dltk

MySQL: Grant **all** privileges on database

I had this challenge when working on MySQL Ver 8.0.21

I wanted to grant permissions of a database named my_app_db to the root user running on localhost host.

But when I run the command:

use my_app_db;

GRANT ALL PRIVILEGES ON my_app_db.* TO 'root'@'localhost';

I get the error:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'my_app_db.* TO 'root'@'localhost'' at line 1>

Here's how I fixed:

Login to your MySQL console. You can change root to the user you want to login with:

mysql -u root -p

Enter your mysql root password

Next, list out all the users and their host on the MySQL server. Unlike PostgreSQL this is often stored in the mysql database. So we need to select the mysql database first:

use mysql;
SELECT user, host FROM user;

Note: if you don't run the use mysql, you get the no database selected error.

This should give you an output of this sort:

+------------------+-----------+
| user             | host      |
+------------------+-----------+
| mysql.infoschema | localhost |
| mysql.session    | localhost |
| mysql.sys        | localhost |
| root             | localhost |
+------------------+-----------+
4 rows in set (0.00 sec)

Next, based on the information gotten from the list, grant privileges to the user that you want. We will need to first select the database before granting permission to it. For me, I am using the root user that runs on the localhost host:

use my_app_db;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';

Note: The GRANT ALL PRIVILEGES ON database_name.* TO 'root'@'localhost'; command may not work for modern versions of MySQL. Most modern versions of MyQL replace the database_name with * in the grant privileges command after you select the database that you want to use.

You can then exit the MySQL console:

exit

That's it.

I hope this helps

merge two object arrays with Angular 2 and TypeScript?

You can also use the form recommended by ES6:

data => {
  this.results = [
    ...this.results,
    data.results,
  ];
  this._next = data.next;
},

This works if you initialize your array first (public results = [];); otherwise replace ...this.results, by ...this.results ? this.results : [],.

Hope this helps

Submit form without page reloading

I did something similar to the jquery above, but I needed to reset my form data and graphic attachment canvases. So here is what I came up with:

    <script>
   $(document).ready(function(){

   $("#text_only_radio_button_id").click(function(){
       $("#single_pic_div").hide();
       $("#multi_pic_div").hide();
   });

   $("#pic_radio_button_id").click(function(){
      $("#single_pic_div").show();
      $("#multi_pic_div").hide();
    });

   $("#gallery_radio_button_id").click(function(){
       $("#single_pic_div").hide();
       $("#multi_pic_div").show();
                 });
    $("#my_Submit_button_ID").click(function() {
          $("#single_pic_div").hide();
          $("#multi_pic_div").hide();
          var url = "script_the_form_gets_posted_to.php"; 

       $.ajax({
       type: "POST",
       url: url,
       data: $("#html_form_id").serialize(), 
       success: function(){  
       document.getElementById("html_form_id").reset();
           var canvas=document.getElementById("canvas");
    var canvasA=document.getElementById("canvasA");
    var canvasB=document.getElementById("canvasB");
    var canvasC=document.getElementById("canvasC");
    var canvasD=document.getElementById("canvasD");

              var ctx=canvas.getContext("2d");
              var ctxA=canvasA.getContext("2d");
              var ctxB=canvasB.getContext("2d");
              var ctxC=canvasC.getContext("2d");
              var ctxD=canvasD.getContext("2d");
               ctx.clearRect(0, 0,480,480);
               ctxA.clearRect(0, 0,480,480);
               ctxB.clearRect(0, 0,480,480);        
               ctxC.clearRect(0, 0,480,480);
               ctxD.clearRect(0, 0,480,480);
               } });
           return false;
                });    });
           </script>

That works well for me, for your application of just an html form, we can simplify this jquery code like this:

       <script>
        $(document).ready(function(){

    $("#my_Submit_button_ID").click(function() {
        var url =  "script_the_form_gets_posted_to.php";
       $.ajax({
       type: "POST",
       url: url,
       data: $("#html_form_id").serialize(), 
       success: function(){  
       document.getElementById("html_form_id").reset();
            } });
           return false;
                });    });
           </script>

what does "dead beef" mean?

Since IPv6-Adresses are written in Hex-notation you can use "Hexspeak" (numbers 0-9 and letters a-f) in Adresses.

There are a number of words you can use as valid adresses to better momorize them.

If you ping6 www.facebook.com -n you will get something like "2a03:2880:f01c:601:face:b00c:0:1".

Here are some examples:

  • :affe:: (Affe - German for Monkey - seen at a vlan for management board)
  • :1bad:babe:: (one bad babe - seen at a smtp-honeypot)
  • :badc:ab1e:: (bad cable - seen as subnet for a unsecure vlan)
  • :da7a:: (Data - seen for fileservers)
  • :d1a1:: (Dial - seen for VPN Dial-In)

Easier way to create circle div than using an image?

Give width and height depending on the size but,keep both equal

_x000D_
_x000D_
.circle {_x000D_
  background-color: gray;_x000D_
  height: 400px;_x000D_
  width: 400px;_x000D_
  border-radius: 100%;_x000D_
}
_x000D_
<div class="circle">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Get generic type of class at runtime

I dont think you can, Java uses type erasure when compiling so your code is compatible with applications and libraries that were created pre-generics.

From the Oracle Docs:

Type Erasure

Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. To implement generics, the Java compiler applies type erasure to:

Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods. Insert type casts if necessary to preserve type safety. Generate bridge methods to preserve polymorphism in extended generic types. Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.

http://docs.oracle.com/javase/tutorial/java/generics/erasure.html

How do I add a resources folder to my Java project in Eclipse

To answer your question posted in the title of this topic...

Step 1--> Right Click on Java Project, Select the option "Properties" Step 1--> Right Click on Java Project, Select the option "Properties"

Step 2--> Select "Java Build Path" from the left side menu, make sure you are on "Source" tab, click "Add Folder" Select "Java Build Path" from the left side menu, make sure you are on "Source" tab, click "Add Folder"

Step 3--> Click the option "Create New Folder..." available at the bottom of the window Click the option "Create New Folder..." available at the bottom of the window

Step 4--> Enter the name of the new folder as "resources" and then click "Finish" Enter the name of the new folder as "resources" and then click "Finish"

Step 5--> Now you'll be able to see the newly created folder "resources" under your java project, Click "Ok", again Click "Ok"
Now you'll be able to see the newly created folder "resources" under your java project, Click "Ok", again Click "Ok"

Final Step --> Now you should be able to see the new folder "resources" under your java project
Now you should be able to see the new folder "resources" under your java project

Coding Conventions - Naming Enums

enum MyEnum {VALUE_1,VALUE_2}

is (approximately) like saying

class MyEnum {

    public static final MyEnum VALUE_1 = new MyEnum("VALUE_1");
    public static final MyEnum VALUE_2 = new MyEnum("VALUE_2");

    private final name;

    private MyEnum(String name) {
        this.name = name;
    }

    public String name() { return this.name }
}

so I guess the all caps is strictly more correct, but still I use the class name convention since I hate all caps wherever

How to add checkboxes to JTABLE swing

1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,

2) AbstractTableModel should be useful, where is in the JTable required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel,

3) consider using DefaultTableModel, (if you are not sure about how to works) instead of AbstractTableModel,

table_with_BooleanType_column

could be generated from simple code:

import javax.swing.*;
import javax.swing.table.*;

public class TableCheckBox extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;

    public TableCheckBox() {
        Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
        Object[][] data = {
            {"Buy", "IBM", new Integer(1000), new Double(80.50), false},
            {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
            {"Sell", "Apple", new Integer(3000), new Double(7.35), true},
            {"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
        };
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            /*@Override
            public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
            }*/
            @Override
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    case 1:
                        return String.class;
                    case 2:
                        return Integer.class;
                    case 3:
                        return Double.class;
                    default:
                        return Boolean.class;
                }
            }
        };
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(scrollPane);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TableCheckBox frame = new TableCheckBox();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocation(150, 150);
                frame.setVisible(true);
            }
        });
    }
}

jQuery UI dialog positioning

I don't think the speech bubble is quite right. I tweaked it a bit so that it would work and the item opens right under the link.

function PositionDialog(link) {
    $('#myDialog').dialog('open');
    var myDialogX = $(link).position().left;
    var myDialogY = $(link).position().top + $(link).outerHeight();
    $('#myDialog').dialog('option', 'position', [myDialogX, myDialogY]);
}

Creating a blurring overlay view

enter image description here

From Xcode you can do it easily. Follow the steps from xcode. Drage visual effect view on your uiview or imageview.

Happy Coding :)

How to check if a service is running on Android?

If the service belongs to another process or APK use the solution based on the ActivityManager.

If you have access to its source, just use the solution based on a static field. But instead using a boolean I would suggest using a Date object. While the service is running, just update its value to 'now' and when it finishes set it to null. From the activity you can check if its null or the date is too old which will mean that it is not running.

You can also send broadcast notification from your service indicating that is running along further info like progress.

How do I use $scope.$watch and $scope.$apply in AngularJS?

You need to be aware about how AngularJS works in order to understand it.

Digest cycle and $scope

First and foremost, AngularJS defines a concept of a so-called digest cycle. This cycle can be considered as a loop, during which AngularJS checks if there are any changes to all the variables watched by all the $scopes. So if you have $scope.myVar defined in your controller and this variable was marked for being watched, then you are implicitly telling AngularJS to monitor the changes on myVar in each iteration of the loop.

A natural follow-up question would be: Is everything attached to $scope being watched? Fortunately, no. If you would watch for changes to every object in your $scope, then quickly a digest loop would take ages to evaluate and you would quickly run into performance issues. That is why the AngularJS team gave us two ways of declaring some $scope variable as being watched (read below).

$watch helps to listen for $scope changes

There are two ways of declaring a $scope variable as being watched.

  1. By using it in your template via the expression <span>{{myVar}}</span>
  2. By adding it manually via the $watch service

Ad 1) This is the most common scenario and I'm sure you've seen it before, but you didn't know that this has created a watch in the background. Yes, it had! Using AngularJS directives (such as ng-repeat) can also create implicit watches.

Ad 2) This is how you create your own watches. $watch service helps you to run some code when some value attached to the $scope has changed. It is rarely used, but sometimes is helpful. For instance, if you want to run some code each time 'myVar' changes, you could do the following:

function MyController($scope) {

    $scope.myVar = 1;

    $scope.$watch('myVar', function() {
        alert('hey, myVar has changed!');
    });

    $scope.buttonClicked = function() {
        $scope.myVar = 2; // This will trigger $watch expression to kick in
    };
}

$apply enables to integrate changes with the digest cycle

You can think of the $apply function as of an integration mechanism. You see, each time you change some watched variable attached to the $scope object directly, AngularJS will know that the change has happened. This is because AngularJS already knew to monitor those changes. So if it happens in code managed by the framework, the digest cycle will carry on.

However, sometimes you want to change some value outside of the AngularJS world and see the changes propagate normally. Consider this - you have a $scope.myVar value which will be modified within a jQuery's $.ajax() handler. This will happen at some point in future. AngularJS can't wait for this to happen, since it hasn't been instructed to wait on jQuery.

To tackle this, $apply has been introduced. It lets you start the digestion cycle explicitly. However, you should only use this to migrate some data to AngularJS (integration with other frameworks), but never use this method combined with regular AngularJS code, as AngularJS will throw an error then.

How is all of this related to the DOM?

Well, you should really follow the tutorial again, now that you know all this. The digest cycle will make sure that the UI and the JavaScript code stay synchronised, by evaluating every watcher attached to all $scopes as long as nothing changes. If no more changes happen in the digest loop, then it's considered to be finished.

You can attach objects to the $scope object either explicitly in the Controller, or by declaring them in {{expression}} form directly in the view.

I hope that helps to clarify some basic knowledge about all this.

Further readings:

PHP Email sending BCC

You have $headers .= '...'; followed by $headers = '...';; the second line is overwriting the first.

Just put the $headers .= "Bcc: $emailList\r\n"; say after the Content-type line and it should be fine.

On a side note, the To is generally required; mail servers might mark your message as spam otherwise.

$headers  = "From: [email protected]\r\n" .
  "X-Mailer: php\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "Bcc: $emailList\r\n";

How to make a <button> in Bootstrap look like a normal link in nav-tabs?

In bootstrap 3, this works well for me:

.btn-link.btn-anchor {
    outline: none !important;
    padding: 0;
    border: 0;
    vertical-align: baseline;
}

Used like:

<button type="button" class="btn-link btn-anchor">My Button</button>

Demo

How to generate a random number between 0 and 1?

Set the seed using srand(). Also, you're not specifying the max value in rand(), so it's using RAND_MAX. I'm not sure if it's actually 10000... why not just specify it. Although, we don't know what your "expected results" are. It's a random number generator. What are you expecting, and what are you seeing?

As noted in another comment, SA() isn't returning anything explicitly.

http://pubs.opengroup.org/onlinepubs/009695399/functions/rand.html http://www.thinkage.ca/english/gcos/expl/c/lib/rand.html

Edit: From Generating random number between [-1, 1] in C? ((float)rand())/RAND_MAX returns a floating-point number in [0,1]

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this?

Not your code is the problem this is perfectly fine:

gray = cv2.cvtColor(imgUMat, cv2.COLOR_RGB2GRAY)

The problem is that imgUMat is None so you probably made a mistake when loading your image:

imgUMat = cv2.imread("your_image.jpg")

I suspect you just entered the wrong image path.

Change bootstrap navbar background color and font color

Most likely these classes are already defined by Bootstrap, make sure that your CSS file that you want to override the classes with is called AFTER the Bootstrap CSS.

<link rel="stylesheet" href="css/bootstrap.css" /> <!-- Call Bootstrap first -->
<link rel="stylesheet" href="css/bootstrap-override.css" /> <!-- Call override CSS second -->

Otherwise, you can put !important at the end of your CSS like this: color:#ffffff!important; but I would advise against using !important at all costs.

jQuery.click() vs onClick

The first method is to prefer. It uses the advanced event registration model[s], which means you can attach multiple handlers to the same element. You can easily access the event object, and the handler can live in any function's scope. Also, it is dynamic, i.e it can be invoked at any time and is especially well-suited for dynamically generated elements. Whether you use jQuery, an other library or the native methods directly does not really matter.

The second method, using inline attributes, needs a lot of global functions (which leads to namespace pollution) and mixes the content/structure (HTML) with the behavior (JavaScript). Do not use that.

Your question about performance or standards can't be easily answered. The two methods are just completely different, and do different things. The first one is mightier, while the second one is despised (considered bad style).

Hunk #1 FAILED at 1. What's that mean?

Follow the instructions here, it solved my problem.

you have to run the command like as follow; patch -p0 --dry-run < path/to/your/patchFile/yourPatch.patch

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

The Reason

You are not opening the page through a server, like Apache, so when the browser tries to obtain the resource it thinks it is from a separate domain, which is not allowed. Though some browsers do allow it.

The Solution

Run inetmgr and host your page locally and browse as http://localhost:portnumber/PageName.html or through a web server like Apache, nginx, node etc.

Alternatively use a different browser No error was shown when directly opening the page using Firefox and Safari. It comes only for Chrome and IE(xx).

If you are using code editors like Brackets, Sublime or Notepad++, those apps handle this error automatically.

How to catch a unique constraint error in a PL/SQL block?

I'm sure you have your reasons, but just in case... you should also consider using a "merge" query instead:

begin
    merge into some_table st
    using (select 'some' name, 'values' value from dual) v
    on (st.name=v.name)
    when matched then update set st.value=v.value
    when not matched then insert (name, value) values (v.name, v.value);
end;

(modified the above to be in the begin/end block; obviously you can run it independantly of the procedure too).

How can I get System variable value in Java?

To clarify, system variables are the same as environment variables. User environment variables are set per user and are different whenever a different user logs in. System wide environment variables are the same no matter what user logs on.

To access either the current value of a system wide variable or a user variable in Java, see below:

String javaHome = System.getenv("JAVA_HOME");

For more information on environment variables see this wikipedia page.

Also make sure the environment variable you are trying to read is properly set before invoking Java by doing a:

echo %MYENVVAR%

You should see the value of the environment variable. If not, you may need to reopen the shell (DOS) or log off and log back on.

What is the standard Python docstring format?

I suggest using Vladimir Keleshev's pep257 Python program to check your docstrings against PEP-257 and the Numpy Docstring Standard for describing parameters, returns, etc.

pep257 will report divergence you make from the standard and is called like pylint and pep8.

python mpl_toolkits installation issue

I can't comment due to the lack of reputation, but if you are on arch linux, you should be able to find the corresponding libraries on the arch repositories directly. For example for mpl_toolkits.basemap:

pacman -S python-basemap

How to check if variable's type matches Type stored in a variable

In order to check if an object is compatible with a given type variable, instead of writing

u is t

you should write

typeof(t).IsInstanceOfType(u)

NuGet auto package restore does not work with MSBuild

Note that if you are using TeamCity as a build server, you get a "NuGet Installer" step that you can use to restore all the packages before the build step.

Check if a column contains text using SQL

Try this:

SElECT * FROM STUDENTS WHERE LEN(CAST(STUDENTID AS VARCHAR)) > 0

With this you get the rows where STUDENTID contains text

SSRS - Checking whether the data is null

Or in your SQL query wrap that field with IsNull or Coalesce (SQL Server).

Either way works, I like to put that logic in the query so the report has to do less.

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 do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

NSData *data = [strChangetoJSON dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data
                                                             options:kNilOptions
                                                               error:&error];

For example you have a NSString with special characters in NSString strChangetoJSON. Then you can convert that string to JSON response using above code.

How to align title at center of ActionBar in default theme(Theme.Holo.Light)

It seems there is no way to do this without custom view. You can get the title view:

View decor = getWindow().getDecorView();
TextView title = (TextView) decor.findViewById(getResources().getIdentifier("action_bar_title", "id", "android"));

But changing of gravity or layout_gravity doesn't have an effect. The problem in the ActionBarView, which layout its children by itself so changing of layout params of its children also doesn't have an effect. To see this excecute following code:

ViewGroup actionBar = (ViewGroup) decor.findViewById(getResources().getIdentifier("action_bar", "id", "android"));
View v = actionBar.getChildAt(0);
ActionBar.LayoutParams p = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
p.gravity= Gravity.CENTER;
v.setLayoutParams(p);
v.setBackgroundColor(Color.BLACK);

Controlling number of decimal digits in print output in R

The reason it is only a suggestion is that you could quite easily write a print function that ignored the options value. The built-in printing and formatting functions do use the options value as a default.

As to the second question, since R uses finite precision arithmetic, your answers aren't accurate beyond 15 or 16 decimal places, so in general, more aren't required. The gmp and rcdd packages deal with multiple precision arithmetic (via an interace to the gmp library), but this is mostly related to big integers rather than more decimal places for your doubles.

Mathematica or Maple will allow you to give as many decimal places as your heart desires.

EDIT:
It might be useful to think about the difference between decimal places and significant figures. If you are doing statistical tests that rely on differences beyond the 15th significant figure, then your analysis is almost certainly junk.

On the other hand, if you are just dealing with very small numbers, that is less of a problem, since R can handle number as small as .Machine$double.xmin (usually 2e-308).

Compare these two analyses.

x1 <- rnorm(50, 1, 1e-15)
y1 <- rnorm(50, 1 + 1e-15, 1e-15)
t.test(x1, y1)  #Should throw an error

x2 <- rnorm(50, 0, 1e-15)
y2 <- rnorm(50, 1e-15, 1e-15)
t.test(x2, y2)  #ok

In the first case, differences between numbers only occur after many significant figures, so the data are "nearly constant". In the second case, Although the size of the differences between numbers are the same, compared to the magnitude of the numbers themselves they are large.


As mentioned by e3bo, you can use multiple-precision floating point numbers using the Rmpfr package.

mpfr("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825")

These are slower and more memory intensive to use than regular (double precision) numeric vectors, but can be useful if you have a poorly conditioned problem or unstable algorithm.

UITextField text change event

Here in swift version for same.

textField.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)

func textFieldDidChange(textField: UITextField) {

}

Thanks

How to get the row number from a datatable?

Why don't you try this

for(int i=0; i < dt.Rows.Count; i++)
{
  // u can use here the i
}

How to find the sum of an array of numbers

i saw all answers going for 'reduce' solution

var array = [1,2,3,4]
var total = 0
for (var i = 0; i < array.length; i++) {
    total += array[i]
}
console.log(total)

git diff between two different files

Specify the paths explicitly:

git diff HEAD:full/path/to/foo full/path/to/bar

Check out the --find-renames option in the git-diff docs.

Credit: twaggs.

How do you implement a circular buffer in C?

A simple implementation could consist of:

  • A buffer, implemented as an array of size n, of whatever type you need
  • A read pointer or index (whichever is more efficient for your processor)
  • A write pointer or index
  • A counter indicating how much data is in the buffer (derivable from the read and write pointers, but faster to track it separately)

Every time you write data, you advance the write pointer and increment the counter. When you read data, you increase the read pointer and decrement the counter. If either pointer reaches n, set it to zero.

You can't write if counter = n. You can't read if counter = 0.

Load a bitmap image into Windows Forms using open file dialog

It's simple. Just add:

PictureBox1.BackgroundImageLayout = ImageLayout.Zoom;

How to calculate number of days between two given dates?

For calculating dates and times, there are several options but I will write the simple way:

from datetime import timedelta, datetime, date
import dateutil.relativedelta

# current time
date_and_time = datetime.now()
date_only = date.today()
time_only = datetime.now().time()

# calculate date and time
result = date_and_time - timedelta(hours=26, minutes=25, seconds=10)

# calculate dates: years (-/+)
result = date_only - dateutil.relativedelta.relativedelta(years=10)

# months
result = date_only - dateutil.relativedelta.relativedelta(months=10)

# days
result = date_only - dateutil.relativedelta.relativedelta(days=10)

# calculate time 
result = date_and_time - timedelta(hours=26, minutes=25, seconds=10)
result.time()

Hope it helps

How to set the range of y-axis for a seaborn boxplot?

It is standard matplotlib.pyplot:

...
import matplotlib.pyplot as plt
plt.ylim(10, 40)

Or simpler, as mwaskom comments below:

ax.set(ylim=(10, 40))

enter image description here

fatal: does not appear to be a git repository

my local and remote machines are both OS X. I was having trouble until I checked the file structure of the git repo that xCode Server provides me. Essentially everything is chmod 777 * in that repo so to setup a separate non xCode repo on the same machine in my remote account there I did this:

REMOTE MACHINE

  1. Login to your account
  2. Create a master dir for all projects 'mkdir git'
  3. chmod 775 git then cd into it
  4. make a project folder 'mkdir project1'
  5. chmod 777 project1 then cd into it
  6. run command 'git init' to make the repo
  7. this creates a .git dir. do command 'chmod 777 .git' then cd into it
  8. run command 'chmod 777 *' to make all files in .git 777 mod
  9. cd back out to myproject1 (cd ..)
  10. setup a test file in the new repo w/command 'touch test.php'
  11. add it to the repo staging area with command 'git add test.php'
  12. run command "git commit -m 'new file'" to add file to repo
  13. run command 'git status' and you should get "working dir clean" msg
  14. cd back to master dir with 'cd ..'
  15. in the master dir make a symlink 'ln -s project1 project1.git'
  16. run command 'pwd' to get full path
  17. in my case the full path was "/Users/myname/git/project1.git'
  18. write down the full path for later use in URL
  19. exit from the REMOTE MACHINE

LOCAL MACHINE

  1. create a project folder somewhere 'newproj1' with 'mkdir newproj1'
  2. cd into it
  3. run command 'git init'
  4. make an alias to the REMOTE MACHINE
  5. the alias command format is 'git remote add your_alias_here URL'
  6. make sure your URL is correct. This caused me headaches initially
  7. URL = 'ssh://[email protected]/Users/myname/git/project1.git'
  8. after you do 'git remote add alias URL' do 'git remote -v'
  9. the command should respond with a fetch and push line
  10. run cmd 'git pull your_alias master' to get test.php from REMOTE repo
  11. after the command in #10 you should see a nice message.
  12. run command 'git push --set-upstream your_alias master'
  13. after command in 12 you should see nice message
  14. command in #12 sets up REMOTE as the project master (root)

For me, i learned getting a clean start with a git repo on a LOCAL and REMOTE requires all initial work in a shell first. Then, after the above i was able to easily setup the LOCAL and REMOTE git repos in my IDE and do all the basic git commands using the GUI of the IDE.

I had difficulty until I started at the remote first, then did the local, and until i opened up all the permissions on remote. In addition, having the exact full path in the URL to the symlink was critical to succeed.

Again, this all worked on OS X, local and remote machines.

How to configure log4j with a properties file

Since JVM arguments are eventually passed to your java program as system variables, you can use this code at the beginning of your execution point to edit the property and have log4j read the property you just set in system properties

try {
        System.setProperty("log4j.configuration", new File(System.getProperty("user.dir")+File.separator+"conf"+File.separator+"log4j.properties").toURI().toURL().toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

How to add white spaces in HTML paragraph

This can be done easily and cleanly with float.

Demo: jsfiddle.net/KcdpW

HTML:

<ul>
    <li>Item 1 <span class="right">(1)</span></li>
    <li>Item 2 <span class="right">(2)</span></li>
</ul>?

CSS:

ul {
    width: 10em
}
.right {
    float: right
}?

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

I had a similar use case, except I wanted to checkout only the commit for a tag and prune the directories. Using --depth 1 makes it really sparse and can really speed things up.

mkdir myrepo
cd myrepo
git init
git config core.sparseCheckout true
git remote add origin <url>  # Note: no -f option
echo "path/within_repo/to/subdir/" > .git/info/sparse-checkout
git fetch --depth 1 origin tag <tagname>
git checkout <tagname>

How do I sum values in a column that match a given condition using pandas?

The essential idea here is to select the data you want to sum, and then sum them. This selection of data can be done in several different ways, a few of which are shown below.

Boolean indexing

Arguably the most common way to select the values is to use Boolean indexing.

With this method, you find out where column 'a' is equal to 1 and then sum the corresponding rows of column 'b'. You can use loc to handle the indexing of rows and columns:

>>> df.loc[df['a'] == 1, 'b'].sum()
15

The Boolean indexing can be extended to other columns. For example if df also contained a column 'c' and we wanted to sum the rows in 'b' where 'a' was 1 and 'c' was 2, we'd write:

df.loc[(df['a'] == 1) & (df['c'] == 2), 'b'].sum()

Query

Another way to select the data is to use query to filter the rows you're interested in, select column 'b' and then sum:

>>> df.query("a == 1")['b'].sum()
15

Again, the method can be extended to make more complicated selections of the data:

df.query("a == 1 and c == 2")['b'].sum()

Note this is a little more concise than the Boolean indexing approach.

Groupby

The alternative approach is to use groupby to split the DataFrame into parts according to the value in column 'a'. You can then sum each part and pull out the value that the 1s added up to:

>>> df.groupby('a')['b'].sum()[1]
15

This approach is likely to be slower than using Boolean indexing, but it is useful if you want check the sums for other values in column a:

>>> df.groupby('a')['b'].sum()
a
1    15
2     8

#include errors detected in vscode

For Windows:

  1. Please add this directory to your environment variable(Path):

C:\mingw-w64\x86_64-8.1.0-win32-seh-rt_v6-rev0\mingw64\bin\

  1. For Include errors detected, mention the path of your include folder into

"includePath": [ "C:/mingw-w64/x86_64-8.1.0-win32-seh-rt_v6-rev0/mingw64/include/" ]

, as this is the path from where the compiler fetches the library to be included in your program.

"Initializing" variables in python?

Python treats comma on the left hand side of equal sign ( = ) as an input splitter, Very useful for functions that return a tuple.

e.g,

x,y = (5,2)

What you want to do is:

grade_1 = grade_2 = grade_3 = average = 0.0

though that might not be the most clear way to write it.

How do I remove all .pyc files from a project?

rm -r recurses into directories, but only the directories you give to rm. It will also delete those directories. One solution is:

for i in $( find . -name *.pyc )
do
  rm $i
done

find will find all *.pyc files recursively in the current directory, and the for loop will iterate through the list of files found, removing each one.

Get each line from textarea

$content = $_POST['content_name'];
$lines = explode("\n", $content);

foreach( $lines as $index => $line )
{
    $lines[$index] = $line . '<br/>';
}

// $lines contains your lines

Constants in Kotlin -- what's a recommended way to create them?

In Kotlin, if you want to create the local constants which are supposed to be used with in the class then you can create it like below

val MY_CONSTANT = "Constants"

And if you want to create a public constant in kotlin like public static final in java, you can create it as follow.

companion object{

     const val MY_CONSTANT = "Constants"

}

SQLAlchemy: What's the difference between flush() and commit()?

commit () records these changes in the database. flush () is always called as part of the commit () (1) call. When you use a Session object to query a database, the query returns results from both the database and the reddened parts of the unrecorded transaction it is performing.

Submit form without reloading page

You can use jQuery serialize function along with get/post as follows:

$.get('server.php?' + $('#theForm').serialize())

$.post('server.php', $('#theform').serialize())

jQuery Serialize Documentation: http://api.jquery.com/serialize/

Simple AJAX submit using jQuery:

// this is the id of the submit button
$("#submitButtonId").click(function() {

    var url = "path/to/your/script.php"; // the script where you handle the form input.

    $.ajax({
           type: "POST",
           url: url,
           data: $("#idForm").serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // show response from the php script.
           }
         });

    return false; // avoid to execute the actual submit of the form.
});

JUnit test for System.out.println()

@dfa answer is great, so I took it a step farther to make it possible to test blocks of ouput.

First I created TestHelper with a method captureOutput that accepts the annoymous class CaptureTest. The captureOutput method does the work of setting and tearing down the output streams. When the implementation of CaptureOutput's test method is called, it has access to the output generate for the test block.

Source for TestHelper:

public class TestHelper {

    public static void captureOutput( CaptureTest test ) throws Exception {
        ByteArrayOutputStream outContent = new ByteArrayOutputStream();
        ByteArrayOutputStream errContent = new ByteArrayOutputStream();

        System.setOut(new PrintStream(outContent));
        System.setErr(new PrintStream(errContent));

        test.test( outContent, errContent );

        System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
        System.setErr(new PrintStream(new FileOutputStream(FileDescriptor.out)));

    }
}

abstract class CaptureTest {
    public abstract void test( ByteArrayOutputStream outContent, ByteArrayOutputStream errContent ) throws Exception;
}

Note that TestHelper and CaptureTest are defined in the same file.

Then in your test, you can import the static captureOutput. Here is an example using JUnit:

// imports for junit
import static package.to.TestHelper.*;

public class SimpleTest {

    @Test
    public void testOutput() throws Exception {

        captureOutput( new CaptureTest() {
            @Override
            public void test(ByteArrayOutputStream outContent, ByteArrayOutputStream errContent) throws Exception {

                // code that writes to System.out

                assertEquals( "the expected output\n", outContent.toString() );
            }
        });
}

Simple way to calculate median with MySQL

This way seems include both even and odd count without subquery.

SELECT AVG(t1.x)
FROM table t1, table t2
GROUP BY t1.x
HAVING SUM(SIGN(t1.x - t2.x)) = 0

Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

Note: This is strictly not production use. If you want to quickly debug, this may be useful. Otherwise, please use @SchizoDuckie's answer above.

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);     
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); 

Just add them. It works.

Linux: copy and create destination dir if it does not exist

Let's say you are doing something like

cp file1.txt A/B/C/D/file.txt

where A/B/C/D are directories which do not exist yet

A possible solution is as follows

DIR=$(dirname A/B/C/D/file.txt)
# DIR= "A/B/C/D"
mkdir -p $DIR
cp file1.txt A/B/C/D/file.txt

hope that helps!

JavaScript: get code to run every minute

Using setInterval:

setInterval(function() {
    // your code goes here...
}, 60 * 1000); // 60 * 1000 milsec

The function returns an id you can clear your interval with clearInterval:

var timerID = setInterval(function() {
    // your code goes here...
}, 60 * 1000); 

clearInterval(timerID); // The setInterval it cleared and doesn't run anymore.

A "sister" function is setTimeout/clearTimeout look them up.


If you want to run a function on page init and then 60 seconds after, 120 sec after, ...:

function fn60sec() {
    // runs every 60 sec and runs on init.
}
fn60sec();
setInterval(fn60sec, 60*1000);

JavaScript, getting value of a td with id name

If by 'td value' you mean text inside of td, then:

document.getElementById('td-id').innerHTML

Read XML file into XmlDocument

Hope you dont mind Xml.Linq and .net3.5+

XElement ele = XElement.Load("text.xml");
String aXmlString = ele.toString(SaveOptions.DisableFormatting);

Depending on what you are interested in, you can probably skip the whole 'string' var part and just use XLinq objects

React - Component Full Screen (with height 100%)

try using !important in height. It is probably because of some other style affecting your html body.

{ height : 100% !important; }

also you can give values in VP which will set height to viee port pixel you mention likeheight : 700vp; but this wont be portable.

How to copy to clipboard in Vim?

I'm a Vim newby but, to copy all the text to system clipboard (e.g if you want to paste it to a word processor or another text editor like gedit, mousepad etc...), in normal mode:

ggVGy

or, more simply:

:%y

As suggested, I also installed vim-gtk and put

set clipboard=unnamedplus

in my .vimrc

and everything works fine

If you want to copy only a portion of text, use visual mode (v), select the text you want to copy and press y.

Finally, I suggest a clipboard program like Clipman (my favorite), Clipit, Parcellite or similar.

(I'm using vim 8.0 in Debian Stretch Xfce)

FORGIVE ME FOR MY ENGLISH! :-)

How to check if JSON return is empty with jquery

Below code(jQuery.isEmptyObject(anyObject) function is already provided) works perfectly fine, no need to write one of your own.

   // works for any Object Including JSON(key value pair) or Array.
  //  var arr = [];
  //  var jsonObj = {};
    if (jQuery.isEmptyObject(anyObjectIncludingJSON))
    {
       console.log("Empty Object");
    }

Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

You need to merge the remote branch into your current branch by running git pull.

If your local branch is already up-to-date, you may also need to run git pull --rebase.

A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

How can I get Apache gzip compression to work?

Enable compression via .htaccess

For most people reading this, compression is enabled by adding some code to a file called .htaccess on their web host/server. This means going to the file manager (or wherever you go to add or upload files) on your webhost.

The .htaccess file controls many important things for your site.

The code below should be added to your .htaccess file...

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

Save the .htaccess file and then refresh your webpage.

Check to see if your compression is working using the Gzip compression tool.

Integer.toString(int i) vs String.valueOf(int i)

Just two different ways of doing the same thing. It may be a historical reason (can't remember if one came before the other).

"The Controls collection cannot be modified because the control contains code blocks"

I solved an error similar to this by putting the <script> inside a contentplaceholder inside the <head> instead of putting the <script> outside the said contentplaceholder inside the <head>

how to check if a datareader is null or empty

Try this simpler equivalent syntax:

ltlAdditional.Text = (myReader["Additional"] == DBNull.Value) ? "is null" : "contains data";

Run PostgreSQL queries from the command line

psql -U username -d mydatabase -c 'SELECT * FROM mytable'

If you're new to postgresql and unfamiliar with using the command line tool psql then there is some confusing behaviour you should be aware of when you've entered an interactive session.

For example, initiate an interactive session:

psql -U username mydatabase 
mydatabase=#

At this point you can enter a query directly but you must remember to terminate the query with a semicolon ;

For example:

mydatabase=# SELECT * FROM mytable;

If you forget the semicolon then when you hit enter you will get nothing on your return line because psql will be assuming that you have not finished entering your query. This can lead to all kinds of confusion. For example, if you re-enter the same query you will have most likely create a syntax error.

As an experiment, try typing any garble you want at the psql prompt then hit enter. psql will silently provide you with a new line. If you enter a semicolon on that new line and then hit enter, then you will receive the ERROR:

mydatabase=# asdfs 
mydatabase=# ;  
ERROR:  syntax error at or near "asdfs"
LINE 1: asdfs
    ^

The rule of thumb is: If you received no response from psql but you were expecting at least SOMETHING, then you forgot the semicolon ;

How can I run a php without a web server?

You can use these kind of programs to emulate an apache web server and run PHP on your computer:

http://www.wampserver.com/en/

http://www.apachefriends.org/en/xampp.html

C pointer to array/array of pointers disambiguation

typedef int (*PointerToIntArray)[];
typedef int *ArrayOfIntPointers[];

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

Simple method to sending data using java script and ajex call.

First right your form like this

<form id="frm_details" method="post" name="frm_details">
<input  id="email" name="email" placeholder="Your Email id" type="text" />
    <button class="subscribe-box__btn" type="submit">Need Assistance</button>
</form> 

javascript logic target on form id #frm_details after sumbit

$(function(){
        $("#frm_details").on("submit", function(event) {
            event.preventDefault();

            var formData = {
                'email': $('input[name=email]').val() //for get email 
            };
            console.log(formData);

            $.ajax({
                url: "/tsmisc/api/subscribe-newsletter",
                type: "post",
                data: formData,
                success: function(d) {
                    alert(d);
                }
            });
        });
    }) 





General 
Request URL:https://test.abc
Request Method:POST
Status Code:200 
Remote Address:13.76.33.57:443

From Data
email:[email protected]

How do you disable viewport zooming on Mobile Safari?

I managed to stop this behavior by adding the following to the HTML header. This works on mobile devices, as desktop browsers support zooming when using the mouse wheel. It's not a big deal on desktop browsers but it's important to take this into account.

_x000D_
_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
_x000D_
_x000D_
_x000D_

and the following rule to the CSS stylesheet

_x000D_
_x000D_
html {_x000D_
 -webkit-text-size-adjust: none;_x000D_
 touch-action: manipulation;_x000D_
}
_x000D_
_x000D_
_x000D_

Count frequency of words in a list and sort by frequency

You can use

from collections import Counter

It supports Python 2.7,read more information here

1.

>>>c = Counter('abracadabra')
>>>c.most_common(3)
[('a', 5), ('r', 2), ('b', 2)]

use dict

>>>d={1:'one', 2:'one', 3:'two'}
>>>c = Counter(d.values())
[('one', 2), ('two', 1)]

But, You have to read the file first, and converted to dict.

2. it's the python docs example,use re and Counter

# Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
 ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]

How to get the number of threads in a Java process

ManagementFactory.getThreadMXBean().getThreadCount() doesn't limit itself to thread groups as Thread.activeCount() does.

java: How can I do dynamic casting of a variable from one type to another?

You can write a simple castMethod like the one below.

private <T> T castObject(Class<T> clazz, Object object) {
  return (T) object;
}

In your method you should be using it like

public ConnectParams(HashMap<String,Object> object) {

for (Map.Entry<String, Object> entry : object.entrySet()) {
    try {
        Field f =  this.getClass().getField(entry.getKey());                
        f.set(this, castObject(entry.getValue().getClass(), entry.getValue()); /* <= CASTING PROBLEM */
    } catch (NoSuchFieldException ex) {
        log.error("did not find field '" + entry.getKey() + '"');
    } catch (IllegalAccessException ex) {    
        log.error(ex.getMessage());          
    }    
}

}

'NOT NULL constraint failed' after adding to models.py

You must create a migration, where you will specify default value for a new field, since you don't want it to be null. If null is not required, simply add null=True and create and run migration.

How does PHP 'foreach' actually work?

PHP foreach loop can be used with Indexed arrays, Associative arrays and Object public variables.

In foreach loop, the first thing php does is that it creates a copy of the array which is to be iterated over. PHP then iterates over this new copy of the array rather than the original one. This is demonstrated in the below example:

<?php
$numbers = [1,2,3,4,5,6,7,8,9]; # initial values for our array
echo '<pre>', print_r($numbers, true), '</pre>', '<hr />';
foreach($numbers as $index => $number){
    $numbers[$index] = $number + 1; # this is making changes to the origial array
    echo 'Inside of the array = ', $index, ': ', $number, '<br />'; # showing data from the copied array
}
echo '<hr />', '<pre>', print_r($numbers, true), '</pre>'; # shows the original values (also includes the newly added values).

Besides this, php does allow to use iterated values as a reference to the original array value as well. This is demonstrated below:

<?php
$numbers = [1,2,3,4,5,6,7,8,9];
echo '<pre>', print_r($numbers, true), '</pre>';
foreach($numbers as $index => &$number){
    ++$number; # we are incrementing the original value
    echo 'Inside of the array = ', $index, ': ', $number, '<br />'; # this is showing the original value
}
echo '<hr />';
echo '<pre>', print_r($numbers, true), '</pre>'; # we are again showing the original value

Note: It does not allow original array indexes to be used as references.

Source: http://dwellupper.io/post/47/understanding-php-foreach-loop-with-examples

Stretch and scale CSS background

Scaling an image with CSS is not quite possible, but a similar effect can be achieved in the following manner, though.

Use this markup:

<div id="background">
    <img src="img.jpg" class="stretch" alt="" />
</div>

with the following CSS:

#background {
    width: 100%; 
    height: 100%; 
    position: absolute; 
    left: 0px; 
    top: 0px; 
    z-index: 0;
}

.stretch {
    width:100%;
    height:100%;
}

and you should be done!

In order to scale the image to be "full bleed" and maintain the aspect ratio, you can do this instead:

.stretch { min-width:100%; min-height:100%; width:auto; height:auto; }

It works out quite nicely! If one dimension is cropped, however, it will be cropped on only one side of the image, rather than being evenly cropped on both sides (and centered). I've tested it in Firefox, Webkit, and Internet Explorer 8.

Turning Sonar off for certain code

I recommend you try to suppress specific warnings by using @SuppressWarnings("squid:S2078").

For suppressing multiple warnings you can do it like this @SuppressWarnings({"squid:S2078", "squid:S2076"})

There is also the //NOSONAR comment that tells SonarQube to ignore all errors for a specific line.

Finally if you have the proper rights for the user interface you can issue a flag as a false positive directly from the interface.

The reason why I recommend suppression of specific warnings is that it's a better practice to block a specific issue instead of using //NOSONAR and risk a Sonar issue creeping in your code by accident.

You can read more about this in the FAQ

Edit: 6/30/16 SonarQube is now called SonarLint

In case you are wondering how to find the squid number. Just click on the Sonar message (ex. Remove this method to simply inherit it.) and the Sonar issue will expand.

On the bottom left it will have the squid number (ex. squid:S1185 Maintainability > Understandability)

So then you can suppress it by @SuppressWarnings("squid:S1185")

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

In addition to Petr's answer, if you want to bind to a specific interface instead of all the interfaces you can use -b or --bind flag.

python -m http.server 8000 --bind 127.0.0.1

The above snippet should do the trick. 8000 is the port number. 80 is used as the standard port for HTTP communications.

How do you import an Eclipse project into Android Studio now?

Here is a simpler way to migrate:

Start off with a sample Android Studio project. Open android studio and create a new project (or) just download a ‘sample’ studio project here: https://github.com/AppLozic/eclipse-to-android-studio-migration. Now, open the downloaded project in Android Studio by following the below instructions.

Import eclipse project modules into Android Studio. Select File -> New -> Import Module Image title

Next, select the path of the eclipse project and import the modules. In case, if you see the message “Failed to sync Gradle project,” then click on “Install Build Tools and sync project…”

Now, remove the sample project modules by following the below simple steps:

Open settings.gradle and remove “include ‘:app’” Right click on “app” module and “Delete” it. Now, what we have is the Eclipse project open in Android studio with the Gradle build.

Here are few other links which might help you:

http://developer.android.com/sdk/installing/migrate.html Source: http://www.applozic.com/blog/migrating-project-from-eclipse-to-studio/

How to break nested loops in JavaScript?

break doesn't take parameters. There are two workarounds:

  1. Wrap them in a function and call return

  2. Set a flag in the inner loop and break again right after the loop if the flag is set.

How to Get the Current URL Inside @if Statement (Blade) in Laravel 4?

@if(request()->path()=='/path/another_path/*')
@endif

Preferred way of getting the selected item of a JComboBox

Note this isn't at heart a question about JComboBox, but about any collection that can include multiple types of objects. The same could be said for "How do I get a String out of a List?" or "How do I get a String out of an Object[]?"

What does the 'export' command do?

I guess you're coming from a windows background. So i'll contrast them (i'm kind of new to linux too). I found user's reply to my comment, to be useful in figuring things out.

In Windows, a variable can be permanent or not. The term Environment variable includes a variable set in the cmd shell with the SET command, as well as when the variable is set within the windows GUI, thus set in the registry, and becoming viewable in new cmd windows. e.g. documentation for the set command in windows https://technet.microsoft.com/en-us/library/bb490998.aspx "Displays, sets, or removes environment variables. Used without parameters, set displays the current environment settings." In Linux, set does not display environment variables, it displays shell variables which it doesn't call/refer to as environment variables. Also, Linux doesn't use set to set variables(apart from positional parameters and shell options, which I explain as a note at the end), only to display them and even then only to display shell variables. Windows uses set for setting and displaying e.g. set a=5, linux doesn't.

In Linux, I guess you could make a script that sets variables on bootup, e.g. /etc/profile or /etc/.bashrc but otherwise, they're not permanent. They're stored in RAM.

There is a distinction in Linux between shell variables, and environment variables. In Linux, shell variables are only in the current shell, and Environment variables, are in that shell and all child shells.

You can view shell variables with the set command (though note that unlike windows, variables are not set in linux with the set command).

set -o posix; set (doing that set -o posix once first, helps not display too much unnecessary stuff). So set displays shell variables.

You can view environment variables with the env command

shell variables are set with e.g. just a = 5

environment variables are set with export, export also sets the shell variable

Here you see shell variable zzz set with zzz = 5, and see it shows when running set but doesn't show as an environment variable.

Here we see yyy set with export, so it's an environment variable. And see it shows under both shell variables and environment variables

$ zzz=5

$ set | grep zzz
zzz=5

$ env | grep zzz

$ export yyy=5

$ set | grep yyy
yyy=5

$ env | grep yyy
yyy=5

$

other useful threads

https://unix.stackexchange.com/questions/176001/how-can-i-list-all-shell-variables

https://askubuntu.com/questions/26318/environment-variable-vs-shell-variable-whats-the-difference

Note- one point which elaborates a bit and is somewhat corrective to what i've written, is that, in linux bash, 'set' can be used to set "positional parameters" and "shell options/attributes", and technically both of those are variables, though the man pages might not describe them as such. But still, as mentioned, set won't set shell variables or environment variables). If you do set asdf then it sets $1 to asdf, and if you do echo $1 you see asdf. If you do set a=5 it won't set the variable a, equal to 5. It will set the positional parameter $1 equal to the string of "a=5". So if you ever saw set a=5 in linux it's probably a mistake unless somebody actually wanted that string a=5, in $1. The other thing that linux's set can set, is shell options/attributes. If you do set -o you see a list of them. And you can do for example set -o verbose, off, to turn verbose on(btw the default happens to be off but that makes no difference to this). Or you can do set +o verbose to turn verbose off. Windows has no such usage for its set command.

Android: resizing imageview in XML

Please try this one works for me:

<ImageView android:id="@+id/image_view"     
  android:layout_width="wrap_content"  
  android:layout_height="wrap_content"  
  android:adjustViewBounds="true"  
  android:maxWidth="60dp" 
  android:layout_gravity="center" 
  android:maxHeight="60dp"  
  android:scaleType="fitCenter"  
  android:src="@drawable/icon"  
  /> 

Vue - Deep watching an array of objects and calculating the change?

This is what I use to deep watch an object. My requirement was watching the child fields of the object.

new Vue({
    el: "#myElement",
    data:{
        entity: {
            properties: []
        }
    },
    watch:{
        'entity.properties': {
            handler: function (after, before) {
                // Changes detected.    
            },
            deep: true
        }
    }
});

How to print variables without spaces between values

It's the comma which is providing that extra white space.

One way is to use the string % method:

print 'Value is "%d"' % (value)

which is like printf in C, allowing you to incorporate and format the items after % by using format specifiers in the string itself. Another example, showing the use of multiple values:

print '%s is %3d.%d' % ('pi', 3, 14159)

For what it's worth, Python 3 greatly improves the situation by allowing you to specify the separator and terminator for a single print call:

>>> print(1,2,3,4,5)
1 2 3 4 5

>>> print(1,2,3,4,5,end='<<\n')
1 2 3 4 5<<

>>> print(1,2,3,4,5,sep=':',end='<<\n')
1:2:3:4:5<<

jquery how to use multiple ajax calls one after the end of the other

Wrap each ajax call in a named function and just add them to the success callbacks of the previous call:

function callA() {
    $.ajax({
    ...
    success: function() {
      //do stuff
      callB();
    }
    });
}

function callB() {
    $.ajax({
    ...
    success: function() {
        //do stuff
        callC();
    }
    });
}

function callC() {
    $.ajax({
    ...
    });
}


callA();

KnockoutJs v2.3.0 : Error You cannot apply bindings multiple times to the same element

In my case, I was adding to a non existing element, or, I was adding bindings to an element that maybe exists, but it's parent did not. Similar to this:

var segDiv =  $("#segments"); //did not exist, wrong id
var theDiv = segDiv.html("<div></div>");

ko.applyBindings(someVM, theDiv);

As far as I can tell, this error seems a bit overloaded in the sense that it will fire on a lot of different errors that can happen with the element, like it not existing. As such, the error description can be highly deceptive. It should have probably read:

"Failure to bind bindings to element. Possible reasons include: multiple binding attempts, element not existing, element not in DOM hierarchy, quirks in browsers, etc"

Query to get only numbers from a string

T-SQL function to read all the integers from text and return the one at the indicated index, starting from left or right, also using a starting search term (optional):

create or alter function dbo.udf_number_from_text(
    @text nvarchar(max),
    @search_term nvarchar(1000) = N'',
    @number_position tinyint = 1,
    @rtl bit = 0
) returns int
as
    begin
        declare @result int = 0;
        declare @search_term_index int = 0;

        if @text is null or len(@text) = 0 goto exit_label;
        set @text = trim(@text);
        if len(@text) = len(@search_term) goto exit_label;

        if len(@search_term) > 0
            begin
                set @search_term_index = charindex(@search_term, @text);
                if @search_term_index = 0 goto exit_label;
            end;

        if @search_term_index > 0
            if @rtl = 0
                set @text = trim(right(@text, len(@text) - @search_term_index - len(@search_term) + 1));
            else
                set @text = trim(left(@text, @search_term_index - 1));
        if len(@text) = 0 goto exit_label;

        declare @patt_number nvarchar(10) = '%[0-9]%';
        declare @patt_not_number nvarchar(10) = '%[^0-9]%';
        declare @number_start int = 1;
        declare @number_end int;
        declare @found_numbers table (id int identity(1,1), val int);

        while @number_start > 0
        begin
            set @number_start = patindex(@patt_number, @text);
            if @number_start > 0
                begin
                    if @number_start = len(@text)
                        begin
                            insert into @found_numbers(val)
                            select cast(substring(@text, @number_start, 1) as int);

                            break;
                        end;
                    else
                        begin
                            set @text = right(@text, len(@text) - @number_start + 1);
                            set @number_end = patindex(@patt_not_number, @text);

                            if @number_end = 0
                                begin
                                    insert into @found_numbers(val)
                                    select cast(@text as int);

                                    break;
                                end;
                            else
                                begin
                                    insert into @found_numbers(val)
                                    select cast(left(@text, @number_end - 1) as int);

                                    if @number_end = len(@text)
                                        break;
                                    else
                                        begin
                                            set @text = trim(right(@text, len(@text) - @number_end));
                                            if len(@text) = 0 break;
                                        end;
                                end;
                        end;
                end;
        end;

        if @rtl = 0
            select @result = coalesce(a.val, 0)
            from (select row_number() over (order by m.id asc) as c_row, m.val
                    from @found_numbers as m) as a
            where a.c_row = @number_position;
        else
            select @result = coalesce(a.val, 0)
            from (select row_number() over (order by m.id desc) as c_row, m.val
                    from @found_numbers as m) as a
            where a.c_row = @number_position;


        exit_label:
            return @result;
    end;

Example:

select dbo.udf_number_from text(N'Text text 10 text, 25 term', N'term',2,1);

returns 10;

Count the number of Occurrences of a Word in a String

I've got another approach here:

String description = "hello india hello india hello hello india hello";
String textToBeCounted = "hello";

// Split description using "hello", which will return 
//string array of words other than hello
String[] words = description.split("hello");

// Get number of characters words other than "hello"
int lengthOfNonMatchingWords = 0;
for (String word : words) {
    lengthOfNonMatchingWords += word.length();
}

// Following code gets length of `description` - length of all non-matching
// words and divide it by length of word to be counted
System.out.println("Number of matching words are " + 
(description.length() - lengthOfNonMatchingWords) / textToBeCounted.length());

How to create an HTTPS server in Node.js?

The minimal setup for an HTTPS server in Node.js would be something like this :

var https = require('https');
var fs = require('fs');

var httpsOptions = {
    key: fs.readFileSync('path/to/server-key.pem'),
    cert: fs.readFileSync('path/to/server-crt.pem')
};

var app = function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}

https.createServer(httpsOptions, app).listen(4433);

If you also want to support http requests, you need to make just this small modification :

var http = require('http');
var https = require('https');
var fs = require('fs');

var httpsOptions = {
    key: fs.readFileSync('path/to/server-key.pem'),
    cert: fs.readFileSync('path/to/server-crt.pem')
};

var app = function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}

http.createServer(app).listen(8888);
https.createServer(httpsOptions, app).listen(4433);

How is AngularJS different from jQuery

I think this is a very good chart describing the differences in short. A quick glance at it shows most of the differences.

enter image description here

One thing I would like to add is that, AngularJS can be made to follow the MVVM design pattern while jQuery does not follow any of the standard Object Oriented patterns.

how to make password textbox value visible when hover an icon

<html>
<head>
</head>
<body>
<script>
function demo(){
    var d=document.getElementById('s1');
    var e=document.getElementById('show_f').value;
    var f=document.getElementById('show_f').type; 

    if(d.value=="show"){
        var f= document.getElementById('show_f').type="text";
        var g=document.getElementById('show_f').value=e;
        d.value="Hide";

    } else{
        var f= document.getElementById('show_f').type="password";
        var g=document.getElementById('show_f').value=e;
        d.value="show";
     }     
  }   
</script>   

<form method='post'>
Password: <input type='password' name='pass_f' maxlength='30' id='show_f'><input type="button" onclick="demo()" id="s1" value="show" style="height:25px; margin-left:5px;margin-top:3px;"><br><br>
<input type='submit' name='sub' value='Submit Now'>

</form>
</body>
</html>

Android Percentage Layout Height

android:layout_weight=".YOURVALUE" is best way to implement in percentage

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/logTextBox"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight=".20"
        android:maxLines="500"
        android:scrollbars="vertical"
        android:singleLine="false"
        android:text="@string/logText" >
    </TextView>

</LinearLayout>

When is TCP option SO_LINGER (0) required?

For my suggestion, please read the last section: “When to use SO_LINGER with timeout 0”.

Before we come to that a little lecture about:

  • Normal TCP termination
  • TIME_WAIT
  • FIN, ACK and RST

Normal TCP termination

The normal TCP termination sequence looks like this (simplified):

We have two peers: A and B

  1. A calls close()
    • A sends FIN to B
    • A goes into FIN_WAIT_1 state
  2. B receives FIN
    • B sends ACK to A
    • B goes into CLOSE_WAIT state
  3. A receives ACK
    • A goes into FIN_WAIT_2 state
  4. B calls close()
    • B sends FIN to A
    • B goes into LAST_ACK state
  5. A receives FIN
    • A sends ACK to B
    • A goes into TIME_WAIT state
  6. B receives ACK
    • B goes to CLOSED state – i.e. is removed from the socket tables

TIME_WAIT

So the peer that initiates the termination – i.e. calls close() first – will end up in the TIME_WAIT state.

To understand why the TIME_WAIT state is our friend, please read section 2.7 in "UNIX Network Programming" third edition by Stevens et al (page 43).

However, it can be a problem with lots of sockets in TIME_WAIT state on a server as it could eventually prevent new connections from being accepted.

To work around this problem, I have seen many suggesting to set the SO_LINGER socket option with timeout 0 before calling close(). However, this is a bad solution as it causes the TCP connection to be terminated with an error.

Instead, design your application protocol so the connection termination is always initiated from the client side. If the client always knows when it has read all remaining data it can initiate the termination sequence. As an example, a browser knows from the Content-Length HTTP header when it has read all data and can initiate the close. (I know that in HTTP 1.1 it will keep it open for a while for a possible reuse, and then close it.)

If the server needs to close the connection, design the application protocol so the server asks the client to call close().

When to use SO_LINGER with timeout 0

Again, according to "UNIX Network Programming" third edition page 202-203, setting SO_LINGER with timeout 0 prior to calling close() will cause the normal termination sequence not to be initiated.

Instead, the peer setting this option and calling close() will send a RST (connection reset) which indicates an error condition and this is how it will be perceived at the other end. You will typically see errors like "Connection reset by peer".

Therefore, in the normal situation it is a really bad idea to set SO_LINGER with timeout 0 prior to calling close() – from now on called abortive close – in a server application.

However, certain situation warrants doing so anyway:

  • If the a client of your server application misbehaves (times out, returns invalid data, etc.) an abortive close makes sense to avoid being stuck in CLOSE_WAIT or ending up in the TIME_WAIT state.
  • If you must restart your server application which currently has thousands of client connections you might consider setting this socket option to avoid thousands of server sockets in TIME_WAIT (when calling close() from the server end) as this might prevent the server from getting available ports for new client connections after being restarted.
  • On page 202 in the aforementioned book it specifically says: "There are certain circumstances which warrant using this feature to send an abortive close. One example is an RS-232 terminal server, which might hang forever in CLOSE_WAIT trying to deliver data to a stuck terminal port, but would properly reset the stuck port if it got an RST to discard the pending data."

I would recommend this long article which I believe gives a very good answer to your question.

Get SELECT's value and text in jQuery

You can do like this, to get the currently selected value:

$('#myDropdownID').val();

& to get the currently selected text:

$('#myDropdownID:selected').text();

Can I embed a .png image into an html page?

Quick google search says you can embed it like this:

<img src="data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub/
/ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcpp
V0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7" 
width="16" height="14" alt="embedded folder icon">

But you need a different implementation in Internet Explorer.

http://www.websiteoptimization.com/speed/tweak/inline-images/

Get current date/time in seconds

I use this:

Math.round(Date.now() / 1000)

No need for new object creation (see doc Date.now())

nodemon not found in npm

NPM is used to manage packages and download them. However, NPX must be used as the tool to execute Node Packages

Try using NPX nodemon ...

Hope this helps!

This version of the application is not configured for billing through Google Play

If you're here from 2018, you need to download the APK directly from Play Store and install the "derived" APK. Maybe it is because of Google's Play Store has a feature "App Signing by Google Play".

Internal vs. Private Access Modifiers

internal members are visible to all code in the assembly they are declared in.
(And to other assemblies referenced using the [InternalsVisibleTo] attribute)

private members are visible only to the declaring class. (including nested classes)

An outer (non-nested) class cannot be declared private, as there is no containing scope to make it private to.

To answer the question you forgot to ask, protected members are like private members, but are also visible in all classes that inherit the declaring type. (But only on an expression of at least the type of the current class)

How to copy commits from one branch to another?

git cherry-pick : Apply the changes introduced by some existing commits

Assume we have branch A with (X, Y, Z) commits. We need to add these commits to branch B. We are going to use the cherry-pick operations.

When we use cherry-pick, we should add commits on branch B in the same chronological order that the commits appear in Branch A.

cherry-pick does support a range of commits, but if you have merge commits in that range, it gets really complicated

git checkout B
git cherry-pick SHA-COMMIT-X
git cherry-pick SHA-COMMIT-Y
git cherry-pick SHA-COMMIT-Z

Example of workflow :

enter image description here

We can use cherry-pick with options

-e or --edit : With this option, git cherry-pick will let you edit the commit message prior to committing.

-n or --no-commit : Usually the command automatically creates a sequence of commits. This flag applies the changes necessary to cherry-pick each named commit to your working tree and the index, without making any commit. In addition, when this option is used, your index does not have to match the HEAD commit. The cherry-pick is done against the beginning state of your index.

Here an interesting article concerning cherry-pick.

How do I get the time difference between two DateTime objects using C#?

The way I usually do it is subtracting the two DateTime and this gets me a TimeSpan that will tell me the diff.

Here's an example:

DateTime start = DateTime.Now;
// Do some work
TimeSpan timeDiff = DateTime.Now - start;
timeDiff.TotalMilliseconds;

Validate phone number using javascript

_x000D_
_x000D_
function validatePhone(inputtxt) {_x000D_
  var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;_x000D_
  return phoneno.test(inputtxt)_x000D_
}
_x000D_
_x000D_
_x000D_

Command to escape a string in bash

You can use perl to replace various characters, for example:

$ echo "Hello\ world" | perl -pe 's/\\/\\\\/g'
Hello\\ world

Depending on the nature of your escape, you can chain multiple calls to escape the proper characters.

How do I specify a password to 'psql' non-interactively?

I tend to prefer passing a URL to psql:

psql "postgresql://$DB_USER:$DB_PWD@$DB_SERVER/$DB_NAME"

This gives me the freedom to name my environment variables as I wish and avoids creating unnecessary files.

This requires libpq. The documentation can be found here.

Create a new txt file using VB.NET

You can try writing into the Documents folder. Here is a "debug" function I did for the debugging needs of my project:

Private Sub writeDebug(ByVal x As String)
    Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
    Dim FILE_NAME As String = path & "\mydebug.txt"
    MsgBox(FILE_NAME)
    If System.IO.File.Exists(FILE_NAME) = False Then
        System.IO.File.Create(FILE_NAME).Dispose()
    End If
    Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
    objWriter.WriteLine(x)
    objWriter.Close()
End Sub

There are more standard folders you can access through the "SpecialFolder" object.

subtract time from date - moment js

Moment.subtract does not support an argument of type Moment - documentation:

moment().subtract(String, Number);
moment().subtract(Number, String); // 2.0.0
moment().subtract(String, String); // 2.7.0
moment().subtract(Duration); // 1.6.0
moment().subtract(Object);

The simplest solution is to specify the time delta as an object:

// Assumes string is hh:mm:ss
var myString = "03:15:00",
    myStringParts = myString.split(':'),
    hourDelta: +myStringParts[0],
    minuteDelta: +myStringParts[1];


date.subtract({ hours: hourDelta, minutes: minuteDelta});
date.toString()
// -> "Sat Jun 07 2014 06:07:06 GMT+0100"

How to loop through Excel files and load them into a database using SSIS package?

I had a similar issue and found that it was much simpler to to get rid of the Excel files as soon as possible. As part of the first steps in my package I used Powershell to extract the data out of the Excel files into CSV files. My own Excel files were simple but here

Extract and convert all Excel worksheets into CSV files using PowerShell

is an excellent article by Tim Smith on extracting data from multiple Excel files and/or multiple sheets.

Once the Excel files have been converted to CSV the data import is much less complicated.

Best way to reverse a string

SELECT REVERSE('somestring'); Done.

Regular expression to allow spaces between words

For alphabets only:

^([a-zA-Z])+(\s)+[a-zA-Z]+$

For alphanumeric value and _:

^(\w)+(\s)+\w+$

Escaping quotes and double quotes

Escaping parameters like that is usually source of frustration and feels a lot like a time wasted. I see you're on v2 so I would suggest using a technique that Joel "Jaykul" Bennet blogged about a while ago.

Long story short: you just wrap your string with @' ... '@ :

Start-Process \\server\toto.exe @'
-batch=B -param="sort1;parmtxt='Security ID=1234'"
'@

(Mind that I assumed which quotes are needed, and which things you were attempting to escape.) If you want to work with the output, you may want to add the -NoNewWindow switch.

BTW: this was so important issue that since v3 you can use --% to stop the PowerShell parser from doing anything with your parameters:

\\server\toto.exe --% -batch=b -param="sort1;paramtxt='Security ID=1234'"

... should work fine there (with the same assumption).

How can I get a web site's favicon?

It's a good practice to minimize the number of requests each page needs. So if you need several icons, yandex can do a sprite of favicons in one query. Here is an example http://favicon.yandex.net/favicon/google.com/stackoverflow.com/yandex.net/

How to clear APC cache entries?

Create APC.php file

foreach(array('user','opcode','') as $v ){
    apc_clear_cache($v);
}

Run it from your browser.

SQL Insert Query Using C#

The most common mistake (especially when using express) to the "my insert didn't happen" is : looking in the wrong file.

If you are using file-based express (rather than strongly attached), then the file in your project folder (say, c:\dev\myproject\mydb.mbd) is not the file that is used in your program. When you build, that file is copied - for example to c:\dev\myproject\bin\debug\mydb.mbd; your program executes in the context of c:\dev\myproject\bin\debug\, and so it is here that you need to look to see if the edit actually happened. To check for sure: query for the data inside the application (after inserting it).

Sending and Parsing JSON Objects in Android

I am surprised these have not been mentioned: but instead of using bare-bones rather manual process with json.org's little package, GSon and Jackson are much more convenient to use. So:

So you can actually bind to your own POJOs, not some half-assed tree nodes or Lists and Maps. (and at least Jackson allows binding to such things too (perhaps GSON as well, not sure), JsonNode, Map, List, if you really want these instead of 'real' objects)

EDIT 19-MAR-2014:

Another new contender is Jackson jr library: it uses same fast Streaming parser/generator as Jackson (jackson-core), but data-binding part is tiny (50kB). Functionality is more limited (no annotations, just regular Java Beans), but performance-wise should be fast, and initialization (first-call) overhead very low as well. So it just might be good choice, especially for smaller apps.

How to start a background process in Python?

I found this here:

On windows (win xp), the parent process will not finish until the longtask.py has finished its work. It is not what you want in CGI-script. The problem is not specific to Python, in PHP community the problems are the same.

The solution is to pass DETACHED_PROCESS Process Creation Flag to the underlying CreateProcess function in win API. If you happen to have installed pywin32 you can import the flag from the win32process module, otherwise you should define it yourself:

DETACHED_PROCESS = 0x00000008

pid = subprocess.Popen([sys.executable, "longtask.py"],
                       creationflags=DETACHED_PROCESS).pid

PostgreSQL - query from bash script as database user 'postgres'

In my case the best solution including the requirement for authentication is:

username="admin"
new_password="helloworld"

PGPASSWORD=DB_PASSWORD \
  psql -h HOSTNAME -U DB_USERNAME -d DATABASE_NAME -c \
  "UPDATE user SET password = '$new_password' WHERE username = '$username'"

This command will update a password of a user e.g. for recovery case.

Info: The trade-off here is that you need to keep in mind that the password will be visible in the bash history. For more information see here.

Update: I'm running the databse in a docker container and there I just need the commmand: docker exec -i container_name psql -U postgres -d postgres -c "$SQL_COMMAND"

WCF named pipe minimal example

Try this.

Here is the service part.

[ServiceContract]
public interface IService
{
    [OperationContract]
    void  HelloWorld();
}

public class Service : IService
{
    public void HelloWorld()
    {
        //Hello World
    }
}

Here is the Proxy

public class ServiceProxy : ClientBase<IService>
{
    public ServiceProxy()
        : base(new ServiceEndpoint(ContractDescription.GetContract(typeof(IService)),
            new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/MyAppNameThatNobodyElseWillUse/helloservice")))
    {

    }
    public void InvokeHelloWorld()
    {
        Channel.HelloWorld();
    }
}

And here is the service hosting part.

var serviceHost = new ServiceHost
        (typeof(Service), new Uri[] { new Uri("net.pipe://localhost/MyAppNameThatNobodyElseWillUse") });
    serviceHost.AddServiceEndpoint(typeof(IService), new NetNamedPipeBinding(), "helloservice");
    serviceHost.Open();

    Console.WriteLine("Service started. Available in following endpoints");
    foreach (var serviceEndpoint in serviceHost.Description.Endpoints)
    {
        Console.WriteLine(serviceEndpoint.ListenUri.AbsoluteUri);
    }

How to get Top 5 records in SqLite?

TOP and square brackets are specific to Transact-SQL. In ANSI SQL one uses LIMIT and backticks (`).

select * from `Table_Name` LIMIT 5;

DataAdapter.Fill(Dataset)

leDbConnection connection = 
new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Inventar.accdb");
DataSet1 DS = new DataSet1();
connection.Open();

OleDbDataAdapter DBAdapter = new OleDbDataAdapter(
@"SELECT tbl_Computer.*,  tbl_Besitzer.*
  FROM tbl_Computer 
  INNER JOIN tbl_Besitzer ON tbl_Computer.FK_Benutzer = tbl_Besitzer.ID 
  WHERE (((tbl_Besitzer.Vorname)='ma'));", 
connection);

JSON.Parse,'Uncaught SyntaxError: Unexpected token o

Maybe what comes from the server is already evaluated as JSON object? For example, using jQuery get method:

$.get('/service', function(data) {  
  var obj = data;

      /* 
         "obj" is evaluated at this point if server responded 
         with "application/json" or similar.
       */
      for (var i = 0; i < obj.length; i++) {
        console.log(obj[i].Name);
      }
    });

Alternatively, if you need to turn JSON object into JSON string literal, you can use JSON.stringify:

var json = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];
var jsonString = JSON.stringify(json);

But in this case I don't understand why you can't just take the json variable and refer to it instead of stringifying and parsing.

Using custom fonts using CSS?

First of all, you can't prevent people from downloading fonts except if it is yours and that usually takes months. And it makes no sense to prevent people from using fonts. A lot of fonts that you see on websites can be found on free platforms like the one I mentioned below.

But if you want to implement a font into your website read this: There is a pretty simple and free way to implement fonts into your website. I would recommend Google fonts because it is free and easy to use. For example, I'll use the Bangers font from Google.(https://fonts.google.com/specimen/Bangers?query=bangers&sidebar.open&selection.family=Bangers) This is how it would look like: HTML

<head>
<link href="https://fonts.googleapis.com/css2?family=Bangers&display=swap" rel="stylesheet">
</head>

CSS

body {
font-family: 'Bangers', cursive;
}

How can I listen for keypress event on the whole page?

Be aware "document:keypress" is deprecated. We should use document:keydown instead.

Link: https://developer.mozilla.org/fr/docs/Web/API/Document/keypress_event

How to find a value in an array and remove it by using PHP array functions?

This is how I would do it:

$terms = array('BMW', 'Audi', 'Porsche', 'Honda');
// -- purge 'make' Porsche from terms --
if (!empty($terms)) {
    $pos = '';
    $pos = array_search('Porsche', $terms);
    if ($pos !== false) unset($terms[$pos]);
}

Enter key press behaves like a Tab in Javascript

Map [Enter] key to work like the [Tab] key

I've rewritten Andre Van Zuydam's answer, which didn't work for me, in jQuery. This caputures both Enter and Shift+Enter. Enter tabs forward, and Shift+Enter tabs back.

I've also rewritten the way self is initialized by the current item in focus. The form is also selected that way. Here's the code:

// Map [Enter] key to work like the [Tab] key
// Daniel P. Clark 2014

// Catch the keydown for the entire document
$(document).keydown(function(e) {

  // Set self as the current item in focus
  var self = $(':focus'),
      // Set the form by the current item in focus
      form = self.parents('form:eq(0)'),
      focusable;

  // Array of Indexable/Tab-able items
  focusable = form.find('input,a,select,button,textarea,div[contenteditable=true]').filter(':visible');

  function enterKey(){
    if (e.which === 13 && !self.is('textarea,div[contenteditable=true]')) { // [Enter] key

      // If not a regular hyperlink/button/textarea
      if ($.inArray(self, focusable) && (!self.is('a,button'))){
        // Then prevent the default [Enter] key behaviour from submitting the form
        e.preventDefault();
      } // Otherwise follow the link/button as by design, or put new line in textarea

      // Focus on the next item (either previous or next depending on shift)
      focusable.eq(focusable.index(self) + (e.shiftKey ? -1 : 1)).focus();

      return false;
    }
  }
  // We need to capture the [Shift] key and check the [Enter] key either way.
  if (e.shiftKey) { enterKey() } else { enterKey() }
});

The reason textarea

is included is because we "do" want to tab into it. Also, once in, we don't want to stop the default behavior of Enter from putting in a new line.

The reason a and button

allow the default action, "and" still focus on the next item, is because they don't always load another page. There can be a trigger/effect on those such as an accordion or tabbed content. So once you trigger the default behavior, and the page does its special effect, you still want to go to the next item since your trigger may have well introduced it.

When should I use curly braces for ES6 import?

If you think of import as just syntax sugar for Node.js modules, objects, and destructuring, I find it's pretty intuitive.

// bar.js
module = {};

module.exports = {
  functionA: () => {},
  functionB: ()=> {}
};

 // Really all that is is this:
 var module = {
   exports: {
      functionA, functionB
   }
  };

// Then, over in foo.js

// The whole exported object:
var fump = require('./bar.js'); //= { functionA, functionB }
// Or
import fump from './bar' // The same thing - object functionA and functionB properties


// Just one property of the object
var fump = require('./bar.js').functionA;

// Same as this, right?
var fump = { functionA, functionB }.functionA;

// And if we use ES6 destructuring:
var { functionA } =  { functionA, functionB };
// We get same result

// So, in import syntax:
import { functionA } from './bar';

SQL Server r2 installation error .. update Visual Studio 2008 to SP1

Finally, I solved it. Even though the solution is a bit lengthy, I think its the simplest. The solution is as follows:

  1. Install Visual Studio 2008
  2. Install the service Package 1 (SP1)
  3. Install SQL Server 2008 r2

Postgres ERROR: could not open file for reading: Permission denied

This answer is only for Linux Beginners.

Assuming initially the DB user didn't have file/folder(directory) permission on the client side.

Let's constrain ourselves to the following:

User: postgres

Purpose: You wanted to (write to / read from) a specific folder

Tool: psql

Connected to a specific database: YES

FILE_PATH: /home/user/training/sql/csv_example.csv

Query: \copy (SELECT * FROM table_name TO FILE_PATH, DELIMITER ',' CSV HEADER;

Actual Results: After running the query you got an error : Permission Denied

Expected Results: COPY COUNT_OF_ROWS_COPIED

Here are the steps I'd follow to try and resolve it.

  1. Confirm the FILE_PATH permissions on your File system.

Inside a terminal to view the permissions for a file/folder you need to long list them by entering the command ls -l.

The output has a section that shows sth like this -> drwxrwxr-x Which is interpreted in the following way:

TYPE | OWNER RIGHTS | GROUP RIGHTS | USER RIGHTS

rwx (r: Read, W: Write, X: Execute)

TYPE (1 Char) = d: directory, -: file

OWNER RIGHTS (3 Chars after TYPE)

GROUP RIGHTS (3 Chars after OWNER)

USER RIGHTS (3 Chars after GROUP)

  1. If permissions are not enough (Ensure that a user can at least enter all folders in the path you wanted path) - x.

This means for FILE_PATH, All the directories (home , user, training, sql) should have at least an x in the USER RIGHTS.

  1. Change permissions for all parent folders that you need to enter to have a x. You can use chmod rights_you_want parent_folder

Assuming /training/ didn't have an execute permission.

I'd go the user folder and enter chmod a+x training

  1. Change the destination folder/directory to have a w if you want to write to it. or at least a r if you want to read from it

Assuming /sql didn't have a write permission.

I would now chmod a+w sql

  1. Restart the postgresql server sudo systemctl restart postgresql
  2. Try again.

This would most probably help you now get a successful expected result.

What is the purpose of XSD files?

Before understanding the XSD(XML Schema Definition) let me explain;

What is schema?

for example; emailID: peter#gmail

You can identify the above emailID is not valid because there is no @, .com or .net or .org.

We know the email schema it looks like [email protected].

Conclusion: Schema does not validate the data, It does the validation of structure.

XSD is actually one of the implementation of XML Schema. others we have

We use XSD to validate XML data.

Uncaught (in promise) TypeError: Failed to fetch and Cors error

See mozilla.org's write-up on how CORS works.

You'll need your server to send back the proper response headers, something like:

Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, PUT, GET, OPTIONS
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization

Bear in mind you can use "*" for Access-Control-Allow-Origin that will only work if you're trying to pass Authentication data. In that case, you need to explicitly list the origin domains you want to allow. To allow multiple domains, see this post

MongoDB query with an 'or' condition

db.Lead.find(

{"name": {'$regex' : '.*' + "Ravi" + '.*'}},
{
"$or": [{
    'added_by':"[email protected]"
}, {
    'added_by':"[email protected]"
}]
}

);

How to pass an array into a SQL Server stored procedure

CREATE TYPE dumyTable
AS TABLE
(
  RateCodeId int,
  RateLowerRange int,
  RateHigherRange int,
  RateRangeValue int
);
GO
CREATE PROCEDURE spInsertRateRanges
  @dt AS dumyTable READONLY
AS
BEGIN
  SET NOCOUNT ON;

  INSERT  tblRateCodeRange(RateCodeId,RateLowerRange,RateHigherRange,RateRangeValue) 
  SELECT * 
  FROM @dt 
END

setBackground vs setBackgroundDrawable (Android)

It's deprecated but it still works so you could just use it. But if you want to be completly correct, just for the completeness of it... You'd do something like following:

int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
    setBackgroundDrawable();
} else {
    setBackground();
}

For this to work you need to set buildTarget api 16 and min build to 7 or something similar.

Get type of all variables

Designed to do essentially the inverse of what you wanted, here's one of my toolkit toys:

 lstype<-function(type='closure'){
inlist<-ls(.GlobalEnv)
if (type=='function') type <-'closure'
typelist<-sapply(sapply(inlist,get),typeof)
return(names(typelist[typelist==type]))
}

Android Studio: Gradle - build fails -- Execution failed for task ':dexDebug'

If you are also using Dagger or Butterknife you should to add guava as a dependency to your build.gradle main file like classpath :

com.google.guava:guava:20.0

In other hand, if you are having problems with larger heap for the Gradle daemon you can increase adding to your radle file:

 dexOptions {
        javaMaxHeapSize "4g"
    } 

Try-catch block in Jenkins pipeline script

This answer worked for me:

pipeline {
  agent any
  stages {
    stage("Run unit tests"){
      steps {
        script {
          try {
            sh  '''
              # Run unit tests without capturing stdout or logs, generates cobetura reports
              cd ./python
              nosetests3 --with-xcoverage --nocapture --with-xunit --nologcapture --cover-package=application
              cd ..
              '''
          } finally {
            junit 'nosetests.xml'
          }
        }
      }
    }
    stage ('Speak') {
      steps{
        echo "Hello, CONDITIONAL"
      }
    }
  }
}

DB2 Date format

One more solution REPLACE (CHAR(current date, ISO),'-','')

How to load external scripts dynamically in Angular?

If you're using system.js, you can use System.import() at runtime:

export class MyAppComponent {
  constructor(){
    System.import('path/to/your/module').then(refToLoadedModule => {
      refToLoadedModule.someFunction();
    }
  );
}

If you're using webpack, you can take full advantage of its robust code splitting support with require.ensure :

export class MyAppComponent {
  constructor() {
     require.ensure(['path/to/your/module'], require => {
        let yourModule = require('path/to/your/module');
        yourModule.someFunction();
     }); 
  }
}

How do you explicitly set a new property on `window` in TypeScript?

Most of the other answers are not perfect.

  • Some of them just suppress the type inference for show.
  • Some of the others only care about global variables as namespaces, but not as interfaces/classes

I also encounter the similar problem this morning. I tried so many "solutions" on StackOverflow, but none of them produced absolutely no type errors and enabled triggering type jumping in IDE(webstorm or vscode).

Finally, from here

https://github.com/Microsoft/TypeScript/issues/3180#issuecomment-102523512

I found a reasonable solution to attach typings for a global variable that acts as interface/class and namespace both.

Example is below:

// typings.d.ts
declare interface Window {
    myNamespace?: MyNamespace & typeof MyNamespace
}

declare interface MyNamespace {
    somemethod?()
}

declare namespace MyNamespace {
    // ...
}

The code above merges the typings of namespace MyNamespace and interface MyNamespace into the global variable myNamespace(the property of window).

Add CSS box shadow around the whole DIV

Just use the below code. It will shadow surround the entire DIV

-webkit-box-shadow: -1px 1px 5px 9px rgba(0,0,0,0.75);
-moz-box-shadow: -1px 1px 5px 9px rgba(0,0,0,0.75);
box-shadow: -1px 1px 5px 9px rgba(0,0,0,0.75);

Hope this will work

Alternative to a goto statement in Java

Use a labeled break as an alternative to goto.

How to find out the number of CPUs using python

If you are using torch you can do:

import torch.multiprocessing as mp

mp.cpu_count()

Replace multiple strings with multiple other strings

This may not meet your exact need in this instance, but I've found this a useful way to replace multiple parameters in strings, as a general solution. It will replace all instances of the parameters, no matter how many times they are referenced:

String.prototype.fmt = function (hash) {
        var string = this, key; for (key in hash) string = string.replace(new RegExp('\\{' + key + '\\}', 'gm'), hash[key]); return string
}

You would invoke it as follows:

var person = '{title} {first} {last}'.fmt({ title: 'Agent', first: 'Jack', last: 'Bauer' });
// person = 'Agent Jack Bauer'

How can I convert a .py to .exe for Python?

Now you can convert it by using PyInstaller. It works with even Python 3.

Steps:

  1. Fire up your PC
  2. Open command prompt
  3. Enter command pip install pyinstaller
  4. When it is installed, use the command 'cd' to go to the working directory.
  5. Run command pyinstaller <filename>

Decrementing for loops

range step should be -1

   for k in range(10,0,-1):
      print k

How to overwrite files with Copy-Item in PowerShell

How about calling the .NET Framework methods?

You can do ANYTHING with them... :

[System.IO.File]::Copy($src, $dest, $true);

The $true argument makes it overwrite.

JavaScript for detecting browser language preference

Javascript way:

var language = window.navigator.userLanguage || window.navigator.language;//returns value like 'en-us'

If you are using jQuery.i18n plugin, you can use:

jQuery.i18n.browserLang();//returns value like '"en-US"'

How to show imageView full screen on imageView click?

It's easy to achieve this is to just use an Intent like this: (I put the method in a custom class that takes in an Activity as a parameter so it can be called from any Fragment or Activity)

    public class UIutils {

private Activity mActivity;

    public UIutils(Activity activity){
        mActivity = activity;
    }

public void showPhoto(Uri photoUri){
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(photoUri, "image/*");
        mActivity.startActivity(intent);
    }
}

Then to use it just do this:

imageView.setOnClickListener(v1 -> new UIutils(getActivity()).showPhoto(Uri.parse(imageURI)));

I use this with an Image URL but it can be used with stored files as well. If you are accessing images form the phones memory you should use a content provider.

Find an element in a list of tuples

Using filter function:

>>> def get_values(iterables, key_to_find):
return list(filter(lambda x:key_to_find in x, iterables)) >>> a = [(1,2),(1,4),(3,5),(5,7)] >>> get_values(a, 1) >>> [(1, 2), (1, 4)]

Open application after clicking on Notification

Here's example using NotificationCompact.Builder class which is the recent version to build notification.

private void startNotification() {
    Log.i("NextActivity", "startNotification");

 // Sets an ID for the notification
      int mNotificationId = 001;

    // Build Notification , setOngoing keeps the notification always in status bar
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ldb)
                    .setContentTitle("Stop LDB")
                    .setContentText("Click to stop LDB")
                    .setOngoing(true);

    // Create pending intent, mention the Activity which needs to be 
    //triggered when user clicks on notification(StopScript.class in this case)

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, StopScript.class), PendingIntent.FLAG_UPDATE_CURRENT);


    mBuilder.setContentIntent(contentIntent);


    // Gets an instance of the NotificationManager service
   NotificationManager mNotificationManager =
            (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);


    // Builds the notification and issues it.
    mNotificationManager.notify(mNotificationId, mBuilder.build());


}

select records from postgres where timestamp is in certain range

SELECT * 
FROM reservations 
WHERE arrival >= '2012-01-01'
AND arrival < '2013-01-01'
   ;

BTW if the distribution of values indicates that an index scan will not be the worth (for example if all the values are in 2012), the optimiser could still choose a full table scan. YMMV. Explain is your friend.

Mapping many-to-many association table with extra column(s)

Since the SERVICE_USER table is not a pure join table, but has additional functional fields (blocked), you must map it as an entity, and decompose the many to many association between User and Service into two OneToMany associations : One User has many UserServices, and one Service has many UserServices.

You haven't shown us the most important part : the mapping and initialization of the relationships between your entities (i.e. the part you have problems with). So I'll show you how it should look like.

If you make the relationships bidirectional, you should thus have

class User {
    @OneToMany(mappedBy = "user")
    private Set<UserService> userServices = new HashSet<UserService>();
}

class UserService {
    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne
    @JoinColumn(name = "service_code")
    private Service service;

    @Column(name = "blocked")
    private boolean blocked;
}

class Service {
    @OneToMany(mappedBy = "service")
    private Set<UserService> userServices = new HashSet<UserService>();
}

If you don't put any cascade on your relationships, then you must persist/save all the entities. Although only the owning side of the relationship (here, the UserService side) must be initialized, it's also a good practice to make sure both sides are in coherence.

User user = new User();
Service service = new Service();
UserService userService = new UserService();

user.addUserService(userService);
userService.setUser(user);

service.addUserService(userService);
userService.setService(service);

session.save(user);
session.save(service);
session.save(userService);

Android: How can I get the current foreground activity (from a service)?

Is there a native android way to get a reference to the currently running Activity from a service?

You may not own the "currently running Activity".

I have a service running on the background, and I would like to update my current Activity when an event occurs (in the service). Is there a easy way to do that (like the one I suggested above)?

  1. Send a broadcast Intent to the activity -- here is a sample project demonstrating this pattern
  2. Have the activity supply a PendingIntent (e.g., via createPendingResult()) that the service invokes
  3. Have the activity register a callback or listener object with the service via bindService(), and have the service call an event method on that callback/listener object
  4. Send an ordered broadcast Intent to the activity, with a low-priority BroadcastReceiver as backup (to raise a Notification if the activity is not on-screen) -- here is a blog post with more on this pattern

Checking if a variable is an integer in PHP

Values $_GET are always strings – that's what GET paramters come as. Therefore, is_int($_GET[...]) is always false.

You can test if a string consists only of digits(i.e. could be interpreted as a number) with is_numeric.

How to take keyboard input in JavaScript?

You can do this by registering an event handler on the document or any element you want to observe keystrokes on and examine the key related properties of the event object.

Example that works in FF and Webkit-based browsers:

document.addEventListener('keydown', function(event) {
    if(event.keyCode == 37) {
        alert('Left was pressed');
    }
    else if(event.keyCode == 39) {
        alert('Right was pressed');
    }
});

DEMO

Limit results in jQuery UI Autocomplete

You can set the minlength option to some big value or you can do it by css like this,

.ui-autocomplete { height: 200px; overflow-y: scroll; overflow-x: hidden;}

Git: How to return from 'detached HEAD' state

I had this edge case, where I checked out a previous version of the code in which my file directory structure was different:

git checkout 1.87.1                                    
warning: unable to unlink web/sites/default/default.settings.php: Permission denied
... other warnings ...
Note: checking out '1.87.1'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. 
Example:

  git checkout -b <new-branch-name>

HEAD is now at 50a7153d7... Merge branch 'hotfix/1.87.1'

In a case like this you may need to use --force (when you know that going back to the original branch and discarding changes is a safe thing to do).

git checkout master did not work:

$ git checkout master
error: The following untracked working tree files would be overwritten by checkout:
web/sites/default/default.settings.php
... other files ...

git checkout master --force (or git checkout master -f) worked:

git checkout master -f
Previous HEAD position was 50a7153d7... Merge branch 'hotfix/1.87.1'
Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.

JBoss vs Tomcat again

Strictly speaking; With no Java EE features your app hardly need an appserver at all ;-)

Like others have pointed out JBoss has a (more or less) full Java EE stack while Tomcat is a webcontainer only. JBoss can be configured to only serve as a webcontainer as well, it'd then just be a thin wrapper around the included tomcat webcontainer. That way you could have an almost as lightweight JBoss, which would actually just be a thin "wrapper" around Tomcat. That would be almost as lightweigth.

If you won't need any of the extras JBoss has to offer, go for the one you're most comfortable with. Which is easiest to configure and maintain for you?

Getting indices of True values in a boolean list

If you have numpy available:

>>> import numpy as np
>>> states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
>>> np.where(states)[0]
array([4, 5, 7])

How get an apostrophe in a string in javascript

This is plain Javascript and has nothing to do with the jQuery library.

You simply escape the apostrophe with a backslash:

theAnchorText = 'I\'m home';

Another alternative is to use quotation marks around the string, then you don't have to escape apostrophes:

theAnchorText = "I'm home";

If input field is empty, disable submit button

Try this code

$(document).ready(function(){
    $('.sendButton').attr('disabled',true);

    $('#message').keyup(function(){
        if($(this).val().length !=0){
            $('.sendButton').attr('disabled', false);
        }
        else
        {
            $('.sendButton').attr('disabled', true);        
        }
    })
});

Check demo Fiddle

You are missing the else part of the if statement (to disable the button again if textbox is empty) and parentheses () after val function in if($(this).val.length !=0){

How to set 24-hours format for date on java?

tl;dr

The modern approach uses java.time classes.

Instant.now()                                        // Capture current moment in UTC.
       .truncatedTo( ChronoUnit.SECONDS )            // Lop off any fractional second.
       .plus( 8 , ChronoUnit.HOURS )                 // Add eight hours.
       .atZone( ZoneId.of( "America/Montreal" ) )    // Adjust from UTC to the wall-clock time used by the people of a certain region (a time zone). Returns a `ZonedDateTime` object.
       .format(                                      // Generate a `String` object representing textually the value of the `ZonedDateTime` object.
           DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" )
                            .withLocale( Locale.US ) // Specify a `Locale` to determine the human language and cultural norms used in localizing the text being generated. 
       )                                             // Returns a `String` object.

23/01/2017 15:34:56

java.time

FYI, the old Calendar and Date classes are now legacy. Supplanted by the java.time classes. Much of java.time is back-ported to Java 6, Java 7, and Android (see below).

Instant

Capture the current moment in UTC with the Instant class.

Instant instantNow = Instant.now();

instant.toString(): 2017-01-23T12:34:56.789Z

If you want only whole seconds, without any fraction of a second, truncate.

Instant instant = instantNow.truncatedTo( ChronoUnit.SECONDS );

instant.toString(): 2017-01-23T12:34:56Z

Math

The Instant class can do math, adding an amount of time. Specify the amount of time to add by the ChronoUnit enum, an implementation of TemporalUnit.

instant = instant.plus( 8 , ChronoUnit.HOURS );

instant.toString(): 2017-01-23T20:34:56Z

ZonedDateTime

To see that same moment through the lens of a particular region’s wall-clock time, apply a ZoneId to get a ZonedDateTime.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

zdt.toString(): 2017-01-23T15:34:56-05:00[America/Montreal]

Generate string

You can generate a String in your desired format by specifying a formatting pattern in a DateTimeFormatter object.

Note that case matters in the letters of your formatting pattern. The Question’s code had hh which is for 12-hour time while uppercase HH is 24-hour time (0-23) in both java.time.DateTimeFormatter as well as the legacy java.text.SimpleDateFormat.

The formatting codes in java.time are similar to those in the legacy SimpleDateFormat but not exactly the same. Carefully study the class doc. Here, HH happens to work identically.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" ).withLocale( Locale.US );
String output = zdt.format( f );

Automatic localization

Rather than hard-coding a formatting pattern, consider letting java.time fully localize the generation of the String text by calling DateTimeFormatter.ofLocalizedDateTime.

And, by the way, be aware that time zone and Locale have nothing to do with one another; orthogonal issues. One is about content, the meaning (the wall-clock time). The other is about presentation, determining the human language and cultural norms used in presenting that meaning to the user.

Instant instant = Instant.parse( "2017-01-23T12:34:56Z" );
ZoneId z = ZoneId.of( "Pacific/Auckland" );  // Notice that time zone is unrelated to the `Locale` used in localizing.
ZonedDateTime zdt = instant.atZone( z );

DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
                                       .withLocale( Locale.CANADA_FRENCH );  // The locale determines human language and cultural norms used in generating the text representing this date-time object.
String output = zdt.format( f );

instant.toString(): 2017-01-23T12:34:56Z

zdt.toString(): 2017-01-24T01:34:56+13:00[Pacific/Auckland]

output: mardi 24 janvier 2017 à 01:34:56 heure avancée de la Nouvelle-Zélande


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?


Joda-Time

Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.

Joda-Time makes this kind of work much easier.

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

DateTime later = DateTime.now().plusHours( 8 );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd/MM/yyyy HH:mm:ss" );
String laterAsText = formatter.print( later );

System.out.println( "laterAsText: " + laterAsText );

When run…

laterAsText: 19/12/2013 02:50:18

Beware that this syntax uses default time zone. A better practice is to use an explicit DateTimeZone instance.

How to use onSaveInstanceState() and onRestoreInstanceState()?

  • onSaveInstanceState() is a method used to store data before pausing the activity.

Description : Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.

  • onRestoreInstanceState() is method used to retrieve that data back.

Description : This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).

Consider this example here:
You app has 3 edit boxes where user was putting in some info , but he gets a call so if you didn't use the above methods what all he entered will be lost.
So always save the current data in onPause() method of Activity as a bundle & in onResume() method call the onRestoreInstanceState() method .

Please see :

How to use onSavedInstanceState example please

http://www.how-to-develop-android-apps.com/tag/onrestoreinstancestate/

SQL: Select columns with NULL values only

SELECT  t.column_name
FROM    user_tab_columns t
WHERE   t.nullable = 'Y' AND t.table_name = 'table name here' AND t.num_distinct = 0;

How can I rename a conda environment?

I'm using Conda on Windows and this answer did not work for me. But I can suggest another solution:

  • rename enviroment folder (old_name to new_name)

  • open shell and activate env with custom folder:

    conda.bat activate "C:\Users\USER_NAME\Miniconda3\envs\new_name"

  • now you can use this enviroment, but it's not on the enviroment list. Update\install\remove any package to fix it. For example, update numpy:

    conda update numpy

  • after applying any action to package, the environment will show in env list. To check this, type:

    conda env list

Github "Updates were rejected because the remote contains work that you do not have locally."

The issue is because the local is not up-to-date with the master branch that is why we are supposed to pull the code before pushing it to the git

git add .
git commit -m 'Comments to be added'
git pull origin master
git push origin master

Does Java have a path joining method?

This concerns Java versions 7 and earlier.

To quote a good answer to the same question:

If you want it back as a string later, you can call getPath(). Indeed, if you really wanted to mimic Path.Combine, you could just write something like:

public static String combine (String path1, String path2) {
    File file1 = new File(path1);
    File file2 = new File(file1, path2);
    return file2.getPath();
}

Sql Server : How to use an aggregate function like MAX in a WHERE clause

yes you need to use a having clause after the Group by clause , as the where is just to filter the data on simple parameters , but group by followed by a Having statement is the idea to group the data and filter it on basis of some aggregate function......

Is there a difference between x++ and ++x in java?

++x is called preincrement while x++ is called postincrement.

int x = 5, y = 5;

System.out.println(++x); // outputs 6
System.out.println(x); // outputs 6

System.out.println(y++); // outputs 5
System.out.println(y); // outputs 6

Copy mysql database from remote server to local computer

Often our databases are really big and the take time to take dump directly from remote machine to other machine as our friends other have suggested above.

In such cases what you can do is to take the dump on remote machine using MYSQLDUMP Command

MYSQLDUMP -uuser -p --all-databases > file_name.sql

and than transfer that file from remote server to your machine using Linux SCP Command

scp user@remote_ip:~/mysql_dump_file_name.sql ./

Difference between two dates in years, months, days in JavaScript

The following is an algorithm which gives correct but not totally precise since it does not take into account leap year. It also assumes 30 days in a month. A good usage for example is if someone lives in an address from 12/11/2010 to 11/10/2011, it can quickly tells that the person lives there for 10 months and 29 days. From 12/11/2010 to 11/12/2011 is 11 months and 1 day. For certain types of applications, that kind of precision is sufficient. This is for those types of applications because it aims for simplicity:

var datediff = function(start, end) {
  var diff = { years: 0, months: 0, days: 0 };
  var timeDiff = end - start;

  if (timeDiff > 0) {
    diff.years = end.getFullYear() - start.getFullYear();
    diff.months = end.getMonth() - start.getMonth();
    diff.days = end.getDate() - start.getDate();

    if (diff.months < 0) {
      diff.years--;
      diff.months += 12;
    }

    if (diff.days < 0) {
      diff.months = Math.max(0, diff.months - 1);
      diff.days += 30;
    }
  }

  return diff;
};

Unit tests

Javascript to set hidden form value on drop down change

If you have HTML like this, for example:

<select id='myselect'>
    <option value='1'>A</option>
    <option value='2'>B</option>
    <option value='3'>C</option>
    <option value='4'>D</option>
</select>
<input type='hidden' id='myhidden' value=''>

All you have to do is bind a function to the change event of the select, and do what you need there:

<script type='text/javascript'>
$(function() {
    $('#myselect').change(function() {
        // if changed to, for example, the last option, then
        // $(this).find('option:selected').text() == D
        // $(this).val() == 4
        // get whatever value you want into a variable
        var x = $(this).val();
        // and update the hidden input's value
        $('#myhidden').val(x);
    });
});
</script>

All things considered, if you're going to be doing a lot of jQuery programming, always have the documentation open. It is very easy to find what you need there if you give it a chance.

Change background color of edittext in android

I worked out a working solution to this problem after 2 days of struggle, below solution is perfect for them who want to change few edit text only, change/toggle color through java code, and want to overcome the problems of different behavior on OS versions due to use setColorFilter() method.

    import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatDrawableManager;
import android.support.v7.widget.AppCompatEditText;
import android.util.AttributeSet;
import com.newco.cooltv.R;

public class RqubeErrorEditText extends AppCompatEditText {

  private int errorUnderlineColor;
  private boolean isErrorStateEnabled;
  private boolean mHasReconstructedEditTextBackground;

  public RqubeErrorEditText(Context context) {
    super(context);
    initColors();
  }

  public RqubeErrorEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    initColors();
  }

  public RqubeErrorEditText(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initColors();
  }

  private void initColors() {
    errorUnderlineColor = R.color.et_error_color_rule;

  }

  public void setErrorColor() {
    ensureBackgroundDrawableStateWorkaround();
    getBackground().setColorFilter(AppCompatDrawableManager.getPorterDuffColorFilter(
        ContextCompat.getColor(getContext(), errorUnderlineColor), PorterDuff.Mode.SRC_IN));
  }

  private void ensureBackgroundDrawableStateWorkaround() {
    final Drawable bg = getBackground();
    if (bg == null) {
      return;
    }
    if (!mHasReconstructedEditTextBackground) {
      // This is gross. There is an issue in the platform which affects container Drawables
      // where the first drawable retrieved from resources will propogate any changes
      // (like color filter) to all instances from the cache. We'll try to workaround it...
      final Drawable newBg = bg.getConstantState().newDrawable();
      //if (bg instanceof DrawableContainer) {
      //  // If we have a Drawable container, we can try and set it's constant state via
      //  // reflection from the new Drawable
      //  mHasReconstructedEditTextBackground =
      //      DrawableUtils.setContainerConstantState(
      //          (DrawableContainer) bg, newBg.getConstantState());
      //}
      if (!mHasReconstructedEditTextBackground) {
        // If we reach here then we just need to set a brand new instance of the Drawable
        // as the background. This has the unfortunate side-effect of wiping out any
        // user set padding, but I'd hope that use of custom padding on an EditText
        // is limited.
        setBackgroundDrawable(newBg);
        mHasReconstructedEditTextBackground = true;
      }
    }
  }

  public boolean isErrorStateEnabled() {
    return isErrorStateEnabled;
  }

  public void setErrorState(boolean isErrorStateEnabled) {
    this.isErrorStateEnabled = isErrorStateEnabled;
    if (isErrorStateEnabled) {
      setErrorColor();
      invalidate();
    } else {
      getBackground().mutate().clearColorFilter();
      invalidate();
    }
  }
}

Uses in xml

<com.rqube.ui.widget.RqubeErrorEditText
            android:id="@+id/f_signup_et_referral_code"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_toEndOf="@+id/referral_iv"
            android:layout_toRightOf="@+id/referral_iv"
            android:ems="10"
            android:hint="@string/lbl_referral_code"
            android:imeOptions="actionNext"
            android:inputType="textEmailAddress"
            android:textSize="@dimen/text_size_sp_16"
            android:theme="@style/EditTextStyle"/>

Add lines in style

<style name="EditTextStyle" parent="android:Widget.EditText">
    <item name="android:textColor">@color/txt_color_change</item>
    <item name="android:textColorHint">@color/et_default_color_text</item>
    <item name="colorControlNormal">@color/et_default_color_rule</item>
    <item name="colorControlActivated">@color/et_engagged_color_rule</item>
  </style>

java code to toggle color

myRqubeEditText.setErrorState(true);
myRqubeEditText.setErrorState(false);

Storing images in SQL Server?

In my experience, storing to the url to the images stored in another location is the best way for a simple project.

NGINX: upstream timed out (110: Connection timed out) while reading response header from upstream

In your case it helps a little optimization in proxy, or you can use "# time out settings"

location / 
{        

  # time out settings
  proxy_connect_timeout 159s;
  proxy_send_timeout   600;
  proxy_read_timeout   600;
  proxy_buffer_size    64k;
  proxy_buffers     16 32k;
  proxy_busy_buffers_size 64k;
  proxy_temp_file_write_size 64k;
  proxy_pass_header Set-Cookie;
  proxy_redirect     off;
  proxy_hide_header  Vary;
  proxy_set_header   Accept-Encoding '';
  proxy_ignore_headers Cache-Control Expires;
  proxy_set_header   Referer $http_referer;
  proxy_set_header   Host   $host;
  proxy_set_header   Cookie $http_cookie;
  proxy_set_header   X-Real-IP  $remote_addr;
  proxy_set_header X-Forwarded-Host $host;
  proxy_set_header X-Forwarded-Server $host;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

error: pathspec 'test-branch' did not match any file(s) known to git

The modern Git should able to detect remote branches and create a local one on checkout.

However if you did a shallow clone (e.g. with --depth 1), try the following commands to correct it:

git config remote.origin.fetch '+refs/heads/*:refs/remotes/origin/*'
git fetch --all

and try to checkout out the branch again.

Alternatively try to unshallow your clone, e.g. git fetch --unshallow and try again.

See also: How to fetch all remote branches?

Add jars to a Spark Job - spark-submit

There is restriction on using --jars: if you want to specify a directory for location of jar/xml file, it doesn't allow directory expansions. This means if you need to specify absolute path for each jar.

If you specify --driver-class-path and you are executing in yarn cluster mode, then driver class doesn't get updated. We can verify if class path is updated or not under spark ui or spark history server under tab environment.

Option which worked for me to pass jars which contain directory expansions and which worked in yarn cluster mode was --conf option. It's better to pass driver and executor class paths as --conf, which adds them to spark session object itself and those paths are reflected on Spark Configuration. But Please make sure to put jars on the same path across the cluster.

spark-submit \
  --master yarn \
  --queue spark_queue \
  --deploy-mode cluster    \
  --num-executors 12 \
  --executor-memory 4g \
  --driver-memory 8g \
  --executor-cores 4 \
  --conf spark.ui.enabled=False \
  --conf spark.driver.extraClassPath=/usr/hdp/current/hbase-master/lib/hbase-server.jar:/usr/hdp/current/hbase-master/lib/hbase-common.jar:/usr/hdp/current/hbase-master/lib/hbase-client.jar:/usr/hdp/current/hbase-master/lib/zookeeper.jar:/usr/hdp/current/hbase-master/lib/hbase-protocol.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/scopt_2.11-3.3.0.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/spark-examples_2.10-1.1.0.jar:/etc/hbase/conf \
  --conf spark.hadoop.mapred.output.dir=/tmp \
  --conf spark.executor.extraClassPath=/usr/hdp/current/hbase-master/lib/hbase-server.jar:/usr/hdp/current/hbase-master/lib/hbase-common.jar:/usr/hdp/current/hbase-master/lib/hbase-client.jar:/usr/hdp/current/hbase-master/lib/zookeeper.jar:/usr/hdp/current/hbase-master/lib/hbase-protocol.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/scopt_2.11-3.3.0.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/spark-examples_2.10-1.1.0.jar:/etc/hbase/conf \
  --conf spark.hadoop.mapreduce.output.fileoutputformat.outputdir=/tmp

How can I find out a file's MIME type (Content-Type)?

file version < 5 : file -i -b /path/to/file
file version >=5 : file --mime-type -b /path/to/file

How do I set GIT_SSL_NO_VERIFY for specific repos only?

This works for me:

git init
git config --global http.sslVerify false
git clone https://myurl/myrepo.git

TypeError: 'str' object cannot be interpreted as an integer

You have to convert input x and y into int like below.

x=int(x)
y=int(y)

How to loop and render elements in React-native?

If u want a direct/ quick away, without assing to variables:

{
 urArray.map((prop, key) => {
     console.log(emp);
     return <Picker.Item label={emp.Name} value={emp.id} />;
 })
}

Javascript Date Validation ( DD/MM/YYYY) & Age Checking

If you want to use forward slashes in the format, the you need to escape with back slashes in the regex:

_x000D_
_x000D_
   _x000D_
var dateformat = /^(0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])[\/\-]\d{4}$/;
_x000D_
_x000D_
_x000D_

What is `git push origin master`? Help with git's refs, heads and remotes

Git has two types of branches: local and remote. To use git pull and git push as you'd like, you have to tell your local branch (my_test) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.

Commands

Make sure you're on your master branch with

1)git checkout master

then create the new branch with

2)git branch --track my_test origin/my_test

and check it out with

3)git checkout my_test.

You can then push and pull without specifying which local and remote.

However if you've already created the branch then you can use the -u switch to tell git's push and pull you'd like to use the specified local and remote branches from now on, like so:

git pull -u my_test origin/my_test
git push -u my_test origin/my_test

Config

The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config and add the following to the bottom.

[remote "origin"]
    url = [email protected]:username/repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
    remote = origin
    merge = refs/heads/my_test

This specifies a remote called origin, in this case a GitHub style one, and then tells the branch my_test to use it as it's remote.

You can find something very similar to this in the config after running the commands above.

Some useful resources:

How do I fix a "Performance counter registry hive consistency" when installing SQL Server R2 Express?

This works for me:

Click on Start and type in CMD
Right click and click on Run as administrator
Then from C:\windows\system32 type 
lodctr /R:PerfStringBackup.INI 

and press Enter
then restart the compurter and retry!

How can I remove space (margin) above HTML header?

Try:

h1 {
    margin-top: 0;
}

You're seeing the effects of margin collapsing.

How to rollback just one step using rake db:migrate

Best way is running Particular migration again by using down or up(in rails 4. It's change)

rails db:migrate:up VERSION=timestamp

Now how you get the timestamp. Go to this path

/db/migrate

Identify migration file you want to revert.pick the timestamp from that file name.

CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105)

In my case I have got the error when trying to create a databae on a new drive. To overcome the problem I created a new folder in that drive and set the user properties Security to full control on it(It may be sufficient to set Modify ). Conclusion: SET the Drive/Folder Properties Security for users to "Modify".

How to make a phone call programmatically?

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); 
   final Button button = (Button) findViewById(R.id.btn_call);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String mobileNo = "123456789";
            String uri = "tel:" + mobileNo.trim();
            Intent intent = new Intent(Intent.ACTION_CALL);
            intent.setData(Uri.parse(uri));
            startActivity(intent);
        }
    });*
 }

Command Line Tools not working - OS X El Capitan, Sierra, High Sierra, Mojave

I tried the solution xcode-select --install but it don't help me, I update from Sierra to High and happened this, my solution:

sudo xcode-select --reset

Count lines in large files

As per my test, I can verify that the Spark-Shell (based on Scala) is way faster than the other tools (GREP, SED, AWK, PERL, WC). Here is the result of the test that I ran on a file which had 23782409 lines

time grep -c $ my_file.txt;

real 0m44.96s user 0m41.59s sys 0m3.09s

time wc -l my_file.txt;

real 0m37.57s user 0m33.48s sys 0m3.97s

time sed -n '$=' my_file.txt;

real 0m38.22s user 0m28.05s sys 0m10.14s

time perl -ne 'END { $_=$.;if(!/^[0-9]+$/){$_=0;};print "$_" }' my_file.txt;

real 0m23.38s user 0m20.19s sys 0m3.11s

time awk 'END { print NR }' my_file.txt;

real 0m19.90s user 0m16.76s sys 0m3.12s

spark-shell
import org.joda.time._
val t_start = DateTime.now()
sc.textFile("file://my_file.txt").count()
val t_end = DateTime.now()
new Period(t_start, t_end).toStandardSeconds()

res1: org.joda.time.Seconds = PT15S

SQL statement to get column type

Use this query to get Schema, Table, Column,Type, max_length, is_nullable

SELECT QUOTENAME(SCHEMA_NAME(tb.[schema_id])) AS 'Schema'
    ,QUOTENAME(OBJECT_NAME(tb.[OBJECT_ID])) AS 'Table'
    ,C.NAME as 'Column'
    ,T.name AS 'Type'
    ,C.max_length
    ,C.is_nullable
FROM SYS.COLUMNS C INNER JOIN SYS.TABLES tb ON tb.[object_id] = C.[object_id]
    INNER JOIN SYS.TYPES T ON C.system_type_id = T.user_type_id
WHERE tb.[is_ms_shipped] = 0
ORDER BY tb.[Name]

CSS Classes & SubClasses

Just need to add a space:

.area2 .item
{
    ...
}

How to check if an array is empty?

Your test:

if (numberSet.length < 2) {
    return 0;
}

should be done before you allocate an array of that length in the below statement:

int[] differenceArray = new int[numberSet.length-1];

else you are already creating an array of size -1, when the numberSet.length = 0. That is quite odd. So, move your if statement as the first statement in your method.

Laravel: How to Get Current Route Name? (v5 ... v7)

Now in Laravel 5.3 I am seeing that can be made similarly you tried:

$route = Route::current();

$name = Route::currentRouteName();

$action = Route::currentRouteAction();

https://laravel.com/docs/5.3/routing#accessing-the-current-route