Programs & Examples On #Capicom

CAPICOM is a discontinued ActiveX control created by Microsoft to help expose a select set of Microsoft Cryptographic Application Programming Interface (CryptoAPI) functions through Microsoft Component Object Model (COM). It was intended to enable every environment that supports ActiveX to use Microsoft Cryptographic technologies, including web pages that are opened with Microsoft Internet Explorer or any other web browser that supports ActiveX.

Display Records From MySQL Database using JTable in Java

If you need to work a lot with database in your code and you know the structure of your table, I suggest you do it as follow:

First of all you can define a class which will help you to make objects capable of keeping your table rows data. For example in my project I created a class named Document.java to keep data of a single document from my database and I made an array list of these objects to keep data of my table which is gain by a query.

package financialdocuments;

import java.lang.*;
import java.util.HashMap;

/**
 *
 * @author Administrator
 */
public class Document {

 private int document_number; 
 private boolean document_type;
 private boolean document_status; 
 private StringBuilder document_date;
 private StringBuilder document_statement;
 private int document_code_number;
 private int document_employee_number;
 private int document_client_number;
 private String document_employee_name;
 private String document_client_name;
 private long document_amount;
 private long document_payment_amount;

 HashMap<Integer,Activity> document_activity_hashmap;


public Document(int dn,boolean dt,boolean ds,String dd,String dst,int dcon,int den,int dcln,long da,String dena,String dcna){

    document_date = new StringBuilder(dd);
    document_date.setLength(10);
    document_date.setCharAt(4, '.');
    document_date.setCharAt(7, '.');
    document_statement = new StringBuilder(dst);
    document_statement.setLength(50);
    document_number = dn; 
    document_type = dt;
    document_status = ds;
    document_code_number = dcon;
    document_employee_number = den;
    document_client_number = dcln;
    document_amount = da;
    document_employee_name = dena;
    document_client_name = dcna;

    document_payment_amount = 0;

    document_activity_hashmap = new HashMap<>();

}

public Document(int dn,boolean dt,boolean ds, long dpa){

    document_number = dn; 
    document_type = dt;
    document_status = ds;

    document_payment_amount = dpa;

    document_activity_hashmap = new HashMap<>();

}

// Print document information 
public void printDocumentInformation (){
    System.out.println("Document Number:" + document_number); 
    System.out.println("Document Date:" + document_date); 
    System.out.println("Document Type:" + document_type); 
    System.out.println("Document Status:" + document_status); 
    System.out.println("Document Statement:" + document_statement); 
    System.out.println("Document Code Number:" + document_code_number); 
    System.out.println("Document Client Number:" + document_client_number); 
    System.out.println("Document Employee Number:" + document_employee_number); 
    System.out.println("Document Amount:" + document_amount); 
    System.out.println("Document Payment Amount:" + document_payment_amount); 
    System.out.println("Document Employee Name:" + document_employee_name); 
    System.out.println("Document Client Name:" + document_client_name); 

} 
} 

Second of all, you can define a class to handle your database needs. For example I defined a class named DataBase.java which handles my connections to the database and my needed queries. And I instantiated an objected of it in my main class.

package financialdocuments;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class DataBase {

/** 
 * 
 * Defining parameters and strings that are going to be used
 * 
 */
//Connection connect;

// Tables which their datas are extracted at the beginning 
HashMap<Integer,String> code_table;
HashMap<Integer,String> activity_table;
HashMap<Integer,String> client_table;
HashMap<Integer,String> employee_table;

// Resultset Returned by queries 
private ResultSet result;

// Strings needed to set connection
String url = "jdbc:mysql://localhost:3306/financial_documents?useUnicode=yes&characterEncoding=UTF-8";
String dbName = "financial_documents";
String driver = "com.mysql.jdbc.Driver";
String userName = "root"; 
String password = "";

public DataBase(){

    code_table = new HashMap<>();
    activity_table = new HashMap<>();
    client_table = new HashMap<>();
    employee_table = new HashMap<>();
    Initialize();

}

/**
 * Set variables and objects for this class.
 */
private void Initialize(){

    System.out.println("Loading driver..."); 
    try {
        Class.forName(driver);
        System.out.println("Driver loaded!"); 
    } catch (ClassNotFoundException e) { 
        throw new IllegalStateException("Cannot find the driver in the classpath!", e); 
    }

    System.out.println("Connecting database...");

try (Connection connect = DriverManager.getConnection(url,userName,password)) {
            System.out.println("Database connected!");
            //Get tables' information 
            selectCodeTableQueryArray(connect);
           // System.out.println("HshMap Print:");
           // printCodeTableQueryArray();

            selectActivityTableQueryArray(connect);
           // System.out.println("HshMap Print:");
           // printActivityTableQueryArray(); 

            selectClientTableQueryArray(connect);
           // System.out.println("HshMap Print:");
           // printClientTableQueryArray();

            selectEmployeeTableQueryArray(connect);
           // System.out.println("HshMap Print:");
           // printEmployeeTableQueryArray();

            connect.close();
    }catch (SQLException e) { 
        throw new IllegalStateException("Cannot connect the database!", e);
    }

} 

/**
 * Write Queries 
 * @param s
 * @return 
 */
public boolean insertQuery(String s){

    boolean ret = false;
    System.out.println("Loading driver..."); 
    try {
        Class.forName(driver);
        System.out.println("Driver loaded!"); 
    } catch (ClassNotFoundException e) { 
        throw new IllegalStateException("Cannot find the driver in the classpath!", e); 
    }

    System.out.println("Connecting database...");

try (Connection connect = DriverManager.getConnection(url,userName,password)) {
            System.out.println("Database connected!");
            //Set tables' information 
            try {
                Statement st = connect.createStatement();
                int val = st.executeUpdate(s);
                if(val==1){ 
                    System.out.print("Successfully inserted value");
                    ret = true;
                }
                else{ 
                    System.out.print("Unsuccessful insertion");
                    ret = false;
                }
                st.close();
            } catch (SQLException ex) {
                Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
            }
            connect.close();
    }catch (SQLException e) { 
        throw new IllegalStateException("Cannot connect the database!", e);
    } 
    return ret;
}

/**
 * Query needed to get code table's data
 * @param c
 * @return 
 */
private void selectCodeTableQueryArray(Connection c) {
    try {
        Statement st = c.createStatement();
        ResultSet res = st.executeQuery("SELECT * FROM  code;");
        while (res.next()) {
                int id = res.getInt("code_number");
                String msg = res.getString("code_statement");
                code_table.put(id, msg);
            }
        st.close();
    } catch (SQLException ex) {
        Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private void printCodeTableQueryArray() {
    for (HashMap.Entry<Integer ,String> entry : code_table.entrySet()){
        System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
    }
}

/**
 * Query needed to get activity table's data
 * @param c
 * @return 
 */
private void selectActivityTableQueryArray(Connection c) {
    try {
        Statement st = c.createStatement();
        ResultSet res = st.executeQuery("SELECT * FROM  activity;");
        while (res.next()) {
                int id = res.getInt("activity_number");
                String msg = res.getString("activity_statement");
                activity_table.put(id, msg);
            }
        st.close();
    } catch (SQLException ex) {
        Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private void printActivityTableQueryArray() {
    for (HashMap.Entry<Integer ,String> entry : activity_table.entrySet()){
        System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
    }
}

/**
 * Query needed to get client table's data
 * @param c
 * @return 
 */
private void selectClientTableQueryArray(Connection c) {
    try {
        Statement st = c.createStatement();
        ResultSet res = st.executeQuery("SELECT * FROM  client;");
        while (res.next()) {
                int id = res.getInt("client_number");
                String msg = res.getString("client_full_name");
                client_table.put(id, msg);
            }
        st.close();
    } catch (SQLException ex) {
        Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private void printClientTableQueryArray() {
    for (HashMap.Entry<Integer ,String> entry : client_table.entrySet()){
        System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
    }
}

/**
 * Query needed to get activity table's data
 * @param c
 * @return 
 */
private void selectEmployeeTableQueryArray(Connection c) {
    try {
        Statement st = c.createStatement();
        ResultSet res = st.executeQuery("SELECT * FROM  employee;");
        while (res.next()) {
                int id = res.getInt("employee_number");
                String msg = res.getString("employee_full_name");
                employee_table.put(id, msg);
            }
        st.close();
    } catch (SQLException ex) {
        Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private void printEmployeeTableQueryArray() {
    for (HashMap.Entry<Integer ,String> entry : employee_table.entrySet()){
        System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
    }
} 
}

I hope this could be a little help.

Difference between jar and war in Java

War -

distribute Java-based web applications. A WAR has the same file structure as a JAR file, which is a single compressed file that contains multiple files bundled inside it.

Jar -

The .jar files contain libraries, resources and accessories files like property files.

WAR files are used to combine JSPs, servlets, Java class files, XML files, javascript libraries, JAR libraries, static web pages, and any other resources needed to run the application.

How do I enable MSDTC on SQL Server?

Use this for windows Server 2008 r2 and Windows Server 2012 R2

  1. Click Start, click Run, type dcomcnfg and then click OK to open Component Services.

  2. In the console tree, click to expand Component Services, click to expand Computers, click to expand My Computer, click to expand Distributed Transaction Coordinator and then click Local DTC.

  3. Right click Local DTC and click Properties to display the Local DTC Properties dialog box.

  4. Click the Security tab.

  5. Check mark "Network DTC Access" checkbox.

  6. Finally check mark "Allow Inbound" and "Allow Outbound" checkboxes.

  7. Click Apply, OK.

  8. A message will pop up about restarting the service.

  9. Click OK and That's all.

Reference : https://msdn.microsoft.com/en-us/library/dd327979.aspx

Note: Sometimes the network firewall on the Local Computer or the Server could interrupt your connection so make sure you create rules to "Allow Inbound" and "Allow Outbound" connection for C:\Windows\System32\msdtc.exe

PHP MySQL Query Where x = $variable

What you are doing right now is you are adding . on the string and not concatenating. It should be,

$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '".$email."'");

or simply

$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '$email'");

Android Studio 3.0 Execution failed for task: unable to merge dex

I was receiving the same error and in my case, the error was resolved when I fixed a build error which was associated with a different build variant than the one I was currently building.

I was building the build variant I was looking at just fine with no errors, but attempting to debug caused a app:transformDexArchiveWithExternalLibsDexMergerForDebug error. Once I switched to build the other build variant, I caught my error in the build process and fixed it. This seemed to resolve my app:transformDexArchiveWithExternalLibsDexMergerForDebug issue for all build variants.

Note that this error wasn't within the referenced external module but within a distinct source set of a build variant which referenced an external module. Hope that's helpful to someone who may be seeing the same case as me!

Delete all local git branches

To delete every branch except the one that you currently have checked out:

for b in `git branch --merged | grep -v \*`; do git branch -D $b; done

I would recommend changing git branch -D $b to an echo $b the first few times to make sure that it deletes the branches that you intend.

'"SDL.h" no such file or directory found' when compiling

Having a similar case and I couldn't use StackAttacks solution as he's referring to SDL2 which is for the legacy code I'm using too new.

Fortunately our friends from askUbuntu had something similar:

Download SDL

tar xvf SDL-1.2.tar.gz
cd SDL-1.2
./configure
make
sudo make install

check if jquery has been loaded, then load it if false

Method 1:

if (window.jQuery) {  
    // jQuery is loaded  
} else {
    // jQuery is not loaded
}

Method 2:

if (typeof jQuery == 'undefined') {  
    // jQuery is not loaded
} else {
    // jQuery is loaded
}

If jquery.js file is not loaded, we can force load it like so:

if (!window.jQuery) {
  var jq = document.createElement('script'); jq.type = 'text/javascript';
  // Path to jquery.js file, eg. Google hosted version
  jq.src = '/path-to-your/jquery.min.js';
  document.getElementsByTagName('head')[0].appendChild(jq);
}

PHP Accessing Parent Class Variable

echo $this->bb;

The variable is inherited and is not private, so it is a part of the current object.


Here is additional information in response to your request for more information about using parent:::

Use parent:: when you want add extra functionality to a method from the parent class. For example, imagine an Airplane class:

class Airplane {
    private $pilot;

    public function __construct( $pilot ) {
        $this->pilot = $pilot;
    }
}

Now suppose we want to create a new type of Airplane that also has a navigator. You can extend the __construct() method to add the new functionality, but still make use of the functionality offered by the parent:

class Bomber extends Airplane {
    private $navigator;

    public function __construct( $pilot, $navigator ) {
        $this->navigator = $navigator;

        parent::__construct( $pilot ); // Assigns $pilot to $this->pilot
    }
}

In this way, you can follow the DRY principle of development but still provide all of the functionality you desire.

Rails 4 image-path, image-url and asset-url no longer work in SCSS files

I just found out, that by using asset_url helper you solve that problem.

asset_url("backgrounds/pattern.png", image)

Tab space instead of multiple non-breaking spaces ("nbsp")?

There is a simple css for it:

white-space: pre;

It keeps the spaces that you add in the HTML rather than unifying them.

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

Complementing @Bob Jarvis and @dmikam answer, Postgres don't perform a good plan when you don't use LATERAL, below a simulation, in both cases the query data results are the same, but the cost are very different

Table structure

CREATE TABLE ITEMS (
    N INTEGER NOT NULL,
    S TEXT NOT NULL
);

INSERT INTO ITEMS
  SELECT
    (random()*1000000)::integer AS n,
    md5(random()::text) AS s
  FROM
    generate_series(1,1000000);

CREATE INDEX N_INDEX ON ITEMS(N);

Performing JOIN with GROUP BY in subquery without LATERAL

EXPLAIN 
SELECT 
    I.*
FROM ITEMS I
INNER JOIN (
    SELECT 
        COUNT(1), n
    FROM ITEMS
    GROUP BY N
) I2 ON I2.N = I.N
WHERE I.N IN (243477, 997947);

The results

Merge Join  (cost=0.87..637500.40 rows=23 width=37)
  Merge Cond: (i.n = items.n)
  ->  Index Scan using n_index on items i  (cost=0.43..101.28 rows=23 width=37)
        Index Cond: (n = ANY ('{243477,997947}'::integer[]))
  ->  GroupAggregate  (cost=0.43..626631.11 rows=861418 width=12)
        Group Key: items.n
        ->  Index Only Scan using n_index on items  (cost=0.43..593016.93 rows=10000000 width=4)

Using LATERAL

EXPLAIN 
SELECT 
    I.*
FROM ITEMS I
INNER JOIN LATERAL (
    SELECT 
        COUNT(1), n
    FROM ITEMS
    WHERE N = I.N
    GROUP BY N
) I2 ON 1=1 --I2.N = I.N
WHERE I.N IN (243477, 997947);

Results

Nested Loop  (cost=9.49..1319.97 rows=276 width=37)
  ->  Bitmap Heap Scan on items i  (cost=9.06..100.20 rows=23 width=37)
        Recheck Cond: (n = ANY ('{243477,997947}'::integer[]))
        ->  Bitmap Index Scan on n_index  (cost=0.00..9.05 rows=23 width=0)
              Index Cond: (n = ANY ('{243477,997947}'::integer[]))
  ->  GroupAggregate  (cost=0.43..52.79 rows=12 width=12)
        Group Key: items.n
        ->  Index Only Scan using n_index on items  (cost=0.43..52.64 rows=12 width=4)
              Index Cond: (n = i.n)

My Postgres version is PostgreSQL 10.3 (Debian 10.3-1.pgdg90+1)

Get time of specific timezone

You can use getUTCDate() and the related getUTC...() methods to access a time based off UTC time, and then convert.

If you wish, you can use valueOf(), which returns the number of seconds, in UTC, since the Unix epoch, and work with that, but it's likely going to be much more involved.

Saving an image in OpenCV

I suggest you run OpenCV sanity check

Its a serie of small executables located in the bin directory of opencv.

It will check if your camera is ok

How to set DialogFragment's width and height?

One way to control your DialogFragment's width and height is to make sure its dialog respects your view's width and height if their value is WRAP_CONTENT.

Using ThemeOverlay.AppCompat.Dialog

One simple way to achieve this is to make use of the ThemeOverlay.AppCompat.Dialog style that's included in Android Support Library.

DialogFragment with Dialog:

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View view = inflater.inflate(R.layout.dialog_view, null);

    Dialog dialog = new Dialog(getContext(), R.style.ThemeOverlay_AppCompat_Dialog);
    dialog.setContentView(view);
    return dialog;
}

DialogFragment with AlertDialog (caveat: minHeight="48dp"):

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View view = inflater.inflate(R.layout.dialog_view, null);

    AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), R.style.ThemeOverlay_AppCompat_Dialog);
    builder.setView(view);
    return builder.create();
}

You can also set ThemeOverlay.AppCompat.Dialog as the default theme when creating your dialogs, by adding it to your app's xml theme.
Be careful, as many dialogs do need the default minimum width to look good.

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- For Android Dialog. -->
    <item name="android:dialogTheme">@style/ThemeOverlay.AppCompat.Dialog</item>

    <!-- For Android AlertDialog. -->
    <item name="android:alertDialogTheme">@style/ThemeOverlay.AppCompat.Dialog</item>

    <!-- For AppCompat AlertDialog. -->
    <item name="alertDialogTheme">@style/ThemeOverlay.AppCompat.Dialog</item>

    <!-- Other attributes. -->
</style>

DialogFragment with Dialog, making use of android:dialogTheme:

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View view = inflater.inflate(R.layout.dialog_view, null);

    Dialog dialog = new Dialog(getContext());
    dialog.setContentView(view);
    return dialog;
}

DialogFragment with AlertDialog, making use of android:alertDialogTheme or alertDialogTheme (caveat: minHeight="48dp"):

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View view = inflater.inflate(R.layout.dialog_view, null);

    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
    builder.setView(view);
    return builder.create();
}

Bonus

On Older Android APIs, Dialogs seem to have some width issues, because of their title (even if you don't set one).
If you don't want to use ThemeOverlay.AppCompat.Dialog style and your Dialog doesn't need a title (or has a custom one), you might want to disable it:

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View view = inflater.inflate(R.layout.dialog_view, null);

    Dialog dialog = new Dialog(getContext());
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(view);
    return dialog;
}

Outdated answer, won't work in most cases

I was trying to make the dialog respect the width and height of my layout, without specifying a fixed size programmatically.

I figured that android:windowMinWidthMinor and android:windowMinWidthMajor were causing the problem. Even though they were not included in the theme of my Activity or Dialog, they were still being applied to the Activity theme, somehow.

I came up with three possible solutions.

Solution 1: create a custom dialog theme and use it when creating the dialog in the DialogFragment.

<style name="Theme.Material.Light.Dialog.NoMinWidth" parent="android:Theme.Material.Light.Dialog">
    <item name="android:windowMinWidthMinor">0dip</item>
    <item name="android:windowMinWidthMajor">0dip</item>
</style>
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    return new Dialog(getActivity(), R.style.Theme_Material_Light_Dialog_NoMinWidth);
}

Solution 2: create a custom theme to be used in a ContextThemeWrapper that will serve as Context for the dialog. Use this if you don't want to create a custom dialog theme (for instance, when you want to use the theme specified by android:dialogTheme).

<style name="Theme.Window.NoMinWidth" parent="">
    <item name="android:windowMinWidthMinor">0dip</item>
    <item name="android:windowMinWidthMajor">0dip</item>
</style>
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    return new Dialog(new ContextThemeWrapper(getActivity(), R.style.Theme_Window_NoMinWidth), getTheme());
}

Solution 3 (with an AlertDialog): enforce android:windowMinWidthMinor and android:windowMinWidthMajor into the ContextThemeWrapper created by the AlertDialog$Builder.

<style name="Theme.Window.NoMinWidth" parent="">
    <item name="android:windowMinWidthMinor">0dip</item>
    <item name="android:windowMinWidthMajor">0dip</item>
</style>
@Override
public final Dialog onCreateDialog(Bundle savedInstanceState) {
    View view = new View(); // Inflate your view here.
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setView(view);
    // Make sure the dialog width works as WRAP_CONTENT.
    builder.getContext().getTheme().applyStyle(R.style.Theme_Window_NoMinWidth, true);
    return builder.create();
}

IF EXISTS before INSERT, UPDATE, DELETE for optimization

I'm not completely sure, but I get the impression that this question is really about upsert, which is the following atomic operation:

  • If the row exists in both the source and target, UPDATE the target;
  • If the row only exists in the source, INSERT the row into the target;
  • (Optionally) If the row exists in the target but not the source, DELETE the row from the target.

Developers-turned-DBAs often naïvely write it row-by-row, like this:

-- For each row in source
IF EXISTS(<target_expression>)
    IF @delete_flag = 1
        DELETE <target_expression>
    ELSE
        UPDATE target
        SET <target_columns> = <source_values>
        WHERE <target_expression>
ELSE
    INSERT target (<target_columns>)
    VALUES (<source_values>)

This is just about the worst thing you can do, for several reasons:

  • It has a race condition. The row can disappear between IF EXISTS and the subsequent DELETE or UPDATE.

  • It's wasteful. For every transaction you have an extra operation being performed; maybe it's trivial, but that depends entirely on how well you've indexed.

  • Worst of all - it's following an iterative model, thinking about these problems at the level of a single row. This will have the largest (worst) impact of all on overall performance.

One very minor (and I emphasize minor) optimization is to just attempt the UPDATE anyway; if the row doesn't exist, @@ROWCOUNT will be 0 and you can then "safely" insert:

-- For each row in source
BEGIN TRAN

UPDATE target
SET <target_columns> = <source_values>
WHERE <target_expression>

IF (@@ROWCOUNT = 0)
    INSERT target (<target_columns>)
    VALUES (<source_values>)

COMMIT

Worst-case, this will still perform two operations for every transaction, but at least there's a chance of only performing one, and it also eliminates the race condition (kind of).

But the real issue is that this is still being done for each row in the source.

Before SQL Server 2008, you had to use an awkward 3-stage model to deal with this at the set level (still better than row-by-row):

BEGIN TRAN

INSERT target (<target_columns>)
SELECT <source_columns> FROM source s
WHERE s.id NOT IN (SELECT id FROM target)

UPDATE t SET <target_columns> = <source_columns>
FROM target t
INNER JOIN source s ON t.d = s.id

DELETE t
FROM target t
WHERE t.id NOT IN (SELECT id FROM source)

COMMIT

As I said, performance was pretty lousy on this, but still a lot better than the one-row-at-a-time approach. SQL Server 2008, however, finally introduced MERGE syntax, so now all you have to do is this:

MERGE target
USING source ON target.id = source.id
WHEN MATCHED THEN UPDATE <target_columns> = <source_columns>
WHEN NOT MATCHED THEN INSERT (<target_columns>) VALUES (<source_columns>)
WHEN NOT MATCHED BY SOURCE THEN DELETE;

That's it. One statement. If you're using SQL Server 2008 and need to perform any sequence of INSERT, UPDATE and DELETE depending on whether or not the row already exists - even if it's just one row - there is no excuse not to be using MERGE.

You can even OUTPUT the rows affected by a MERGE into a table variable if you need to find out afterward what was done. Simple, fast, and risk-free. Do it.

Apache is downloading php files instead of displaying them

It's also possible that you have nginx running but your php is set up to run with apache. To verify, run service nginx status and service apache2 status to see which is running. In the case that nginx is running and apache is not, just run sudo service nginx stop; sudo service apache2 start and your server will now serve php files as expected.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

Please open terminal and fire the below command:

export LC_ALL="en_US.UTF-8"

How do you specify a different port number in SQL Management Studio?

On Windows plattform with server execute command:

netstat -a -b

look for sql server processes and find port f.e 49198

Or easier. Connect with dbvisualizer, run netstat -a -b find dbvis.exe process and get port.

How to switch between python 2.7 to python 3 from command line?

They are 3 ways you can achieve this using the py command (py-launcher) in python 3, virtual environment or configuring your default python system path. For illustration purpose, you may see tutorial https://www.youtube.com/watch?v=ynDlb0n27cw&t=38s

Repository Pattern Step by Step Explanation

As a summary, I would describe the wider impact of the repository pattern. It allows all of your code to use objects without having to know how the objects are persisted. All of the knowledge of persistence, including mapping from tables to objects, is safely contained in the repository.

Very often, you will find SQL queries scattered in the codebase and when you come to add a column to a table you have to search code files to try and find usages of a table. The impact of the change is far-reaching.

With the repository pattern, you would only need to change one object and one repository. The impact is very small.

Perhaps it would help to think about why you would use the repository pattern. Here are some reasons:

  • You have a single place to make changes to your data access

  • You have a single place responsible for a set of tables (usually)

  • It is easy to replace a repository with a fake implementation for testing - so you don't need to have a database available to your unit tests

There are other benefits too, for example, if you were using MySQL and wanted to switch to SQL Server - but I have never actually seen this in practice!

How to get the range of occupied cells in excel sheet

I had a very similar issue as you had. What actually worked is this:

iTotalColumns = xlWorkSheet.UsedRange.Columns.Count;
iTotalRows = xlWorkSheet.UsedRange.Rows.Count;

//These two lines do the magic.
xlWorkSheet.Columns.ClearFormats();
xlWorkSheet.Rows.ClearFormats();

iTotalColumns = xlWorkSheet.UsedRange.Columns.Count;
iTotalRows = xlWorkSheet.UsedRange.Rows.Count;

IMHO what happens is that when you delete data from Excel, it keeps on thinking that there is data in those cells, though they are blank. When I cleared the formats, it removes the blank cells and hence returns actual counts.

how to end ng serve or firebase serve

Exit the IDE and boots up IDE again , try it.

Redirecting to authentication dialog - "An error occurred. Please try again later"

Solution for me is to set option 'Authenticated Referrals' to enabled. Its realy fixed after that.

Fix permissions error

Determining the current foreground application from a background task or service

Taking into account that getRunningTasks() is deprecated and getRunningAppProcesses() is not reliable, I came to decision to combine 2 approaches mentioned in StackOverflow:

   private boolean isAppInForeground(Context context)
    {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
        {
            ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
            ActivityManager.RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
            String foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();

            return foregroundTaskPackageName.toLowerCase().equals(context.getPackageName().toLowerCase());
        }
        else
        {
            ActivityManager.RunningAppProcessInfo appProcessInfo = new ActivityManager.RunningAppProcessInfo();
            ActivityManager.getMyMemoryState(appProcessInfo);
            if (appProcessInfo.importance == IMPORTANCE_FOREGROUND || appProcessInfo.importance == IMPORTANCE_VISIBLE)
            {
                return true;
            }

            KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
            // App is foreground, but screen is locked, so show notification
            return km.inKeyguardRestrictedInputMode();
        }
    }

java : non-static variable cannot be referenced from a static context Error

Your main() method is static, but it is referencing two non-static members: con2 and getConnectionUrl2(). You need to do one of three things:

1) Make con2 and getConnectionUrl2() static.

2) Inside main(), create an instance of class testconnect and access con2 and getConnectionUrl2() off of that.

3) Break out a different class to hold con2 and getConnectionUrl2() so that testconnect only has main in it. It will still need to instantiate the different class and call the methods off that.

Option #3 is the best option. #1 is the worst.

But, you cannot access non-static members from within a static method.

Is there a command for formatting HTML in the Atom editor?

You can add atom beauty package for formatting text in atom..

file --> setting --> Install

then you type atom-beautify in search area.

then click Package button.. select atom beuty and install it.

next you can format your text using (Alt + ctrl + b) or right click and select beautify editor contents

How do I add space between two variables after a print in Python

print str(count) + ' ' + str(conv) - This did not work. However, replacing + with , works for me

How do I force Postgres to use a particular index?

Sometimes PostgreSQL fails to make the best choice of indexes for a particular condition. As an example, suppose there is a transactions table with several million rows, of which there are several hundred for any given day, and the table has four indexes: transaction_id, client_id, date, and description. You want to run the following query:

SELECT client_id, SUM(amount)
FROM transactions
WHERE date >= 'yesterday'::timestamp AND date < 'today'::timestamp AND
      description = 'Refund'
GROUP BY client_id

PostgreSQL may choose to use the index transactions_description_idx instead of transactions_date_idx, which may lead to the query taking several minutes instead of less than one second. If this is the case, you can force using the index on date by fudging the condition like this:

SELECT client_id, SUM(amount)
FROM transactions
WHERE date >= 'yesterday'::timestamp AND date < 'today'::timestamp AND
      description||'' = 'Refund'
GROUP BY client_id

What is the difference between UTF-8 and ISO-8859-1?

UTF-8 is a multibyte encoding that can represent any Unicode character. ISO 8859-1 is a single-byte encoding that can represent the first 256 Unicode characters. Both encode ASCII exactly the same way.

What is the best place for storing uploaded images, SQL database or disk file system?

Option A.

Once the image is loaded you can verify the format and resize it before saving. There a number of .Net code samples to resize images on http://www.codeproject.com. For instance: http://www.codeproject.com/KB/cs/Photo_Resize.aspx

Why is there no xrange function in Python3?

One way to fix up your python2 code is:

import sys

if sys.version_info >= (3, 0):
    def xrange(*args, **kwargs):
        return iter(range(*args, **kwargs))

Evaluate a string with a switch in C++

As said before, switch can be used only with integer values. So, you just need to convert your "case" values to integer. You can achieve it by using constexpr from c++11, thus some calls of constexpr functions can be calculated in compile time.

something like that...

switch (str2int(s))
{
  case str2int("Value1"):
    break;
  case str2int("Value2"):
    break;
}

where str2int is like (implementation from here):

constexpr unsigned int str2int(const char* str, int h = 0)
{
    return !str[h] ? 5381 : (str2int(str, h+1) * 33) ^ str[h];
}

Another example, the next function can be calculated in compile time:

constexpr int factorial(int n)
{
    return n <= 1 ? 1 : (n * factorial(n-1));
}  

int f5{factorial(5)};
// Compiler will run factorial(5) 
// and f5 will be initialized by this value. 
// so programm instead of wasting time for running function, 
// just will put the precalculated constant to f5 

What is the use of hashCode in Java?

hashCode() is used for bucketing in Hash implementations like HashMap, HashTable, HashSet, etc.

The value received from hashCode() is used as the bucket number for storing elements of the set/map. This bucket number is the address of the element inside the set/map.

When you do contains() it will take the hash code of the element, then look for the bucket where hash code points to. If more than 1 element is found in the same bucket (multiple objects can have the same hash code), then it uses the equals() method to evaluate if the objects are equal, and then decide if contains() is true or false, or decide if element could be added in the set or not.

Mosaic Grid gallery with dynamic sized images

I suggest Freewall. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.

Home page and document: also found here.

Using pickle.dump - TypeError: must be str, not bytes

The output file needs to be opened in binary mode:

f = open('varstor.txt','w')

needs to be:

f = open('varstor.txt','wb')

Echoing the last command run in Bash?

The command history is an interactive feature. Only complete commands are entered in the history. For example, the case construct is entered as a whole, when the shell has finished parsing it. Neither looking up the history with the history built-in (nor printing it through shell expansion (!:p)) does what you seem to want, which is to print invocations of simple commands.

The DEBUG trap lets you execute a command right before any simple command execution. A string version of the command to execute (with words separated by spaces) is available in the BASH_COMMAND variable.

trap 'previous_command=$this_command; this_command=$BASH_COMMAND' DEBUG
…
echo "last command is $previous_command"

Note that previous_command will change every time you run a command, so save it to a variable in order to use it. If you want to know the previous command's return status as well, save both in a single command.

cmd=$previous_command ret=$?
if [ $ret -ne 0 ]; then echo "$cmd failed with error code $ret"; fi

Furthermore, if you only want to abort on a failed commands, use set -e to make your script exit on the first failed command. You can display the last command from the EXIT trap.

set -e
trap 'echo "exit $? due to $previous_command"' EXIT

Note that if you're trying to trace your script to see what it's doing, forget all this and use set -x.

Generate insert script for selected records?

CREATE PROCEDURE sp_generate_insertscripts
(
    @TABLENAME VARCHAR(MAX),
    @FILTER_CONDITION VARCHAR(MAX)=''   -- where TableId = 5 or some value
)
AS
BEGIN

SET NOCOUNT ON

DECLARE @TABLE_NAME VARCHAR(MAX),
        @CSV_COLUMN VARCHAR(MAX),
        @QUOTED_DATA VARCHAR(MAX),
        @TEXT VARCHAR(MAX),
        @FILTER VARCHAR(MAX) 

SET @TABLE_NAME=@TABLENAME

SELECT @FILTER=@FILTER_CONDITION

SELECT @CSV_COLUMN=STUFF
(
    (
     SELECT ',['+ NAME +']' FROM sys.all_columns 
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND 
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @QUOTED_DATA=STUFF
(
    (
     SELECT ' ISNULL(QUOTENAME('+NAME+','+QUOTENAME('''','''''')+'),'+'''NULL'''+')+'','''+'+' FROM sys.all_columns 
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND 
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @TEXT='SELECT ''INSERT INTO '+@TABLE_NAME+'('+@CSV_COLUMN+')VALUES('''+'+'+SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)+'+'+''')'''+' Insert_Scripts FROM '+@TABLE_NAME + @FILTER

--SELECT @CSV_COLUMN AS CSV_COLUMN,@QUOTED_DATA AS QUOTED_DATA,@TEXT TEXT

EXECUTE (@TEXT)

SET NOCOUNT OFF

END

How to declare a variable in a PostgreSQL query

Using a Temp Table outside of pl/PgSQL

Outside of using pl/pgsql or other pl/* language as suggested, this is the only other possibility I could think of.

begin;
select 5::int as var into temp table myvar;
select *
  from somewhere s, myvar v
 where s.something = v.var;
commit;

How can I install pip on Windows?

Even if I installed Python 3.7, added it to PATH, and checked the checkbox "Install pip", pip3.exe or pip.exe was finally not present on the computer (even in the Scripts subfolder).

This solved it:

python -m ensurepip

(The solution from the accepted answer did not work for me.)

TypeScript static classes

Defining static properties and methods of a class is described in 8.2.1 of the Typescript Language Specification:

class Point { 
  constructor(public x: number, public y: number) { 
    throw new Error('cannot instantiate using a static class');
  } 
  public distance(p: Point) { 
    var dx = this.x - p.x; 
    var dy = this.y - p.y; 
    return Math.sqrt(dx * dx + dy * dy); 
  } 
  static origin = new Point(0, 0); 
  static distance(p1: Point, p2: Point) { 
    return p1.distance(p2); 
  } 
}

where Point.distance() is a static (or "class") method.

jQuery: how to get which button was clicked upon form submission?

Here is a sample, that uses this.form to get the correct form the submit is into, and data fields to store the last clicked/focused element. I also wrapped submit code inside a timeout to be sure click events happen before it is executed (some users reported in comments that on Chrome sometimes a click event is fired after a submit).

Works when navigating both with keys and with mouse/fingers without counting on browsers to send a click event on RETURN key (doesn't hurt though), I added an event handler for focus events for buttons and fields.

You might add buttons of type="submit" to the items that save themselves when clicked.

In the demo I set a red border to show the selected item and an alert that shows name and value/label.

Here is the FIDDLE

And here is the (same) code:

Javascript:

$("form").submit(function(e) {
  e.preventDefault();
  // Use this for rare/buggy cases when click event is sent after submit
  setTimeout(function() {

    var $this=$(this);
    var lastFocus = $this.data("lastFocus");
    var $defaultSubmit=null;

    if(lastFocus) $defaultSubmit=$(lastFocus);

    if(!$defaultSubmit || !$defaultSubmit.is("input[type=submit]")) {
      // If for some reason we don't have a submit, find one (the first)
      $defaultSubmit=$(this).find("input[type=submit]").first();
    }

    if($defaultSubmit) {
      var submitName=$defaultSubmit.attr("name");
      var submitLabel=$defaultSubmit.val();

       // Just a demo, set hilite and alert
      doSomethingWith($defaultSubmit);
      setTimeout(function() {alert("Submitted "+submitName+": '"+submitLabel+"'")},1000);
    } else {
      // There were no submit in the form
    }

  }.bind(this),0);

});

$("form input").focus(function() {
  $(this.form).data("lastFocus", this);
});
$("form input").click(function() {
  $(this.form).data("lastFocus", this);
});

// Just a demo, setting hilite
function doSomethingWith($aSelectedEl) {
  $aSelectedEl.css({"border":"4px solid red"});
  setTimeout(function() { $aSelectedEl.removeAttr("style"); },1000);
}

DUMMY HTML:

<form>
<input type="text" name="testtextortexttest" value="Whatever you write, sir."/>
<input type="text" name="moretesttextormoretexttest" value="Whatever you write, again, sir."/>

<input type="submit" name="test1" value="Action 1"/>
<input type="submit" name="test2" value="Action 2"/>
<input type="submit" name="test3" value="Action 3"/>
<input type="submit" name="test4" value="Action 4"/>
<input type="submit" name="test5" value="Action 5"/>
</form>

DUMB CSS:

input {display:block}

show and hide divs based on radio button click

You were pretty close. You're description div tags didn't have the .desc class defined. For your scenario you should have the radio button value equal to the div that you're trying to show.

HTML

<div id="myRadioGroup">

    2 Cars<input type="radio" name="cars" checked="checked" value="twoCarDiv"  />

    3 Cars<input type="radio" name="cars" value="threeCarDiv" />

    <div id="twoCarDiv" class="desc">
        2 Cars Selected
    </div>
    <div id="threeCarDiv" class="desc">
        3 Cars Selected
    </div>
</div>

jQuery

$(document).ready(function() {
    $("div.desc").hide();
    $("input[name$='cars']").click(function() {
        var test = $(this).val();
        $("div.desc").hide();
        $("#" + test).show();
    });
});

working example: http://jsfiddle.net/hunter/tcDtr/

How can I format a decimal to always show 2 decimal places?

if you have multiple parameters you can use

 print('some string {0:.2f} & {1:.2f}'.format(1.1234,2.345))
 >>> some string 1.12 & 2.35

JavaScript ES6 promise for loop

You can use async/await for this. I would explain more, but there's nothing really to it. It's just a regular for loop but I added the await keyword before the construction of your Promise

What I like about this is your Promise can resolve a normal value instead of having a side effect like your code (or other answers here) include. This gives you powers like in The Legend of Zelda: A Link to the Past where you can affect things in both the Light World and the Dark World – ie, you can easily work with data before/after the Promised data is available without having to resort to deeply nested functions, other unwieldy control structures, or stupid IIFEs.

// where DarkWorld is in the scary, unknown future
// where LightWorld is the world we saved from Ganondorf
LightWorld ... await DarkWorld

So here's what that will look like ...

_x000D_
_x000D_
const someProcedure = async n =>_x000D_
  {_x000D_
    for (let i = 0; i < n; i++) {_x000D_
      const t = Math.random() * 1000_x000D_
      const x = await new Promise(r => setTimeout(r, t, i))_x000D_
      console.log (i, x)_x000D_
    }_x000D_
    return 'done'_x000D_
  }_x000D_
_x000D_
someProcedure(10).then(x => console.log(x)) // => Promise_x000D_
// 0 0_x000D_
// 1 1_x000D_
// 2 2_x000D_
// 3 3_x000D_
// 4 4_x000D_
// 5 5_x000D_
// 6 6_x000D_
// 7 7_x000D_
// 8 8_x000D_
// 9 9_x000D_
// done
_x000D_
_x000D_
_x000D_

See how we don't have to deal with that bothersome .then call within our procedure? And async keyword will automatically ensure that a Promise is returned, so we can chain a .then call on the returned value. This sets us up for great success: run the sequence of n Promises, then do something important – like display a success/error message.

Best Timer for using in a Windows service

Don't use a service for this. Create a normal application and create a scheduled task to run it.

This is the commonly held best practice. Jon Galloway agrees with me. Or maybe its the other way around. Either way, the fact is that it is not best practices to create a windows service to perform an intermittent task run off a timer.

"If you're writing a Windows Service that runs a timer, you should re-evaluate your solution."

–Jon Galloway, ASP.NET MVC community program manager, author, part time superhero

Consider marking event handler as 'passive' to make the page more responsive

For those stuck with legacy issues, find the line throwing the error and add {passive: true} - eg:

this.element.addEventListener(t, e, !1)

becomes

this.element.addEventListener(t, e, { passive: true} )

Xampp localhost/dashboard

Try this solution:

Go to->

  1. xammp ->htdocs-> then open index.php from the htdocs folder
  2. you can modify the dashboard
  3. restart the server

Example Code index.php :

    <?php
    if (!empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'])) {
        $uri = 'https://';
    } else {
        $uri = 'http://';
    }
    $uri .= $_SERVER['HTTP_HOST'];
    header('Location: '.$uri.'/dashboard/');
    exit;
   ?>

Show/Hide Table Rows using Javascript classes

Well one way to do it would be to just put a class on the "parent" rows and remove all the ids and inline onclick attributes:

<table id="products">
    <thead>
    <tr>
        <th>Product</th>
        <th>Price</th>
        <th>Destination</th>
        <th>Updated on</th>
    </tr>
    </thead>
    <tbody>
    <tr class="parent">
        <td>Oranges</td>
        <td>100</td>
        <td><a href="#">+ On Store</a></td>
        <td>22/10</td>
    </tr>
    <tr>
        <td></td>
        <td>120</td>
        <td>City 1</td>
        <td>22/10</td>
    </tr>
    <tr>
        <td></td>
        <td>140</td>
        <td>City 2</td>
        <td>22/10</td>
    </tr>
    ...etc.
    </tbody>
</table>

And then have some CSS that hides all non-parents:

tbody tr {
    display : none;          // default is hidden
}
tr.parent {
    display : table-row;     // parents are shown
}
tr.open {
    display : table-row;     // class to be given to "open" child rows
}

That greatly simplifies your html. Note that I've added <thead> and <tbody> to your markup to make it easy to hide data rows and ignore heading rows.

With jQuery you can then simply do this:

// when an anchor in the table is clicked
$("#products").on("click","a",function(e) {
    // prevent default behaviour
    e.preventDefault();
    // find all the following TR elements up to the next "parent"
    // and toggle their "open" class
    $(this).closest("tr").nextUntil(".parent").toggleClass("open");
});

Demo: http://jsfiddle.net/CBLWS/1/

Or, to implement something like that in plain JavaScript, perhaps something like the following:

document.getElementById("products").addEventListener("click", function(e) {
    // if clicked item is an anchor
    if (e.target.tagName === "A") {
        e.preventDefault();
        // get reference to anchor's parent TR
        var row = e.target.parentNode.parentNode;
        // loop through all of the following TRs until the next parent is found
        while ((row = nextTr(row)) && !/\bparent\b/.test(row.className))
            toggle_it(row);
    }
});

function nextTr(row) {
    // find next sibling that is an element (skip text nodes, etc.)
    while ((row = row.nextSibling) && row.nodeType != 1);
    return row;
}

function toggle_it(item){ 
     if (/\bopen\b/.test(item.className))       // if item already has the class
         item.className = item.className.replace(/\bopen\b/," "); // remove it
     else                                       // otherwise
         item.className += " open";             // add it
}

Demo: http://jsfiddle.net/CBLWS/

Either way, put the JavaScript in a <script> element that is at the end of the body, so that it runs after the table has been parsed.

Python check if website exists

Try this one::

import urllib2  
website='https://www.allyourmusic.com'  
try:  
    response = urllib2.urlopen(website)  
    if response.code==200:  
        print("site exists!")  
    else:  
        print("site doesn't exists!")  
except urllib2.HTTPError, e:  
    print(e.code)  
except urllib2.URLError, e:  
    print(e.args)  

Sending an Intent to browser to open specific URL

In some cases URL may start with "www". In this case you will get an exception:

android.content.ActivityNotFoundException: No Activity found to handle Intent

The URL must always start with "http://" or "https://" so I use this snipped of code:

if (!url.startsWith("https://") && !url.startsWith("http://")){
    url = "http://" + url;
}
Intent openUrlIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(openUrlIntent);

Run JavaScript when an element loses focus

onblur is the opposite of onfocus.

Difference between CR LF, LF and CR line break types?

CR and LF are control characters, respectively coded 0x0D (13 decimal) and 0x0A (10 decimal).

They are used to mark a line break in a text file. As you indicated, Windows uses two characters the CR LF sequence; Unix only uses LF and the old MacOS ( pre-OSX MacIntosh) used CR.

An apocryphal historical perspective:

As indicated by Peter, CR = Carriage Return and LF = Line Feed, two expressions have their roots in the old typewriters / TTY. LF moved the paper up (but kept the horizontal position identical) and CR brought back the "carriage" so that the next character typed would be at the leftmost position on the paper (but on the same line). CR+LF was doing both, i.e. preparing to type a new line. As time went by the physical semantics of the codes were not applicable, and as memory and floppy disk space were at a premium, some OS designers decided to only use one of the characters, they just didn't communicate very well with one another ;-)

Most modern text editors and text-oriented applications offer options/settings etc. that allow the automatic detection of the file's end-of-line convention and to display it accordingly.

Storing Form Data as a Session Variable

Yes this is possible. kizzie is correct with the session_start(); having to go first.

another observation I made is that you need to filter your form data using:

strip_tags($value);

and/or

stripslashes($value);

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

I understand this question is for sql server 2012, but if the same scenario for SQL Server 2017 or SQL Azure you can use Trim directly as below:

UPDATE *tablename*
   SET *columnname* = trim(*columnname*);

Best practice for localization and globalization of strings and labels

When you’re faced with a problem to solve (and frankly, who isn’t these days?), the basic strategy usually taken by we computer people is called “divide and conquer.” It goes like this:

  • Conceptualize the specific problem as a set of smaller sub-problems.
  • Solve each smaller problem.
  • Combine the results into a solution of the specific problem.

But “divide and conquer” is not the only possible strategy. We can also take a more generalist approach:

  • Conceptualize the specific problem as a special case of a more general problem.
  • Somehow solve the general problem.
  • Adapt the solution of the general problem to the specific problem.

- Eric Lippert

I believe many solutions already exist for this problem in server-side languages such as ASP.Net/C#.

I've outlined some of the major aspects of the problem

  • Issue: We need to load data only for the desired language

    Solution: For this purpose we save data to a separate files for each language

ex. res.de.js, res.fr.js, res.en.js, res.js(for default language)

  • Issue: Resource files for each page should be separated so we only get the data we need

    Solution: We can use some tools that already exist like https://github.com/rgrove/lazyload

  • Issue: We need a key/value pair structure to save our data

    Solution: I suggest a javascript object instead of string/string air. We can benefit from the intellisense from an IDE

  • Issue: General members should be stored in a public file and all pages should access them

    Solution: For this purpose I make a folder in the root of web application called Global_Resources and a folder to store global file for each sub folders we named it 'Local_Resources'

  • Issue: Each subsystems/subfolders/modules member should override the Global_Resources members on their scope

    Solution: I considered a file for each

Application Structure

root/
    Global_Resources/
        default.js
        default.fr.js
    UserManagementSystem/
        Local_Resources/
            default.js
            default.fr.js
            createUser.js
        Login.htm
        CreateUser.htm

The corresponding code for the files:

Global_Resources/default.js

var res = {
    Create : "Create",
    Update : "Save Changes",
    Delete : "Delete"
};

Global_Resources/default.fr.js

var res = {
    Create : "créer",
    Update : "Enregistrer les modifications",
    Delete : "effacer"
};

The resource file for the desired language should be loaded on the page selected from Global_Resource - This should be the first file that is loaded on all the pages.

UserManagementSystem/Local_Resources/default.js

res.Name = "Name";
res.UserName = "UserName";
res.Password = "Password";

UserManagementSystem/Local_Resources/default.fr.js

res.Name = "nom";
res.UserName = "Nom d'utilisateur";
res.Password = "Mot de passe";

UserManagementSystem/Local_Resources/createUser.js

// Override res.Create on Global_Resources/default.js
res.Create = "Create User"; 

UserManagementSystem/Local_Resources/createUser.fr.js

// Override Global_Resources/default.fr.js
res.Create = "Créer un utilisateur";

manager.js file (this file should be load last)

res.lang = "fr";

var globalResourcePath = "Global_Resources";
var resourceFiles = [];

var currentFile = globalResourcePath + "\\default" + res.lang + ".js" ;

if(!IsFileExist(currentFile))
    currentFile = globalResourcePath + "\\default.js" ;
if(!IsFileExist(currentFile)) throw new Exception("File Not Found");

resourceFiles.push(currentFile);

// Push parent folder on folder into folder
foreach(var folder in parent folder of current page)
{
    currentFile = folder + "\\Local_Resource\\default." + res.lang + ".js";

    if(!IsExist(currentFile))
        currentFile = folder + "\\Local_Resource\\default.js";
    if(!IsExist(currentFile)) throw new Exception("File Not Found");

    resourceFiles.push(currentFile);
}

for(int i = 0; i < resourceFiles.length; i++) { Load.js(resourceFiles[i]); }

// Get current page name
var pageNameWithoutExtension = "SomePage";

currentFile = currentPageFolderPath + pageNameWithoutExtension + res.lang + ".js" ;

if(!IsExist(currentFile))
    currentFile = currentPageFolderPath + pageNameWithoutExtension + ".js" ;
if(!IsExist(currentFile)) throw new Exception("File Not Found");

Hope it helps :)

javascript cell number validation

<script type="text/javascript">
    function MobileNoValidation()
    {
       var phno=/^\d{10}$/
       if(textMobileNo.value=="")
       {
        alert("Mobile No Should Not Be Empty");
       }
       else if(!textMobileNo.value.match(phno))
       {
        alert("Mobile no must be ten digit");
       }
       else
       {
        alert("valid Mobile No");
       }
    }
</script>

SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP

I use the AdWords API, and sometimes I have the same problem. My solution is to add ini_set('default_socket_timeout', 900); on the file vendor\googleads\googleads-php-lib\src\Google\AdsApi\AdsSoapClient.php line 65

and in the vendor\googleads-php-lib\src\Google\AdsApi\Adwords\Reporting\v201702\ReportDownloader.php line 126 ini_set('default_socket_timeout', 900); $requestOptions['stream_context']['http']['timeout'] = "900";

Google package overwrite the default php.ini parameter.

Sometimes, the page could connect to 'https://adwords.google.com/ap i/adwords/mcm/v201702/ManagedCustomerService?wsdl and sometimes no. If the page connects once, The WSDL cache will contain the same page, and the program will be ok until the code refreshes the cache...

Change label text using JavaScript

Try this:

<label id="lbltipAddedComment"></label>
<script type="text/javascript"> 
      document.getElementById('<%= lbltipAddedComment.ClientID %>').innerHTML = 'your tip has been submitted!';
</script>

WAMP 403 Forbidden message on Windows 7

I read & tried All Fixes But Not one worked. At last i Found that the Wamp Server Logo Is Green But Need to Be "PUT ONLINE". So simple & a Quick Fix After Checking Your PHPMyAdmin.Cofg & HttPD.cofg Just Click on PUT ONLINE

How can I merge properties of two JavaScript objects dynamically?

ECMAScript 2018 Standard Method

You would use object spread:

let merged = {...obj1, ...obj2};

merged is now the union of obj1 and obj2. Properties in obj2 will overwrite those in obj1.

/** There's no limit to the number of objects you can merge.
 *  Later properties overwrite earlier properties with the same name. */
const allRules = {...obj1, ...obj2, ...obj3};

Here is also the MDN documentation for this syntax. If you're using babel you'll need the babel-plugin-transform-object-rest-spread plugin for it to work.

ECMAScript 2015 (ES6) Standard Method

/* For the case in question, you would do: */
Object.assign(obj1, obj2);

/** There's no limit to the number of objects you can merge.
 *  All objects get merged into the first object. 
 *  Only the object in the first argument is mutated and returned.
 *  Later properties overwrite earlier properties with the same name. */
const allRules = Object.assign({}, obj1, obj2, obj3, etc);

(see MDN JavaScript Reference)


Method for ES5 and Earlier

for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }

Note that this will simply add all attributes of obj2 to obj1 which might not be what you want if you still want to use the unmodified obj1.

If you're using a framework that craps all over your prototypes then you have to get fancier with checks like hasOwnProperty, but that code will work for 99% of cases.

Example function:

/**
 * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
 * @param obj1
 * @param obj2
 * @returns obj3 a new object based on obj1 and obj2
 */
function merge_options(obj1,obj2){
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
}

How to detect the device orientation using CSS media queries?

I would go for aspect-ratio, it offers way more possibilities.

/* Exact aspect ratio */
@media (aspect-ratio: 2/1) {
    ...
}

/* Minimum aspect ratio */
@media (min-aspect-ratio: 16/9) {
    ...
}

/* Maximum aspect ratio */
@media (max-aspect-ratio: 8/5) {
    ...
}

Both, orientation and aspect-ratio depend on the actual size of the viewport and have nothing todo with the device orientation itself.

Read more: https://dev.to/ananyaneogi/useful-css-media-query-features-o7f

how do I insert a column at a specific column index in pandas?

You could try to extract columns as list, massage this as you want, and reindex your dataframe:

>>> cols = df.columns.tolist()
>>> cols = [cols[-1]]+cols[:-1] # or whatever change you need
>>> df.reindex(columns=cols)

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

EDIT: this can be done in one line ; however, this looks a bit ugly. Maybe some cleaner proposal may come...

>>> df.reindex(columns=['n']+df.columns[:-1].tolist())

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

Javascript Date - set just the date, ignoring time?

How about .toDateString()?

Alternatively, use .getDate(), .getMonth(), and .getYear()?

In my mind, if you want to group things by date, you simply want to access the date, not set it. Through having some set way of accessing the date field, you can compare them and group them together, no?

Check out all the fun Date methods here: MDN Docs


Edit: If you want to keep it as a date object, just do this:

var newDate = new Date(oldDate.toDateString());

Date's constructor is pretty smart about parsing Strings (though not without a ton of caveats, but this should work pretty consistently), so taking the old Date and printing it to just the date without any time will result in the same effect you had in the original post.

Setting font on NSAttributedString on UITextView disregards line spacing

There was a bug in iOS 6, that causes line height to be ignored when font is set. See answer to NSParagraphStyle line spacing ignored and longer bug analysis at Radar: UITextView Ignores Minimum/Maximum Line Height in Attributed String.

Getting the base url of the website and globally passing it to twig in Symfony 2

For Symfony 2.3+, to get the base url in a controller should be

$this->get('request')->getSchemeAndHttpHost();

How to add http:// if it doesn't exist in the URL

The best answer for this would be something like this:

function addhttp($url, $scheme="http://" )
{
  return $url = empty(parse_url($url)['scheme']) ? $scheme . ltrim($url, '/') : $url;
}

The protocol flexible, so the same function can be used with ftp, https, etc.

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Pscp.exe is painfully slow.

Uploading files using WinSCP is like 10 times faster.

So, to do that from command line, first you got to add the winscp.com file to your %PATH%. It's not a top-level domain, but an executable .com file, which is located in your WinSCP installation directory.

Then just issue a simple command and your file will be uploaded much faster putty ever could:

WinSCP.com /command "open sftp://username:[email protected]:22" "put your_large_file.zip /var/www/somedirectory/" "exit"

And make sure your check the synchronize folders feature, which is basically what rsync does, so you won't ever want to use pscp.exe again.

WinSCP.com /command "help synchronize"

C# Interfaces. Implicit implementation versus Explicit implementation

Implicit is when you define your interface via a member on your class. Explicit is when you define methods within your class on the interface. I know that sounds confusing but here is what I mean: IList.CopyTo would be implicitly implemented as:

public void CopyTo(Array array, int index)
{
    throw new NotImplementedException();
}

and explicitly as:

void ICollection.CopyTo(Array array, int index)
{
    throw new NotImplementedException();
}

The difference is that implicit implementation allows you to access the interface through the class you created by casting the interface as that class and as the interface itself. Explicit implementation allows you to access the interface only by casting it as the interface itself.

MyClass myClass = new MyClass(); // Declared as concrete class
myclass.CopyTo //invalid with explicit
((IList)myClass).CopyTo //valid with explicit.

I use explicit primarily to keep the implementation clean, or when I need two implementations. Regardless, I rarely use it.

I am sure there are more reasons to use/not use explicit that others will post.

See the next post in this thread for excellent reasoning behind each.

What does $1 mean in Perl?

$1, $2, etc will contain the value of captures from the last successful match - it's important to check whether the match succeeded before accessing them, i.e.

 if ( $var =~ m/( )/ ) { # use $1 etc... }

An example of the problem - $1 contains 'Quick' in both print statements below:

#!/usr/bin/perl

'Quick brown fox' =~ m{ ( quick ) }ix;
print "Found: $1\n";

'Lazy dog' =~ m{ ( quick ) }ix;
print "Found: $1\n";

syntax error when using command line in python

Come out of the "python interpreter."

  1. Check out your PATH variable c:\python27
  2. cd and your file location. 3.Now type Python yourfilename.py.

I hope this should work

Autowiring two beans implementing same interface - how to set default bean to autowire?

For Spring 2.5, there's no @Primary. The only way is to use @Qualifier.

How to Delete node_modules - Deep Nested Folder in Windows

Advance a little beat for multiple folders...

If you have a project folder with multiple 'builds' that contains 'node_module'. Like:

C:/Project/build-1/node_modules
C:/Project/build-2/node_modules
C:/Project/build-3/node_modules
C:/Project/build-4/node_modules

You want to delete all folders starts with "build"

! First install nodejs and rimraf as suggested above !

Then go to path with project and run PowerShell command

cd  C:/Project/
Get-ChildItem build* | foreach {rimraf -Path $_.FullName}

It will take a wile

NodeJS accessing file with relative path

Simple! The folder named .. is the parent folder, so you can make the path to the file you need as such

var foobar = require('../config/dev/foobar.json');

If you needed to go up two levels, you would write ../../ etc

Some more details about this in this SO answer and it's comments

Error occurred during initialization of boot layer FindException: Module not found

The reason behind this is that meanwhile creating your own class, you had also accepted to create a default class as prescribed by your IDE and after writing your code in your own class, you are getting such an error. In order to eliminate this, go to the PROJECT folder ? src ? Default package. Keep only one class (in which you had written code) and delete others.

After that, run your program and it will definitely run without any error.

Converting JSONarray to ArrayList

Instead of converting the JSON string to an ArrayList or even a Map, you can just create a JSONObject itself. This object has the ability to get string values by key, as you want and also to remove objects.

To create a JSONObject from a properly formatted JSON string, you simply call the appropriate constructor.

JSONObject json = new JSONObject(jsonString);

What is an HttpHandler in ASP.NET

An HttpHandler (or IHttpHandler) is basically anything that is responsible for serving content. An ASP.NET page (aspx) is a type of handler.

You might write your own, for example, to serve images etc from a database rather than from the web-server itself, or to write a simple POX service (rather than SOAP/WCF/etc)

How to return JSON with ASP.NET & jQuery

This structure works for me - I used it in a small tasks management application.

The controller:

public JsonResult taskCount(string fDate)
{
  // do some stuff based on the date

  // totalTasks is a count of the things I need to do today
  // tasksDone is a count of the tasks I actually did
  // pcDone is the percentage of tasks done

  return Json(new {
    totalTasks = totalTasks,
    tasksDone = tasksDone,
    percentDone = pcDone
  });
}

In the AJAX call I access the data like this:

.done(function (data) {
  // data.totalTasks
  // data.tasksDone
  // data.percentDone
});

OpenCV !_src.empty() in function 'cvtColor' error

Your code can't find the figure or the name of your figure named the by error message. Solution:

import cv2
import numpy as np 
import matplotlib.pyplot as plt 
img=cv2.imread('??.jpg')#solution:img=cv2.imread('haha.jpg')
print(img)

Android BroadcastReceiver within Activity

I think your problem is that you send the broadcast before the other activity start ! so the other activity will not receive anything .

  1. The best practice to test your code is to sendbroadcast from thread or from a service so the activity is opened and its registered the receiver and the background process sends a message.
  2. start the ToastDisplay activity from the sender activity ( I didn't test that but it may work probably )

Creating a pandas DataFrame from columns of other DataFrames with similar indexes

What you ask for is the join operation. With the how argument, you can define how unique indices are handled. Here, some article, which looks helpful concerning this point. In the example below, I left out cosmetics (like renaming columns) for simplicity.

Code

import numpy as np
import pandas as pd
df1 = pd.DataFrame(np.random.randn(5,3), index=pd.date_range('01/02/2014',periods=5,freq='D'), columns=['a','b','c'] )
df2 = pd.DataFrame(np.random.randn(8,3), index=pd.date_range('01/01/2014',periods=8,freq='D'), columns=['a','b','c'] )

df3 = df1.join(df2, how='outer', lsuffix='_df1', rsuffix='_df2')
print(df3)

Output

               a_df1     b_df1     c_df1     a_df2     b_df2     c_df2
2014-01-01       NaN       NaN       NaN  0.109898  1.107033 -1.045376
2014-01-02  0.573754  0.169476 -0.580504 -0.664921 -0.364891 -1.215334
2014-01-03 -0.766361 -0.739894 -1.096252  0.962381 -0.860382 -0.703269
2014-01-04  0.083959 -0.123795 -1.405974  1.825832 -0.580343  0.923202
2014-01-05  1.019080 -0.086650  0.126950 -0.021402 -1.686640  0.870779
2014-01-06 -1.036227 -1.103963 -0.821523 -0.943848 -0.905348  0.430739
2014-01-07       NaN       NaN       NaN  0.312005  0.586585  1.531492
2014-01-08       NaN       NaN       NaN -0.077951 -1.189960  0.995123

Fully custom validation error message with Rails

A unique approach I haven't seen anyone mention!

The only way I was able to get all the customisation I wanted was to use an after_validation callback to allow me to manipulate the error message.

  1. Allow the validation message to be created as normal, you don't need to try and change it in the validation helper.

  2. create an after_validation callback that will replace that validation message in the back-end before it gets to the view.

  3. In the after_validation method you can do anything you want with the validation message, just like a normal string! You can even use dynamic values and insert them into the validation message.


#this could be any validation
validates_presence_of :song_rep_xyz, :message => "whatever you want - who cares - we will replace you later"

after_validation :replace_validation_message

def replace_validation_message
    custom_value = #any value you would like
    errors.messages[:name_of_the_attribute] = ["^This is the replacement message where 
    you can now add your own dynamic values!!! #{custom_value}"]
end

The after_validation method will have far greater scope than the built in rails validation helper, so you will be able to access the object you are validating like you are trying to do with object.file_name. Which does not work in the validation helper where you are trying to call it.

Note: we use the ^ to get rid of the attribute name at the beginning of the validation as @Rystraum pointed out referencing this gem

Forwarding port 80 to 8080 using NGINX

Simple is:

server {
    listen   80;
    server_name  p3000;
    location / {
        proxy_pass http://0.0.0.0:3000;
        include /etc/nginx/proxy_params;
    }
}

In React Native, how do I put a view on top of another view, with part of it lying outside the bounds of the view behind?

You can use elevation property for Android if you don't mind the shadow.

{
  elevation:1
} 

How to negate 'isblank' function

The solution is isblank(cell)=false

C++ printing boolean, what is displayed?

The standard streams have a boolalpha flag that determines what gets displayed -- when it's false, they'll display as 0 and 1. When it's true, they'll display as false and true.

There's also an std::boolalpha manipulator to set the flag, so this:

#include <iostream>
#include <iomanip>

int main() {
    std::cout<<false<<"\n";
    std::cout << std::boolalpha;   
    std::cout<<false<<"\n";
    return 0;
}

...produces output like:

0
false

For what it's worth, the actual word produced when boolalpha is set to true is localized--that is, <locale> has a num_put category that handles numeric conversions, so if you imbue a stream with the right locale, it can/will print out true and false as they're represented in that locale. For example,

#include <iostream>
#include <iomanip>
#include <locale>

int main() {
    std::cout.imbue(std::locale("fr"));

    std::cout << false << "\n";
    std::cout << std::boolalpha;
    std::cout << false << "\n";
    return 0;
}

...and at least in theory (assuming your compiler/standard library accept "fr" as an identifier for "French") it might print out faux instead of false. I should add, however, that real support for this is uneven at best--even the Dinkumware/Microsoft library (usually quite good in this respect) prints false for every language I've checked.

The names that get used are defined in a numpunct facet though, so if you really want them to print out correctly for particular language, you can create a numpunct facet to do that. For example, one that (I believe) is at least reasonably accurate for French would look like this:

#include <array>
#include <string>
#include <locale>
#include <ios>
#include <iostream>

class my_fr : public std::numpunct< char > {
protected:
    char do_decimal_point() const { return ','; }
    char do_thousands_sep() const { return '.'; }
    std::string do_grouping() const { return "\3"; }
    std::string do_truename() const { return "vrai";  }
    std::string do_falsename() const { return "faux"; }
};

int main() {
    std::cout.imbue(std::locale(std::locale(), new my_fr));

    std::cout << false << "\n";
    std::cout << std::boolalpha;
    std::cout << false << "\n";
    return 0;
}

And the result is (as you'd probably expect):

0
faux

jQuery - Call ajax every 10 seconds

This worked for me

setInterval(ajax_query, 10000);

function ajax_query(){
   //Call ajax here
}

How do I reflect over the members of dynamic object?

In the case of ExpandoObject, the ExpandoObject class actually implements IDictionary<string, object> for its properties, so the solution is as trivial as casting:

IDictionary<string, object> propertyValues = (IDictionary<string, object>)s;

Note that this will not work for general dynamic objects. In these cases you will need to drop down to the DLR via IDynamicMetaObjectProvider.

Trying to get property of non-object MySQLi result

Just thought I would expand on this a bit.

If you perform a MYSQLI SELECT query that returns 0 results, it returns FALSE.

However, if you get this error and you have written your own MYSQLI Query function, then you can also get this error if the query you are running is not a select but an update. An update query will return either TRUE or FALSE. So if you just assume that any non false result will have records returned, then you will trip up when you run an update or anything other than select.

The easiest solution, once you have checked that its not false, is to first check that the result of the query is an object.

    $sqlResult = $connection->query($sql);
    if (!$sqlResult)
    {
     ... 
    }
    else if (is_object($sqlResult))
    {
        $sqlRowCount = $sqlResult->num_rows;
    }
    else
    {
        $sqlRowCount = 0;
    }

Node.js - How to send data from html to express

I'd like to expand on Obertklep's answer. In his example it is an NPM module called body-parser which is doing most of the work. Where he puts req.body.name, I believe he/she is using body-parser to get the contents of the name attribute(s) received when the form is submitted.

If you do not want to use Express, use querystring which is a built-in Node module. See the answers in the link below for an example of how to use querystring.

It might help to look at this answer, which is very similar to your quest.

How to store directory files listing into an array?

Running any shell command inside $(...) will help to store the output in a variable. So using that we can convert the files to array with IFS.

IFS=' ' read -r -a array <<< $(ls /path/to/dir)

PHP Pass variable to next page

HTML / HTTP is stateless, in other words, what you did / saw on the previous page, is completely unconnected with the current page. Except if you use something like sessions, cookies or GET / POST variables. Sessions and cookies are quite easy to use, with session being by far more secure than cookies. More secure, but not completely secure.

Session:

//On page 1
$_SESSION['varname'] = $var_value;

//On page 2
$var_value = $_SESSION['varname'];

Remember to run the session_start(); statement on both these pages before you try to access the $_SESSION array, and also before any output is sent to the browser.

Cookie:

//One page 1
$_COOKIE['varname'] = $var_value;

//On page 2
$var_value = $_COOKIE['varname'];

The big difference between sessions and cookies is that the value of the variable will be stored on the server if you're using sessions, and on the client if you're using cookies. I can't think of any good reason to use cookies instead of sessions, except if you want data to persist between sessions, but even then it's perhaps better to store it in a DB, and retrieve it based on a username or id.

GET and POST

You can add the variable in the link to the next page:

<a href="page2.php?varname=<?php echo $var_value ?>">Page2</a>

This will create a GET variable.

Another way is to include a hidden field in a form that submits to page two:

<form method="get" action="page2.php">
    <input type="hidden" name="varname" value="var_value">
    <input type="submit">
</form>

And then on page two:

//Using GET
$var_value = $_GET['varname'];

//Using POST
$var_value = $_POST['varname'];

//Using GET, POST or COOKIE.
$var_value = $_REQUEST['varname'];

Just change the method for the form to post if you want to do it via post. Both are equally insecure, although GET is easier to hack.

The fact that each new request is, except for session data, a totally new instance of the script caught me when I first started coding in PHP. Once you get used to it, it's quite simple though.

is there a require for json in node.js

Two of the most common

First way :

let jsonData = require('./JsonFile.json')

let jsonData = require('./JsonFile') // if we omitting .json also works

OR

import jsonData from ('./JsonFile.json')

Second way :

1) synchronously

const fs = require('fs')
let jsonData = JSON.parse(fs.readFileSync('JsonFile.json', 'utf-8'))

2) asynchronously

const fs = require('fs')
let jsonData = {}
fs.readFile('JsonFile.json', 'utf-8', (err, data) => {
  if (err) throw err

  jsonData = JSON.parse(data)
})

Note: 1) if we JsonFile.json is changed, we not get the new data, even if we re run require('./JsonFile.json')

2) The fs.readFile or fs.readFileSync will always re read the file, and get changes

Remove table row after clicking table row delete button

As @gaurang171 mentioned, we can use .closest() which will return the first ancestor, or the closest to our delete button, and use .remove() to remove it.

This is how we can implement it using jQuery click event instead of using JavaScript onclick.

HTML:

<table id="myTable">
<tr>
  <th width="30%" style="color:red;">ID</th>
  <th width="25%" style="color:red;">Name</th>
  <th width="25%" style="color:red;">Age</th>
  <th width="1%"></th>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-001</td>
  <td width="25%" style="color:red;">Ben</td>
  <td width="25%" style="color:red;">25</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-002</td>
  <td width="25%" style="color:red;">Anderson</td>
  <td width="25%" style="color:red;">47</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-003</td>
  <td width="25%" style="color:red;">Rocky</td>
  <td width="25%" style="color:red;">32</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-004</td>
  <td width="25%" style="color:red;">Lee</td>
  <td width="25%" style="color:red;">15</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>
                            

jQuery

 $(document).ready(function(){
     $("#myTable").on('click','.btnDelete',function(){
         $(this).closest('tr').remove();
      });
  });

Try in JSFiddle: click here.

bootstrap button shows blue outline when clicked

Try

.btn-primary:focus { 
  box-shadow: none !important; 
}

<div style display="none" > inside a table not working

Semantically what you are trying is invalid html, table element cannot have a div element as a direct child. What you can do is, get your div element inside a td element and than try to hide it

Input widths on Bootstrap 3

If you are using the Master.Site template in Visual Studio 15, the base project has "Site.css" which OVERRIDES the width of form-control fields.

I could not get the width of my text boxes to get any wider than about 300px wide. I tried EVERYTHING and nothing worked. I found that there is a setting in Site.css which was causing the problem.

Get rid of this and you can get control over your field widths.

/* Set widths on the form inputs since otherwise they're 100% wide */
input[type="text"],
input[type="password"],
input[type="email"],
input[type="tel"],
input[type="select"] {
    max-width: 280px;
}

How to convert an object to a byte array in C#

You are really talking about serialization, which can take many forms. Since you want small and binary, protocol buffers may be a viable option - giving version tolerance and portability as well. Unlike BinaryFormatter, the protocol buffers wire format doesn't include all the type metadata; just very terse markers to identify data.

In .NET there are a few implementations; in particular

I'd humbly argue that protobuf-net (which I wrote) allows more .NET-idiomatic usage with typical C# classes ("regular" protocol-buffers tends to demand code-generation); for example:

[ProtoContract]
public class Person {
   [ProtoMember(1)]
   public int Id {get;set;}
   [ProtoMember(2)]
   public string Name {get;set;}
}
....
Person person = new Person { Id = 123, Name = "abc" };
Serializer.Serialize(destStream, person);
...
Person anotherPerson = Serializer.Deserialize<Person>(sourceStream);

How should I read a file line-by-line in Python?

There is exactly one reason why the following is preferred:

with open('filename.txt') as fp:
    for line in fp:
        print line

We are all spoiled by CPython's relatively deterministic reference-counting scheme for garbage collection. Other, hypothetical implementations of Python will not necessarily close the file "quickly enough" without the with block if they use some other scheme to reclaim memory.

In such an implementation, you might get a "too many files open" error from the OS if your code opens files faster than the garbage collector calls finalizers on orphaned file handles. The usual workaround is to trigger the GC immediately, but this is a nasty hack and it has to be done by every function that could encounter the error, including those in libraries. What a nightmare.

Or you could just use the with block.

Bonus Question

(Stop reading now if are only interested in the objective aspects of the question.)

Why isn't that included in the iterator protocol for file objects?

This is a subjective question about API design, so I have a subjective answer in two parts.

On a gut level, this feels wrong, because it makes iterator protocol do two separate things—iterate over lines and close the file handle—and it's often a bad idea to make a simple-looking function do two actions. In this case, it feels especially bad because iterators relate in a quasi-functional, value-based way to the contents of a file, but managing file handles is a completely separate task. Squashing both, invisibly, into one action, is surprising to humans who read the code and makes it more difficult to reason about program behavior.

Other languages have essentially come to the same conclusion. Haskell briefly flirted with so-called "lazy IO" which allows you to iterate over a file and have it automatically closed when you get to the end of the stream, but it's almost universally discouraged to use lazy IO in Haskell these days, and Haskell users have mostly moved to more explicit resource management like Conduit which behaves more like the with block in Python.

On a technical level, there are some things you may want to do with a file handle in Python which would not work as well if iteration closed the file handle. For example, suppose I need to iterate over the file twice:

with open('filename.txt') as fp:
    for line in fp:
        ...
    fp.seek(0)
    for line in fp:
        ...

While this is a less common use case, consider the fact that I might have just added the three lines of code at the bottom to an existing code base which originally had the top three lines. If iteration closed the file, I wouldn't be able to do that. So keeping iteration and resource management separate makes it easier to compose chunks of code into a larger, working Python program.

Composability is one of the most important usability features of a language or API.

How do I modify a MySQL column to allow NULL?

Your syntax error is caused by a missing "table" in the query

ALTER TABLE mytable MODIFY mycolumn varchar(255) null;

Center a column using Twitter Bootstrap 3

You can use text-center for the row and can make sure the internal divs have display:inline-block (with not float).

As:

<div class="container">
    <div class="row text-center" style="background-color : black;">
        <div class="redBlock">A red block</div>
        <div class="whiteBlock">A white block</div>
        <div class="yellowBlock">A yellow block</div>
    </div>
</div>

And CSS:

.redBlock {
    width: 100px;
    height: 100px;
    background-color: aqua;
    display: inline-block
}
.whiteBlock {
    width: 100px;
    height: 100px;
    background-color: white;
    display: inline-block
}
.yellowBlock {
    width: 100px;
    height: 100px;
    background-color: yellow;
    display: inline-block
}

The fiddle: http://jsfiddle.net/DTcHh/3177/

String array initialization in Java

It is just not a valid Java syntax. You can do

names = new String[] {"Ankit","Bohra","Xyz"};

How to disable Hyper-V in command line?

I tried all of stack overflow and all didn't works. But this works for me:

  1. Open System Configuration
  2. Click Service tab
  3. Uncheck all of Hyper-V related

Bootstrap datepicker hide after selection

For datetime picker

$('yourpickerid').datetimepicker({
        format: 'dd/mm/yyyy',
}).on('changeDate', function(e){
        $(this).datetimepicker('hide');
});

What is the best way to filter a Java Collection?

I'll throw RxJava in the ring, which is also available on Android. RxJava might not always be the best option, but it will give you more flexibility if you wish add more transformations on your collection or handle errors while filtering.

Observable.from(Arrays.asList(1, 2, 3, 4, 5))
    .filter(new Func1<Integer, Boolean>() {
        public Boolean call(Integer i) {
            return i % 2 != 0;
        }
    })
    .subscribe(new Action1<Integer>() {
        public void call(Integer i) {
            System.out.println(i);
        }
    });

Output:

1
3
5

More details on RxJava's filter can be found here.

Android: I lost my android key store, what should I do?

If you lost a keystore file, don't create/update the new one with another set of value. First do the thorough search. Because it will overwrite the old one, so it will not match to your previous apk.

If you use eclipse most probably it will store in default path. For MAC (eclipse) it will be in your elispse installation path something like:

/Applications/eclipse/Eclipse.app/Contents/MacOS/

then your keystore file without any extension. You need root privilege to access this path (file).

Convert JavaScript String to be all lower case?

you can use the in built .toLowerCase() method on javascript strings. ex: var x = "Hello"; x.toLowerCase();

Convert Int to String in Swift

Multiple ways to do this :

var str1:String="\(23)"
var str2:String=String(format:"%d",234)

What's the difference between the atomic and nonatomic attributes?

The atomic property ensures to retain a fully initialised value irrespective of how many threads are doing getter & setter on it.

The nonatomic property specifies that synthesized accessors simply set or return a value directly, with no guarantees about what happens if that same value is accessed simultaneously from different threads.

How do I specify local .gem files in my Gemfile?

This isn't strictly an answer to your question about installing .gem packages, but you can specify all kinds of locations on a gem-by-gem basis by editing your Gemfile.

Specifying a :path attribute will install the gem from that path on your local machine.

gem "foreman", path: "/Users/pje/my_foreman_fork"

Alternately, specifying a :git attribute will install the gem from a remote git repository.

gem "foreman", git: "git://github.com/pje/foreman.git"

# ...or at a specific SHA-1 ref
gem "foreman", git: "git://github.com/pje/foreman.git", ref: "bf648a070c"

# ...or branch
gem "foreman", git: "git://github.com/pje/foreman.git", branch: "jruby"

# ...or tag
gem "foreman", git: "git://github.com/pje/foreman.git", tag: "v0.45.0"

(As @JHurrah mentioned in his comment.)

What is Model in ModelAndView from Spring MVC?

ModelAndView: The name itself explains it is data structure which contains Model and View data.

Map() model=new HashMap(); 
model.put("key.name", "key.value");
new ModelAndView("view.name", model);

// or as follows

ModelAndView mav = new ModelAndView();
mav.setViewName("view.name");
mav.addObject("key.name", "key.value");

if model contains only single value, we can write as follows:

ModelAndView("view.name","key.name", "key.value");

Generating HTML email body in C#

Use the System.Web.UI.HtmlTextWriter class.

StringWriter writer = new StringWriter();
HtmlTextWriter html = new HtmlTextWriter(writer);

html.RenderBeginTag(HtmlTextWriterTag.H1);
html.WriteEncodedText("Heading Here");
html.RenderEndTag();
html.WriteEncodedText(String.Format("Dear {0}", userName));
html.WriteBreak();
html.RenderBeginTag(HtmlTextWriterTag.P);
html.WriteEncodedText("First part of the email body goes here");
html.RenderEndTag();
html.Flush();

string htmlString = writer.ToString();

For extensive HTML that includes the creation of style attributes HtmlTextWriter is probably the best way to go. However it can be a bit clunky to use and some developers like the markup itself to be easily read but perversly HtmlTextWriter's choices with regard indentation is a bit wierd.

In this example you can also use XmlTextWriter quite effectively:-

writer = new StringWriter();
XmlTextWriter xml = new XmlTextWriter(writer);
xml.Formatting = Formatting.Indented;
xml.WriteElementString("h1", "Heading Here");
xml.WriteString(String.Format("Dear {0}", userName));
xml.WriteStartElement("br");
xml.WriteEndElement();
xml.WriteElementString("p", "First part of the email body goes here");
xml.Flush();

How to recover Git objects damaged by hard disk failure?

Banengusk was putting me on the right track. For further reference, I want to post the steps I took to fix my repository corruption. I was lucky enough to find all needed objects either in older packs or in repository backups.

# Unpack last non-corrupted pack
$ mv .git/objects/pack .git/objects/pack.old
$ git unpack-objects -r < .git/objects/pack.old/pack-012066c998b2d171913aeb5bf0719fd4655fa7d0.pack
$ git log
fatal: bad object HEAD

$ cat .git/HEAD 
ref: refs/heads/master

$ ls .git/refs/heads/

$ cat .git/packed-refs 
# pack-refs with: peeled 
aa268a069add6d71e162c4e2455c1b690079c8c1 refs/heads/master

$ git fsck --full 
error: HEAD: invalid sha1 pointer aa268a069add6d71e162c4e2455c1b690079c8c1
error: refs/heads/master does not point to a valid object!
missing blob 75405ef0e6f66e48c1ff836786ff110efa33a919
missing blob 27c4611ffbc3c32712a395910a96052a3de67c9b
dangling tree 30473f109d87f4bcde612a2b9a204c3e322cb0dc

# Copy HEAD object from backup of repository
$ cp repobackup/.git/objects/aa/268a069add6d71e162c4e2455c1b690079c8c1 .git/objects/aa
# Now copy all missing objects from backup of repository and run "git fsck --full" afterwards
# Repeat until git fsck --full only reports dangling objects

# Now garbage collect repo
$ git gc
warning: reflog of 'HEAD' references pruned commits
warning: reflog of 'refs/heads/master' references pruned commits
Counting objects: 3992, done.
Delta compression using 2 threads.
fatal: object bf1c4953c0ea4a045bf0975a916b53d247e7ca94 inconsistent object length (6093 vs 415232)
error: failed to run repack

# Check reflogs...
$ git reflog

# ...then clean
$ git reflog expire --expire=0 --all

# Now garbage collect again
$ git gc       
Counting objects: 3992, done.
Delta compression using 2 threads.
Compressing objects: 100% (3970/3970), done.
Writing objects: 100% (3992/3992), done.
Total 3992 (delta 2060), reused 0 (delta 0)
Removing duplicate objects: 100% (256/256), done.
# Done!

Rails: How do I create a default value for attributes in Rails activerecord's model?

You can set a default option for the column in the migration

....
add_column :status, :string, :default => "P"
....

OR

You can use a callback, before_save

class Task < ActiveRecord::Base
  before_save :default_values
  def default_values
    self.status ||= 'P' # note self.status = 'P' if self.status.nil? might be safer (per @frontendbeauty)
  end
end

Join/Where with LINQ and Lambda

Posting because when I started LINQ + EntityFramework, I stared at these examples for a day.

If you are using EntityFramework, and you have a navigation property named Meta on your Post model object set up, this is dirt easy. If you're using entity and don't have that navigation property, what are you waiting for?

database
  .Posts
  .Where(post => post.ID == id)
  .Select(post => new { post, post.Meta });

If you're doing code first, you'd set up the property thusly:

class Post {
  [Key]
  public int ID {get; set}
  public int MetaID { get; set; }
  public virtual Meta Meta {get; set;}
}

How do I activate C++ 11 in CMake?

As it turns out, SET(CMAKE_CXX_FLAGS "-std=c++0x") does activate many C++11 features. The reason it did not work was that the statement looked like this:

set(CMAKE_CXX_FLAGS "-std=c++0x ${CMAKE_CXX_FLAGS} -g -ftest-coverage -fprofile-arcs")

Following this approach, somehow the -std=c++0x flag was overwritten and it did not work. Setting the flags one by one or using a list method is working.

list( APPEND CMAKE_CXX_FLAGS "-std=c++0x ${CMAKE_CXX_FLAGS} -g -ftest-coverage -fprofile-arcs")

How to make a dropdown readonly using jquery?

As @Kanishka said , if we disable a form element it will not be submitted . I have created a snippet for this problem . When the select element is disabled it creates a hidden input field and store the value . When it is enabled it delete the created hidden input fields .

More info

_x000D_
_x000D_
jQuery(document).ready(function($) {_x000D_
  var $dropDown = $('#my-select'),_x000D_
    name = $dropDown.prop('name'),_x000D_
    $form = $dropDown.parent('form');_x000D_
_x000D_
  $dropDown.data('original-name', name); //store the name in the data attribute _x000D_
_x000D_
  $('#toggle').on('click', function(event) {_x000D_
    if ($dropDown.is('.disabled')) {_x000D_
      //enable it _x000D_
      $form.find('input[type="hidden"][name=' + name + ']').remove(); // remove the hidden fields if any_x000D_
      $dropDown.removeClass('disabled') //remove disable class _x000D_
        .prop({_x000D_
          name: name,_x000D_
          disabled: false_x000D_
        }); //restore the name and enable _x000D_
    } else {_x000D_
      //disable it _x000D_
      var $hiddenInput = $('<input/>', {_x000D_
        type: 'hidden',_x000D_
        name: name,_x000D_
        value: $dropDown.val()_x000D_
      });_x000D_
      $form.append($hiddenInput); //append the hidden field with same name and value from the dropdown field _x000D_
      $dropDown.addClass('disabled') //disable class_x000D_
        .prop({_x000D_
          'name': name + "_1",_x000D_
          disabled: true_x000D_
        }); //change name and disbale _x000D_
    }_x000D_
  });_x000D_
});
_x000D_
/*Optional*/_x000D_
_x000D_
select.disabled {_x000D_
  color: graytext;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<form action="#" name="my-form">_x000D_
  <select id="my-select" name="alpha">_x000D_
    <option value="A">A</option>_x000D_
    <option value="B">B</option>_x000D_
    <option value="C">C</option>_x000D_
  </select>_x000D_
</form>_x000D_
<br/>_x000D_
<button id="toggle">toggle enable/disable</button>
_x000D_
_x000D_
_x000D_

Image change every 30 seconds - loop

setInterval function is the one that has to be used. Here is an example for the same without any fancy fading option. Simple Javascript that does an image change every 30 seconds. I have assumed that the images were kept in a separate images folder and hence _images/ is present at the beginning of every image. You can have your own path as required to be set.

CODE:

var im = document.getElementById("img");

var images = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg"];
var index=0;

function changeImage()
{
  im.setAttribute("src", images[index]);
  index++;
  if(index >= images.length)
  {
    index=0;
  }
}

setInterval(changeImage, 30000);

Using openssl to get the certificate from a server

It turns out there is more complexity here: I needed to provide many more details to get this rolling. I think its something to do with the fact that its a connection that needs client authentication, and the hankshake needed more info to continue to the stage where the certificates were dumped.

Here is my working command:

openssl s_client -connect host:port -key our_private_key.pem -showcerts \
                 -cert our_server-signed_cert.pem

Hopefully this is a nudge in the right direction for anyone who could do with some more info.

How to toggle boolean state of react component?

I was landed in this page when I am searching to use toggle state in React component using Redux but I don't find here any approach using the same.

So, I think it might help someone who was struggling to implement toggle state using Redux.

My reducer file goes here. I get the initial state false by default.

const INITIAL_STATE = { popup: false };
export default (state = INITIAL_STATE, action) => {
    switch (action.type) {
        case "POPUP":
            return {
                ...state,
                popup: action.value
            };
        default:
            return state;
    }
    return state;
};

I change state on clicking the image. So, my img tag goes here with onClick function.

<img onClick={togglePopup} src={props.currentUser.image} className="avatar-image avatar-image--icon" />

My Toggle Popup function goes below, which call Dispatcher.

const togglePopup = ev => {
    ev.preventDefault();
    props.handlePopup(!props.popup);
};

This call goes to below mapDispatchToProps function which reflects back the toggled state.

const mapDispatchToProps = dispatch => ({
    handlePopup: value => dispatch({ type: "POPUP", value })
});

Thank you.

Uncaught TypeError: Cannot set property 'onclick' of null

Make sure your javascript is being executed after your element(s) have loaded, perhaps try putting the js file call just before the tag or use the defer attribute in your script, like so: <script src="app.js" defer></script> this makes sure that your script will be executed after the dom has loaded.

Nesting optgroups in a dropdownlist/select

This is just fine but if you add option which is not in optgroup it gets buggy.

_x000D_
_x000D_
<select>_x000D_
  <optgroup label="Level One">_x000D_
    <option> A.1 </option>_x000D_
    <optgroup label="&nbsp;&nbsp;&nbsp;&nbsp;Level Two">_x000D_
      <option>&nbsp;&nbsp;&nbsp;&nbsp; A.B.1 </option>_x000D_
    </optgroup>_x000D_
    <option> A.2 </option>_x000D_
  </optgroup>_x000D_
  <option> A </option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Would be much better if you used css and close optgroup right away :

_x000D_
_x000D_
<select>_x000D_
  <optgroup label="Level One"></optgroup>_x000D_
  <option style="padding-left:15px"> A.1 </option>_x000D_
  <optgroup label="Level Two" style="padding-left:15px"></optgroup>_x000D_
  <option style="padding-left:30px"> A.B.1 </option>_x000D_
  <option style="padding-left:15px"> A.2 </option>_x000D_
  <option> A </option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to convert an entire MySQL database characterset and collation to UTF-8?

You can also DB tool Navicat, which does it more easier.

  • Siva.

Right Click Your Database & select DB Properties & Change as you desired in Drop Down

enter image description here

grep for multiple strings in file on different lines (ie. whole file, not line based search)?

awk '/Dansk/{a=1}/Norsk/{b=1}/Svenska/{c=1}END{ if (a && b && c) print "0" }' 

you can then catch the return value with the shell

if you have Ruby(1.9+)

ruby -0777 -ne 'print if /Dansk/ and /Norsk/ and /Svenka/' file

Scraping html tables into R data frames using the XML package

The rvest along with xml2 is another popular package for parsing html web pages.

library(rvest)
theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
file<-read_html(theurl)
tables<-html_nodes(file, "table")
table1 <- html_table(tables[4], fill = TRUE)

The syntax is easier to use than the xml package and for most web pages the package provides all of the options ones needs.

How to add plus one (+1) to a SQL Server column in a SQL Query

"UPDATE TableName SET TableField = TableField + 1 WHERE SomeFilterField = @ParameterID"

Converting Pandas dataframe into Spark dataframe error

Type related errors can be avoided by imposing a schema as follows:

note: a text file was created (test.csv) with the original data (as above) and hypothetical column names were inserted ("col1","col2",...,"col25").

import pyspark
from pyspark.sql import SparkSession
import pandas as pd

spark = SparkSession.builder.appName('pandasToSparkDF').getOrCreate()

pdDF = pd.read_csv("test.csv")

contents of the pandas data frame:

       col1     col2    col3    col4    col5    col6    col7    col8   ... 
0      10000001 1       0       1       12:35   OK      10002   1      ...
1      10000001 2       0       1       12:36   OK      10002   1      ...
2      10000002 1       0       4       12:19   PA      10003   1      ...

Next, create the schema:

from pyspark.sql.types import *

mySchema = StructType([ StructField("col1", LongType(), True)\
                       ,StructField("col2", IntegerType(), True)\
                       ,StructField("col3", IntegerType(), True)\
                       ,StructField("col4", IntegerType(), True)\
                       ,StructField("col5", StringType(), True)\
                       ,StructField("col6", StringType(), True)\
                       ,StructField("col7", IntegerType(), True)\
                       ,StructField("col8", IntegerType(), True)\
                       ,StructField("col9", IntegerType(), True)\
                       ,StructField("col10", IntegerType(), True)\
                       ,StructField("col11", StringType(), True)\
                       ,StructField("col12", StringType(), True)\
                       ,StructField("col13", IntegerType(), True)\
                       ,StructField("col14", IntegerType(), True)\
                       ,StructField("col15", IntegerType(), True)\
                       ,StructField("col16", IntegerType(), True)\
                       ,StructField("col17", IntegerType(), True)\
                       ,StructField("col18", IntegerType(), True)\
                       ,StructField("col19", IntegerType(), True)\
                       ,StructField("col20", IntegerType(), True)\
                       ,StructField("col21", IntegerType(), True)\
                       ,StructField("col22", IntegerType(), True)\
                       ,StructField("col23", IntegerType(), True)\
                       ,StructField("col24", IntegerType(), True)\
                       ,StructField("col25", IntegerType(), True)])

Note: True (implies nullable allowed)

create the pyspark dataframe:

df = spark.createDataFrame(pdDF,schema=mySchema)

confirm the pandas data frame is now a pyspark data frame:

type(df)

output:

pyspark.sql.dataframe.DataFrame

Aside:

To address Kate's comment below - to impose a general (String) schema you can do the following:

df=spark.createDataFrame(pdDF.astype(str)) 

What's an easy way to read random line from a file in Unix command line?

Here's a simple Python script that will do the job:

import random, sys
lines = open(sys.argv[1]).readlines()
print(lines[random.randrange(len(lines))])

Usage:

python randline.py file_to_get_random_line_from

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

Just putting in my 5 cents here. For me none of the above worked, so I was forced to stress down and actually look at every part of the process with fresh eyes.

In rushing this I forgot that I was trying to install my app on a totally new device.

So my error was that I hadn't updated my provisioning profile by ticking off my new device int the "Devices" section of the provisioning profile setup in the Provisioning Portal.

Apparently not including your device in the provisioning profile also generates this error message.

Using SELECT result in another SELECT

You are missing table NewScores, so it can't be found. Just join this table.

If you really want to avoid joining it directly you can replace NewScores.NetScore with SELECT NetScore FROM NewScores WHERE {conditions on which they should be matched}

Make div (height) occupy parent remaining height

Expanding the #down child to fill the remaining space of #container can be accomplished in various ways depending on the browser support you wish to achieve and whether or not #up has a defined height.

Samples

_x000D_
_x000D_
.container {_x000D_
  width: 100px;_x000D_
  height: 300px;_x000D_
  border: 1px solid red;_x000D_
  float: left;_x000D_
}_x000D_
.up {_x000D_
  background: green;_x000D_
}_x000D_
.down {_x000D_
  background: pink;_x000D_
}_x000D_
.grid.container {_x000D_
  display: grid;_x000D_
  grid-template-rows: 100px;_x000D_
}_x000D_
.flexbox.container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
.flexbox.container .down {_x000D_
  flex-grow: 1;_x000D_
}_x000D_
.calc .up {_x000D_
  height: 100px;_x000D_
}_x000D_
.calc .down {_x000D_
  height: calc(100% - 100px);_x000D_
}_x000D_
.overflow.container {_x000D_
  overflow: hidden;_x000D_
}_x000D_
.overflow .down {_x000D_
  height: 100%;_x000D_
}
_x000D_
<div class="grid container">_x000D_
  <div class="up">grid_x000D_
    <br />grid_x000D_
    <br />grid_x000D_
    <br />_x000D_
  </div>_x000D_
  <div class="down">grid_x000D_
    <br />grid_x000D_
    <br />grid_x000D_
    <br />_x000D_
  </div>_x000D_
</div>_x000D_
<div class="flexbox container">_x000D_
  <div class="up">flexbox_x000D_
    <br />flexbox_x000D_
    <br />flexbox_x000D_
    <br />_x000D_
  </div>_x000D_
  <div class="down">flexbox_x000D_
    <br />flexbox_x000D_
    <br />flexbox_x000D_
    <br />_x000D_
  </div>_x000D_
</div>_x000D_
<div class="calc container">_x000D_
  <div class="up">calc_x000D_
    <br />calc_x000D_
    <br />calc_x000D_
    <br />_x000D_
  </div>_x000D_
  <div class="down">calc_x000D_
    <br />calc_x000D_
    <br />calc_x000D_
    <br />_x000D_
  </div>_x000D_
</div>_x000D_
<div class="overflow container">_x000D_
  <div class="up">overflow_x000D_
    <br />overflow_x000D_
    <br />overflow_x000D_
    <br />_x000D_
  </div>_x000D_
  <div class="down">overflow_x000D_
    <br />overflow_x000D_
    <br />overflow_x000D_
    <br />_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Grid

CSS's grid layout offers yet another option, though it may not be as straightforward as the Flexbox model. However, it only requires styling the container element:

.container { display: grid; grid-template-rows: 100px }

The grid-template-rows defines the first row as a fixed 100px height, and the remain rows will automatically stretch to fill the remaining space.

I'm pretty sure IE11 requires -ms- prefixes, so make sure to validate the functionality in the browsers you wish to support.

Flexbox

CSS3's Flexible Box Layout Module (flexbox) is now well-supported and can be very easy to implement. Because it is flexible, it even works when #up does not have a defined height.

#container { display: flex; flex-direction: column; }
#down { flex-grow: 1; }

It's important to note that IE10 & IE11 support for some flexbox properties can be buggy, and IE9 or below has no support at all.

Calculated Height

Another easy solution is to use the CSS3 calc functional unit, as Alvaro points out in his answer, but it requires the height of the first child to be a known value:

#up { height: 100px; }
#down { height: calc( 100% - 100px ); }

It is pretty widely supported, with the only notable exceptions being <= IE8 or Safari 5 (no support) and IE9 (partial support). Some other issues include using calc in conjunction with transform or box-shadow, so be sure to test in multiple browsers if that is of concern to you.

Other Alternatives

If older support is needed, you could add height:100%; to #down will make the pink div full height, with one caveat. It will cause overflow for the container, because #up is pushing it down.

Therefore, you could add overflow: hidden; to the container to fix that.

Alternatively, if the height of #up is fixed, you could position it absolutely within the container, and add a padding-top to #down.

And, yet another option would be to use a table display:

#container { width: 300px; height: 300px; border: 1px solid red; display: table;}
#up { background: green; display: table-row; height: 0; }
#down { background: pink; display: table-row;}?

User Control - Custom Properties

You do this via attributes on the properties, like this:

[Description("Test text displayed in the textbox"),Category("Data")] 
public string Text {
  get => myInnerTextBox.Text;
  set => myInnerTextBox.Text = value;
}

The category is the heading under which the property will appear in the Visual Studio Properties box. Here's a more complete MSDN reference, including a list of categories.

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

private void btnSent_Click(object sender, EventArgs e)
{
    try
    {
        MailMessage mail = new MailMessage();
        SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

        mail.From = new MailAddress(txtAcc.Text);
        mail.To.Add(txtToAdd.Text);
        mail.Subject = txtSub.Text;
        mail.Body = txtContent.Text;
        System.Net.Mail.Attachment attachment;
        attachment = new System.Net.Mail.Attachment(txtAttachment.Text);
        mail.Attachments.Add(attachment);

        SmtpServer.Port = 587;
        SmtpServer.Credentials = new System.Net.NetworkCredential(txtAcc.Text, txtPassword.Text);

        SmtpServer.EnableSsl = true;

        SmtpServer.Send(mail);
        MessageBox.Show("mail send");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

private void button1_Click(object sender, EventArgs e)
{
    MailMessage mail = new MailMessage();
    openFileDialog1.ShowDialog();
    System.Net.Mail.Attachment attachment;
    attachment = new System.Net.Mail.Attachment(openFileDialog1.FileName);
    mail.Attachments.Add(attachment);
    txtAttachment.Text =Convert.ToString (openFileDialog1.FileName);
}

Creating a 3D sphere in Opengl using Visual C++

I don't understand how can datenwolf`s index generation can be correct. But still I find his solution rather clear. This is what I get after some thinking:

inline void push_indices(vector<GLushort>& indices, int sectors, int r, int s) {
    int curRow = r * sectors;
    int nextRow = (r+1) * sectors;

    indices.push_back(curRow + s);
    indices.push_back(nextRow + s);
    indices.push_back(nextRow + (s+1));

    indices.push_back(curRow + s);
    indices.push_back(nextRow + (s+1));
    indices.push_back(curRow + (s+1));
}

void createSphere(vector<vec3>& vertices, vector<GLushort>& indices, vector<vec2>& texcoords,
             float radius, unsigned int rings, unsigned int sectors)
{
    float const R = 1./(float)(rings-1);
    float const S = 1./(float)(sectors-1);

    for(int r = 0; r < rings; ++r) {
        for(int s = 0; s < sectors; ++s) {
            float const y = sin( -M_PI_2 + M_PI * r * R );
            float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
            float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );

            texcoords.push_back(vec2(s*S, r*R));
            vertices.push_back(vec3(x,y,z) * radius);
            push_indices(indices, sectors, r, s);
        }
    }
}

Secure hash and salt for PHP passwords

DISCLAIMER: This answer was written in 2008.

Since then, PHP has given us password_hash and password_verify and, since their introduction, they are the recommended password hashing & checking method.

The theory of the answer is still a good read though.

TL;DR

Don'ts

  • Don't limit what characters users can enter for passwords. Only idiots do this.
  • Don't limit the length of a password. If your users want a sentence with supercalifragilisticexpialidocious in it, don't prevent them from using it.
  • Don't strip or escape HTML and special characters in the password.
  • Never store your user's password in plain-text.
  • Never email a password to your user except when they have lost theirs, and you sent a temporary one.
  • Never, ever log passwords in any manner.
  • Never hash passwords with SHA1 or MD5 or even SHA256! Modern crackers can exceed 60 and 180 billion hashes/second (respectively).
  • Don't mix bcrypt and with the raw output of hash(), either use hex output or base64_encode it. (This applies to any input that may have a rogue \0 in it, which can seriously weaken security.)

Dos

  • Use scrypt when you can; bcrypt if you cannot.
  • Use PBKDF2 if you cannot use either bcrypt or scrypt, with SHA2 hashes.
  • Reset everyone's passwords when the database is compromised.
  • Implement a reasonable 8-10 character minimum length, plus require at least 1 upper case letter, 1 lower case letter, a number, and a symbol. This will improve the entropy of the password, in turn making it harder to crack. (See the "What makes a good password?" section for some debate.)

Why hash passwords anyway?

The objective behind hashing passwords is simple: preventing malicious access to user accounts by compromising the database. So the goal of password hashing is to deter a hacker or cracker by costing them too much time or money to calculate the plain-text passwords. And time/cost are the best deterrents in your arsenal.

Another reason that you want a good, robust hash on a user accounts is to give you enough time to change all the passwords in the system. If your database is compromised you will need enough time to at least lock the system down, if not change every password in the database.

Jeremiah Grossman, CTO of Whitehat Security, stated on White Hat Security blog after a recent password recovery that required brute-force breaking of his password protection:

Interestingly, in living out this nightmare, I learned A LOT I didn’t know about password cracking, storage, and complexity. I’ve come to appreciate why password storage is ever so much more important than password complexity. If you don’t know how your password is stored, then all you really can depend upon is complexity. This might be common knowledge to password and crypto pros, but for the average InfoSec or Web Security expert, I highly doubt it.

(Emphasis mine.)

What makes a good password anyway?

Entropy. (Not that I fully subscribe to Randall's viewpoint.)

In short, entropy is how much variation is within the password. When a password is only lowercase roman letters, that's only 26 characters. That isn't much variation. Alpha-numeric passwords are better, with 36 characters. But allowing upper and lower case, with symbols, is roughly 96 characters. That's a lot better than just letters. One problem is, to make our passwords memorable we insert patterns—which reduces entropy. Oops!

Password entropy is approximated easily. Using the full range of ascii characters (roughly 96 typeable characters) yields an entropy of 6.6 per character, which at 8 characters for a password is still too low (52.679 bits of entropy) for future security. But the good news is: longer passwords, and passwords with unicode characters, really increase the entropy of a password and make it harder to crack.

There's a longer discussion of password entropy on the Crypto StackExchange site. A good Google search will also turn up a lot of results.

In the comments I talked with @popnoodles, who pointed out that enforcing a password policy of X length with X many letters, numbers, symbols, etc, can actually reduce entropy by making the password scheme more predictable. I do agree. Randomess, as truly random as possible, is always the safest but least memorable solution.

So far as I've been able to tell, making the world's best password is a Catch-22. Either its not memorable, too predictable, too short, too many unicode characters (hard to type on a Windows/Mobile device), too long, etc. No password is truly good enough for our purposes, so we must protect them as though they were in Fort Knox.

Best practices

Bcrypt and scrypt are the current best practices. Scrypt will be better than bcrypt in time, but it hasn't seen adoption as a standard by Linux/Unix or by webservers, and hasn't had in-depth reviews of its algorithm posted yet. But still, the future of the algorithm does look promising. If you are working with Ruby there is an scrypt gem that will help you out, and Node.js now has its own scrypt package. You can use Scrypt in PHP either via the Scrypt extension or the Libsodium extension (both are available in PECL).

I highly suggest reading the documentation for the crypt function if you want to understand how to use bcrypt, or finding yourself a good wrapper or use something like PHPASS for a more legacy implementation. I recommend a minimum of 12 rounds of bcrypt, if not 15 to 18.

I changed my mind about using bcrypt when I learned that bcrypt only uses blowfish's key schedule, with a variable cost mechanism. The latter lets you increase the cost to brute-force a password by increasing blowfish's already expensive key schedule.

Average practices

I almost can't imagine this situation anymore. PHPASS supports PHP 3.0.18 through 5.3, so it is usable on almost every installation imaginable—and should be used if you don't know for certain that your environment supports bcrypt.

But suppose that you cannot use bcrypt or PHPASS at all. What then?

Try an implementation of PDKBF2 with the maximum number of rounds that your environment/application/user-perception can tolerate. The lowest number I'd recommend is 2500 rounds. Also, make sure to use hash_hmac() if it is available to make the operation harder to reproduce.

Future Practices

Coming in PHP 5.5 is a full password protection library that abstracts away any pains of working with bcrypt. While most of us are stuck with PHP 5.2 and 5.3 in most common environments, especially shared hosts, @ircmaxell has built a compatibility layer for the coming API that is backward compatible to PHP 5.3.7.

Cryptography Recap & Disclaimer

The computational power required to actually crack a hashed password doesn't exist. The only way for computers to "crack" a password is to recreate it and simulate the hashing algorithm used to secure it. The speed of the hash is linearly related to its ability to be brute-forced. Worse still, most hash algorithms can be easily parallelized to perform even faster. This is why costly schemes like bcrypt and scrypt are so important.

You cannot possibly foresee all threats or avenues of attack, and so you must make your best effort to protect your users up front. If you do not, then you might even miss the fact that you were attacked until it's too late... and you're liable. To avoid that situation, act paranoid to begin with. Attack your own software (internally) and attempt to steal user credentials, or modify other user's accounts or access their data. If you don't test the security of your system, then you cannot blame anyone but yourself.

Lastly: I am not a cryptographer. Whatever I've said is my opinion, but I happen to think it's based on good ol' common sense ... and lots of reading. Remember, be as paranoid as possible, make things as hard to intrude as possible, and then, if you are still worried, contact a white-hat hacker or cryptographer to see what they say about your code/system.

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

For what it's worth, I had the issue as well in IE11:

  • I was not in Enterprise mode.
  • The "Display intranet sites in Compatibility View" was checked.
  • I had all the <!DOCTYPE html> and IE=Edge settings mentioned in the question
  • The meta header was indeed the 1st element in the <head> element

After a while, I found out that:

  • the User Agent header sent to the server was IE7 but...
  • the JavaScript value was IE11!

HTTP Header:

User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E) but

JavaScript:

window.navigator.userAgent === 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; rv:11.0) like Gecko'

So I ended up doing the check on the client side.

And BTW, meanwhile, checking the user agent is no longer recommended. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent (but there might be a good case)

What's the best practice to round a float to 2 decimals?

I've tried to support the -ve values for @Ivan Stin excellent 2nd method. (Major credit goes to @Ivan Stin for his method)

public static float round(float value, int scale) {
    int pow = 10;
    for (int i = 1; i < scale; i++) {
        pow *= 10;
    }
    float tmp = value * pow;
    float tmpSub = tmp - (int) tmp;

    return ( (float) ( (int) (
            value >= 0
            ? (tmpSub >= 0.5f ? tmp + 1 : tmp)
            : (tmpSub >= -0.5f ? tmp : tmp - 1)
            ) ) ) / pow;

    // Below will only handles +ve values
    // return ( (float) ( (int) ((tmp - (int) tmp) >= 0.5f ? tmp + 1 : tmp) ) ) / pow;
}

Below are the tests cases I've tried. Please let me know if this is not addressing any other cases.

@Test
public void testFloatRound() {
    // +ve values
    Assert.assertEquals(0F, NumberUtils.round(0F), 0);
    Assert.assertEquals(1F, NumberUtils.round(1F), 0);
    Assert.assertEquals(23.46F, NumberUtils.round(23.4567F), 0);
    Assert.assertEquals(23.45F, NumberUtils.round(23.4547F), 0D);
    Assert.assertEquals(1.00F, NumberUtils.round(0.49999999999999994F + 0.5F), 0);
    Assert.assertEquals(123.12F, NumberUtils.round(123.123F), 0);
    Assert.assertEquals(0.12F, NumberUtils.round(0.123F), 0);
    Assert.assertEquals(0.55F, NumberUtils.round(0.55F), 0);
    Assert.assertEquals(0.55F, NumberUtils.round(0.554F), 0);
    Assert.assertEquals(0.56F, NumberUtils.round(0.556F), 0);
    Assert.assertEquals(123.13F, NumberUtils.round(123.126F), 0);
    Assert.assertEquals(123.15F, NumberUtils.round(123.15F), 0);
    Assert.assertEquals(123.17F, NumberUtils.round(123.1666F), 0);
    Assert.assertEquals(123.46F, NumberUtils.round(123.4567F), 0);
    Assert.assertEquals(123.87F, NumberUtils.round(123.8711F), 0);
    Assert.assertEquals(123.15F, NumberUtils.round(123.15123F), 0);
    Assert.assertEquals(123.89F, NumberUtils.round(123.8909F), 0);
    Assert.assertEquals(124.00F, NumberUtils.round(123.9999F), 0);
    Assert.assertEquals(123.70F, NumberUtils.round(123.7F), 0);
    Assert.assertEquals(123.56F, NumberUtils.round(123.555F), 0);
    Assert.assertEquals(123.00F, NumberUtils.round(123.00F), 0);
    Assert.assertEquals(123.50F, NumberUtils.round(123.50F), 0);
    Assert.assertEquals(123.93F, NumberUtils.round(123.93F), 0);
    Assert.assertEquals(123.93F, NumberUtils.round(123.9312F), 0);
    Assert.assertEquals(123.94F, NumberUtils.round(123.9351F), 0);
    Assert.assertEquals(123.94F, NumberUtils.round(123.9350F), 0);
    Assert.assertEquals(123.94F, NumberUtils.round(123.93501F), 0);
    Assert.assertEquals(99.99F, NumberUtils.round(99.99F), 0);
    Assert.assertEquals(100.00F, NumberUtils.round(99.999F), 0);
    Assert.assertEquals(100.00F, NumberUtils.round(99.9999F), 0);

    // -ve values
    Assert.assertEquals(-123.94F, NumberUtils.round(-123.93501F), 0);
    Assert.assertEquals(-123.00F, NumberUtils.round(-123.001F), 0);
    Assert.assertEquals(-0.94F, NumberUtils.round(-0.93501F), 0);
    Assert.assertEquals(-1F, NumberUtils.round(-1F), 0);
    Assert.assertEquals(-0.50F, NumberUtils.round(-0.50F), 0);
    Assert.assertEquals(-0.55F, NumberUtils.round(-0.55F), 0);
    Assert.assertEquals(-0.55F, NumberUtils.round(-0.554F), 0);
    Assert.assertEquals(-0.56F, NumberUtils.round(-0.556F), 0);
    Assert.assertEquals(-0.12F, NumberUtils.round(-0.1234F), 0);
    Assert.assertEquals(-0.12F, NumberUtils.round(-0.123456789F), 0);
    Assert.assertEquals(-0.13F, NumberUtils.round(-0.129F), 0);
    Assert.assertEquals(-99.99F, NumberUtils.round(-99.99F), 0);
    Assert.assertEquals(-100.00F, NumberUtils.round(-99.999F), 0);
    Assert.assertEquals(-100.00F, NumberUtils.round(-99.9999F), 0);
}

How to replace values at specific indexes of a python list?

You can use operator.setitem.

from operator import setitem
a = [5, 4, 3, 2, 1, 0]
ell = [0, 1, 3, 5]
m = [0, 0, 0, 0]
for b, c in zip(ell, m):
    setitem(a, b, c)
>>> a
[0, 0, 3, 0, 1, 0]

Is it any more readable or efficient than your solution? I am not sure!

How to add and remove classes in Javascript without jQuery

For future friendliness, I second the recommendation for classList with polyfill/shim: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#wrapper

var elem = document.getElementById( 'some-id' );
elem.classList.add('some-class'); // Add class
elem.classList.remove('some-other-class'); // Remove class
elem.classList.toggle('some-other-class'); // Add or remove class
if ( elem.classList.contains('some-third-class') ) { // Check for class
    console.log('yep!');
}

SQL: How to get the id of values I just INSERTed?

There's no standard way to do it (just as there is no standard way to create auto-incrementing IDs). Here are two ways to do it in PostgreSQL. Assume this is your table:

CREATE TABLE mytable (
  id SERIAL PRIMARY KEY,
  lastname VARCHAR NOT NULL,
  firstname VARCHAR
);

You can do it in two statements as long as they're consecutive statements in the same connection (this will be safe in PHP with connection pooling because PHP doesn't give the connection back to the pool until your script is done):

INSERT INTO mytable (lastname, firstname) VALUES ('Washington', 'George');
SELECT lastval();

lastval() gives you the last auto-generated sequence value used in the current connection.

The other way is to use PostgreSQL's RETURNING clause on the INSERT statement:

INSERT INTO mytable (lastname) VALUES ('Cher') RETURNING id;

This form returns a result set just like a SELECT statement, and is also handy for returning any kind of calculated default value.

Import mysql DB with XAMPP in command LINE

Do your trouble shooting in controlled steps:

(1) Does the script looks ok?

DOS E:\trials\SoTrials\SoDbTrials\MySQLScripts
type ansi.sql
show databases

(2) Can you connect to your database (even without specified the host)?

DOS E:\trials\SoTrials\SoDbTrials\MySQLScripts
mysql -u root -p mysql
Enter password: ********
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 5.0.51b-community-nt MySQL Community Edition (GPL)
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

(3) Can you source the script? (Hoping for more/better error info)

mysql> source ansi.sql
+--------------------+
| Database           |
+--------------------+
| information_schema |
| ...                |
| test               |
+--------------------+
7 rows in set (0.01 sec)
mysql> quit
Bye

(4) Why does it (still not) work?

DOS E:\trials\SoTrials\SoDbTrials\MySQLScripts
mysql -u root -p mysql < ansi.sql
Enter password: ********
Database
information_schema
...
test

I suspected that the encoding of the script could be the culprit, but I got syntax errors for UTF8 or UTF16 encoded files:

ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near '´++
show databases' at line 1

This could be a version thing; so I think you should make sure of the encoding of your script.

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

I have used MySQL DB for Hive MetaStore. Please follow the below steps:

  • in hive-site.xml the metastore should be proper
<property>
 <name>javax.jdo.option.ConnectionURL</name> 
 <value>jdbc:mysql://localhost/metastorecreateDatabaseIfNotExist=true&amp;useSSL=false</value>
</property>
  • go to the mysql: mysql -u hduser -p
  • then run drop database metastore
  • then come out from MySQL and execute schematool -initSchema dbType mysql

Now error will go.

Laravel 5 How to switch from Production mode

What you could also have a look at is the exposed method Application->loadEnvironmentFrom($file)

I needed one application to run on multiple subdomains. So in bootstrap/app.php I added something like:

$envFile = '.env';
// change $envFile conditionally here
$app->loadEnvironmentFrom($envFile);

Animate background image change with jQuery

It can be done by jquery and css. i did it in a way that can be used in dynamic situations , you just have to change background-image in jquery and it will do every thing , also you can change the time in css.

The fiddle : https://jsfiddle.net/Naderial/zohfvqz7/

Html:

<div class="test">

CSS :

.test {
  /* as default, we set a background-image , but it is not nessesary */
  background-image: url(http://lorempixel.com/400/200);
  width: 200px;
  height: 200px;
  /* we set transition to 'all' properies - but you can use it just for background image either - by default the time is set to 1 second, you can change it yourself*/
  transition: linear all 1s;
  /* if you don't use delay , background will disapear and transition will start from a white background - you have to set the transition-delay the same as transition time OR more , so there won't be any problems */
  -webkit-transition-delay: 1s;/* Safari */
  transition-delay: 1s;
}

JS:

$('.test').click(function() {
  //you can use all properties : background-color  - background-image ...
  $(this).css({
    'background-image': 'url(http://lorempixel.com/400/200)'
  });
});

Pass a variable to a PHP script running from the command line

There are four main alternatives. Both have their quirks, but Method 4 has many advantages from my view.


./script is a shell script starting by #!/usr/bin/php


Method 1: $argv

./script hello wo8844rld
// $argv[0] = "script", $argv[1] = "hello", $argv[2] = "wo8844rld"

?? Using $argv, the parameter order is critical.


Method 2: getopt()

./script -p7 -e3
// getopt("p::")["p"] = "7", getopt("e::")["e"] = "3"

It's hard to use in conjunction of $argv, because:

?? The parsing of options will end at the first non-option found, anything that follows is discarded.

?? Only 26 parameters as the alphabet.


Method 3: Bash Global variable

P9="xptdr" ./script
// getenv("P9") = "xptdr"
// $_SERVER["P9"] = "xptdr"

Those variables can be used by other programs running in the same shell.

They are blown when the shell is closed, but not when the PHP program is terminated. We can set them permanent in file ~/.bashrc!


Method 4: STDIN pipe and stream_get_contents()

Some piping examples:


Feed a string:

./script <<< "hello wo8844rld"
// stream_get_contents(STDIN) = "hello wo8844rld"

Feed a string using bash echo:

echo "hello wo8844rld" | ./script
// explode(" ",stream_get_contents(STDIN)) ...

Feed a file content:

./script < ~/folder/Special_params.txt
// explode("\n",stream_get_contents(STDIN)) ...

Feed an array of values:

./script <<< '["array entry","lol"]'
// var_dump( json_decode(trim(stream_get_contents(STDIN))) );

Feed JSON content from a file:

echo params.json | ./script
// json_decode(stream_get_contents(STDIN)) ...

It might work similarly to fread() or fgets(), by reading the STDIN.


Bash-Scripting Guide

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Use content="IE=edge,chrome=1"   Skip other X-UA-Compatible modes

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
                                   -------------------------- 
  • No compatibility icon
    The IE9 Address bar does not show up the Compatibility View button
    and the page does not also show up a jumble of out-of-place menus, images, and text boxes.

  • Features
    This meta tag is required to enable javascript::JSON.parse() on IE8
    (even when <!DOCTYPE html> is present)

  • Correctness
    Rendering/Execution of modern HTML/CSS/JavaScript is more valid (nicer).

  • Performance
    The Trident rendering engine should run faster in its edge mode.


Usage

In your HTML

<!DOCTYPE html> 
<html> 
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

Or better in the configuration of your web server:
(see also the RiaD's answer)

  • Apache as proposed by pixeline

    <IfModule mod_setenvif.c>
      <IfModule mod_headers.c>
        BrowserMatch MSIE ie
        Header set X-UA-Compatible "IE=Edge,chrome=1" env=ie
      </IfModule>
    </IfModule>
    <IfModule mod_headers.c>
      Header append Vary User-Agent
    </IfModule>
    
  • Nginx as proposed by Stef Pause

    server {
      #...
      add_header X-UA-Compatible "IE=Edge,chrome=1";
    }
    
  • Varnish proxy as proposed by Lucas Riutzel

    sub vcl_deliver {
      if( resp.http.Content-Type ~ "text/html" ) {
        set resp.http.X-UA-Compatible = "IE=edge,chrome=1";
      }
    }
    
  • IIS (since v7)

    <configuration>
      <system.webServer>
         <httpProtocol>
            <customHeaders>
               <add name="X-UA-Compatible" value="IE=edge,chrome=1" />
            </customHeaders>
         </httpProtocol>
      </system.webServer>
    </configuration>
    

Microsoft recommends Edge mode since IE11

As noticed by Lynda (see comments), the Compatibility changes in IE11 recommends Edge mode:

Starting with IE11, edge mode is the preferred document mode; it represents the highest support for modern standards available to the browser.

But the position of Microsoft was not clear. Another MSDN page did not recommend Edge mode:

Because Edge mode forces all pages to be opened in standards mode, regardless of the version of Internet Explorer, you might be tempted to use this for all pages viewed with Internet Explorer. Don't do this, as the X-UA-Compatible header is only supported starting with Windows Internet Explorer 8.

Instead, Microsoft recommended using <!DOCTYPE html>:

If you want all supported versions of Internet Explorer to open your pages in standards mode, use the HTML5 document type declaration [...]

As Ricardo explains (in the comments below) any DOCTYPE (HTML4, XHTML1...) can be used to trigger Standards Mode, not only HTML5's DOCTYPE. The important thing is to always have a DOCTYPE in the page.

Clara Onager has even noticed in an older version of Specifying legacy document modes:

Edge mode is intended for testing purposes only; do not use it in a production environment.

It is so confusing that Usman Y thought Clara Onager was speaking about:

The [...] example is provided for illustrative purposes only; don't use it in a production environment.

<meta http-equiv="X-UA-Compatible" content="IE=7,9,10" >

Well... In the rest of this answer I give more explanations why using content="IE=edge,chrome=1" is a good practice in production.


History

For many years (2000 to 2008), IE market share was more than 80%. And IE v6 was considered as a de facto standard (80% to 97% market share in 2003, 2004, 2005 and 2006 for IE6 only, more market share with all IE versions).

As IE6 was not respecting Web standards, developers had to test their website using IE6. That situation was great for Microsoft (MS) as web developers had to buy MS products (e.g. IE cannot be used without buying Windows), and it was more profit-making to stay non-compliant (i.e. Microsoft wanted to become the standard excluding other companies).

Therefore many many sites were IE6 compliant only, and as IE was not compliant with web standard, all these web sites was not well rendered on standards compliant browsers. Even worse, many sites required only IE.

However, at this time, Mozilla started Firefox development respecting as much as possible all the web standards (other browser were implemented to render pages as done by IE6). As more and more web developers wanted to use the new web standards features, more and more websites were more supported by Firefox than IE.

When IE market sharing was decreasing, MS realized staying standard incompatible was not a good idea. Therefore MS started to release new IE version (IE8/IE9/IE10) respecting more and more the web standards.


The web-incompatible issue

But the issue is all the websites designed for IE6: Microsoft could not release new IE versions incompatible with these old IE6-designed websites. Instead of deducing the IE version a website has been designed, MS requested developers to add extra data (X-UA-Compatible) in their pages.

IE6 is still used in 2016

Nowadays, IE6 is still used (0.7% in 2016) (4.5% in January 2014), and some internet websites are still IE6-only-compliant. Some intranet website/applications are tested using IE6. Some intranet website are 100% functional only on IE6. These companies/departments prefer to postpone the migration cost: other priorities, nobody no longer knows how the website/application has been implemented, the owner of the legacy website/application went bankrupt...

China represents 50% of IE6 usage in 2013, but it may change in the next years as Chinese Linux distribution is being broadcast.

Be confident with your web skills

If you (try to) respect web standard, you can simply always use http-equiv="X-UA-Compatible" content="IE=edge,chrome=1". To keep compatibility with old browsers, just avoid using latest web features: use the subset supported by the oldest browser you want to support. Or If you want to go further, you may adopt concepts as Graceful degradation, Progressive enhancement and Unobtrusive JavaScript. (You may also be pleased to read What should a web developer consider?.)

Do do not care about the best IE version rendering: this is not your job as browsers have to be compliant with web standards. If your site is standard compliant and use moderately latest features, therefore browsers have to be compliant with your website.

Moreover, as there are many campaigns to kill IE6 (IE6 no more, MS campaign), nowadays you may avoid wasting time with IE testing!

Personal IE6 experience

In 2009-2012, I worked for a company using IE6 as the official single browser allowed. I had to implement an intranet website for IE6 only. I decided to respect web standard but using the IE6-capable subset (HTML/CSS/JS).

It was hard, but when the company switched to IE8, the website was still well rendered because I had used Firefox and firebug to check the web-standard compatibility ;)

Split output of command by columns using Bash?

Bash's set will parse all output into position parameters.

For instance, with set $(free -h) command, echo $7 will show "Mem:"

Appending items to a list of lists in python

import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions) 
with open('data.csv', 'r') as f:
    for rec in csv.DictReader(f):
        for l, col in zip(data, cols):
            l.append(float(rec[col]))
print data

# [[3.0, 3.0], [0.01, 0.01]]

Moment.js get day name from date

With moment you can parse the date string you have:

var dt = moment(myDate.date, "YYYY-MM-DD HH:mm:ss")

That's for UTC, you'll have to convert the time zone from that point if you so desire.

Then you can get the day of the week:

dt.format('dddd');

How to generate a simple popup using jQuery

First the CSS - tweak this however you like:

a.selected {
  background-color:#1F75CC;
  color:white;
  z-index:100;
}

.messagepop {
  background-color:#FFFFFF;
  border:1px solid #999999;
  cursor:default;
  display:none;
  margin-top: 15px;
  position:absolute;
  text-align:left;
  width:394px;
  z-index:50;
  padding: 25px 25px 20px;
}

label {
  display: block;
  margin-bottom: 3px;
  padding-left: 15px;
  text-indent: -15px;
}

.messagepop p, .messagepop.div {
  border-bottom: 1px solid #EFEFEF;
  margin: 8px 0;
  padding-bottom: 8px;
}

And the JavaScript:

function deselect(e) {
  $('.pop').slideFadeToggle(function() {
    e.removeClass('selected');
  });    
}

$(function() {
  $('#contact').on('click', function() {
    if($(this).hasClass('selected')) {
      deselect($(this));               
    } else {
      $(this).addClass('selected');
      $('.pop').slideFadeToggle();
    }
    return false;
  });

  $('.close').on('click', function() {
    deselect($('#contact'));
    return false;
  });
});

$.fn.slideFadeToggle = function(easing, callback) {
  return this.animate({ opacity: 'toggle', height: 'toggle' }, 'fast', easing, callback);
};

And finally the html:

<div class="messagepop pop">
  <form method="post" id="new_message" action="/messages">
    <p><label for="email">Your email or name</label><input type="text" size="30" name="email" id="email" /></p>
    <p><label for="body">Message</label><textarea rows="6" name="body" id="body" cols="35"></textarea></p>
    <p><input type="submit" value="Send Message" name="commit" id="message_submit"/> or <a class="close" href="/">Cancel</a></p>
  </form>
</div>

<a href="/contact" id="contact">Contact Us</a>

Here is a jsfiddle demo and implementation.

Depending on the situation you may want to load the popup content via an ajax call. It's best to avoid this if possible as it may give the user a more significant delay before seeing the content. Here couple changes that you'll want to make if you take this approach.

HTML becomes:

<div>
    <div class="messagepop pop"></div> 
    <a href="/contact" id="contact">Contact Us</a>
</div>

And the general idea of the JavaScript becomes:

$("#contact").on('click', function() {
    if($(this).hasClass("selected")) {
        deselect();               
    } else {
        $(this).addClass("selected");
        $.get(this.href, function(data) {
            $(".pop").html(data).slideFadeToggle(function() { 
                $("input[type=text]:first").focus();
            });
        }
    }
    return false;
});

Xcode 9 Swift Language Version (SWIFT_VERSION)

I just got this after creating a new Objective-C project in Xcode 10, after I added a Core Data model file to the project.

I found two ways to fix this:

  1. The Easy Way: Open the Core Data model's File Inspector (??-1) and change the language from Swift to Objective-C

Change Core Data model language

  1. Longer and more dangerous method

The model contains a "contents" file with this line:

<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="14460.32" systemVersion="17G5019" minimumToolsVersion="Automatic" sourceLanguage="Swift" userDefinedModelVersionIdentifier="">

In there is a sourceLanguage="Swift" entry. Change it to sourceLanguage="Objective-C" and the error goes away.

To find the "contents" file, right click on the .xcdatamodeld in Xcode and do "Show in Finder". Right-click on the actual (Finder) file and do "Show Package Contents"

Also: Changing the model's language will stop Xcode from generating managed object subclass files in Swift.

How to print a stack trace in Node.js?

Try Error.captureStackTrace(targetObject[, constructorOpt]).

const myObj = {};
function c() {
  // pass
}

function b() {
    Error.captureStackTrace(myObj)
    c()
} 

function a() {
    b()
}

a()

console.log(myObj.stack)

The function a and b are captured in error stack and stored in myObj.

Variable that has the path to the current ansible-playbook that is executing?

There is no build-in variable for this purpose, but you can always find out the playbook's absolute path with "pwd" command, and register its output to a variable.

- name: Find out playbook's path
  shell: pwd
  register: playbook_path_output
- debug: var=playbook_path_output.stdout

Now the path is available in variable playbook_path_output.stdout

How to bind event listener for rendered elements in Angular 2?

import { AfterViewInit, Component, ElementRef} from '@angular/core';

constructor(private elementRef:ElementRef) {}

ngAfterViewInit() {
  this.elementRef.nativeElement.querySelector('my-element')
                                .addEventListener('click', this.onClick.bind(this));
}

onClick(event) {
  console.log(event);
}

How can I use Bash syntax in Makefile targets?

If portability is important you may not want to depend on a specific shell in your Makefile. Not all environments have bash available.

nginx: connect() failed (111: Connection refused) while connecting to upstream

I don't think that solution would work anyways because you will see some error message in your error log file.

The solution was a lot easier than what I thought.

simply, open the following path to your php5-fpm

sudo nano /etc/php5/fpm/pool.d/www.conf

or if you're the admin 'root'

nano /etc/php5/fpm/pool.d/www.conf

Then find this line and uncomment it:

listen.allowed_clients = 127.0.0.1

This solution will make you be able to use listen = 127.0.0.1:9000 in your vhost blocks

like this: fastcgi_pass 127.0.0.1:9000;

after you make the modifications, all you need is to restart or reload both Nginx and Php5-fpm

Php5-fpm

sudo service php5-fpm restart

or

sudo service php5-fpm reload

Nginx

sudo service nginx restart

or

sudo service nginx reload

From the comments:

Also comment

;listen = /var/run/php5-fpm.sock 

and add

listen = 9000

Oracle SQL query for Date format

you can use this command by getting your data. this will extract your data...

select * from employees where to_char(es_date,'dd/mon/yyyy')='17/jun/2003';

How to keep Docker container running after starting services?

How about using the supervise form of service if available?

service YOUR_SERVICE supervise

Once supervise is successfully running, it will not exit unless it is killed or specifically asked to exit.

Saves having to create a supervisord.conf

Include in SELECT a column that isn't actually in the database

You may want to use:

SELECT Name, 'Unpaid' AS Status FROM table;

The SELECT clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:

SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ] 
<select_list> 

Where the expression can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.

Check if Internet Connection Exists with jQuery?

Sending XHR requests is bad because it could fail if that particular server is down. Instead, use googles API library to load their cached version(s) of jQuery.

You can use googles API to perform a callback after loading jQuery, and this will check if jQuery was loaded successfully. Something like the code below should work:

<script type="text/javascript">
    google.load("jquery");

    // Call this function when the page has been loaded
    function test_connection() {
        if($){
            //jQuery WAS loaded.
        } else {
            //jQuery failed to load.  Grab the local copy.
        }
    }
    google.setOnLoadCallback(test_connection);
</script>

The google API documentation can be found here.

Converting data frame column from character to numeric

If we need only one column to be numeric

yyz$b <- as.numeric(as.character(yyz$b))

But, if all the columns needs to changed to numeric, use lapply to loop over the columns and convert to numeric by first converting it to character class as the columns were factor.

yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))

Both the columns in the OP's post are factor because of the string "n/a". This could be easily avoided while reading the file using na.strings = "n/a" in the read.table/read.csv or if we are using data.frame, we can have character columns with stringsAsFactors=FALSE (the default is stringsAsFactors=TRUE)


Regarding the usage of apply, it converts the dataset to matrix and matrix can hold only a single class. To check the class, we need

lapply(yyz, class)

Or

sapply(yyz, class)

Or check

str(yyz)

Run a single test method with maven

New versions of JUnit contains the Categories runner: http://kentbeck.github.com/junit/doc/ReleaseNotes4.8.html

But releasing procedure of JUnit is not maven based, so maven users have to put it manually to their repositories.

MySQL - count total number of rows in php

<?php
$conn=mysqli_connect("127.0.0.1:3306","root","","admin");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="select count('user_id') from login_user";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_array($result);
echo "$row[0]";
mysqli_close($conn);
?>

Still having problem visit my tutorial http://www.studentstutorial.com/php/php-count-rows.php

What is the equivalent of "!=" in Excel VBA?

In VBA, the != operator is the Not operator, like this:

If Not strTest = "" Then ...

Fix CSS hover on iPhone/iPad/iPod

The hover pseudo class only functions on iOS when applied to a link tag. They do that because there is no hover on a touch device reall. It acts more like the active class. So they can't have one unless its a link going somewhere for usability reasons. Change your div to a link tag and you will have no problem.

How to generate a git patch for a specific commit?

For generating the patches from the topmost commits from a specific sha1 hash:

git format-patch -<n> <SHA1>

The last 10 patches from head in a single patch file:

git format-patch -10 HEAD --stdout > 0001-last-10-commits.patch

Cookie blocked/not saved in IFRAME in Internet Explorer

I've spend a large part of my day looking into this P3P thing and I feel the need to share what I've found out.

I've noticed that the P3P concept is very outdated and seems only to be really used/enforced by Internet Explorer (IE).

The simplest explanation is: IE wants you to define a P3P header if you are using cookies.

This is a nice idea, and luckily most of the time not providing this header won't cause any issues (read browser warnings). Unless your website/web application is loaded into an other website using an (i)Frame. This is where IE becomes a massive pain in the ***. It will not allow you to set a cookie unless the P3P header is set.

Knowing this I wanted to find an answer to the following two questions:

  1. Who cares? In other words, can I be sued if I put the word "Potato" in the header?
  2. What do other companies do?

My findings are:

  1. No one cares. I'm unable to find a single document that suggests this technology has any legal weight. During my research I didn't find a single country around the world that has adopted a law that prevents you from putting the word "Potato" in the P3P header
  2. Both Google and Facebook put a link in their P3P header field referring to a page describing why they don't have a P3P header.

The concept was born in 2002 and it baffles me that this outdated and legally unimplemented concept is still forced upon developers within IE. If this header doesn't have have any legal ramifications this header should be ignored (or alternatively, generate a warning or notification in the console). Not enforced! I'm now forced to put a line in my code (and send a header to the client) that does absolutely nothing.

In short - to keep IE happy - add the following line to your PHP code (Other languages should look similar)

header('P3P: CP="Potato"');

Problem solved, and IE is happy with this potato.

Java 8: merge lists with stream API

Alternative: Stream.concat()

Stream.concat(map.values().stream(), listContainer.lst.stream())
                             .collect(Collectors.toList()

Alternate background colors for list items

You can achieve this by adding alternating style classes to each list item

<ul>
    <li class="odd"><a href="link">Link 1</a></li>
    <li><a href="link">Link 2</a></li>
    <li class="odd"><a href="link">Link 2</a></li>
    <li><a href="link">Link 2</a></li>
</ul>

And then styling it like

li { backgorund:white; }
li.odd { background:silver; }

You can further automate this process with javascript (jQuery example below)

$(document).ready(function() {
  $('table tbody tr:odd').addClass('odd');
});

Using Python's list index() method on a list of tuples or objects?

Python's list.index(x) returns index of the first occurrence of x in the list. So we can pass objects returned by list compression to get their index.

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> [tuple_list.index(t) for t in tuple_list if t[1] == 7]
[1]
>>> [tuple_list.index(t) for t in tuple_list if t[0] == 'kumquat']
[2]

With the same line, we can also get the list of index in case there are multiple matched elements.

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11), ("banana", 7)]
>>> [tuple_list.index(t) for t in tuple_list if t[1] == 7]
[1, 4]

Angularjs how to upload multipart form data and a file?

You can check out this method for sending image and form data altogether

<div class="form-group ml-5 mt-4" ng-app="myApp" ng-controller="myCtrl">
                    <label for="image_name">Image Name:</label>
                    <input type="text"   placeholder="Image name" ng-model="fileName" class="form-control" required>
                    <br>

                    <br>
                    <input id="file_src" type="file"   accept="image/jpeg" file-input="files"   >
                    <br>
                        {{file_name}}
            <img class="rounded mt-2 mb-2 " id="prvw_img" width="150" height="100" >
                    <hr>
                      <button class="btn btn-info" ng-click="uploadFile()">Upload</button>
                        <br>

                       <div ng-show = "IsVisible" class="alert alert-info w-100 shadow mt-2" role="alert">
              <strong> {{response_msg}} </strong>
            </div>
                            <div class="alert alert-danger " id="filealert"> <strong> File Size should be less than 4 MB </strong></div>
                    </div>

Angular JS Code

    var app = angular.module("myApp", []);
 app.directive("fileInput", function($parse){
      return{
           link: function($scope, element, attrs){
                element.on("change", function(event){
                     var files = event.target.files;


                     $parse(attrs.fileInput).assign($scope, element[0].files);
                     $scope.$apply();
                });
           }
      }
 });
 app.controller("myCtrl", function($scope, $http){
      $scope.IsVisible = false;
      $scope.uploadFile = function(){
           var form_data = new FormData();
           angular.forEach($scope.files, function(file){
                form_data.append('file', file); //form file
                                form_data.append('file_Name',$scope.fileName); //form text data
           });
           $http.post('upload.php', form_data,
           {
                //'file_Name':$scope.file_name;
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined,'Process-Data': false}
           }).success(function(response){
             $scope.IsVisible = $scope.IsVisible = true;
                      $scope.response_msg=response;
               // alert(response);
               // $scope.select();
           });
      }

 });

How can I make Bootstrap columns all the same height?

You can use inline-flex as well which works pretty good and may be a little cleaner than modifying every row element with CSS.

For my project I wanted every row who's child elements had borders to be the same height so the borders would look jagged. For this I created a simple css class.

.row.borders{
    display: inline-flex;
    width: 100%;
}

How to select between brackets (or quotes or ...) in Vim?

I've made a plugin vim-textobj-quotes: https://github.com/beloglazov/vim-textobj-quotes

It provides text objects for the closest pairs of quotes of any type. Using only iq or aq it allows you to operate on the content of single ('), double ("), or back (`) quotes that currently surround the cursor, are in front of the cursor, or behind (in that order of preference). In other words, it jumps forward or backwards when needed to reach the quotes.

It's easier to understand by looking at examples (the cursor is shown with |):

  1. Before: foo '1, |2, 3' bar; after pressing diq: foo '|' bar
  2. Before: foo| '1, 2, 3' bar; after pressing diq: foo '|' bar
  3. Before: foo '1, 2, 3' |bar; after pressing diq: foo '|' bar
  4. Before: foo '1, |2, 3' bar; after pressing daq: foo | bar
  5. Before: foo| '1, 2, 3' bar; after pressing daq: foo | bar
  6. Before: foo '1, 2, 3' |bar; after pressing daq: foo | bar

The examples above are given for single quotes, the plugin works exactly the same way for double (") and back (`) quotes.

You can also use any other operators: ciq, diq, yiq, viq, etc.

Please have a look at the github page linked above for more details.

MVC3 EditorFor readOnly

Old post I know.. but now you can do this to keep alignment and all looking consistent..

 @Html.EditorFor(model => model.myField, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })

Can a table have two foreign keys?

create table Table1
(
  id varchar(2),
  name varchar(2),
  PRIMARY KEY (id)
)


Create table Table1_Addr
(
  addid varchar(2),
  Address varchar(2),
  PRIMARY KEY (addid)
)

Create table Table1_sal
(
  salid varchar(2),`enter code here`
  addid varchar(2),
  id varchar(2),
  PRIMARY KEY (salid),
  index(addid),
  index(id),
  FOREIGN KEY (addid) REFERENCES Table1_Addr(addid),
  FOREIGN KEY (id) REFERENCES Table1(id)
)

"unmappable character for encoding" warning in Java

Gradle Steps

If you are using Gradle then you can find the line that applies the java plugin:

apply plugin: 'java'

Then set the encoding for the compile task to be UTF-8:

compileJava {options.encoding = "UTF-8"}   

If you have unit tests, then you probably want to compile those with UTF-8 too:

compileTestJava {options.encoding = "UTF-8"}

Overall Gradle Example

This means that the overall gradle code would look something like this:

apply plugin: 'java'
compileJava {options.encoding = "UTF-8"}
compileTestJava {options.encoding = "UTF-8"}

How to navigate to a section of a page

My Solutions:

$("body").scrollspy({ target: ".target", offset: fix_header_height });

$(".target").click(function() {
 $("body").animate(
  {
   scrollTop: $($(this).attr("href")).offset().top - fix_header_height
  },
  500
 );
 return;
});

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

In my case the problem was that GNOME keyring was holding an invalid passphrase for the ssh key to be used. After spending indecent amount of time troubleshooting this issue I ran seahorse and found the entry to hold empty string. I can only guess that it was caused by mistyping the passphrase at first use some time earlier, and then probably cancelling the requester or so in order to fall back to command line. Updating the entry with correct passphrase immediately solved the problem. Deleting that entry (from "login" keyring) and reentering passphrase at that first prompt (and checking the appropriate checkbox) solves this too. Now agent gets the correct passphrase from the unlocked at login keyring named "login" and neither asks for passphrase nor "refuses operation" anymore. Of course YMMV.

How can I tell when a MySQL table was last updated?

I'm surprised no one has suggested tracking last update time per row:

mysql> CREATE TABLE foo (
  id INT PRIMARY KEY
  x INT,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP 
                     ON UPDATE CURRENT_TIMESTAMP,
  KEY (updated_at)
);

mysql> INSERT INTO foo VALUES (1, NOW() - INTERVAL 3 DAY), (2, NOW());

mysql> SELECT * FROM foo;
+----+------+---------------------+
| id | x    | updated_at          |
+----+------+---------------------+
|  1 | NULL | 2013-08-18 03:26:28 |
|  2 | NULL | 2013-08-21 03:26:28 |
+----+------+---------------------+

mysql> UPDATE foo SET x = 1234 WHERE id = 1;

This updates the timestamp even though we didn't mention it in the UPDATE.

mysql> SELECT * FROM foo;
+----+------+---------------------+
| id | x    | updated_at          |
+----+------+---------------------+
|  1 | 1235 | 2013-08-21 03:30:20 | <-- this row has been updated
|  2 | NULL | 2013-08-21 03:26:28 |
+----+------+---------------------+

Now you can query for the MAX():

mysql> SELECT MAX(updated_at) FROM foo;
+---------------------+
| MAX(updated_at)     |
+---------------------+
| 2013-08-21 03:30:20 |
+---------------------+

Admittedly, this requires more storage (4 bytes per row for TIMESTAMP).
But this works for InnoDB tables before 5.7.15 version of MySQL, which INFORMATION_SCHEMA.TABLES.UPDATE_TIME doesn't.

How get all values in a column using PHP?

How to put MySQL functions back into PHP 7
Step 1

First get the mysql extension source which was removed in March:

https://github.com/php/php-src/tree/PRE_PHP7_EREG_MYSQL_REMOVALS/ext/mysql

Step 2

Then edit your php.ini

Somewhere either in the “Extensions” section or “MySQL” section, simply add this line:

extension = /usr/local/lib/php/extensions/no-debug-non-zts-20141001/mysql.so

Step 3

Restart PHP and mysql_* functions should now be working again.

Step 4

Turn off all deprecated warnings including them from mysql_*:

error_reporting(E_ALL ^ E_DEPRECATED);

Now Below Code Help You :

$result = mysql_query("SELECT names FROM Customers");
$Data= Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) 
{
        $Data[] =  $row['names'];  
}

You can also get all values in column using mysql_fetch_assoc

$result = mysql_query("SELECT names FROM Customers");
    $Data= Array();
    while ($row = mysql_fetch_assoc($result)) 
    {
            $Data[] =  $row['names'];  
    }

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.

Reference


YOU CAN USE MYSQLI ALTERNATIVE OF MYSQL EASY WAY


*

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

$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
$result=mysqli_query($con,$sql);

// Numeric array
$row=mysqli_fetch_array($result,MYSQLI_NUM);
printf ("%s (%s)\n",$row[0],$row[1]);

// Associative array
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
printf ("%s (%s)\n",$row["Lastname"],$row["Age"]);

// Free result set
mysqli_free_result($result);

mysqli_close($con);
?> 

Is bool a native C type?

C99 defines bool, true and false in stdbool.h.

Convert array values from string to int?

You can achieve this by following code,

$integerIDs = array_map('intval', explode(',', $string));

How to initialize HashSet values by construction?

I feel the most readable is to simply use google Guava:

Set<String> StringSet = Sets.newSet("a", "b", "c");

Cannot use string offset as an array in php

I was able to reproduce this once I upgraded to PHP 7. It breaks when you try to force array elements into a string.

$params = '';
foreach ($foo) {
  $index = 0;
  $params[$index]['keyName'] = $name . '.' . $fileExt;
}

After changing:

$params = '';

to:

$params = array();

I stopped getting the error. I found the solution in this bug report thread. I hope this helps.

how to call a function from another function in Jquery

I assume you don't want to rebind the event, but call the handler.

You can use trigger() to trigger events:

$('#billing_state_id').trigger('change');

If your handler doesn't rely on the event context and you don't want to trigger other handlers for the event, you could also name the function:

function someFunction() {
    //do stuff
}

$(document).ready(function(){
    //Load City by State
    $('#billing_state_id').live('change', someFunction);   
    $('#click_me').live('click', function() {
       //do something
       someFunction();
    });
  });

Also note that live() is deprecated, on() is the new hotness.

Change SQLite database mode to read-write

In the project path Terminal django_project#

sudo chown django:django *

Displaying a vector of strings in C++

Your vector<string> userString has size 0, so the loop is never entered. You could start with a vector of a given size:

vector<string> userString(10);      
string word;        
string sentence;           
for (decltype(userString.size()) i = 0; i < userString.size(); ++i)
{
    cin >> word;
    userString[i] = word;
    sentence += userString[i] + " ";
}

although it is not clear why you need the vector at all:

string word;        
string sentence;           
for (int i = 0; i < 10; ++i)
{
    cin >> word;
    sentence += word + " ";
}

If you don't want to have a fixed limit on the number of input words, you can use std::getline in a while loop, checking against a certain input, e.g. "q":

while (std::getline(std::cin, word) && word != "q")
{
    sentence += word + " ";
}

This will add words to sentence until you type "q".

How to set width of mat-table column in angular?

You can easily do this one. In each column you will get a class with the field name prefixed with mat-column, so the class will be like mat-column-yourFieldName. So for that you can set the style like following

.mat-column-yourFieldName {
    flex: none;
    width: 100px;
}

So we can give fixed width for column as per our requirement.

Hope this helps for someone.

Subclipse svn:ignore

to ignore certain files or turn off ignoring you can use the eclipse preferences-->Team -->Ignored Resource. Check or uncheck the resources you want to be tracked.

numpy array TypeError: only integer scalar arrays can be converted to a scalar index

try the following to change your array to 1D

a.reshape((1, -1))

Add a common Legend for combined ggplots

If the legend is the same for both plots, there is a simple solution using grid.arrange(assuming you want your legend to align with both plots either vertically or horizontally). Simply keep the legend for the bottom-most or right-most plot while omitting the legend for the other. Adding a legend to just one plot, however, alters the size of one plot relative to the other. To avoid this use the heights command to manually adjust and keep them the same size. You can even use grid.arrange to make common axis titles. Note that this will require library(grid) in addition to library(gridExtra). For vertical plots:

y_title <- expression(paste(italic("E. coli"), " (CFU/100mL)"))

grid.arrange(arrangeGrob(p1, theme(legend.position="none"), ncol=1), 
   arrangeGrob(p2, theme(legend.position="bottom"), ncol=1), 
   heights=c(1,1.2), left=textGrob(y_title, rot=90, gp=gpar(fontsize=20)))

Here is the result for a similar graph for a project I was working on: enter image description here

Notification not showing in Oreo

private void addNotification() {
                NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentTitle("Notifications Example")
                .setContentText("This is a test notification");
                Intent notificationIntent = new Intent(this, MainActivity.class);
                PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
                builder.setContentIntent(contentIntent);
                // Add as notification
                NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
                {
                NotificationChannel nChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH);
                nChannel.enableLights(true);
                assert manager != null;
                builder.setChannelId(NOTIFICATION_CHANNEL_ID);
                manager.createNotificationChannel(nChannel);
                }
                assert manager != null;
                manager.notify(0, builder.build());
    }

Trim last character from a string

String withoutLast = yourString.Substring(0,(yourString.Length - 1));

java.sql.SQLException: Exhausted Resultset

When there is no records returned from Database for a particular condition and When I tried to access the rs.getString(1); I got this error "exhausted resultset".

Before the issue, my code was:

rs.next();
sNr= rs.getString(1);

After the fix:

while (rs.next()) {
    sNr = rs.getString(1);
}

Can an Android App connect directly to an online mysql database

you can definitely make such application, you need to make http conection to the database, by calling a php script which will in response run specific queries according to your project, and generated the result in the form of xml, or json formate , whihc can be displayed on your android application!. for complete tutorial on how to connect android application to mysql i would recommend to check out this tutorila

Bootstrap 3 collapsed menu doesn't close on click

I had the same issue only on mobile but for an Angular application and this is what I did:

app.component.html

<nav class="navbar navbar-default navbar-fixed-top">
  <div class="container">
    <div class="col-md-12">
      <div class="navbar-header page-scroll">
      <button id ="navButton" style="color:red"type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" routerLink="/"><img id="navbrand" class="site-logo"  src="assets/img/yayaka_logo.png"/></a>
    </div>
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav navbar-right">
        <li class="hidden">
          <a href="#page-top"></a>
        </li>
        <li class="dropdown" appDropdown>
          <a class="dropdown-toggle" style="cursor: pointer;">
            ?? ????? ?? yayaka<span class="caret"></span>
          </a>
          <ul class="dropdown-menu">
            <li><a (click) = "closeMenu()" href="/#about">About</a></li>
            <li><a (click) = "closeMenu()" href="/#services">Services</a></li>
          </ul>
        </li>
        <li class="page-scroll">
          <a (click) = "closeMenu()" routerLink="/profiles"><strong>Profiles</strong></a>
        </li>
      </ul>
    </div>
  </div>
  </div>
</nav>

app.component.ts

 closeMenu() {
    var isMobile = /iPhone|iPad|iPod|BlackBerry|Opera Mini|IEMobile|Android/i.test(navigator.userAgent);
    if (isMobile) {
      document.getElementById('navButton').click();
    }
  }

Hope it helps :)

Get current url in Angular

With pure JavaScript:

console.log(window.location.href)

Using Angular:

this.router.url

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
    template: 'The href is: {{href}}'
    /*
    Other component settings
    */
})
export class Component {
    public href: string = "";

    constructor(private router: Router) {}

    ngOnInit() {
        this.href = this.router.url;
        console.log(this.router.url);
    }
}

The plunkr is here: https://plnkr.co/edit/0x3pCOKwFjAGRxC4hZMy?p=preview

How do I set up Eclipse/EGit with GitHub?

In Eclipse, go to Help -> Install New Software -> Add -> Name: any name like egit; Location: http://download.eclipse.org/egit/updates -> Okay. Now Search for egit in Work with and select all the check boxes and press Next till finish.

File -> Import -> search Git and select "Projects from Git" -> Clone URI. In the URI, paste the HTTPS URL of the repository (the one with .git extension). -> Next ->It will show all the branches "Next" -> Local Destination "Next" -> "Import as a general project" -> Next till finish.

You can refer to this Youtube tutorial: https://www.youtube.com/watch?v=ptK9-CNms98

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

If you are using NodeJs for your server side, just add these to your route and you will be Ok

     res.header("Access-Control-Allow-Origin", "*");
     res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

Your route will then look somehow like this

    router.post('/odin', function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");


    return res.json({Name: req.body.name, Phone: req.body.phone});
});

Client side for Ajax call

 var sendingData = {
   name: "Odinfono Emmanuel",
   phone: "1234567890"
}

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

    $.ajax({
        url: 'http://127.0.0.1:3000/odin',            
        method: 'POST',
        type: 'json',
        data: sendingData,
        success: function (response) {
            console.log(response);
        },
        error: function (error) {
            console.log(error);
        }
        });
    });
</script>

You should have something like this in your browser console as response

{ name: "Odinfono Emmanuel", phone: "1234567890"}

Enjoy coding....

Explanation of the UML arrows

Here is simplified tutorial:

Practical UML

For more I recommend to get some literature.