Programs & Examples On #Send

is a generic tag for communication between programmed elements using some protocol.

How to send value attribute from radio button in PHP

The radio buttons are sent on form submit when they are checked only...

use isset() if true then its checked otherwise its not

Send HTML in email via PHP

You can easily send the email with HTML content via PHP. Use the following script.

<?php
$to = '[email protected]';
$subject = "Send HTML Email Using PHP";

$htmlContent = '
<html>
<body>
    <h1>Send HTML Email Using PHP</h1>
    <p>This is a HTMl email using PHP by CodexWorld</p>
</body>
</html>';

// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// Additional headers
$headers .= 'From: CodexWorld<[email protected]>' . "\r\n";
$headers .= 'Cc: [email protected]' . "\r\n";
$headers .= 'Bcc: [email protected]' . "\r\n";

// Send email
if(mail($to,$subject,$htmlContent,$headers)):
    $successMsg = 'Email has sent successfully.';
else:
    $errorMsg = 'Email sending fail.';
endif;
?>

Source code and live demo can be found from here - Send Beautiful HTML Email using PHP

websocket.send() parameter

As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.

This is some pseudocodish JavaScript:

Client:

var websocket = new WebSocket("server address");

websocket.onmessage = function(str) {
  console.log("Someone sent: ", str);
};

// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
  id: "client1"
}));

// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
  to: "client2",
  data: "foo"
}));

Server:

var clients = {};

server.on("data", function(client, str) {
  var obj = JSON.parse(str);

  if("id" in obj) {
    // New client, add it to the id/client object
    clients[obj.id] = client;
  } else {
    // Send data to the client requested
    clients[obj.to].send(obj.data);
  }
});

How to send HTML email using linux command line

My version of mail does not have --append and it too smart for the echo -e \n-trick (it simply replaces \n with space). It does, however, have -a:

mail -a "Content-type: text/html" -s "Built notification" [email protected] < /var/www/report.html

Android sample bluetooth code to send a simple string via bluetooth

I made the following code so that even beginners can understand. Just copy the code and read comments. Note that message to be send is declared as a global variable which you can change just before sending the message. General changes can be done in Handler function.

multiplayerConnect.java

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;

public class multiplayerConnect extends AppCompatActivity {

public static final int REQUEST_ENABLE_BT=1;
ListView lv_paired_devices;
Set<BluetoothDevice> set_pairedDevices;
ArrayAdapter adapter_paired_devices;
BluetoothAdapter bluetoothAdapter;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public static final int MESSAGE_READ=0;
public static final int MESSAGE_WRITE=1;
public static final int CONNECTING=2;
public static final int CONNECTED=3;
public static final int NO_SOCKET_FOUND=4;


String bluetooth_message="00";




@SuppressLint("HandlerLeak")
Handler mHandler=new Handler()
{
    @Override
    public void handleMessage(Message msg_type) {
        super.handleMessage(msg_type);

        switch (msg_type.what){
            case MESSAGE_READ:

                byte[] readbuf=(byte[])msg_type.obj;
                String string_recieved=new String(readbuf);

                //do some task based on recieved string

                break;
            case MESSAGE_WRITE:

                if(msg_type.obj!=null){
                    ConnectedThread connectedThread=new ConnectedThread((BluetoothSocket)msg_type.obj);
                    connectedThread.write(bluetooth_message.getBytes());

                }
                break;

            case CONNECTED:
                Toast.makeText(getApplicationContext(),"Connected",Toast.LENGTH_SHORT).show();
                break;

            case CONNECTING:
                Toast.makeText(getApplicationContext(),"Connecting...",Toast.LENGTH_SHORT).show();
                break;

            case NO_SOCKET_FOUND:
                Toast.makeText(getApplicationContext(),"No socket found",Toast.LENGTH_SHORT).show();
                break;
        }
    }
};



@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.multiplayer_bluetooth);
    initialize_layout();
    initialize_bluetooth();
    start_accepting_connection();
    initialize_clicks();

}

public void start_accepting_connection()
{
    //call this on button click as suited by you

    AcceptThread acceptThread = new AcceptThread();
    acceptThread.start();
    Toast.makeText(getApplicationContext(),"accepting",Toast.LENGTH_SHORT).show();
}
public void initialize_clicks()
{
    lv_paired_devices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            Object[] objects = set_pairedDevices.toArray();
            BluetoothDevice device = (BluetoothDevice) objects[position];

            ConnectThread connectThread = new ConnectThread(device);
            connectThread.start();

            Toast.makeText(getApplicationContext(),"device choosen "+device.getName(),Toast.LENGTH_SHORT).show();
        }
    });
}

public void initialize_layout()
{
    lv_paired_devices = (ListView)findViewById(R.id.lv_paired_devices);
    adapter_paired_devices = new ArrayAdapter(getApplicationContext(),R.layout.support_simple_spinner_dropdown_item);
    lv_paired_devices.setAdapter(adapter_paired_devices);
}

public void initialize_bluetooth()
{
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter == null) {
        // Device doesn't support Bluetooth
        Toast.makeText(getApplicationContext(),"Your Device doesn't support bluetooth. you can play as Single player",Toast.LENGTH_SHORT).show();
        finish();
    }

    //Add these permisions before
//        <uses-permission android:name="android.permission.BLUETOOTH" />
//        <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
//        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
//        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    if (!bluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }

    else {
        set_pairedDevices = bluetoothAdapter.getBondedDevices();

        if (set_pairedDevices.size() > 0) {

            for (BluetoothDevice device : set_pairedDevices) {
                String deviceName = device.getName();
                String deviceHardwareAddress = device.getAddress(); // MAC address

                adapter_paired_devices.add(device.getName() + "\n" + device.getAddress());
            }
        }
    }
}


public class AcceptThread extends Thread
{
    private final BluetoothServerSocket serverSocket;

    public AcceptThread() {
        BluetoothServerSocket tmp = null;
        try {
            // MY_UUID is the app's UUID string, also used by the client code
            tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord("NAME",MY_UUID);
        } catch (IOException e) { }
        serverSocket = tmp;
    }

    public void run() {
        BluetoothSocket socket = null;
        // Keep listening until exception occurs or a socket is returned
        while (true) {
            try {
                socket = serverSocket.accept();
            } catch (IOException e) {
                break;
            }

            // If a connection was accepted
            if (socket != null)
            {
                // Do work to manage the connection (in a separate thread)
                mHandler.obtainMessage(CONNECTED).sendToTarget();
            }
        }
    }
}


private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mmDevice = device;

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    public void run() {
        // Cancel discovery because it will slow down the connection
        bluetoothAdapter.cancelDiscovery();

        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mHandler.obtainMessage(CONNECTING).sendToTarget();

            mmSocket.connect();
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }

        // Do work to manage the connection (in a separate thread)
//            bluetooth_message = "Initial message"
//            mHandler.obtainMessage(MESSAGE_WRITE,mmSocket).sendToTarget();
    }

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
private class ConnectedThread extends Thread {

    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer = new byte[2];  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();

            } catch (IOException e) {
                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
}

multiplayer_bluetooth.xml

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Challenge player"/>

    <ListView
        android:id="@+id/lv_paired_devices"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1">
    </ListView>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Make sure Device is paired"/>

</LinearLayout>

Pushing value of Var into an Array

Off the top of my head I think it should be done like this:

var veggies = "carrot";
var fruitvegbasket = [];
fruitvegbasket.push(veggies);

MySQL Query - Records between Today and Last 30 Days

You need to apply DATE_FORMAT in the SELECT clause, not the WHERE clause:

SELECT  DATE_FORMAT(create_date, '%m/%d/%Y')
FROM    mytable
WHERE   create_date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()

Also note that CURDATE() returns only the DATE portion of the date, so if you store create_date as a DATETIME with the time portion filled, this query will not select the today's records.

In this case, you'll need to use NOW instead:

SELECT  DATE_FORMAT(create_date, '%m/%d/%Y')
FROM    mytable
WHERE   create_date BETWEEN NOW() - INTERVAL 30 DAY AND NOW()

What is the use of BindingResult interface in spring MVC?

From the official Spring documentation:

General interface that represents binding results. Extends the interface for error registration capabilities, allowing for a Validator to be applied, and adds binding-specific analysis and model building.

Serves as result holder for a DataBinder, obtained via the DataBinder.getBindingResult() method. BindingResult implementations can also be used directly, for example to invoke a Validator on it (e.g. as part of a unit test).

How to input matrix (2D list) in Python?

a,b=[],[]
n=int(input("Provide me size of squre matrix row==column : "))
for i in range(n):
   for j in range(n):
      b.append(int(input()))
    a.append(b)
    print("Here your {} column {}".format(i+1,a))
    b=[]
for m in range(n):
    print(a[m])

works perfectly

How to fix "Attempted relative import in non-package" even with __init__.py

You can use import components.core directly if you append the current directory to sys.path:

if __name__ == '__main__' and __package__ is None:
    from os import sys, path
    sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))

How do I loop through items in a list box and then remove those item?

Do you want to remove all items? If so, do the foreach first, then just use Items.Clear() to remove all of them afterwards.

Otherwise, perhaps loop backwards by indexer:

listBox1.BeginUpdate();
try {
  for(int i = listBox1.Items.Count - 1; i >= 0 ; i--) {
    // do with listBox1.Items[i]

    listBox1.Items.RemoveAt(i);
  }
} finally {
  listBox1.EndUpdate();
}

How to make padding:auto work in CSS?

You can reset the padding (and I think everything else) with initial to the default.

p {
    padding: initial;
}

Refresh (reload) a page once using jQuery?

For refreshing page with javascript, you can simply use:

location.reload();

How do JavaScript closures work?

I think it is valuable to take a step back, and examine a more general notion of a "closure" -- the so-called "join operator".

In mathematics, a "join" operator is a function on a partially ordered set which returns the smallest object greater than or equal to its arguments. In symbols, join [a,b] = d such that d >= a and d >= b, but there does not exist an e such that d > e >= a or d > e >= b.

So the join gives you the smallest thing "bigger" than the parts.

Now, note that JavaScript scopes are a partially ordered structure. So that there is a sensible notion of a join. In particular, a join of scopes is the smallest scope bigger than the original scopes. That scope is called the closure.

So a closure for the variables a, b, c is the smallest scope (in the lattice of scopes for your program!) that brings a, b, and c into scope.

Linux / Bash, using ps -o to get process by specific name?

Sometimes you need to grep the process by name - in that case:

ps aux | grep simple-scan

Example output:

simple-scan  1090  0.0  0.1   4248  1432 ?        S    Jun11   0:00

Bootstrap: Position of dropdown menu relative to navbar item

Based on Bootstrap doc:

As of v3.1.0, .pull-right is deprecated on dropdown menus. use .dropdown-menu-right

eg:

<ul class="dropdown-menu dropdown-menu-right" role="menu" aria-labelledby="dLabel">

The network path was not found

I recently had the same issue. It's more likely that your application can not connect to database server due to the network issues.

In my case I was connected to wrong WiFi.

Java ArrayList how to add elements at the beginning

import java.util.*:
public class Logic {
  List<String> list = new ArrayList<String>();
  public static void main(String...args) {
  Scanner input = new Scanner(System.in);
    Logic obj = new Logic();
      for (int i=0;i<=20;i++) {
        String string = input.nextLine();
        obj.myLogic(string);
        obj.printList();
      }
 }
 public void myLogic(String strObj) {
   if (this.list.size()>=10) {
      this.list.remove(this.list.size()-1);
   } else {
     list.add(strObj); 
   }
 }
 public void printList() {
 System.out.print(this.list);
 }
}

Access to ES6 array element index inside for-of loop

In this world of flashy new native functions, we sometimes forget the basics.

for (let i = 0; i < arr.length; i++) {
    console.log('index:', i, 'element:', arr[i]);
}

Clean, efficient, and you can still break the loop. Bonus! You can also start from the end and go backwards with i--!

Additional note: If you're using the value a lot within the loop, you may wish to do const value = arr[i]; at the top of the loop for an easy, readable reference.

How to compress a String in Java?

If the passwords are more or less "random" you are out of luck, you will not be able to get a significant reduction in size.

But: Why do you need to compress the passwords? Maybe what you need is not a compression, but some sort of hash value? If you just need to check if a name matches a given password, you don't need do save the password, but can save the hash of a password. To check if a typed in password matches a given name, you can build the hash value the same way and compare it to the saved hash. As a hash (Object.hashCode()) is an int you will be able to store all 20 password-hashes in 80 bytes).

How to edit CSS style of a div using C# in .NET

This question makes me nervous. It indicates that maybe you don't understand how using server-side code will impact you're page's DOM state.

Whenever you run server-side code the entire page is rebuilt from scratch. This has several implications:

  • A form is submitted from the client to the web server. This is about the slowest action that a web browser can take, especially in ASP.Net where the form might be padded with extra fields (ie: ViewState). Doing it too often for trivial activities will make your app appear to be sluggish, even if everything else is nice and snappy.
  • It adds load to your server, in terms of bandwidth (up and down stream) and CPU/memory. Everything involved in rebuilding your page will have to happen again. If there are dynamic controls on the page, don't forget to create them.
  • Anything you've done to the DOM since the last request is lost, unless you remember to do it again for this request. Your page's DOM is reset.

If you can get away with it, you might want to push this down to javascript and avoid the postback. Perhaps use an XmlHttpRequest() call to trigger any server-side action you need.

How can I get color-int from color resource?

If your current min. API level is 23, you can simply use getColor() like we are using for getString():

//example
textView.setTextColor(getColor(R.color.green));
// if context is not available(ex: not in activity) use with context.getColor()

If you want below API level 23, just use this:

textView.setTextColor(getResources().getColor(R.color.green));

But note that getResources().getColor() is deprecated in API Level 23. In that case replace above with:

textView.setTextColor(ContextCompat.getColor(this /*context*/, R.color.green)) //Im in an activity, so I can use `this`

ContextCompat: Helper for accessing features in Context

If You want, you can constraint with SDK_INT like below:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    textView.setTextColor(getColor(R.color.green));
} else {
    textView.setTextColor(getResources().getColor(R.color.green));
}

C# Get/Set Syntax Usage

I do not understand what this is unclear

Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as though they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily while still providing the safety and flexibility of methods.

In this example, the class TimePeriod stores a time period. Internally the class stores the time in seconds, but a property called Hours is provided that allows a client to specify a time in hours. The accessors for the Hours property perform the conversion between hours and seconds.

Example

class TimePeriod
{
    private double seconds;

    public double Hours
    {
        get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
}

class Program
{
    static void Main()
    {
        TimePeriod t = new TimePeriod();

        // Assigning the Hours property causes the 'set' accessor to be called.
        t.Hours = 24;

        // Evaluating the Hours property causes the 'get' accessor to be called.
        System.Console.WriteLine("Time in hours: " + t.Hours);
    }
}

Properties Overview

Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.

A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels.

The value keyword is used to define the value being assigned by the set indexer.

Properties that do not implement a set method are read only.

http://msdn.microsoft.com/en-US/library/x9fsa0sw%28v=vs.80%29.aspx

jQuery val is undefined?

you may forgot to wrap your object with $()

  var tableChild = children[i];
  tableChild.val("my Value");// this is wrong 

and the ccorrect one is

$(tableChild).val("my Value");// this is correct

Are there .NET implementation of TLS 1.2?

The latest version of SSPI (bundled with Windows 7) has an implementation of TLS 1.2, which can be found in schannel.dll

PHP Checking if the current date is before or after a set date

if(strtotime($row['database_date']) > strtotime('now')) echo $row['database_date'];
else echo date("d-m-Y");

No need to check the hours because if they are on the same day it will show the same date either way...

How do I format a date in VBA with an abbreviated month?

I'm using

Sheet1.Range("E2", "E3000").NumberFormat = "dd/mm/yyyy hh:mm:ss"

to format a column

So I guess

Sheet1.Range("E2", "E3000").NumberFormat = "MMM dd yyyy"

would do the trick for you.

More: NumberFormat function.

Rails select helper - Default selected value, how?

If try to print the f object, then you will see that there is f.object that can be probed for getting the selected item (applicable for all rails version > 2.3)

logger.warn("f #{f.object.inspect}")

so, use the following script to get the proper selected option:

:selected => f.object.your_field 

php string to int

You can use the str_replace when you declare your variable $b like that :

$b = str_replace(" ", "", '88 8888');
echo (int)$b;

Or the most beautiful solution is to use intval :

$b = intval(str_replace(" ", "", '88 8888');
echo $b;

If your value '88 888' is from an other variable, just replace the '88 888' by the variable who contains your String.

Viewing my IIS hosted site on other machines on my network

Very Late Answer but I will highlight some point as I had to deal with it years ago setting up my IIS site across network

  1. Both your machines should be connected to the same network (same wireless network is fine)
  2. Access your remote machine via IP 168.192.x.x or via http://his-pc-name (do not forget the http part)
  3. This will server the default IIS page on the remote machine (same that is served through localhost). If you want to server another site, [you have to make that default] first1.

Make sure your IIS is working fine on remote machine by checking localhost which should served the default site. Also make sure your firewall is configured to allow connection via port 80 or you can just disable firewall for the time being for testing purposes.

CSS-moving text from left to right

I like using the following to prevent things being outside my div elements. It helps with CSS rollovers too.

.marquee{
    overflow:hidden;
}

this will hide anything that moves/is outside of the div which will prevent the browser expanding and causing a scroll bar to appear.

Should ol/ul be inside <p> or outside?

actually you should only put in-line elements inside the p, so in your case ol is better outside

Controller not a function, got undefined, while defining controllers globally

I just migrate to angular 1.3.3 and I found that If I had multiple controllers in different files when app is override and I lost first declared containers.

I don't know if is a good practise, but maybe can be helpful for another one.

var app = app;
if(!app) {
    app = angular.module('web', ['ui.bootstrap']);
}
app.controller('SearchCtrl', SearchCtrl);

Replace a value in a data frame based on a conditional (`if`) statement

If you are working with character variables (note that stringsAsFactors is false here) you can use replace:

junk <- data.frame(x <- rep(LETTERS[1:4], 3), y <- letters[1:12], stringsAsFactors = FALSE)
colnames(junk) <- c("nm", "val")

junk$nm <- replace(junk$nm, junk$nm == "B", "b")
junk
#    nm val
# 1   A   a
# 2   b   b
# 3   C   c
# 4   D   d
# ...

Use .corr to get the correlation between two columns

When you call this:

data = Top15[['Citable docs per Capita','Energy Supply per Capita']]
correlation = data.corr(method='pearson')

Since, DataFrame.corr() function performs pair-wise correlations, you have four pair from two variables. So, basically you are getting diagonal values as auto correlation (correlation with itself, two values since you have two variables), and other two values as cross correlations of one vs another and vice versa.

Either perform correlation between two series to get a single value:

from scipy.stats.stats import pearsonr
docs_col = Top15['Citable docs per Capita'].values
energy_col = Top15['Energy Supply per Capita'].values
corr , _ = pearsonr(docs_col, energy_col)

or, if you want a single value from the same function (DataFrame's corr):

single_value = correlation[0][1] 

Hope this helps.

java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver

Your URL should be jdbc:sqlserver://server:port;DatabaseName=dbname
and Class name should be like com.microsoft.sqlserver.jdbc.SQLServerDriver
Use MicrosoftSQL Server JDBC Driver 2.0

How to trigger event in JavaScript?

What you want is something like this:

document.getElementByClassName("example").click();

Using jQuery, it would be something like this:

$(".example").trigger("click");

"for" vs "each" in Ruby

See "The Evils of the For Loop" for a good explanation (there's one small difference considering variable scoping).

Using each is considered more idiomatic use of Ruby.

Java String new line

you can use <br> tag in your string for show in html pages

Check synchronously if file/directory exists in Node.js

I use below function to test if file exists. It catches also other exceptions. So in case there are rights issues e.g. chmod ugo-rwx filename or in Windows Right Click -> Properties -> Security -> Advanced -> Permission entries: empty list .. function returns exception as it should. The file exists but we don't have rights to access it. It would be wrong to ignore this kinds of exceptions.

function fileExists(path) {

  try  {
    return fs.statSync(path).isFile();
  }
  catch (e) {

    if (e.code == 'ENOENT') { // no such file or directory. File really does not exist
      console.log("File does not exist.");
      return false;
    }

    console.log("Exception fs.statSync (" + path + "): " + e);
    throw e; // something else went wrong, we don't have rights, ...
  }
}

Exception output, nodejs errors documentation in case file doesn't exist:

{
  [Error: ENOENT: no such file or directory, stat 'X:\\delsdfsdf.txt']
  errno: -4058,
  code: 'ENOENT',
  syscall: 'stat',
  path: 'X:\\delsdfsdf.txt'
}

Exception in case we don't have rights to the file, but exists:

{
  [Error: EPERM: operation not permitted, stat 'X:\file.txt']
  errno: -4048,
  code: 'EPERM',
  syscall: 'stat',
  path: 'X:\\file.txt'
}

How to check if a function exists on a SQL database

This is what SSMS uses when you script using the DROP and CREATE option

IF EXISTS (SELECT *
           FROM   sys.objects
           WHERE  object_id = OBJECT_ID(N'[dbo].[foo]')
                  AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
  DROP FUNCTION [dbo].[foo]

GO 

This approach to deploying changes means that you need to recreate all permissions on the object so you might consider ALTER-ing if Exists instead.

reading from app.config file

Just for the future reference, you just need to add System.Configuration to your references library:

enter image description here

Verify host key with pysftp

Hi We sort of had the same problem if I understand you well. So check what pysftp version you're using. If it's the latest one which is 0.2.9 downgrade to 0.2.8. Check this out. https://github.com/Yenthe666/auto_backup/issues/47

How do I run a bat file in the background from another bat file?

Other than foreground/background term. Another way to hide running window is via vbscript, if is is still available in your system.

DIM objShell
set objShell=wscript.createObject("wscript.shell")
iReturn=objShell.Run("yourcommand.exe", 0, TRUE)

name it as sth.vbs and call it from bat, put in sheduled task, etc. PersonallyI'll disable vbs with no haste at any Windows system I manage :)

getting the table row values with jquery

$(document).ready(function () {
        $("#tbl_Customer tbody tr .companyname").click(function () {

            var comapnyname = $(this).closest(".trclass").find(".companyname").text();
            var CompanyAddress = $(this).closest(".trclass").find(".CompanyAddress").text();
            var CompanyEmail = $(this).closest(".trclass").find(".CompanyEmail").text();
            var CompanyContactNumber = $(this).closest(".trclass").find(".CompanyContactNumber").text();
            var CompanyContactPerson = $(this).closest(".trclass").find(".CompanyContactPerson").text();
           // var clickedCell = $(this);
            alert(comapnyname);
            alert(CompanyAddress);
            alert(CompanyEmail);
            alert(CompanyContactNumber);
            alert(CompanyContactPerson);

            //alert(clickedCell.text());
        });
    });

How to set the value for Radio Buttons When edit?

    Gender :<br>
    <input type="radio" name="g" value="male"  <?php echo ($g=='Male')?'checked':'' ?>>male <br>
    <input type="radio" name="g" value="female"<?php echo ($g=='female')?'checked':'' ?>>female
            <?php echo $errors['g'];?>

List all files in one directory PHP

Check this out : readdir()

This bit of code should list all entries in a certain directory:

if ($handle = opendir('.')) {

    while (false !== ($entry = readdir($handle))) {

        if ($entry != "." && $entry != "..") {

            echo "$entry\n";
        }
    }

    closedir($handle);
}

Edit: miah's solution is much more elegant than mine, you should use his solution instead.

When should an Excel VBA variable be killed or set to Nothing?

VBA uses a garbage collector which is implemented by reference counting.

There can be multiple references to a given object (for example, Dim aw = ActiveWorkbook creates a new reference to Active Workbook), so the garbage collector only cleans up an object when it is clear that there are no other references. Setting to Nothing is an explicit way of decrementing the reference count. The count is implicitly decremented when you exit scope.

Strictly speaking, in modern Excel versions (2010+) setting to Nothing isn't necessary, but there were issues with older versions of Excel (for which the workaround was to explicitly set)

How to Ignore "Duplicate Key" error in T-SQL (SQL Server)

I think you are looking for the IGNORE_DUP_KEY option on your index. Have a look at IGNORE_DUP_KEY ON option documented at http://msdn.microsoft.com/en-us/library/ms186869.aspx which causes duplicate insertion attempts to produce a warning instead of an error.

SVN icon overlays not showing properly

In my case all icons suddenly disappeared .

Solution :

  1. Go To Task Manager and kill Explorer
  2. In Task Manager File (New Task (Run) ) => explorer

and all appeared again...

What is the difference between 'git pull' and 'git fetch'?

Here is Oliver Steele's image of how all it all fits together:

enter image description here

If there is sufficient interest, I suppose I could update the image to add git clone and git merge...

Difference between JPanel, JFrame, JComponent, and JApplet

JFrame and JApplet are top level containers. If you wish to create a desktop application, you will use JFrame and if you plan to host your application in browser you will use JApplet.

JComponent is an abstract class for all Swing components and you can use it as the base class for your new component. JPanel is a simple usable component you can use for almost anything.

Since this is for a fun project, the simplest way for you is to work with JPanel and then host it inside JFrame or JApplet. Netbeans has a visual designer for Swing with simple examples.

how to remove multiple columns in r dataframe?

x <-dplyr::select(dataset_df, -c('coloumn1', 'column2'))

This works for me.

How to include a class in PHP

You can use either of the following:

include "class.twitter.php";

or

require "class.twitter.php";

Using require (or require_once if you want to ensure the class is only loaded once during execution) will cause a fatal error to be raised if the file doesn't exist, whereas include will only raise a warning. See http://php.net/require and http://php.net/include for more details

What is the correct way to check for string equality in JavaScript?

Considering that both strings may be very large, there are 2 main approaches bitwise search and localeCompare

I recommed this function

function compareLargeStrings(a,b){
    if (a.length !== b.length) {
         return false;
    }
    return a.localeCompare(b) === 0;
}

How do I put double quotes in a string in vba?

Another work-around is to construct a string with a temporary substitute character. Then you can use REPLACE to change each temp character to the double quote. I use tilde as the temporary substitute character.

Here is an example from a project I have been working on. This is a little utility routine to repair a very complicated formula if/when the cell gets stepped on accidentally. It is a difficult formula to enter into a cell, but this little utility fixes it instantly.

Sub RepairFormula()
Dim FormulaString As String

FormulaString = "=MID(CELL(~filename~,$A$1),FIND(~[~,CELL(~filename~,$A$1))+1,FIND(~]~, CELL(~filename~,$A$1))-FIND(~[~,CELL(~filename~,$A$1))-1)"
FormulaString = Replace(FormulaString, Chr(126), Chr(34)) 'this replaces every instance of the tilde with a double quote.
Range("WorkbookFileName").Formula = FormulaString

This is really just a simple programming trick, but it makes entering the formula in your VBA code pretty easy.

How to get 0-padded binary representation of an integer in java?

I think this is a suboptimal solution, but you could do

String.format("%16s", Integer.toBinaryString(1)).replace(' ', '0')

Ignore mapping one property with Automapper

Could use IgnoreAttribute on the property which needs to be ignored

What is the difference between SessionState and ViewState?

Session state is saved on the server, ViewState is saved in the page.

Session state is usually cleared after a period of inactivity from the user (no request happened containing the session id in the request cookies).

The view state is posted on subsequent post back in a hidden field.

Run PostgreSQL queries from the command line

I also noticed that the query

SELECT * FROM tablename;

gives an error on the psql command prompt and

SELECT * FROM "tablename";

runs fine, really strange, so don't forget the double quotes. I always liked databases :-(

"Untrusted App Developer" message when installing enterprise iOS Application

In my case, i just change some step below with iOS 9.3 To solve this problem:

Settings -> General -> Device Management -> Developer app Choose your current developer account name. Taps Trust "Your developer account name" Taps "Trust" in pop up. Done

How to parse a JSON Input stream

if you have JSON file you can set it on assets folder then call it using this code

InputStream in = mResources.getAssets().open("fragrances.json"); 
// where mResources object from Resources class

repository element was not specified in the POM inside distributionManagement element or in -DaltDep loymentRepository=id::layout::url parameter

In your pom.xml you should add distributionManagement configuration to where to deploy.

In the following example I have used file system as the locations.

<distributionManagement>
       <repository>
         <id>internal.repo</id>
         <name>Internal repo</name>
         <url>file:///home/thara/testesb/in</url>
       </repository>
   </distributionManagement>

you can add another location while deployment by using the following command (but to avoid above error you should have at least 1 repository configured) :

mvn deploy -DaltDeploymentRepository=internal.repo::default::file:///home/thara/testesb/in

Set default time in bootstrap-datetimepicker

This is my solution for your problem :

$('#startdatetime-from').datetimepicker({
language: 'en',
format: 'yyyy-MM-dd hh:mm'
}).on('dp.change', function (e) {
        var specifiedDate = new Date(e.date);
        if (specifiedDate.getMinutes() == 0)
        {
            specifiedDate.setMinutes(1);
            $(this).data('DateTimePicker').date(specifiedDate);
        }
    });

This also work for setting a default hour or both. Note that this code sample works with the useCurrent: false parameter too.

When the user pick a date, we check if the minute is 0 (hard-coded default value). In this case, we set a 1. Then, the user cannot select 0.

How to use the CSV MIME-type?

You are not specifying a language or framework, but the following header is used for file downloads:

"Content-Disposition: attachment; filename=abc.csv"

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

For any method in a Spring CrudRepository you should be able to specify the @Query yourself. Something like this should work:

@Query( "select o from MyObject o where inventoryId in :ids" )
List<MyObject> findByInventoryIds(@Param("ids") List<Long> inventoryIdList);

Get Image Height and Width as integer values?

PHP's getimagesize() returns an array of data. The first two items in the array are the two items you're interested in: the width and height. To get these, you would simply request the first two indexes in the returned array:

var $imagedata = getimagesize("someimage.jpg");

print "Image width  is: " . $imagedata[0];
print "Image height is: " . $imagedata[1];

For further information, see the documentation.

Why does Math.Round(2.5) return 2 instead of 3?

using a custom rounding

public int Round(double value)
{
    double decimalpoints = Math.Abs(value - Math.Floor(value));
    if (decimalpoints > 0.5)
        return (int)Math.Round(value);
    else
        return (int)Math.Floor(value);
}

Xcode error - Thread 1: signal SIGABRT

You are trying to load a XIB named DetailViewController, but no such XIB exists or it's not member of your current target.

Difference Between Cohesion and Coupling

Cohesion in software engineering is the degree to which the elements of a certain module belong together. Thus, it is a measure of how strongly related each piece of functionality expressed by the source code of a software module is.

Coupling in simple words, is how much one component (again, imagine a class, although not necessarily) knows about the inner workings or inner elements of another one, i.e. how much knowledge it has of the other component.

I wrote a blog post about this, if you want to read up in a little bit more details with examples and drawings. I think it answers most of your questions.

Converting List<Integer> to List<String>

A slightly more concise solution using the forEach method on the original list:

    List<Integer> oldList = Arrays.asList(1, 2, 3, 4, 5);
    List<String> newList = new ArrayList<>(oldList.size());
    oldList.forEach(e -> newList.add(String.valueOf(e)));

vertical & horizontal lines in matplotlib

This may be a common problem for new users of Matplotlib to draw vertical and horizontal lines. In order to understand this problem, you should be aware that different coordinate systems exist in Matplotlib.

The method axhline and axvline are used to draw lines at the axes coordinate. In this coordinate system, coordinate for the bottom left point is (0,0), while the coordinate for the top right point is (1,1), regardless of the data range of your plot. Both the parameter xmin and xmax are in the range [0,1].

On the other hand, method hlines and vlines are used to draw lines at the data coordinate. The range for xmin and xmax are the in the range of data limit of x axis.

Let's take a concrete example,

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 5, 100)
y = np.sin(x)

fig, ax = plt.subplots()

ax.plot(x, y)
ax.axhline(y=0.5, xmin=0.0, xmax=1.0, color='r')
ax.hlines(y=0.6, xmin=0.0, xmax=1.0, color='b')

plt.show()

It will produce the following plot: enter image description here

The value for xmin and xmax are the same for the axhline and hlines method. But the length of produced line is different.

Conda command is not recognized on Windows 10

The newest version of the Anaconda installer for Windows will also install a windows launcher for "Anaconda Prompt" and "Anaconda Powershell Prompt". If you use one of those instead of the regular windows cmd shell, the conda command, python etc. should be available by default in this shell.

enter image description here

How to calculate age (in years) based on Date of Birth and getDate()

Just check whether the below answer is feasible.

DECLARE @BirthDate DATE = '09/06/1979'

SELECT 
 (
 YEAR(GETDATE()) - YEAR(@BirthDate) - 
 CASE  WHEN (MONTH(GETDATE()) * 100) + DATEPART(dd, GETDATE()) >     
 (MONTH(@BirthDate) * 100) + DATEPART(dd, @BirthDate)
 THEN 1             
 ELSE 0             
 END        
 )

How to get the separate digits of an int number?

To do this, you will use the % (mod) operator.

int number; // = some int

while (number > 0) {
    print( number % 10);
    number = number / 10;
}

The mod operator will give you the remainder of doing int division on a number.

So,

10012 % 10 = 2

Because:

10012 / 10 = 1001, remainder 2

Note: As Paul noted, this will give you the numbers in reverse order. You will need to push them onto a stack and pop them off in reverse order.

Code to print the numbers in the correct order:

int number; // = and int
LinkedList<Integer> stack = new LinkedList<Integer>();
while (number > 0) {
    stack.push( number % 10 );
    number = number / 10;
}

while (!stack.isEmpty()) {
    print(stack.pop());
}

Read data from SqlDataReader

using(SqlDataReader rdr = cmd.ExecuteReader())
{
    while (rdr.Read())
    {
        var myString = rdr.GetString(0); //The 0 stands for "the 0'th column", so the first column of the result.
        // Do somthing with this rows string, for example to put them in to a list
        listDeclaredElsewhere.Add(myString);
    }
}

Wait for all promises to resolve

I want the all to resolve when all the chains have been resolved.

Sure, then just pass the promise of each chain into the all() instead of the initial promises:

$q.all([one.promise, two.promise, three.promise]).then(function() {
    console.log("ALL INITIAL PROMISES RESOLVED");
});

var onechain   = one.promise.then(success).then(success),
    twochain   = two.promise.then(success),
    threechain = three.promise.then(success).then(success).then(success);

$q.all([onechain, twochain, threechain]).then(function() {
    console.log("ALL PROMISES RESOLVED");
});

What is the most efficient way to store a list in the Django models?

As this is an old question, and Django techniques must have changed significantly since, this answer reflects Django version 1.4, and is most likely applicable for v 1.5.

Django by default uses relational databases; you should make use of 'em. Map friendships to database relations (foreign key constraints) with the use of ManyToManyField. Doing so allows you to use RelatedManagers for friendlists, which use smart querysets. You can use all available methods such as filter or values_list.

Using ManyToManyField relations and properties:

class MyDjangoClass(models.Model):
    name = models.CharField(...)
    friends = models.ManyToManyField("self")

    @property
    def friendlist(self):
        # Watch for large querysets: it loads everything in memory
        return list(self.friends.all())

You can access a user's friend list this way:

joseph = MyDjangoClass.objects.get(name="Joseph")
friends_of_joseph = joseph.friendlist

Note however that these relations are symmetrical: if Joseph is a friend of Bob, then Bob is a friend of Joseph.

Comprehensive methods of viewing memory usage on Solaris

"top" is usually available on Solaris.

If not then revert to "vmstat" which is available on most UNIX system.

It should look something like this (from an AIX box)

vmstat

System configuration: lcpu=4 mem=12288MB ent=2.00

kthr    memory              page              faults              cpu
----- ----------- ------------------------ ------------ -----------------------
 r  b   avm   fre  re  pi  po  fr   sr  cy  in   sy  cs us sy id wa    pc    ec
 2  1 1614644 585722   0   0   1  22  104   0 808 29047 2767 12  8 77  3  0.45  22.3

the colums "avm" and "fre" tell you the total memory and free memery.

a "man vmstat" should get you the gory details.

Limit the length of a string with AngularJS

You can simply add a css class to the div, and add a tool tip via angularjs so that trimmed text will be visible on mouse over.

<div class="trim-info" tooltip="{{modal.title}}">{{modal.title}}</div>

   .trim-info {
      max-width: 50px;
      display: inline-block;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;  
      line-height: 15px;
      position: relative;
   }

Jquery post, response in new window

I did it with an ajax post and then returned using a data url:

$(document).ready(function () {
    var exportClick = function () {
        $.ajax({
           url: "/api/test.php",
           type: "POST",
           dataType: "text",
           data: {
              action: "getCSV",
              filter: "name = 'smith'",
           },
           success: function(data) {
              var w = window.open('data:text/csv;charset=utf-8,' + encodeURIComponent(data));
              w.focus();
           },
           error: function () {
              alert('Problem getting data');
           },
        });
    }
});

How to assert two list contain the same elements in Python?

Slightly faster version of the implementation (If you know that most couples lists will have different lengths):

def checkEqual(L1, L2):
    return len(L1) == len(L2) and sorted(L1) == sorted(L2)

Comparing:

>>> timeit(lambda: sorting([1,2,3], [3,2,1]))
2.42745304107666
>>> timeit(lambda: lensorting([1,2,3], [3,2,1]))
2.5644469261169434 # speed down not much (for large lists the difference tends to 0)

>>> timeit(lambda: sorting([1,2,3], [3,2,1,0]))
2.4570400714874268
>>> timeit(lambda: lensorting([1,2,3], [3,2,1,0]))
0.9596951007843018 # speed up

Google Chrome display JSON AJAX response as tree and not as a plain text

There was an issue with a build of Google Chrome Dev build 24.0.1312.5 that caused the preview panel to no longer display a json object tree but rather flat text. It should be fixed in the next dev

See more here: http://code.google.com/p/chromium/issues/detail?id=160733

How to join two tables by multiple columns in SQL?

You would basically want something along the lines of:

SELECT e.*, v.Score
  FROM Evaluation e
LEFT JOIN Value v
ON v.CaseNum = e.CaseNum AND
v.FileNum = e.FileNum AND
v.ActivityNum = e.ActivityNum;

CSS Pseudo-classes with inline styles

Rather than needing inline you could use Internal CSS

<a href="http://www.google.com" style="hover:text-decoration:none;">Google</a>

You could have:

<a href="http://www.google.com" id="gLink">Google</a>
<style>
  #gLink:hover {
     text-decoration: none;
  }
</style>

Flexbox: 4 items per row

Add a width to the .child elements. I personally would use percentages on the margin-left if you want to have it always 4 per row.

DEMO

.child {
    display: inline-block;
    background: blue;
    margin: 10px 0 0 2%;
    flex-grow: 1;
    height: 100px;
    width: calc(100% * (1/4) - 10px - 1px);
}

Determining the size of an Android view at runtime

Are you calling getWidth() before the view is actually laid out on the screen?

A common mistake made by new Android developers is to use the width and height of a view inside its constructor. When a view’s constructor is called, Android doesn’t know yet how big the view will be, so the sizes are set to zero. The real sizes are calculated during the layout stage, which occurs after construction but before anything is drawn. You can use the onSizeChanged() method to be notified of the values when they are known, or you can use the getWidth() and getHeight() methods later, such as in the onDraw() method.

How do I POST form data with UTF-8 encoding by using curl?

You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.

You should use this request:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod

Hash table in JavaScript

Using the function above, you would do:

var myHash = new Hash('one',[1,10,5],'two', [2], 'three',[3,30,300]);

Of course, the following would also work:

var myHash = {}; // New object
myHash['one'] = [1,10,5];
myHash['two'] = [2];
myHash['three'] = [3, 30, 300];

since all objects in JavaScript are hash tables! It would, however, be harder to iterate over since using foreach(var item in object) would also get you all its functions, etc., but that might be enough depending on your needs.

Rollback a Git merge

Just reset the merge commit with git reset --hard HEAD^.

If you use --no-ff git always creates a merge, even if you did not commit anything in between. Without --no-ff git will just do a fast forward, meaning your branches HEAD will be set to HEAD of the merged branch. To resolve this find the commit-id you want to revert to and git reset --hard $COMMITID.

Simplest way to do grouped barplot

There are several ways to do plots in R; lattice is one of them, and always a reasonable solution, +1 to @agstudy. If you want to do this in base graphics, you could try the following:

Reasonstats <- read.table(text="Category         Reason  Species
                                 Decline        Genuine       24
                                Improved        Genuine       16
                                Improved  Misclassified       85
                                 Decline  Misclassified       41
                                 Decline      Taxonomic        2
                                Improved      Taxonomic        7
                                 Decline        Unclear       41
                                Improved        Unclear      117", header=T)

ReasonstatsDec <- Reasonstats[which(Reasonstats$Category=="Decline"),]
ReasonstatsImp <- Reasonstats[which(Reasonstats$Category=="Improved"),]
Reasonstats3   <- cbind(ReasonstatsImp[,3], ReasonstatsDec[,3])
colnames(Reasonstats3) <- c("Improved", "Decline")
rownames(Reasonstats3) <- ReasonstatsImp$Reason

windows()
  barplot(t(Reasonstats3), beside=TRUE, ylab="number of species", 
          cex.names=0.8, las=2, ylim=c(0,120), col=c("darkblue","red"))
  box(bty="l")

enter image description here

Here's what I did: I created a matrix with two columns (because your data were in columns) where the columns were the species counts for Decline and for Improved. Then I made those categories the column names. I also made the Reasons the row names. The barplot() function can operate over this matrix, but wants the data in rows rather than columns, so I fed it a transposed version of the matrix. Lastly, I deleted some of your arguments to your barplot() function call that were no longer needed. In other words, the problem was that your data weren't set up the way barplot() wants for your intended output.

C# constructors overloading

Maybe your class isn't quite complete. Personally, I use a private init() function with all of my overloaded constructors.

class Point2D {

  double X, Y;

  public Point2D(double x, double y) {
    init(x, y);
  }

  public Point2D(Point2D point) {
    if (point == null)
      throw new ArgumentNullException("point");
    init(point.X, point.Y);
  }

  void init(double x, double y) {
    // ... Contracts ...
    X = x;
    Y = y;
  }
}

Equal height rows in a flex container

This seems to be working in cases with fixed parent height (tested in Chrome and Firefox):

.child {
        height    : 100%;
        overflow  : hidden;
}

.parent {
        display: flex;
        flex-direction: column;
        height: 70vh; // ! won't work unless parent container height is set
        position: relative;
}

If it's not possible to use grids for some reason, maybe it's the solution.

CodeIgniter - File upload required validation

I found a solution that works exactly how I want.

I changed

$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
$this->form_validation->set_rules('userfile', 'Document', 'required');

To

$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
if (empty($_FILES['userfile']['name']))
{
    $this->form_validation->set_rules('userfile', 'Document', 'required');
}

Getting the client's time zone (and offset) in JavaScript

Using an offset to calculate Timezone is a wrong approach, and you will always encounter problems. Time zones and daylight saving rules may change on several occasions during a year, and It's difficult to keep up with changes.

To get the system's IANA timezone in JavaScript, you should use

_x000D_
_x000D_
console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)
_x000D_
_x000D_
_x000D_

As of September 2019, this works in 95% of the browsers used globally.

Old compatibility information

ecma-402/1.0 says that timeZone may be undefined if not provided to constructor. However, future draft (3.0) fixed that issue by changing to system default timezone.

In this version of the ECMAScript Internationalization API, the timeZone property will remain undefined if no timeZone property was provided in the options object provided to the Intl.DateTimeFormat constructor. However, applications should not rely on this, as future versions may return a String value identifying the host environment’s current time zone instead.

in ecma-402/3.0 which is still in a draft it changed to

In this version of the ECMAScript 2015 Internationalization API, the timeZone property will be the name of the default time zone if no timeZone property was provided in the options object provided to the Intl.DateTimeFormat constructor. The previous version left the timeZone property undefined in this case.

Simple way to calculate median with MySQL

I propose a faster way.

Get the row count:

SELECT CEIL(COUNT(*)/2) FROM data;

Then take the middle value in a sorted subquery:

SELECT max(val) FROM (SELECT val FROM data ORDER BY val limit @middlevalue) x;

I tested this with a 5x10e6 dataset of random numbers and it will find the median in under 10 seconds.

Parsing JSON in Excel VBA

Two small contributions to Codo's answer:

' "recursive" version of GetObjectProperty
Public Function GetObjectProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Object
    Dim names() As String
    Dim i As Integer

    names = Split(propertyName, ".")

    For i = 0 To UBound(names)
        Set JsonObject = ScriptEngine.Run("getProperty", JsonObject, names(i))
    Next

    Set GetObjectProperty = JsonObject
End Function

' shortcut to object array
Public Function GetObjectArrayProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Object()
    Dim a() As Object
    Dim i As Integer
    Dim l As Integer

    Set JsonObject = GetObjectProperty(JsonObject, propertyName)

    l = GetProperty(JsonObject, "length") - 1

    ReDim a(l)

    For i = 0 To l
        Set a(i) = GetObjectProperty(JsonObject, CStr(i))
    Next

    GetObjectArrayProperty = a
End Function

So now I can do stuff like:

Dim JsonObject As Object
Dim Value() As Object
Dim i As Integer
Dim Total As Double

Set JsonObject = DecodeJsonString(CStr(request.responseText))

Value = GetObjectArrayProperty(JsonObject, "d.Data")

For i = 0 To UBound(Value)
    Total = Total + Value(i).Amount
Next

how to set the query timeout from SQL connection string

you can set Timeout in connection string (time for Establish connection between client and sql). commandTimeout is set per command but its default time is 30 secend

Return from lambda forEach() in java

The return there is returning from the lambda expression rather than from the containing method. Instead of forEach you need to filter the stream:

players.stream().filter(player -> player.getName().contains(name))
       .findFirst().orElse(null);

Here filter restricts the stream to those items that match the predicate, and findFirst then returns an Optional with the first matching entry.

This looks less efficient than the for-loop approach, but in fact findFirst() can short-circuit - it doesn't generate the entire filtered stream and then extract one element from it, rather it filters only as many elements as it needs to in order to find the first matching one. You could also use findAny() instead of findFirst() if you don't necessarily care about getting the first matching player from the (ordered) stream but simply any matching item. This allows for better efficiency when there's parallelism involved.

Angularjs if-then-else construction in expression

Angular expressions do not support the ternary operator before 1.1.5, but it can be emulated like this:

condition && (answer if true) || (answer if false)

So in example, something like this would work:

<div ng-repeater="item in items">
    <div>{{item.description}}</div>
    <div>{{isExists(item) && 'available' || 'oh no, you don't have it'}}</div>
</div>

UPDATE: Angular 1.1.5 added support for ternary operators:

{{myVar === "two" ? "it's true" : "it's false"}}

Python None comparison: should I use "is" or ==?

is is generally preferred when comparing arbitrary objects to singletons like None because it is faster and more predictable. is always compares by object identity, whereas what == will do depends on the exact type of the operands and even on their ordering.

This recommendation is supported by PEP 8, which explicitly states that "comparisons to singletons like None should always be done with is or is not, never the equality operators."

Batch script to find and replace a string in text file within a minute for files up to 12 MB

Give this a shot:

@echo off
setlocal

call :FindReplace "findstr" "replacestr" input.txt

exit /b 

:FindReplace <findstr> <replstr> <file>
set tmp="%temp%\tmp.txt"
If not exist %temp%\_.vbs call :MakeReplace
for /f "tokens=*" %%a in ('dir "%3" /s /b /a-d /on') do (
  for /f "usebackq" %%b in (`Findstr /mic:"%~1" "%%a"`) do (
    echo(&Echo Replacing "%~1" with "%~2" in file %%~nxa
    <%%a cscript //nologo %temp%\_.vbs "%~1" "%~2">%tmp%
    if exist %tmp% move /Y %tmp% "%%~dpnxa">nul
  )
)
del %temp%\_.vbs
exit /b

:MakeReplace
>%temp%\_.vbs echo with Wscript
>>%temp%\_.vbs echo set args=.arguments
>>%temp%\_.vbs echo .StdOut.Write _
>>%temp%\_.vbs echo Replace(.StdIn.ReadAll,args(0),args(1),1,-1,1)
>>%temp%\_.vbs echo end with

Reading a key from the Web.Config using ConfigurationManager

There will be two Web.config files. I think you may have confused with those two files.

Check this image:

click this link and check this image

In this image you can see two Web.config files. You should add your constants to the one which is in the project folder not in the views folder

Hope this may help you

"Debug only" code that should run only when "turned on"

You could try this if you only need the code to run when you have a debugger attached to the process.

if (Debugger.IsAttached)
{
     // do some stuff here
}

Do I need to compile the header files in a C program?

Okay, let's understand the difference between active and passive code.

The active code is the implementation of functions, procedures, methods, i.e. the pieces of code that should be compiled to executable machine code. We store it in .c files and sure we need to compile it.

The passive code is not being execute itself, but it needed to explain the different modules how to communicate with each other. Usually, .h files contains only prototypes (function headers), structures.

An exception are macros, that formally can contain an active pieces, but you should understand that they are using at the very early stage of building (preprocessing) with simple substitution. At the compile time macros already are substituted to your .c file.

Another exception are C++ templates, that should be implemented in .h files. But here is the story similar to macros: they are substituted on the early stage (instantiation) and formally, each other instantiation is another type.

In conclusion, I think, if the modules formed properly, we should never compile the header files.

How to set the opacity/alpha of a UIImage?

I just needed to do this, but thought Steven's solution would be slow. This should hopefully use graphics HW. Create a category on UIImage:

- (UIImage *)imageByApplyingAlpha:(CGFloat) alpha {
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect area = CGRectMake(0, 0, self.size.width, self.size.height);

    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -area.size.height);

    CGContextSetBlendMode(ctx, kCGBlendModeMultiply);

    CGContextSetAlpha(ctx, alpha);

    CGContextDrawImage(ctx, area, self.CGImage);

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;
}

Laravel - check if Ajax request

after writing the jquery code perform this validation in your route or in controller.

$.ajax({
url: "/id/edit",
data:
name:name,
method:'get',
success:function(data){
  console.log(data);}
});

Route::get('/', function(){
if(Request::ajax()){
  return 'it's ajax request';}
});

Why do I need an IoC container as opposed to straightforward DI code?

In the .NET world AOP isn't too popular, so for DI a framework is your only real option, whether you write one yourself or use another framework.

If you used AOP you can inject when you compile your application, which is more common in Java.

There are many benefits to DI, such as reduced coupling so unit testing is easier, but how will you implement it? Do you want to use reflection to do it yourself?

How do I limit the number of decimals printed for a double?

okay one other solution that I thought of just for the fun of it would be to turn your decimal into a string and then cut the string into 2 strings, one containing the point and the decimals and the other containing the Int to the left of the point. after that you limit the String of the point and decimals to 3 chars, one for the decimal point and the others for the decimals. then just recombine.

double shippingCost = ((nCartons * 1.44) + (lbs + 1) * 0.96) + 3.0;
String ShippingCost = (String) shippingCost;
String decimalCost = ShippingCost.subString(indexOf('.'),ShippingCost.Length());
ShippingCost = ShippingCost.subString(0,indexOf('.'));
ShippingCost = ShippingCost + decimalCost;

There! Simple, right?

How to have a a razor action link open in a new tab?

Looks like you are confusing Html.ActionLink() for Url.Action(). Url.Action has no parameters to set the Target, because it only returns a URL.

Based on your current code, the anchor should probably look like:

<a href="@Url.Action("RunReport", "Performance", new { reportView = Model.ReportView.ToString() })" 
   type="submit" 
   id="runReport" 
   target="_blank"
   class="button Secondary">
     @Reports.RunReport
</a>

Pause Console in C++ program

I just want to add that there is a way to get what you want, but it will require to use some a third party library (or that you write the platform dependent code yourself).

As far as I'm concerned, the biggest drawback with cin is that you are required to hit Return, and not just any key.

Assuming you had a key-listener you could quite easily write a function that waits for the user to hit any key. However finding a platform independent key listener is no trivial task, and will most likely require you to load parts of a larger library.

I am thinking something along the lines of:

char wait_for_key() {
    int key;
    while ( ! (key == key_pressed(ANY)) ) {
          this_thread::yield();
    }
    return convert_virtual_key_to_char(key);
}

The actual function would obviously be quite different from what I wrote, depending on the library you use.

I know the following libraries have keylisteners (Feel free to add more in an edit if you know of any.):

PHP add elements to multidimensional array with array_push

As in the multi-dimensional array an entry is another array, specify the index of that value to array_push:

array_push($md_array['recipe_type'], $newdata);

Why doesn't Dijkstra's algorithm work for negative weight edges?

You can use dijkstra's algorithm with negative edges not including negative cycle, but you must allow a vertex can be visited multiple times and that version will lose it's fast time complexity.

In that case practically I've seen it's better to use SPFA algorithm which have normal queue and can handle negative edges.

C# nullable string error

You are making it complicated. string is already nullable. You don't need to make it more nullable. Take out the ? on the property type.

Is there a template engine for Node.js?

Did you try PURE ?
If you give it a try, feel free to post any trouble you may face at the forum

While it was primarly designed for the browser, it works well with Jaxer and Rhino.

I don't know node.js yet but if you can cache some JS and functions in memory, the speed should be even more impressive.

APT command line interface-like yes/no input?

I'd do it this way:

# raw_input returns the empty string for "enter"
yes = {'yes','y', 'ye', ''}
no = {'no','n'}

choice = raw_input().lower()
if choice in yes:
   return True
elif choice in no:
   return False
else:
   sys.stdout.write("Please respond with 'yes' or 'no'")

Error: Generic Array Creation

The following will give you an array of the type you want while preserving type safety.

PCB[] getAll(Class<PCB[]> arrayType) {  
    PCB[] res = arrayType.cast(java.lang.reflect.Array.newInstance(arrayType.getComponentType(), list.size()));  
    for (int i = 0; i < res.length; i++)  {  
        res[i] = list.get(i);  
    }  
    list.clear();  
    return res;  
}

How this works is explained in depth in my answer to the question that Kirk Woll linked as a duplicate.

Detect if a jQuery UI dialog box is open

Nick Craver's comment is the simplest to avoid the error that occurs if the dialog has not yet been defined:

if ($('#elem').is(':visible')) { 
  // do something
}

You should set visibility in your CSS first though, using simply:

#elem { display: none; }

sql try/catch rollback/commit - preventing erroneous commit after rollback

Below might be useful.

Source: https://msdn.microsoft.com/en-us/library/ms175976.aspx

BEGIN TRANSACTION;

BEGIN TRY
    -- your code --
END TRY
BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
GO

Undefined symbols for architecture armv7

Another possible cause of "undefined symbol" linker errors is attempting to call a C function from a .mm file. In this case you'll need to use extern "C" {...} when you import the header files.

Linker error calling C-Function from Objective-C++

Pandas: Setting no. of max rows

Personally, I like setting the options directly with an assignment statement as it is easy to find via tab completion thanks to iPython. I find it hard to remember what the exact option names are, so this method works for me.

For instance, all I have to remember is that it begins with pd.options

pd.options.<TAB>

enter image description here

Most of the options are available under display

pd.options.display.<TAB>

enter image description here

From here, I usually output what the current value is like this:

pd.options.display.max_rows
60

I then set it to what I want it to be:

pd.options.display.max_rows = 100

Also, you should be aware of the context manager for options, which temporarily sets the options inside of a block of code. Pass in the option name as a string followed by the value you want it to be. You may pass in any number of options in the same line:

with pd.option_context('display.max_rows', 100, 'display.max_columns', 10):
    some pandas stuff

You can also reset an option back to its default value like this:

pd.reset_option('display.max_rows')

And reset all of them back:

pd.reset_option('all')

It is still perfectly good to set options via pd.set_option. I just find using the attributes directly is easier and there is less need for get_option and set_option.

How to get HttpRequestMessage data

In case you want to cast to a class and not just a string:

YourClass model = await request.Content.ReadAsAsync<YourClass>();

Guzzle 6: no more json() method for responses

$response is instance of PSR-7 ResponseInterface. For more details see https://www.php-fig.org/psr/psr-7/#3-interfaces

getBody() returns StreamInterface:

/**
 * Gets the body of the message.
 *
 * @return StreamInterface Returns the body as a stream.
 */
public function getBody();

StreamInterface implements __toString() which does

Reads all data from the stream into a string, from the beginning to end.

Therefore, to read body as string, you have to cast it to string:

$stringBody = (string) $response->getBody()


Gotchas

  1. json_decode($response->getBody() is not the best solution as it magically casts stream into string for you. json_decode() requires string as 1st argument.
  2. Don't use $response->getBody()->getContents() unless you know what you're doing. If you read documentation for getContents(), it says: Returns the remaining contents in a string. Therefore, calling getContents() reads the rest of the stream and calling it again returns nothing because stream is already at the end. You'd have to rewind the stream between those calls.

Docker: How to use bash with an Alpine based docker image?

To Install bash you can do:

RUN apk add --update bash && rm -rf /var/cache/apk/*

If you do not want to add extra size to your image, you can use ash or sh that ships with alpine.

Reference: https://github.com/smebberson/docker-alpine/issues/43

Using sessions & session variables in a PHP Login Script

$session_start();

extract($_POST);         
//extract data from submit post 

if(isset($submit))  
  {    
    if($user=="user" && $pass=="pass")    
      {     
        $_SESSION['user']= $user;       
        //if correct password and name store in session 
    } else {
        echo "Invalid user and password";
        header("Locatin:form.php")
    }
if(isset($_SESSION['user']))     
  {
  }

Toggle input disabled attribute using jQuery


    $('#checkbox').click(function(){
        $('#submit').attr('disabled', !$(this).attr('checked'));
    });

What is the purpose of flush() in Java streams?

If the buffer is full, all strings that is buffered on it, they will be saved onto the disk. Buffers is used for avoiding from Big Deals! and overhead.

In BufferedWriter class that is placed in java libs, there is a one line like:

private static int defaultCharBufferSize = 8192;

If you do want to send data before the buffer is full, you do have control. Just Flush It. Calls to writer.flush() say, "send whatever's in the buffer, now!

reference book: https://www.amazon.com/Head-First-Java-Kathy-Sierra/dp/0596009208

pages:453

Eclipse projects not showing up after placing project files in workspace/projects

For Juno: (With Source in E:\workspace and destination in C:\workspace)

  1. Copy project directory in its entirety to the workspace directory. (e.g. Copy E:\workspace\HelloWorld C:\workspace\helloWorld)

  2. Start Eclipse.

  3. Perform: File --> Import

  4. Select: General -- > "Existing Project into Workspace"

  5. "Next >"

  6. Check "Select root Directory"

  7. Select with "Browse Button"

  8. Select "C:\workspace"

  9. A list of existing projects will appear. Just check the ones that are in Bold (To Be Imported) then press the "Finish" button.

Review the Package Explorer and your copied projects should now be there.

How to implement debounce in Vue2?

Please note that I posted this answer before the accepted answer. It's not correct. It's just a step forward from the solution in the question. I have edited the accepted question to show both the author's implementation and the final implementation I had used.


Based on comments and the linked migration document, I've made a few changes to the code:

In template:

<input type="text" v-on:input="debounceInput" v-model="searchInput">

In script:

watch: {
  searchInput: function () {
    this.debounceInput();
  }
},

And the method that sets the filter key stays the same:

methods: {
  debounceInput: _.debounce(function () {
    this.filterKey = this.searchInput;
  }, 500)
}

This looks like there is one less call (just the v-model, and not the v-on:input).

What's the difference between F5 refresh and Shift+F5 in Google Chrome browser?

It ignores the cached content when refreshing...

https://support.google.com/a/answer/3001912?hl=en

F5 or Control + R = Reload the current page
Control+Shift+R or Shift + F5 = Reload your current page, ignoring cached content

Why is semicolon allowed in this python snippet?

Python uses the ; as a separator, not a terminator. You can also use them at the end of a line, which makes them look like a statement terminator, but this is legal only because blank statements are legal in Python -- a line that contains a semicolon at the end is two statements, the second one blank.

How do I call a dynamically-named method in Javascript?

Within a ServiceWorker or Worker, replace window with self:

self[method_prefix + method_name](arg1, arg2);

Workers have no access to the DOM, therefore window is an invalid reference. The equivalent global scope identifier for this purpose is self.

Convert HTML to PDF in .NET

Quite likely most projects will wrap a C/C++ Engine rather than implementing a C# solution from scratch. Try Project Gotenberg.

To test it

docker run --rm -p 3000:3000 thecodingmachine/gotenberg:6

Curl sample

curl --request POST \
    --url http://localhost:3000/convert/url \
    --header 'Content-Type: multipart/form-data' \
    --form remoteURL=https://brave.com \
    --form marginTop=0 \
    --form marginBottom=0 \
    --form marginLeft=0 \
    --form marginRight=0 \
    -o result.pdf

C# sample.cs

using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
using static System.Console;

namespace Gotenberg
{
    class Program
    {
        public static async Task Main(string[] args)
        {
            try
            {
                var client = new HttpClient();            
                var formContent = new MultipartFormDataContent
                    {
                        {new StringContent("https://brave.com/"), "remoteURL"},
                        {new StringContent("0"), "marginTop" }
                    };
                var result = await client.PostAsync(new Uri("http://localhost:3000/convert/url"), formContent);
                await File.WriteAllBytesAsync("duckduck.com.pdf", await result.Content.ReadAsByteArrayAsync());
            }
            catch (Exception ex)
            {
                WriteLine(ex);
            }
        }
    }
}

To compile

csc sample.cs -langversion:latest -reference:System.Net.Http.dll && mono ./sample.exe

How can I remove specific rules from iptables?

Assume that, if you want to remove NAT rules,

List the appended IPtables using the command below,

# sudo iptables -L -t nat -v

Chain PREROUTING (policy ACCEPT 18 packets, 1382 bytes)
 pkts bytes target     prot opt in     out     source               destination         
    7   420 DNAT       tcp  --  any    any     anywhere             saltmaster           tcp dpt:http to:172.31.5.207:80
    0     0 DNAT       tcp  --  eth0   any     anywhere             anywhere             tcp dpt:http to:172.31.5.207:8080

If you would like to remove the nat rule from the IPtables, just execute the command,

# sudo iptables -F -t nat -v

Flushing chain `PREROUTING'
Flushing chain `INPUT'
Flushing chain `OUTPUT'
Flushing chain `POSTROUTING'

Then, you can verify that,

# sudo iptables -L -t nat -v

How do I debug "Error: spawn ENOENT" on node.js?

solution in my case

var spawn = require('child_process').spawn;

const isWindows = /^win/.test(process.platform); 

spawn(isWindows ? 'twitter-proxy.cmd' : 'twitter-proxy');
spawn(isWindows ? 'http-server.cmd' : 'http-server');

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

How to disable textbox from editing?

You can set the ReadOnly property to true.

Quoth the link:

When this property is set to true, the contents of the control cannot be changed by the user at runtime. With this property set to true, you can still set the value of the Text property in code. You can use this feature instead of disabling the control with the Enabled property to allow the contents to be copied and ToolTips to be shown.

How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4

Here I'm basically wrapping a button in a link. The advantage is that you can post to different action methods in the same form.

<a href="Controller/ActionMethod">
    <input type="button" value="Click Me" />
</a>

Adding parameters:

<a href="Controller/ActionMethod?userName=ted">
    <input type="button" value="Click Me" />
</a>

Adding parameters from a non-enumerated Model:

<a href="Controller/[email protected]">
    <input type="button" value="Click Me" />
</a>

You can do the same for an enumerated Model too. You would just have to reference a single entity first. Happy Coding!

How to store decimal values in SQL Server?

You can try this

decimal(18,1)

The length of numbers should be totally 18. The length of numbers after the decimal point should be 1 only and not more than that.

Unsigned keyword in C++

Yes, it means unsigned int. It used to be that if you didn't specify a data type in C there were many places where it just assumed int. This was try, for example, of function return types.

This wart has mostly been eradicated, but you are encountering its last vestiges here. IMHO, the code should be fixed to say unsigned int to avoid just the sort of confusion you are experiencing.

javascript Unable to get property 'value' of undefined or null reference

you have many HTML and java script mistakes includes: tag, using non UTF-8 encoding for form submission, no need,... You must use document.forms.FORMNAME or document.forms[0] for first appear form in page Corrected:

_x000D_
_x000D_
 function validate_frm_new_user_request()_x000D_
{_x000D_
    alert('test');_x000D_
    var valid = true;_x000D_
_x000D_
    if ( document.forms.frm_new_user_request.u_userid.value == "" )_x000D_
    {_x000D_
        alert ( "Please enter your valid ISID Information." );_x000D_
        document.forms.frm_new_user_request.u_userid.focus();_x000D_
        valid = false;_x000D_
  console.log("FALSE::Empty Value ");_x000D_
    }_x000D_
return valid;_x000D_
}
_x000D_
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
    <title></title>_x000D_
    <meta content="text/html;charset=UTF-8" http-equiv="content-type" />_x000D_
_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<form method="post" action="" name="frm_new_user_request" id="frm_new_user_request" onsubmit="return validate_frm_new_user_request();">_x000D_
<center>_x000D_
<table>_x000D_
_x000D_
        <tr align="left">_x000D_
            <td><Label>ISID<em>*:</Label><input maxlength="15" id="u_userid" name="u_userid" size="20" type="text"/></td>_x000D_
            </tr>_x000D_
_x000D_
<tr>_x000D_
            <td align="center" colspan="4">_x000D_
                <input type="image" src="btn.png" border="0" ALT="Create New Request">_x000D_
_x000D_
                </td>_x000D_
        </tr>_x000D_
    </table>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

php timeout - set_time_limit(0); - don't work

ini_set('max_execution_time', 300);

use this

How to add a jar in External Libraries in android studio

A simple way to add Jar file Android Studio Steps:

  1. Copy and paste your jar file to libs folder of your project.
  2. Click File from File menu -> Project Structure (CTRL + SHIFT + ALT + S on Windows/Linux, ? + ; on Mac OS X).
  3. Select Modules at the left panel -> Dependencies tab.
  4. Add... ? Project Library ? Attach Jar.

React PropTypes : Allow different types of PropTypes for one prop

Here is pro example of using multi proptypes and single proptype.

import React, { Component } from 'react';
import { string, shape, array, oneOfType } from 'prop-types';

class MyComponent extends Component {
  /**
   * Render
   */
  render() {
    const { title, data } = this.props;

    return (
      <>
        {title}
        <br />
        {data}
      </>
    );
  }
}

/**
 * Define component props
 */
MyComponent.propTypes = {
  data: oneOfType([array, string, shape({})]),
  title: string,
};

export default MyComponent;

How to run console application from Windows Service?

As pierre said, there is no way to have a user interface for a windows service (or no easy way). What I do in that kind of situation is to have a settings file that is read from the service on whatever interval the service operates on and have a standalone application that makes changes to the settings file.

Where are static variables stored in C and C++?

they're both going to be stored independently, however if you want to make it clear to other developers you might want to wrap them up in namespaces.

How can I get the nth character of a string?

char* str = "HELLO";
char c = str[1];

Keep in mind that arrays and strings in C begin indexing at 0 rather than 1, so "H" is str[0], "E" is str[1], the first "L" is str[2] and so on.

Get the item doubleclick event of listview

i see this subject is high on google, there is my simple and working sample :)

XAML:

    <ListView Name="MainTCList" HorizontalAlignment="Stretch" MinHeight="440" Height="Auto" Margin="10,10,5.115,4" VerticalAlignment="Stretch" MinWidth="500" Width="Auto" Grid.Column="0" MouseDoubleClick="MainTCList_MouseDoubleClick" IsSynchronizedWithCurrentItem="True">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="UserTID" DisplayMemberBinding="{Binding UserTID}" Width="80"/>
                <GridViewColumn Header="Title" DisplayMemberBinding="{Binding Title}" Width="410" />
            </GridView>
        </ListView.View>
    </ListView>

C#

    private void MainTCList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
            TC item = (TC)MainTCList.Items.CurrentItem;
            Wyswietlacz.Content = item.UserTID;  
    }

Wyswietlacz is a test Label to see item content :) I add here in this last line a method to Load Page with data from item.

In Bootstrap 3,How to change the distance between rows in vertical?

Instead of adding any tag which is never a good solution. You can always use margin property with the required element.

You can add the margin on row class itself. So it will affect globally.

.row{
  margin-top: 30px;
  margin-bottom: 30px
}

Update: Better solution in all cases would be to introduce a new class and then use it along with .row class.

.row-m-t{
  margin-top : 20px
}

Then use it wherever you want

<div class="row row-m-t"></div>

PHP: HTTP or HTTPS?

If the request was sent with HTTPS you will have a extra parameter in the $_SERVER superglobal - $_SERVER['HTTPS']. You can check if it is set or not

if( isset($_SERVER['HTTPS'] ) ) {

std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

They are not really same mutexes, lock_guard<muType> has nearly the same as std::mutex, with a difference that it's lifetime ends at the end of the scope (D-tor called) so a clear definition about these two mutexes :

lock_guard<muType> has a mechanism for owning a mutex for the duration of a scoped block.

And

unique_lock<muType> is a wrapper allowing deferred locking, time-constrained attempts at locking, recursive locking, transfer of lock ownership, and use with condition variables.

Here is an example implemetation :

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <chrono>

using namespace std::chrono;

class Product{

   public:

       Product(int data):mdata(data){
       }

       virtual~Product(){
       }

       bool isReady(){
       return flag;
       }

       void showData(){

        std::cout<<mdata<<std::endl;
       }

       void read(){

         std::this_thread::sleep_for(milliseconds(2000));

         std::lock_guard<std::mutex> guard(mmutex);

         flag = true;

         std::cout<<"Data is ready"<<std::endl;

         cvar.notify_one();

       }

       void task(){

       std::unique_lock<std::mutex> lock(mmutex);

       cvar.wait(lock, [&, this]() mutable throw() -> bool{ return this->isReady(); });

       mdata+=1;

       }

   protected:

    std::condition_variable cvar;
    std::mutex mmutex;
    int mdata;
    bool flag = false;

};

int main(){

     int a = 0;
     Product product(a);

     std::thread reading(product.read, &product);
     std::thread setting(product.task, &product);

     reading.join();
     setting.join();


     product.showData();
    return 0;
}

In this example, i used the unique_lock<muType> with condition variable

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

Difference between 'cls' and 'self' in Python classes?

Instead of accepting a self parameter, class methods take a cls parameter that points to the class—and not the object instance—when the method is called. Since the class method only has access to this cls argument, it can’t modify object instance state. That would require access to self . However, class methods can still modify class state that applies across all instances of the class.

-Python Tricks

Last element in .each() set

each passes into your function index and element. Check index against the length of the set and you're good to go:

var set = $('.requiredText');
var length = set.length;
set.each(function(index, element) {
      thisVal = $(this).val();
      if(parseInt(thisVal) !== 0) {
          console.log('Valid Field: ' + thisVal);
          if (index === (length - 1)) {
              console.log('Last field, submit form here');
          }
      }
});

jQuery Upload Progress and AJAX file upload

Here are some options for using AJAX to upload files:

UPDATE: Here is a JQuery plug-in for Multiple File Uploading.

Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo

It appears to only be availabe using the mysqlnd driver.
Try replacing it with the integer it represents; 1002, if I am not mistaken.

How to detect incoming calls, in an Android device?

With Android P - Api Level 28: You need to get READ_CALL_LOG permission

Restricted access to call logs

Android P moves the CALL_LOG, READ_CALL_LOG, WRITE_CALL_LOG, and PROCESS_OUTGOING_CALLS permissions from the PHONE permission group to the new CALL_LOG permission group. This group gives users better control and visibility to apps that need access to sensitive information about phone calls, such as reading phone call records and identifying phone numbers.

To read numbers from the PHONE_STATE intent action, you need both the READ_CALL_LOG permission and the READ_PHONE_STATE permission. To read numbers from onCallStateChanged(), you now need the READ_CALL_LOG permission only. You no longer need the READ_PHONE_STATE permission.

'JSON' is undefined error in JavaScript in Internet Explorer

Change the content type to 'application/x-www-form-urlencoded'

Force Internet Explorer to use a specific Java Runtime Environment install?

I'd give all the responses here a try first. But I wanted to just throw in what I do, just in case these do not work for you.

I've tried to solve the same problem you're having before, and in the end, what I decided on doing is to have only one JRE installed on my system at a given time. I do have about 10 different JDKs (1.3 through 1.6, and from various vendors - Sun, Oracle, IBM), since I do need it for development, but only one standalone JRE.

This has worked for me on my Windows 2000 + IE 6 computer at home, as well as my Windows XP + Multiple IE computer at work.

Using the rJava package on Win7 64 bit with R

The last question has an easy answer:

> .Machine$sizeof.pointer
[1] 8

Meaning I am running R64. If I were running 32 bit R it would return 4. Just because you are running a 64 bit OS does not mean you will be running 64 bit R, and from the error message it appears you are not.

EDIT: If the package has binaries, then they are in separate directories. The specifics will depend on the OS. Notice that your LoadLibrary error occurred when it attempted to find the dll in ...rJava/libs/x64/... On my MacOS system the ...rJava/libs/...` folder has 3 subdirectories: i386, ppc, and x86_64. (The ppc files are obviously useless baggage.)

How to replace substrings in windows batch file

I have made a function for that, you only call it in a batch program within needing to code more.

The working is basically the same as the others, as it's the best way to do it.
Here's the link where I have that function

CSS selector for "foo that contains bar"?

Is there any way you could programatically apply a class to the object?

<object class="hasparams">

then do

object.hasparams

Filter df when values matches part of a string in pyspark

When filtering a DataFrame with string values, I find that the pyspark.sql.functions lower and upper come in handy, if your data could have column entries like "foo" and "Foo":

import pyspark.sql.functions as sql_fun
result = source_df.filter(sql_fun.lower(source_df.col_name).contains("foo"))

How to select unique records by SQL

There are 4 methods you can use:

  1. DISTINCT
  2. GROUP BY
  3. Subquery
  4. Common Table Expression (CTE) with ROW_NUMBER()

Consider the following sample TABLE with test data:

/** Create test table */
CREATE TEMPORARY TABLE dupes(word text, num int, id int);

/** Add test data with duplicates */
INSERT INTO dupes(word, num, id)
VALUES ('aaa', 100, 1)
      ,('bbb', 200, 2)
      ,('ccc', 300, 3)
      ,('bbb', 400, 4)
      ,('bbb', 200, 5)     -- duplicate
      ,('ccc', 300, 6)     -- duplicate
      ,('ddd', 400, 7)
      ,('bbb', 400, 8)     -- duplicate
      ,('aaa', 100, 9)     -- duplicate
      ,('ccc', 300, 10);   -- duplicate

Option 1: SELECT DISTINCT

This is the most simple and straight forward, but also the most limited way:

SELECT DISTINCT word, num 
FROM    dupes
ORDER BY word, num;

/*
word|num|
----|---|
aaa |100|
bbb |200|
bbb |400|
ccc |300|
ddd |400|
*/

Option 2: GROUP BY

Grouping allows you to add aggregated data, like the min(id), max(id), count(*), etc:

SELECT  word, num, min(id), max(id), count(*)
FROM    dupes
GROUP BY word, num
ORDER BY word, num;

/*
word|num|min|max|count|
----|---|---|---|-----|
aaa |100|  1|  9|    2|
bbb |200|  2|  5|    2|
bbb |400|  4|  8|    2|
ccc |300|  3| 10|    3|
ddd |400|  7|  7|    1|
*/

Option 3: Subquery

Using a subquery, you can first identify the duplicate rows to ignore, and then filter them out in the outer query with the WHERE NOT IN (subquery) construct:

/** Find the higher id values of duplicates, distinct only added for clarity */
    SELECT  distinct d2.id
    FROM    dupes d1
        INNER JOIN dupes d2 ON d2.word=d1.word AND d2.num=d1.num
    WHERE d2.id > d1.id

/*
id|
--|
 5|
 6|
 8|
 9|
10|
*/

/** Use the previous query in a subquery to exclude the dupliates with higher id values */
SELECT  *
FROM    dupes
WHERE   id NOT IN (
    SELECT  d2.id
    FROM    dupes d1
        INNER JOIN dupes d2 ON d2.word=d1.word AND d2.num=d1.num
    WHERE d2.id > d1.id
)
ORDER BY word, num;

/*
word|num|id|
----|---|--|
aaa |100| 1|
bbb |200| 2|
bbb |400| 4|
ccc |300| 3|
ddd |400| 7|
*/

Option 4: Common Table Expression with ROW_NUMBER()

In the Common Table Expression (CTE), select the ROW_NUMBER(), partitioned by the group column and ordered in the desired order. Then SELECT only the records that have ROW_NUMBER() = 1:

WITH CTE AS (
    SELECT  *
           ,row_number() OVER(PARTITION BY word, num ORDER BY id) AS row_num
    FROM    dupes
)
SELECT  word, num, id 
FROM    cte
WHERE   row_num = 1
ORDER BY word, num;

/*
word|num|id|
----|---|--|
aaa |100| 1|
bbb |200| 2|
bbb |400| 4|
ccc |300| 3|
ddd |400| 7|
*/

How to fix git error: RPC failed; curl 56 GnuTLS

All I did was disconnect and reconnect my pc from the wifi and it worked. Sometimes the answer might be very simple. Mine works now

Add a common Legend for combined ggplots

If you are plotting the same variables in both plots, the simplest way would be to combine the data frames into one, then use facet_wrap.

For your example:

big_df <- rbind(df1,df2)

big_df <- data.frame(big_df,Df = rep(c("df1","df2"),
times=c(nrow(df1),nrow(df2))))

ggplot(big_df,aes(x=x, y=y,colour=group)) 
+ geom_point(position=position_jitter(w=0.04,h=0.02),size=1.8) 
+ facet_wrap(~Df)

Plot 1

Another example using the diamonds data set. This shows that you can even make it work if you have only one variable common between your plots.

diamonds_reshaped <- data.frame(price = diamonds$price,
independent.variable = c(diamonds$carat,diamonds$cut,diamonds$color,diamonds$depth),
Clarity = rep(diamonds$clarity,times=4),
Variable.name = rep(c("Carat","Cut","Color","Depth"),each=nrow(diamonds)))

ggplot(diamonds_reshaped,aes(independent.variable,price,colour=Clarity)) + 
geom_point(size=2) + facet_wrap(~Variable.name,scales="free_x") + 
xlab("")

Plot 2

Only tricky thing with the second example is that the factor variables get coerced to numeric when you combine everything into one data frame. So ideally, you will do this mainly when all your variables of interest are the same type.

DB query builder toArray() laravel 4

And another solution

$objectData = DB::table('user')
    ->select('column1', 'column2')
    ->where('name', '=', 'Jhon')
    ->get();
$arrayData = array_map(function($item) {
    return (array)$item; 
}, $objectData->toArray());

It good in case when you need only several columns from entity.

How to write multiple line string using Bash with variables?

I'm using Mac OS and to write multiple lines in a SH Script following code worked for me

#! /bin/bash
FILE_NAME="SomeRandomFile"

touch $FILE_NAME

echo """I wrote all
the  
stuff
here.
And to access a variable we can use
$FILE_NAME  

""" >> $FILE_NAME

cat $FILE_NAME

Please don't forget to assign chmod as required to the script file. I have used

chmod u+x myScriptFile.sh

How to pad a string to a fixed length with spaces in Python?

name = "John" // your variable
result = (name+"               ")[:15] # this adds 15 spaces to the "name"
                                       # but cuts it at 15 characters

How do I get the APK of an installed app without root access?

Open ES explorer -> push Menu button at the left upper corner (three horizontal stripes) -> in the Libraries section choose APPs.

Thus, you get the list of all the user apps. Find your app and select it with long pushing on it. Then press "More" in the right low corner and choose "Send". Then you can use different options, e.g. you can choose "ES Save To" in order to save the .apk file to your home directory or anywhere else.

File Upload with Angular Material

html:
    <div class="upload">
        <span>upload image</span>
        <input
          #Image
          type="file"
          (change)="handleFileInput($event.target.files)"
          accept=".jpg,.svg,.png,.jpeg"
        />
        <img
          width="100%"
          height="100%"
          *ngIf="imageUrl"
          [src]="imageUrl"
          class="image"
        />
    </div>

app.component.ts

export class AppComponent {
  options = [{ value: "This is value 1", checked: true }];
  statuses = ["control"];

  // name = "Angular";//
  fileToUpload: any;
  imageUrl: any;
  handleFileInput(file: FileList) {
    this.fileToUpload = file.item(0);

    //Show image preview
    let reader = new FileReader();
    reader.onload = (event: any) => {
      this.imageUrl = event.target.result;
    };
    reader.readAsDataURL(this.fileToUpload);
  }
}

Why does datetime.datetime.utcnow() not contain timezone information?

from datetime import datetime 
from dateutil.relativedelta import relativedelta
d = datetime.now()
date = datetime.isoformat(d).split('.')[0]
d_month = datetime.today() + relativedelta(months=1)
next_month = datetime.isoformat(d_month).split('.')[0]

How do I load a file from resource folder?

Non spring project:

String filePath = Objects.requireNonNull(getClass().getClassLoader().getResource("any.json")).getPath();

Stream<String> lines = Files.lines(Paths.get(filePath));

Or

String filePath = Objects.requireNonNull(getClass().getClassLoader().getResource("any.json")).getPath();

InputStream in = new FileInputStream(filePath);

For spring projects, you can also use one line code to get any file under resources folder:

File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "any.json");

String content = new String(Files.readAllBytes(file.toPath()));

Java - What does "\n" mean?

Its is a new line

Escape Sequences
Escape Sequence Description
\t  Insert a tab in the text at this point.
\b  Insert a backspace in the text at this point.
\n  Insert a newline in the text at this point.
\r  Insert a carriage return in the text at this point.
\f  Insert a formfeed in the text at this point.
\'  Insert a single quote character in the text at this point.
\"  Insert a double quote character in the text at this point.
\\  Insert a backslash character in the text at this point.

http://docs.oracle.com/javase/tutorial/java/data/characters.html

Append text to input field

If you are planning to use appending more then once, you might want to write a function:

//Append text to input element
function jQ_append(id_of_input, text){
    var input_id = '#'+id_of_input;
    $(input_id).val($(input_id).val() + text);
}

After you can just call it:

jQ_append('my_input_id', 'add this text');

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

Select and display only duplicate records in MySQL

Hi above answer will not work if I want to select one or more column value which is not same or may be same for both row data

For Ex. I want to select username, birth date also. But in database is username is not duplicate but birth date will be duplicate then this solution will not work.

For this use this solution Need to take self join on same table/

SELECT  
    distinct(p1.id),  p1.payer_email , p1.username, p1.birth_date

FROM 
    paypal_ipn_orders AS p1 

INNER JOIN paypal_ipn_orders AS p2 

ON p1.payer_email=p2.payer_email

WHERE 

p1.birth_date=p2.birth_date

Above query will return all records having same email_id and same birth date

What is difference between functional and imperative programming languages?

Definition: An imperative language uses a sequence of statements to determine how to reach a certain goal. These statements are said to change the state of the program as each one is executed in turn.

Examples: Java is an imperative language. For example, a program can be created to add a series of numbers:

 int total = 0;
 int number1 = 5;
 int number2 = 10;
 int number3 = 15;
 total = number1 + number2 + number3; 

Each statement changes the state of the program, from assigning values to each variable to the final addition of those values. Using a sequence of five statements the program is explicitly told how to add the numbers 5, 10 and 15 together.

Functional languages: The functional programming paradigm was explicitly created to support a pure functional approach to problem solving. Functional programming is a form of declarative programming.

Advantages of Pure Functions: The primary reason to implement functional transformations as pure functions is that pure functions are composable: that is, self-contained and stateless. These characteristics bring a number of benefits, including the following: Increased readability and maintainability. This is because each function is designed to accomplish a specific task given its arguments. The function does not rely on any external state.

Easier reiterative development. Because the code is easier to refactor, changes to design are often easier to implement. For example, suppose you write a complicated transformation, and then realize that some code is repeated several times in the transformation. If you refactor through a pure method, you can call your pure method at will without worrying about side effects.

Easier testing and debugging. Because pure functions can more easily be tested in isolation, you can write test code that calls the pure function with typical values, valid edge cases, and invalid edge cases.

For OOP People or Imperative languages:

Object-oriented languages are good when you have a fixed set of operations on things and as your code evolves, you primarily add new things. This can be accomplished by adding new classes which implement existing methods and the existing classes are left alone.

Functional languages are good when you have a fixed set of things and as your code evolves, you primarily add new operations on existing things. This can be accomplished by adding new functions which compute with existing data types and the existing functions are left alone.

Cons:

It depends on the user requirements to choose the way of programming, so there is harm only when users don’t choose the proper way.

When evolution goes the wrong way, you have problems:

  • Adding a new operation to an object-oriented program may require editing many class definitions to add a new method
  • Adding a new kind of thing to a functional program may require editing many function definitions to add a new case.

Finding all positions of substring in a larger string in C#

Hi nice answer by @Matti Virkkunen

public static List<int> AllIndexesOf(this string str, string value) {
    if (String.IsNullOrEmpty(value))
        throw new ArgumentException("the string to find may not be empty", "value");
    List<int> indexes = new List<int>();
    for (int index = 0;; index += value.Length) {
        index = str.IndexOf(value, index);
        if (index == -1)
            return indexes;
        indexes.Add(index);
        index--;
    }
}

But this covers tests cases like AOOAOOA where substring

are AOOA and AOOA

Output 0 and 3

Get response from PHP file using AJAX

var data="your data";//ex data="id="+id;
      $.ajax({
       method : "POST",
       url : "file name",  //url: "demo.php"
       data : "data",
       success : function(result){
               //set result to div or target 
              //ex $("#divid).html(result)
        }
   });

Select objects based on value of variable in object using jq

To obtain a stream of just the names:

$ jq '.[] | select(.location=="Stockholm") | .name' json

produces:

"Donald"
"Walt"

To obtain a stream of corresponding (key name, "name" attribute) pairs, consider:

$ jq -c 'to_entries[]
        | select (.value.location == "Stockholm")
        | [.key, .value.name]' json

Output:

["FOO","Donald"]
["BAR","Walt"]

The model backing the 'ApplicationDbContext' context has changed since the database was created

remove all tables identity

Delete _MigrationHistory
Delete AspNetRoles
Delete AspNetUserClaims
Delete AspNetUserLogins
Delete AspNetRoles
Delete AspNetUser

TypeError: 'DataFrame' object is not callable

It seems you need DataFrame.var:

Normalized by N-1 by default. This can be changed using the ddof argument

var1 = credit_card.var()

Sample:

#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
   A  B  C  D  E
0  8  8  3  7  7
1  0  4  2  5  2
2  2  2  1  0  8
3  4  0  9  6  2
4  4  1  5  3  4

var1 = credit_card.var()
print (var1)
A     8.8
B    10.0
C    10.0
D     7.7
E     7.8
dtype: float64

var2 = credit_card.var(axis=1)
print (var2)
0     4.3
1     3.8
2     9.8
3    12.2
4     2.3
dtype: float64

If need numpy solutions with numpy.var:

print (np.var(credit_card.values, axis=0))
[ 7.04  8.    8.    6.16  6.24]

print (np.var(credit_card.values, axis=1))
[ 3.44  3.04  7.84  9.76  1.84]

Differences are because by default ddof=1 in pandas, but you can change it to 0:

var1 = credit_card.var(ddof=0)
print (var1)
A    7.04
B    8.00
C    8.00
D    6.16
E    6.24
dtype: float64

var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0    3.44
1    3.04
2    7.84
3    9.76
4    1.84
dtype: float64

Counting the number of elements in array

Best practice of getting length is use length filter returns the number of items of a sequence or mapping, or the length of a string. For example: {{ notcount | length }}

But you can calculate count of elements in for loop. For example:

{% set count = 0 %}
{% for nc in notcount %}
    {% set count = count + 1 %}
{% endfor %}

{{ count }}

This solution helps if you want to calculate count of elements by condition, for example you have a property name inside object and you want to calculate count of objects with not empty names:

{% set countNotEmpty = 0 %}
{% for nc in notcount if nc.name %}
    {% set countNotEmpty = countNotEmpty + 1 %}
{% endfor %}

{{ countNotEmpty }}

Useful links:

ORA-12170: TNS:Connect timeout occurred

Beside the oci.dll there are a few .jar files. This gave me the idea to install Java. Then everything worked.

Fastest way to check if a string is JSON in PHP?

Hi here's a little snippet from my library, in this first condition I'm just checking if the data is json then return it if correctly decoded, please note the substr usage for performance ( I haven't seen yet any json file not begining neither by { or [

$input=trim($input);
if ((substr($input, 0, 1) == '{' && substr($input, -1) == '}') or (substr($input, 0, 1) == '[' && substr($input, -1) == ']')) {
    $output = json_decode($input, 1);
    if (in_array(gettype($output),['object','array'])) {
        #then it's definitely JSON
    }
}

NSURLErrorDomain error codes description

I received the error Domain=NSURLErrorDomain Code=-1011 when using Parse, and providing the wrong clientKey. As soon as I corrected that, it began working.

How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?

i called activity_name.this.finish() after starting new intent and it worked for me.

I tried "FLAG_ACTIVITY_CLEAR_TOP" and "FLAG_ACTIVITY_NEW_TASK"

But it won't work for me... I am not suggesting this solution for use but if setting flag won't work for you than you can try this..But still i recommend don't use it

exception.getMessage() output with class name

My guess is that you've got something in method1 which wraps one exception in another, and uses the toString() of the nested exception as the message of the wrapper. I suggest you take a copy of your project, and remove as much as you can while keeping the problem, until you've got a short but complete program which demonstrates it - at which point either it'll be clear what's going on, or we'll be in a better position to help fix it.

Here's a short but complete program which demonstrates RuntimeException.getMessage() behaving correctly:

public class Test {
    public static void main(String[] args) {
        try {
            failingMethod();
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }       

    private static void failingMethod() {
        throw new RuntimeException("Just the message");
    }
}

Output:

Error: Just the message

Print Html template in Angular 2 (ng-print in Angular 2)

The best option I found to solve this without getting into trouble with my styles was using a separate route for my printed output and load this route into an iframe.

My surrounding component is shown as a tab page.

@Component({
  template: '<iframe id="printpage" name="printpage" *ngIf="printSrc" [src]="printSrc"></iframe>',
  styleUrls: [ 'previewTab.scss' ]
})
export class PreviewTabPage {
  printSrc: SafeUrl;

  constructor(
    private navParams: NavParams,
    private sanitizer: DomSanitizer,
  ) {
    // item to print is passed as url parameter
    const itemId = navParams.get('itemId');

    // set print page source for iframe in template
    this.printSrc = this.sanitizer.bypassSecurityTrustResourceUrl(this.getAbsoluteUrl(itemId));
  }

  getAbsoluteUrl(itemId: string): string {
    // some code to generate an absolute url for your item
    return itemUrl;
  }
}

The iframe just loads the print route that renders a print component in the app. In this page the print might be triggered after the view is fully initialized. Another way could be a print button on the parent component that triggers the print on the iframe by window.frames["printpage"].print();.

@Component({
  templateUrl: './print.html',
  styleUrls: [ 'print.scss' ]
})
export class PrintPage implements AfterViewInit {

  constructor() {}

  ngAfterViewInit() {
    // wait some time, so all images or other async data are loaded / rendered.
    // print could be triggered after button press in the parent component as well.
    setTimeout(() => {
      // print current iframe
      window.print();
    }, 2000);
  }

}

How to change text transparency in HTML/CSS?

Easy! after your:

    <font color=\"black\" face=\"arial\" size=\"4\">

add this one:

    <font style="opacity:.6"> 

you just have to change the ".6" for a decimal number between 1 and 0

Does overflow:hidden applied to <body> work on iPhone Safari?

Its working in Safari browser.

html,
body {
  overflow: hidden;
  position: fixed
}

setTimeout / clearTimeout problems

The problem is that the timer variable is local, and its value is lost after each function call.

You need to persist it, you can put it outside the function, or if you don't want to expose the variable as global, you can store it in a closure, e.g.:

var endAndStartTimer = (function () {
  var timer; // variable persisted here
  return function () {
    window.clearTimeout(timer);
    //var millisecBeforeRedirect = 10000; 
    timer = window.setTimeout(function(){alert('Hello!');},10000); 
  };
})();

Remove characters from C# string

It seems that the shortest way is to combine LINQ and string.Concat:

var input = @"My name @is ,Wan.;'; Wan";
var chrs = new[] {'@', ',', '.', ';', '\''};
var result = string.Concat(input.Where(c => !chrs.Contains(c)));
// => result = "My name is Wan Wan" 

See the C# demo. Note that string.Concat is a shortcut to string.Join("", ...).

Note that using a regex to remove individual known chars is still possible to build dynamically, although it is believed that regex is slower. However, here is a way to build such a dynamic regex (where all you need is a character class):

var pattern = $"[{Regex.Escape(new string(chrs))}]+";
var result = Regex.Replace(input, pattern, string.Empty);

See another C# demo. The regex will look like [@,\.;']+ (matching one or more (+) consecutive occurrences of @, ,, ., ; or ' chars) where the dot does not have to be escaped, but Regex.Escape will be necessary to escape other chars that must be escaped, like \, ^, ] or - whose position inside the character class you cannot predict.

What does the ELIFECYCLE Node.js error mean?

In my case I generated a similar error when I copied the project over from another directory. some hidden files, like the critical .babelrc, were missing. SO ahhh... make sure you copy all the files! :)

How to compare two vectors for equality element by element in C++?

According to the discussion here you can directly compare two vectors using

==

if (vector1 == vector2){
   //true
}
else{
   //false
}

Count distinct values

You can do a distinct count as follows:

SELECT COUNT(DISTINCT column_name) FROM table_name;

EDIT:

Following your clarification and update to the question, I see now that it's quite a different question than we'd originally thought. "DISTINCT" has special meaning in SQL. If I understand correctly, you want something like this:

  • 2 customers had 1 pets
  • 3 customers had 2 pets
  • 1 customers had 3 pets

Now you're probably going to want to use a subquery:

select COUNT(*) column_name FROM (SELECT DISTINCT column_name);

Let me know if this isn't quite what you're looking for.

how to put image in center of html page?

If:

X is image width,
Y is image height,

then:

img {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -(X/2)px;
    margin-top: -(Y/2)px;
}

But keep in mind this solution is valid only if the only element on your site will be this image. I suppose that's the case here.

Using this method gives you the benefit of fluidity. It won't matter how big (or small) someone's screen is. The image will always stay in the middle.

Remove multiple items from a Python list in just one statement

I don't know why everyone forgot to mention the amazing capability of sets in python. You can simply cast your list into a set and then remove whatever you want to remove in a simple expression like so:

>>> item_list = ['item', 5, 'foo', 3.14, True]
>>> item_list = set(item_list) - {'item', 5}
>>> item_list
{True, 3.14, 'foo'}
>>> # you can cast it again in a list-from like so
>>> item_list = list(item_list)
>>> item_list
[True, 3.14, 'foo']

Detect if PHP session exists

function is_session_started()
{
    if ( php_sapi_name() !== 'cli' ) {
        if ( version_compare(phpversion(), '5.4.0', '>=') ) {
            return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
        } else {
            return session_id() === '' ? FALSE : TRUE;
        }
    }
    return FALSE;
}

// Example
if ( is_session_started() === FALSE ) session_start();

How do I pull files from remote without overwriting local files?

You can stash your local changes first, then pull, then pop the stash.

git stash
git pull origin master
git stash pop

Anything that overrides changes from remote will have conflicts which you will have to manually resolve.