Programs & Examples On #Video editing

Cutting the videos based on start and end time using ffmpeg

feel free to use this tool https://github.com/rooty0/ffmpeg_video_cutter I wrote awhile ago Pretty much that's cli front-end for ffmpeg... you just need to create a yaml what you want to cut out... something like this

cut_method: delete  # we're going to delete following video fragments from a video
timeframe:
  - from: start   # waiting for people to join the conference
    to: 4m
  - from: 10m11s  # awkward silence
    to: 15m50s
  - from: 30m5s   # Off-Topic Discussion
    to: end

and then just run a tool to get result

What is the difference between user and kernel modes in operating systems?

A processor in a computer running Windows has two different modes: user mode and kernel mode. The processor switches between the two modes depending on what type of code is running on the processor. Applications run in user mode, and core operating system components run in kernel mode. While many drivers run in kernel mode, some drivers may run in user mode.

When you start a user-mode application, Windows creates a process for the application. The process provides the application with a private virtual address space and a private handle table. Because an application's virtual address space is private, one application cannot alter data that belongs to another application. Each application runs in isolation, and if an application crashes, the crash is limited to that one application. Other applications and the operating system are not affected by the crash.

In addition to being private, the virtual address space of a user-mode application is limited. A processor running in user mode cannot access virtual addresses that are reserved for the operating system. Limiting the virtual address space of a user-mode application prevents the application from altering, and possibly damaging, critical operating system data.

All code that runs in kernel mode shares a single virtual address space. This means that a kernel-mode driver is not isolated from other drivers and the operating system itself. If a kernel-mode driver accidentally writes to the wrong virtual address, data that belongs to the operating system or another driver could be compromised. If a kernel-mode driver crashes, the entire operating system crashes.

If you are a Windows user once go through this link you will get more.

Communication between user mode and kernel mode

CSS: How to remove pseudo elements (after, before,...)?

You need to add a css rule that removes the after content (through a class)..


An update due to some valid comments.

The more correct way to completely remove/disable the :after rule is to use

p.no-after:after{content:none;}

as Gillian Lo Wong answered.


Original answer

You need to add a css rule that removes the after content (through a class)..

p.no-after:after{content:"";}

and add that class to your p when you want to with this line

$('p').addClass('no-after'); // replace the p selector with what you need...

a working example at : http://www.jsfiddle.net/G2czw/

Eloquent Collection: Counting and Detect Empty

You can use: $counter = count($datas);

C/C++ NaN constant (literal)?

Is this possible to assign a NaN to a double or float in C ...?

Yes, since C99, (C++11) <math.h> offers the below functions:

#include <math.h>
double nan(const char *tagp);
float nanf(const char *tagp);
long double nanl(const char *tagp);

which are like their strtod("NAN(n-char-sequence)",0) counterparts and NAN for assignments.

// Sample C code
uint64_t u64;
double x;
x = nan("0x12345");
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
x = -strtod("NAN(6789A)",0);
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
x = NAN;
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);

Sample output: (Implementation dependent)

(7ff8000000012345)
(fff000000006789a)
(7ff8000000000000)

ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

You get this error because one of your variables is actually a factor variable . Execute

str(df) 

to check this. Then do this double variable change to keep the year numbers instead of transforming into "1,2,3,4" level numbers:

df$year <- as.numeric(as.character(df$year))

EDIT: it appears that your data.frame has a variable of class "array" which might cause the pb. Try then:

df <- data.frame(apply(df, 2, unclass))

and plot again?

How can I disable selected attribute from select2() dropdown Jquery?

For those using Select2 4.x, you can disable an individual option by doing:

$('select option:selected').prop('disabled', true);

For those using Select2 4.x, you can disable the entire dropdown with:

$('select').prop('disabled', true);

AngularJS How to dynamically add HTML and bind to controller

I would use the built-in ngInclude directive. In the example below, you don't even need to write any javascript. The templates can just as easily live at a remote url.

Here's a working demo: http://plnkr.co/edit/5ImqWj65YllaCYD5kX5E?p=preview

<p>Select page content template via dropdown</p>
<select ng-model="template">
    <option value="page1">Page 1</option>
    <option value="page2">Page 2</option>
</select>

<p>Set page content template via button click</p>
<button ng-click="template='page2'">Show Page 2 Content</button>

<ng-include src="template"></ng-include>

<script type="text/ng-template" id="page1">
    <h1 style="color: blue;">This is the page 1 content</h1>
</script>

<script type="text/ng-template" id="page2">
    <h1 style="color:green;">This is the page 2 content</h1>
</script>

Handle file download from ajax post

This is a 3 years old question but I had the same problem today. I looked your edited solution but I think that it can sacrifice the performance because it has to make a double request. So if anyone needs another solution that doesn't imply to call the service twice then this is the way I did it:

<form id="export-csv-form" method="POST" action="/the/path/to/file">
    <input type="hidden" name="anyValueToPassTheServer" value="">
</form>

This form is just used to call the service and avoid to use a window.location(). After that you just simply have to make a form submit from jquery in order to call the service and get the file. It's pretty simple but this way you can make a download using a POST. I now that this could be easier if the service you're calling is a GET, but that's not my case.

Bluetooth pairing without user confirmation

If you are asking if you can pair two devices without the user EVER approving the pairing, no it cannot be done, it is a security feature. If you are paired over Bluetooth there is no need to exchange data over NFC, just exchange data over the Bluetooth link.

I don't think you can circumvent Bluetooth security by passing an authentication packet over NFC, but I could be wrong.

Remove a symlink to a directory

you can use unlink in the folder where you have created your symlink

How do I start PowerShell from Windows Explorer?

I created a fully automated solution to add PS and CMD context items. Just run set_registry.cmd and it will update registry to add two buttons when click RMB on folder or inside some opened folder: enter image description here

This will change owner of registry keys to admin and add context menus
Change registry to enable PS and CWD context menus

Using SSIS BIDS with Visual Studio 2012 / 2013

First Off, I object to this other question regarding Visual Studio 2015 as a duplicate question. How do I open SSRS (.rptproj) and SSIS (.dtproj) files in Visual Studio 2015? [duplicate]

Basically this question has the title ...Visual Studio 2012 / 2013 What about ALL the improvements and changes to VS 2015 ??? SSDT has been updated and changed. The entire way of doing various additions and updates is different.

So having vented / rant - I did open a VS 2015 update 2 instance and proceeded to open an existing solution that include a .rptproj project. Now this computer does not yet have sql server installed on it yet.

Solution for ME : Tools --> Extension and Updates --> Updates --> sql server tooling updates

Click on Update button and wait a long time and SSDT then installs and close visual studio 2015 and re-open and it works for me.

In case it is NOT found in VS 2015 for some reason : scroll to the bottom, pick your language iso https://msdn.microsoft.com/en-us/mt186501.aspx?f=255&MSPPError=-2147217396

How do I read a resource file from a Java jar file?

The problem was that I was going a step too far in calling the parse method of XMLReader. The parse method accepts an InputSource, so there was no reason to even use a FileReader. Changing the last line of the code above to

xr.parse( new InputSource( filename ));

works just fine.

How to create Toast in Flutter?

Add flutter_just_toast to your dependencies in your Pubspecs.yaml

dependencies:

flutter_just_toast: ^1.0.1

Next import package into your class:

import 'package:flutter_just_toast/flutter_just_toast.dart';

Implement Toast with message

Toast.show( message: "Your toast message", 
    duration: Delay.SHORT, 
    textColor: Colors.black);

Manually map column names with class properties

for all of you who use Dapper 1.12, Here's what you need to do to get this done:

  • Add a new column attribute class:

      [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property]
    
      public class ColumnAttribute : Attribute
      {
    
        public string Name { get; set; }
    
        public ColumnAttribute(string name)
        {
          this.Name = name;
        }
      }
    

  • Search for this line:

    map = new DefaultTypeMap(type);
    

    and comment it out.

  • Write this instead:

            map = new CustomPropertyTypeMap(type, (t, columnName) =>
            {
              PropertyInfo pi = t.GetProperties().FirstOrDefault(prop =>
                                prop.GetCustomAttributes(false)
                                    .OfType<ColumnAttribute>()
                                    .Any(attr => attr.Name == columnName));
    
              return pi != null ? pi : t.GetProperties().FirstOrDefault(prop => prop.Name == columnName);
            });
    

  • Java and SSL - java.security.NoSuchAlgorithmException

    Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

    The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

    You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

    jQuery prevent change for select

    Implement custom readonly like eventHandler

    <select id='country' data-changeable=false>
      <option selected value="INDIA">India</option>
      <option value="USA">United States</option>
      <option value="UK">United Kingdom</option>
    </select>
    
    <script>
        var lastSelected = $("#country option:selected");
    
        $("#country").on("change", function() {
           if(!$(this).data(changeable)) {
                lastSelected.attr("selected", true);              
           }        
        });
    
        $("#country").on("click", function() {
           lastSelected = $("#country option:selected");
        });
    </script>
    

    Demo : https://jsfiddle.net/0mvajuay/8/

    SQL LIKE condition to check for integer?

    That will select (by a regex) every book which has a title starting with a number, is that what you want?

    SELECT * FROM books WHERE title ~ '^[0-9]'
    

    if you want integers which start with specific digits, you could use:

    SELECT * FROM books WHERE CAST(price AS TEXT) LIKE '123%'
    

    or use (if all your numbers have the same number of digits (a constraint would be useful then))

    SELECT * FROM books WHERE price BETWEEN 123000 AND 123999;
    

    html tables & inline styles

    This should do the trick:

    <table width="400" border="0" cellpadding="0" cellspacing="0">
      <tr>
        <td width="50" height="40" valign="top" rowspan="3">
          <img alt="" src="" width="40" height="40" style="margin: 0; border: 0; padding: 0; display: block;">
        </td>
        <td width="350" height="40" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
    <a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">LAST FIRST</a><br>
    REALTOR | P 123.456.789
        </td>
      </tr>
      <tr>
        <td width="350" height="70" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
    <img alt="" src="" width="200" height="60" style="margin: 0; border: 0; padding: 0; display: block;">
        </td>
      </tr>
      <tr>
        <td width="350" height="20" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
    all your minor text here | all your minor text here | all your minor text here
        </td>
      </tr>
    </table>
    

    UPDATE: Adjusted code per the comments:

    After viewing your jsFiddle, an important thing to note about tables is that table cell widths in each additional row all have to be the same width as the first, and all cells must add to the total width of your table.

    Here is an example that will NOT WORK:

    <table width="600" border="0" cellpadding="0" cellspacing="0">
      <tr>
        <td width="200" bgcolor="#252525">&nbsp;
        </td>
        <td width="400" bgcolor="#454545">&nbsp;
        </td>
      </tr>
      <tr>
        <td width="300" bgcolor="#252525">&nbsp;
        </td>
        <td width="300" bgcolor="#454545">&nbsp;
        </td>
      </tr>
    </table>
    

    Although the 2nd row does add up to 600, it (and any additional rows) must have the same 200-400 split as the first row, unless you are using colspans. If you use a colspan, you could have one row, but it needs to have the same width as the cells it is spanning, so this works:

    <table width="600" border="0" cellpadding="0" cellspacing="0">
      <tr>
        <td width="200" bgcolor="#252525">&nbsp;
        </td>
        <td width="400" bgcolor="#454545">&nbsp;
        </td>
      </tr>
      <tr>
        <td width="600" colspan="2" bgcolor="#353535">&nbsp;
        </td>
      </tr>
    </table>
    

    Not a full tutorial, but I hope that helps steer you in the right direction in the future.

    Here is the code you are after:

    <table width="900" border="0" cellpadding="0" cellspacing="0">
      <tr>
        <td width="57" height="43" valign="top" rowspan="2">
          <img alt="Rashel Adragna" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_head.png" width="47" height="43" style="margin: 0; border: 0; padding: 0; display: block;">
        </td>
        <td width="843" height="43" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
    <a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">RASHEL ADRAGNA</a><br>
    REALTOR | P 855.900.24KW
        </td>
      </tr>
      <tr>
        <td width="843" height="64" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
    <img alt="Zopa Realty Group logo" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_logo.png" width="177" height="54" style="margin: 0; border: 0; padding: 0; display: block;">
        </td>
      </tr>
      <tr>
        <td width="843" colspan="2" height="20" valign="bottom" align="center" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
    all your minor text here | all your minor text here | all your minor text here
        </td>
      </tr>
    </table>
    

    You'll note that I've added an extra 10px to some of your table cells. This in combination with align/valigns act as padding between your cells. It is a clever way to aviod actually having to add padding, margins or empty padding cells.

    View more than one project/solution in Visual Studio

    You can create a new blank solution and add your different projects to it.

    SQL Server 2005 Setting a variable to the result of a select query

    This will work for original question asked:

    DECLARE @Result INT;
    SELECT @Result = COUNT(*)
    FROM  TableName
    WHERE Condition
    

    "Could not find Developer Disk Image"

    This solution works only if you create in Xcode 7 the directory "10.0" and you have a mistake in your sentence:

    ln -s /Applications/Xcode_8.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/10.0 \(14A345\) /Applications/Xcode_7.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/10.0
    

    How do I kill an Activity when the Back button is pressed?

    Simple Override onBackPressed Method:

        @Override
        public void onBackPressed() {
                super.onBackPressed();
                this.finish();
        }
    

    How to plot a function curve in R

    You mean like this?

    > eq = function(x){x*x}
    > plot(eq(1:1000), type='l')
    

    Plot of eq over range 1:1000

    (Or whatever range of values is relevant to your function)

    How do I download and save a file locally on iOS using objective C?

    There are so many ways:

    1. NSURL

    2. ASIHTTP

    3. libcurl

    4. easyget, a commercial one with powerful features.

    What is an unsigned char?

    In terms of direct values a regular char is used when the values are known to be between CHAR_MIN and CHAR_MAX while an unsigned char provides double the range on the positive end. For example, if CHAR_BIT is 8, the range of regular char is only guaranteed to be [0, 127] (because it can be signed or unsigned) while unsigned char will be [0, 255] and signed char will be [-127, 127].

    In terms of what it's used for, the standards allow objects of POD (plain old data) to be directly converted to an array of unsigned char. This allows you to examine the representation and bit patterns of the object. The same guarantee of safe type punning doesn't exist for char or signed char.

    Differences between key, superkey, minimal superkey, candidate key and primary key

    Largely based on the accepted answer, but with a few tweaks to fit better the definitions taught in some courses:

    • Key: A set of = 1 columns.
    • Superkey: A key that ? a candidate key.
      • Therefore, a superkey must contain > 1 columns.
      • Minimal Super key = Candidate Key: A key that can uniquely identify each row in a table.
      • Primary Key: The chosen Candidate Key for doing that.
      • Secondary key / Alternate key: A Candidate Key not chosen for doing that.
    • Search Key: A key used for locating records.
    • Composite key or concatenate key: A key with > 1 columns.
      • Usually implies "composite primary key", although "composite alternate key" is also a thing.
    • Sort or control key: A key used to physically sequence the stored data.
    • Foreign Key A key in one table that matches the Primary Key of another table.
      • The table in which foreign key resides is called as dependent table.
      • The table to which foreign key refers is known as parent table.

    From Now() to Current_timestamp in Postgresql

    Here is an example ...

    select * from tablename where to_char(added_time, 'YYYY-MM-DD')  = to_char( now(), 'YYYY-MM-DD' )
    

    added_time is a column name which I converted to char for match

    python pandas: apply a function with arguments to a series

    You can pass any number of arguments to the function that apply is calling through either unnamed arguments, passed as a tuple to the args parameter, or through other keyword arguments internally captured as a dictionary by the kwds parameter.

    For instance, let's build a function that returns True for values between 3 and 6, and False otherwise.

    s = pd.Series(np.random.randint(0,10, 10))
    s
    
    0    5
    1    3
    2    1
    3    1
    4    6
    5    0
    6    3
    7    4
    8    9
    9    6
    dtype: int64
    
    s.apply(lambda x: x >= 3 and x <= 6)
    
    0     True
    1     True
    2    False
    3    False
    4     True
    5    False
    6     True
    7     True
    8    False
    9     True
    dtype: bool
    

    This anonymous function isn't very flexible. Let's create a normal function with two arguments to control the min and max values we want in our Series.

    def between(x, low, high):
        return x >= low and x =< high
    

    We can replicate the output of the first function by passing unnamed arguments to args:

    s.apply(between, args=(3,6))
    

    Or we can use the named arguments

    s.apply(between, low=3, high=6)
    

    Or even a combination of both

    s.apply(between, args=(3,), high=6)
    

    JQuery add class to parent element

    $(this.parentNode).addClass('newClass');

    What is the argument for printf that formats a long?

    Put an l (lowercased letter L) directly before the specifier.

    unsigned long n;
    long m;
    
    printf("%lu %ld", n, m);
    

    Building a complete online payment gateway like Paypal

    Big task, chances are you shouldn't reinvent the wheel rather using an existing wheel (such as paypal).

    However, if you insist on continuing. Start small, you can use a credit card processing facility (Moneris, Authorize.NET) to process credit cards. Most providers have an API you can use. Be wary that you may need to use different providers depending on the card type (Discover, Visa, Amex, Mastercard) and Country (USA, Canada, UK). So build it so that you can communicate with multiple credit card processing APIs.

    Security is essential if you are storing credit cards and payment details. Ensure that you are encrypting things properly.

    Again, don't reinvent the wheel. You are better off using an existing provider and focussing your development attention on solving an problem that can't easily be purchase.

    Comprehensive beginner's virtualenv tutorial?

    Here's another good one: http://www.saltycrane.com/blog/2009/05/notes-using-pip-and-virtualenv-django/

    This one shows how to use pip and a pip requirements file with virtualenv; Scobal's two suggested tutorials are both very helpful but are both easy_install-centric.

    Note that none of these tutorials explain how to run a different version of Python within a virtualenv - for this, see this SO question: Use different Python version with virtualenv

    AngularJS: ng-show / ng-hide not working with `{{ }}` interpolation

    Try wrapping expression with:

    $scope.$apply(function() {
       $scope.foo.bar=true;
    })
    

    Is there any way to kill a Thread?

    You can kill a thread by installing trace into the thread that will exit the thread. See attached link for one possible implementation.

    Kill a thread in Python

    Appending a list or series to a pandas DataFrame as a row?

    If you want to add a Series and use the Series' index as columns of the DataFrame, you only need to append the Series between brackets:

    In [1]: import pandas as pd
    
    In [2]: df = pd.DataFrame()
    
    In [3]: row=pd.Series([1,2,3],["A","B","C"])
    
    In [4]: row
    Out[4]: 
    A    1
    B    2
    C    3
    dtype: int64
    
    In [5]: df.append([row],ignore_index=True)
    Out[5]: 
       A  B  C
    0  1  2  3
    
    [1 rows x 3 columns]
    

    Whitout the ignore_index=True you don't get proper index.

    How to get calendar Quarter from a date in TSQL

    Here is another option. Use a CTE to define the months of the quarter and then join to it to determine the quarter:

    WITH Quarters AS (
       SELECT Q = 'Q1', MonthBegin = 1, MonthEnd = 3 UNION
       SELECT Q = 'Q2', MonthBegin = 4, MonthEnd = 6 UNION
       SELECT Q = 'Q3', MonthBegin = 7, MonthEnd = 9 UNION
       SELECT Q = 'Q4', MonthBegin = 10, MonthEnd = 12
    )
    SELECT
       [Year] = DATEPART(yyyy, CONVERT(DATETIME, Dates.[date])),
       [Quarter] = CONVERT(VARCHAR(4), DATEPART(yyyy, CONVERT(DATETIME, Dates.[date]))) + '-' + q.Q
    FROM
       (VALUES
           ('20080102'),
           ('20070821')
       ) AS Dates ([date])
       INNER JOIN Quarters q ON
          DATEPART(m, CONVERT(DATETIME, Dates.[date])) >= q.MonthBegin AND
          DATEPART(m, CONVERT(DATETIME, Dates.[date])) <= q.MonthEnd;
    

    Returns:

    Year  Quarter
    ----- ----------
    2008  2008-Q1
    2007  2007-Q3
    

    SQL Fiddle

    Handle column type of int (04/23/2014):

    WITH Quarters AS (
        SELECT Q = 'Q1', MonthBegin = 1, MonthEnd = 3 UNION
        SELECT Q = 'Q2', MonthBegin = 4, MonthEnd = 6 UNION
        SELECT Q = 'Q3', MonthBegin = 7, MonthEnd = 9 UNION
        SELECT Q = 'Q4', MonthBegin = 10, MonthEnd = 12
    )
    SELECT
        [Year] = DATEPART(yyyy, CONVERT(DATETIME, CONVERT(VARCHAR(8), Dates.[date]))),
        [Quarter] = CONVERT(VARCHAR(4), DATEPART(yyyy, CONVERT(DATETIME, CONVERT(VARCHAR(8), Dates.[date])))) + '-' + q.Q
    FROM
        (VALUES
            (20080102),
            (20070821)
        ) AS Dates ([date])
        INNER JOIN Quarters q ON
            DATEPART(m, CONVERT(DATETIME, CONVERT(VARCHAR(8), Dates.[date]))) >= q.MonthBegin AND
            DATEPART(m, CONVERT(DATETIME, CONVERT(VARCHAR(8), Dates.[date]))) <= q.MonthEnd;
    

    Get File Path (ends with folder)

    Have added ErrorHandler to this in case the user hits the cancel button instead of selecting a folder. So instead of getting a horrible error message you get a message that a folder must be selected and then the routine ends. Below code also stores the folder path in a range name (Which is just linked to cell A1 on a sheet).

    Sub SelectFolder()
    
    Dim diaFolder As FileDialog
    
    'Open the file dialog
    On Error GoTo ErrorHandler
    Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
    diaFolder.AllowMultiSelect = False
    diaFolder.Title = "Select a folder then hit OK"
    diaFolder.Show
    Range("IC_Files_Path").Value = diaFolder.SelectedItems(1)
    Set diaFolder = Nothing
    Exit Sub
    
    ErrorHandler:
    Msg = "No folder selected, you must select a folder for program to run"
    Style = vbError
    Title = "Need to Select Folder"
    Response = MsgBox(Msg, Style, Title)
    
    End Sub
    

    Replacing objects in array

    I am only submitting this answer because people expressed concerns over browsers and maintaining the order of objects. I recognize that it is not the most efficient way to accomplish the goal.

    Having said this, I broke the problem down into two functions for readability.

    // The following function is used for each itertion in the function updateObjectsInArr
    const newObjInInitialArr = function(initialArr, newObject) {
      let id = newObject.id;
      let newArr = [];
      for (let i = 0; i < initialArr.length; i++) {
        if (id === initialArr[i].id) {
          newArr.push(newObject);
        } else {
          newArr.push(initialArr[i]);
        }
      }
      return newArr;
    };
    
    const updateObjectsInArr = function(initialArr, newArr) {
        let finalUpdatedArr = initialArr;  
        for (let i = 0; i < newArr.length; i++) {
          finalUpdatedArr = newObjInInitialArr(finalUpdatedArr, newArr[i]);
        }
    
        return finalUpdatedArr
    }
    
    const revisedArr = updateObjectsInArr(arr1, arr2);
    

    jsfiddle

    How to use the toString method in Java?

    Use of the String.toString:

    Whenever you require to explore the constructor called value in the String form, you can simply use String.toString... for an example...

    package pack1;
    
    import java.util.*;
    
    class Bank {
    
        String n;
        String add;
        int an;
        int bal;
        int dep;
    
        public Bank(String n, String add, int an, int bal) {
    
            this.add = add;
            this.bal = bal;
            this.an = an;
            this.n = n;
    
        }
    
        public String toString() {
            return "Name of the customer.:" + this.n + ",, "
                    + "Address of the customer.:" + this.add + ",, " + "A/c no..:"
                    + this.an + ",, " + "Balance in A/c..:" + this.bal;
        }
    }
    
    public class Demo2 {
    
        public static void main(String[] args) {
    
            List<Bank> l = new LinkedList<Bank>();
    
            Bank b1 = new Bank("naseem1", "Darbhanga,bihar", 123, 1000);
            Bank b2 = new Bank("naseem2", "patna,bihar", 124, 1500);
            Bank b3 = new Bank("naseem3", "madhubani,bihar", 125, 1600);
            Bank b4 = new Bank("naseem4", "samastipur,bihar", 126, 1700);
            Bank b5 = new Bank("naseem5", "muzafferpur,bihar", 127, 1800);
            l.add(b1);
            l.add(b2);
            l.add(b3);
            l.add(b4);
            l.add(b5);
            Iterator<Bank> i = l.iterator();
            while (i.hasNext()) {
                System.out.println(i.next());
            }
        }
    
    }
    

    ... copy this program into your Eclipse, and run it... you will get the ideas about String.toString...

    Python def function: How do you specify the end of the function?

    In my opinion, it's better to explicitly mark the end of the function by comment

    def func():
         # funcbody
         ## end of subroutine func ##
    

    The point is that some subroutine is very long and is not convenient to scroll up the editor to check for which function is ended. In addition, if you use Sublime, you can right click -> Goto Definition and it will automatically jump to the subroutine declaration.

    QString to char* conversion

    Maybe

    my_qstring.toStdString().c_str();

    or safer, as Federico points out:

    std::string str = my_qstring.toStdString();
    const char* p = str.c_str();
    

    It's far from optimal, but will do the work.

    Adding rows dynamically with jQuery

    Building on the other answers, I simplified things a bit. By cloning the last element, we get the "add new" button for free (you have to change the ID to a class because of the cloning) and also reduce DOM operations. I had to use filter() instead of find() to get only the last element.

    $('.js-addNew').on('click', function(e) {
       e.preventDefault();
       var $rows   = $('.person'),
           $last   = $rows.filter(':last'),
           $newRow = $last.clone().insertAfter($last);
    
       $last.find($('.js-addNew')).remove(); // remove old button
       $newRow.hide().find('input').val('');
       $newRow.slideDown(500);
    });
    

    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);
    

    In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

    If you really want it to look more semantic like having the <body> in the middle you can use the <main> element. With all the recent advances the <body>element is not as semantic as it once was but you just have to think of it as a wrapper in which the view port sees.

    <html>
        <head>
        </head>
        <body>
            <header>
            </header>
            <main>
                <section></section>
                <article></article>
            </main>
            <footer>
            </footer>
        <body>
    </html>
    

    How to convert a file to utf-8 in Python?

    Thanks for the replies, it works!

    And since the source files are in mixed formats, I added a list of source formats to be tried in sequence (sourceFormats), and on UnicodeDecodeError I try the next format:

    from __future__ import with_statement
    
    import os
    import sys
    import codecs
    from chardet.universaldetector import UniversalDetector
    
    targetFormat = 'utf-8'
    outputDir = 'converted'
    detector = UniversalDetector()
    
    def get_encoding_type(current_file):
        detector.reset()
        for line in file(current_file):
            detector.feed(line)
            if detector.done: break
        detector.close()
        return detector.result['encoding']
    
    def convertFileBestGuess(filename):
       sourceFormats = ['ascii', 'iso-8859-1']
       for format in sourceFormats:
         try:
            with codecs.open(fileName, 'rU', format) as sourceFile:
                writeConversion(sourceFile)
                print('Done.')
                return
          except UnicodeDecodeError:
            pass
    
    def convertFileWithDetection(fileName):
        print("Converting '" + fileName + "'...")
        format=get_encoding_type(fileName)
        try:
            with codecs.open(fileName, 'rU', format) as sourceFile:
                writeConversion(sourceFile)
                print('Done.')
                return
        except UnicodeDecodeError:
            pass
    
        print("Error: failed to convert '" + fileName + "'.")
    
    
    def writeConversion(file):
        with codecs.open(outputDir + '/' + fileName, 'w', targetFormat) as targetFile:
            for line in file:
                targetFile.write(line)
    
    # Off topic: get the file list and call convertFile on each file
    # ...
    

    (EDIT by Rudro Badhon: this incorporates the original try multiple formats until you don't get an exception as well as an alternate approach that uses chardet.universaldetector)

    Multiple modals overlay

    I realize an answer has been accepted, but I strongly suggest not hacking bootstrap to fix this.

    You can pretty easily achieve the same effect by hooking the shown.bs.modal and hidden.bs.modal event handlers and adjusting the z-index there.

    Here's a working example

    A bit more info is available here.

    This solution works automatically with arbitrarily deeply stacks modals.

    The script source code:

    $(document).ready(function() {
    
        $('.modal').on('hidden.bs.modal', function(event) {
            $(this).removeClass( 'fv-modal-stack' );
            $('body').data( 'fv_open_modals', $('body').data( 'fv_open_modals' ) - 1 );
        });
    
        $('.modal').on('shown.bs.modal', function (event) {
            // keep track of the number of open modals
            if ( typeof( $('body').data( 'fv_open_modals' ) ) == 'undefined' ) {
                $('body').data( 'fv_open_modals', 0 );
            }
    
            // if the z-index of this modal has been set, ignore.
            if ($(this).hasClass('fv-modal-stack')) {
                return;
            }
    
            $(this).addClass('fv-modal-stack');
            $('body').data('fv_open_modals', $('body').data('fv_open_modals' ) + 1 );
            $(this).css('z-index', 1040 + (10 * $('body').data('fv_open_modals' )));
            $('.modal-backdrop').not('.fv-modal-stack').css('z-index', 1039 + (10 * $('body').data('fv_open_modals')));
            $('.modal-backdrop').not('fv-modal-stack').addClass('fv-modal-stack'); 
    
        });        
    });
    

    UL list style not applying

    If I'm not mistaken, you should be applying this rule to the li, not the ul.

    ul li {list-style-type: disc;}
    

    Check Whether a User Exists

    Depending on your shell implementation (e.g. Busybox vs. grown-up) the [ operator might start a process, changing $?.

    Try

    getent passwd $1 > /dev/null 2&>1
    RES=$?
    
    if [ $RES -eq 0 ]; then
        echo "yes the user exists"
    else
        echo "No, the user does not exist"
    fi
    

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

    Keys must be unique. Don't do that. Redesign as needed.

    (if you are trying to insert, then delete, and the insert fails... just do the delete first. Rollback on error in either statement).

    Split an integer into digits to compute an ISBN checksum

    Answer: 165

    Method: brute-force! Here is a tiny bit of Python (version 2.7) code to count'em all.

    from math import sqrt, floor
    is_ps = lambda x: floor(sqrt(x)) ** 2 == x
    count = 0
    for n in range(1002, 10000, 3):
        if n % 11 and is_ps(sum(map(int, str(n)))):
            count += 1
            print "#%i: %s" % (count, n)
    

    SQL Server : fetching records between two dates?

    You need to be more explicit and add the start and end times as well, down to the milliseconds:

    select * 
    from xxx 
    where dates between '2012-10-26 00:00:00.000' and '2012-10-27 23:59:59.997'
    

    The database can very well interpret '2012-10-27' as '2012-10-27 00:00:00.000'.

    cannot be cast to java.lang.Comparable

    • the object which implements Comparable is Fegan.

    The method compareTo you are overidding in it should have a Fegan object as a parameter whereas you are casting it to a FoodItems. Your compareTo implementation should describe how a Fegan compare to another Fegan.

    • To actually do your sorting, you might want to make your FoodItems implement Comparable aswell and copy paste your actual compareTo logic in it.

    Run an OLS regression with Pandas Data Frame

    This would require me to reformat the data into lists inside lists, which seems to defeat the purpose of using pandas in the first place.

    No it doesn't, just convert to a NumPy array:

    >>> data = np.asarray(df)
    

    This takes constant time because it just creates a view on your data. Then feed it to scikit-learn:

    >>> from sklearn.linear_model import LinearRegression
    >>> lr = LinearRegression()
    >>> X, y = data[:, 1:], data[:, 0]
    >>> lr.fit(X, y)
    LinearRegression(copy_X=True, fit_intercept=True, normalize=False)
    >>> lr.coef_
    array([  4.01182386e-01,   3.51587361e-04])
    >>> lr.intercept_
    14.952479503953672
    

    UITableView - scroll to the top

    Swift 5, iOS 13

    I know this question already has a lot of answers but from my experience this method always works:

    let last = IndexPath(row: someArray.count - 1, section: 0)
    tableView.scrollToRow(at: last, at: .bottom, animated: true)
    

    And this is especially true if you're working with animations (like keyboard) or certain async tasks—the other answers will often scroll to the almost bottom. If for some reason this doesn't get you all the way to the bottom, it's almost certainly because of a competing animation so the workaround is to dispatch this animation to the end of the main queue:

    DispatchQueue.main.async {
        let last = IndexPath(row: self.someArray.count - 1, section: 0)
        self.tableView.scrollToRow(at: last, at: .bottom, animated: true)
    }
    

    This may seem redundant since you're already on the main queue but it's not because it serializes the animations.

    Java: String - add character n-times

    Keep in mind that if the "n" is large, it might not be such a great idea to use +=, since every time you add another String through +=, the JVM will create a brand new object (plenty of info on this around).

    Something like:

    StringBuilder b = new StringBuilder(existing_string);
    for(int i = 0; i<n; i++){
        b.append("other_string");
    }
    return b.toString();
    

    Not actually coding this in an IDE, so minor flaws may occur, but this is the basic idea.

    Python script to copy text to clipboard

    One more answer to improve on: https://stackoverflow.com/a/4203897/2804197 and https://stackoverflow.com/a/25476462/1338797 (Tkinter).

    Tkinter is nice, because it's either included with Python (Windows) or easy to install (Linux), and thus requires little dependencies for the end user.

    Here I have a "full-blown" example, which copies the arguments or the standard input, to clipboard, and - when not on Windows - waits for the user to close the application:

    import sys
    
    try:
        from Tkinter import Tk
    except ImportError:
        # welcome to Python3
        from tkinter import Tk
        raw_input = input
    
    r = Tk()
    r.withdraw()
    r.clipboard_clear()
    
    if len(sys.argv) < 2:
        data = sys.stdin.read()
    else:
        data = ' '.join(sys.argv[1:])
    
    r.clipboard_append(data)
    
    if sys.platform != 'win32':
        if len(sys.argv) > 1:
            raw_input('Data was copied into clipboard. Paste and press ENTER to exit...')
        else:
            # stdin already read; use GUI to exit
            print('Data was copied into clipboard. Paste, then close popup to exit...')
            r.deiconify()
            r.mainloop()
    else:
        r.destroy()
    

    This showcases:

    • importing Tk across Py2 and Py3
    • raw_input and print() compatibility
    • "unhiding" Tk root window when needed
    • waiting for exit on Linux in two different ways.

    Can not find the tag library descriptor of springframework

    I had the same issue with weblogic 12c and maven I initially while deploying from eclipse (kepler) (deploying from the console gave no errors).

    The other solutions given on this page didn't help.

    I extracted the spring.tld spring-form.tld files of the spring-webmvc jar (which I found in my repository) in the web\WEB-INF folder of my war module;

    I did a fresh build; deployed (from eclipse) into weblogic 12c, tested the application and the error was gone;

    I removed the spring.tld spring-form.tld files again and after deleting; rebuilding and redeploying the application the error didn't show up again.

    I double checked whether the files were gone in the war and they were indeed not present.

    hope this helps others with a similar issue...

    Verilog generate/genvar in an always block

    You need to reverse the nesting inside the generate block:

    genvar c;
    generate
        for (c = 0; c < ROWBITS; c = c + 1) begin: test
            always @(posedge sysclk) begin
                temp[c] <= 1'b0;
            end
        end
    endgenerate
    

    Technically, this generates four always blocks:

    always @(posedge sysclk) temp[0] <= 1'b0;
    always @(posedge sysclk) temp[1] <= 1'b0;
    always @(posedge sysclk) temp[2] <= 1'b0;
    always @(posedge sysclk) temp[3] <= 1'b0;
    

    In this simple example, there's no difference in behavior between the four always blocks and a single always block containing four assignments, but in other cases there could be.

    The genvar-dependent operation needs to be resolved when constructing the in-memory representation of the design (in the case of a simulator) or when mapping to logic gates (in the case of a synthesis tool). The always @posedge doesn't have meaning until the design is operating.

    Subject to certain restrictions, you can put a for loop inside the always block, even for synthesizable code. For synthesis, the loop will be unrolled. However, in that case, the for loop needs to work with a reg, integer, or similar. It can't use a genvar, because having the for loop inside the always block describes an operation that occurs at each edge of the clock, not an operation that can be expanded statically during elaboration of the design.

    Testing for empty or nil-value string

    variable = id if variable.to_s.empty?
    

    How do I create test and train samples from one dataframe with pandas?

    You can use below code to create test and train samples :

    from sklearn.model_selection import train_test_split
    trainingSet, testSet = train_test_split(df, test_size=0.2)
    

    Test size can vary depending on the percentage of data you want to put in your test and train dataset.

    Make new column in Panda dataframe by adding values from other columns

    Concerning n00b's comment: "I get the following warning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead"

    I was getting the same error. In my case it was because I was trying to perform the column addition on a dataframe that was created like this:

    df_b = df[['colA', 'colB', 'colC']]
    

    instead of:

    df_c = pd.DataFrame(df, columns=['colA', 'colB', 'colC'])
    

    df_b is a copy of a slice from df
    df_c is an new dataframe. So

    df_c['colD'] = df['colA'] + df['colB']+ df['colC']
    

    will add the columns and won't raise any warning. Same if .sum(axis=1) is used.

    Search all the occurrences of a string in the entire project in Android Studio

    Android Studio Version 4.0.1 on Mac combination is for me:

    Shift + Control + F

    What are Aggregates and PODs and how/why are they special?

    What changes for C++11?

    Aggregates

    The standard definition of an aggregate has changed slightly, but it's still pretty much the same:

    An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no brace-or-equal-initializers for non-static data members (9.2), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

    Ok, what changed?

    1. Previously, an aggregate could have no user-declared constructors, but now it can't have user-provided constructors. Is there a difference? Yes, there is, because now you can declare constructors and default them:

      struct Aggregate {
          Aggregate() = default; // asks the compiler to generate the default implementation
      };
      

      This is still an aggregate because a constructor (or any special member function) that is defaulted on the first declaration is not user-provided.

    2. Now an aggregate cannot have any brace-or-equal-initializers for non-static data members. What does this mean? Well, this is just because with this new standard, we can initialize members directly in the class like this:

      struct NotAggregate {
          int x = 5; // valid in C++11
          std::vector<int> s{1,2,3}; // also valid
      };
      

      Using this feature makes the class no longer an aggregate because it's basically equivalent to providing your own default constructor.

    So, what is an aggregate didn't change much at all. It's still the same basic idea, adapted to the new features.

    What about PODs?

    PODs went through a lot of changes. Lots of previous rules about PODs were relaxed in this new standard, and the way the definition is provided in the standard was radically changed.

    The idea of a POD is to capture basically two distinct properties:

    1. It supports static initialization, and
    2. Compiling a POD in C++ gives you the same memory layout as a struct compiled in C.

    Because of this, the definition has been split into two distinct concepts: trivial classes and standard-layout classes, because these are more useful than POD. The standard now rarely uses the term POD, preferring the more specific trivial and standard-layout concepts.

    The new definition basically says that a POD is a class that is both trivial and has standard-layout, and this property must hold recursively for all non-static data members:

    A POD struct is a non-union class that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types). Similarly, a POD union is a union that is both a trivial class and a standard layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types). A POD class is a class that is either a POD struct or a POD union.

    Let's go over each of these two properties in detail separately.

    Trivial classes

    Trivial is the first property mentioned above: trivial classes support static initialization. If a class is trivially copyable (a superset of trivial classes), it is ok to copy its representation over the place with things like memcpy and expect the result to be the same.

    The standard defines a trivial class as follows:

    A trivially copyable class is a class that:

    — has no non-trivial copy constructors (12.8),

    — has no non-trivial move constructors (12.8),

    — has no non-trivial copy assignment operators (13.5.3, 12.8),

    — has no non-trivial move assignment operators (13.5.3, 12.8), and

    — has a trivial destructor (12.4).

    A trivial class is a class that has a trivial default constructor (12.1) and is trivially copyable.

    [ Note: In particular, a trivially copyable or trivial class does not have virtual functions or virtual base classes.—end note ]

    So, what are all those trivial and non-trivial things?

    A copy/move constructor for class X is trivial if it is not user-provided and if

    — class X has no virtual functions (10.3) and no virtual base classes (10.1), and

    — the constructor selected to copy/move each direct base class subobject is trivial, and

    — for each non-static data member of X that is of class type (or array thereof), the constructor selected to copy/move that member is trivial;

    otherwise the copy/move constructor is non-trivial.

    Basically this means that a copy or move constructor is trivial if it is not user-provided, the class has nothing virtual in it, and this property holds recursively for all the members of the class and for the base class.

    The definition of a trivial copy/move assignment operator is very similar, simply replacing the word "constructor" with "assignment operator".

    A trivial destructor also has a similar definition, with the added constraint that it can't be virtual.

    And yet another similar rule exists for trivial default constructors, with the addition that a default constructor is not-trivial if the class has non-static data members with brace-or-equal-initializers, which we've seen above.

    Here are some examples to clear everything up:

    // empty classes are trivial
    struct Trivial1 {};
    
    // all special members are implicit
    struct Trivial2 {
        int x;
    };
    
    struct Trivial3 : Trivial2 { // base class is trivial
        Trivial3() = default; // not a user-provided ctor
        int y;
    };
    
    struct Trivial4 {
    public:
        int a;
    private: // no restrictions on access modifiers
        int b;
    };
    
    struct Trivial5 {
        Trivial1 a;
        Trivial2 b;
        Trivial3 c;
        Trivial4 d;
    };
    
    struct Trivial6 {
        Trivial2 a[23];
    };
    
    struct Trivial7 {
        Trivial6 c;
        void f(); // it's okay to have non-virtual functions
    };
    
    struct Trivial8 {
         int x;
         static NonTrivial1 y; // no restrictions on static members
    };
    
    struct Trivial9 {
         Trivial9() = default; // not user-provided
          // a regular constructor is okay because we still have default ctor
         Trivial9(int x) : x(x) {};
         int x;
    };
    
    struct NonTrivial1 : Trivial3 {
        virtual void f(); // virtual members make non-trivial ctors
    };
    
    struct NonTrivial2 {
        NonTrivial2() : z(42) {} // user-provided ctor
        int z;
    };
    
    struct NonTrivial3 {
        NonTrivial3(); // user-provided ctor
        int w;
    };
    NonTrivial3::NonTrivial3() = default; // defaulted but not on first declaration
                                          // still counts as user-provided
    struct NonTrivial5 {
        virtual ~NonTrivial5(); // virtual destructors are not trivial
    };
    

    Standard-layout

    Standard-layout is the second property. The standard mentions that these are useful for communicating with other languages, and that's because a standard-layout class has the same memory layout of the equivalent C struct or union.

    This is another property that must hold recursively for members and all base classes. And as usual, no virtual functions or virtual base classes are allowed. That would make the layout incompatible with C.

    A relaxed rule here is that standard-layout classes must have all non-static data members with the same access control. Previously these had to be all public, but now you can make them private or protected, as long as they are all private or all protected.

    When using inheritance, only one class in the whole inheritance tree can have non-static data members, and the first non-static data member cannot be of a base class type (this could break aliasing rules), otherwise, it's not a standard-layout class.

    This is how the definition goes in the standard text:

    A standard-layout class is a class that:

    — has no non-static data members of type non-standard-layout class (or array of such types) or reference,

    — has no virtual functions (10.3) and no virtual base classes (10.1),

    — has the same access control (Clause 11) for all non-static data members,

    — has no non-standard-layout base classes,

    — either has no non-static data members in the most derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and

    — has no base classes of the same type as the first non-static data member.

    A standard-layout struct is a standard-layout class defined with the class-key struct or the class-key class.

    A standard-layout union is a standard-layout class defined with the class-key union.

    [ Note: Standard-layout classes are useful for communicating with code written in other programming languages. Their layout is specified in 9.2.—end note ]

    And let's see a few examples.

    // empty classes have standard-layout
    struct StandardLayout1 {};
    
    struct StandardLayout2 {
        int x;
    };
    
    struct StandardLayout3 {
    private: // both are private, so it's ok
        int x;
        int y;
    };
    
    struct StandardLayout4 : StandardLayout1 {
        int x;
        int y;
    
        void f(); // perfectly fine to have non-virtual functions
    };
    
    struct StandardLayout5 : StandardLayout1 {
        int x;
        StandardLayout1 y; // can have members of base type if they're not the first
    };
    
    struct StandardLayout6 : StandardLayout1, StandardLayout5 {
        // can use multiple inheritance as long only
        // one class in the hierarchy has non-static data members
    };
    
    struct StandardLayout7 {
        int x;
        int y;
        StandardLayout7(int x, int y) : x(x), y(y) {} // user-provided ctors are ok
    };
    
    struct StandardLayout8 {
    public:
        StandardLayout8(int x) : x(x) {} // user-provided ctors are ok
    // ok to have non-static data members and other members with different access
    private:
        int x;
    };
    
    struct StandardLayout9 {
        int x;
        static NonStandardLayout1 y; // no restrictions on static members
    };
    
    struct NonStandardLayout1 {
        virtual f(); // cannot have virtual functions
    };
    
    struct NonStandardLayout2 {
        NonStandardLayout1 X; // has non-standard-layout member
    };
    
    struct NonStandardLayout3 : StandardLayout1 {
        StandardLayout1 x; // first member cannot be of the same type as base
    };
    
    struct NonStandardLayout4 : StandardLayout3 {
        int z; // more than one class has non-static data members
    };
    
    struct NonStandardLayout5 : NonStandardLayout3 {}; // has a non-standard-layout base class
    

    Conclusion

    With these new rules a lot more types can be PODs now. And even if a type is not POD, we can take advantage of some of the POD properties separately (if it is only one of trivial or standard-layout).

    The standard library has traits to test these properties in the header <type_traits>:

    template <typename T>
    struct std::is_pod;
    template <typename T>
    struct std::is_trivial;
    template <typename T>
    struct std::is_trivially_copyable;
    template <typename T>
    struct std::is_standard_layout;
    

    How to access Spring MVC model object in javascript file?

    in controller:

    JSONObject jsonobject=new JSONObject();
    jsonobject.put("error","Invalid username");
    response.getWriter().write(jsonobject.toString());
    

    in javascript:

    f(data!=success){
    
    
    
     var errorMessage=jQuery.parseJson(data);
      alert(errorMessage.error);
    }
    

    Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

    As promised, I'm putting an example for how to use annotations to serialize/deserialize polymorphic objects, I based this example in the Animal class from the tutorial you were reading.

    First of all your Animal class with the Json Annotations for the subclasses.

    import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
    import com.fasterxml.jackson.annotation.JsonSubTypes;
    import com.fasterxml.jackson.annotation.JsonTypeInfo;
    
    @JsonIgnoreProperties(ignoreUnknown = true)
    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
    @JsonSubTypes({
        @JsonSubTypes.Type(value = Dog.class, name = "Dog"),
    
        @JsonSubTypes.Type(value = Cat.class, name = "Cat") }
    )
    public abstract class Animal {
    
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
    }
    

    Then your subclasses, Dog and Cat.

    public class Dog extends Animal {
    
        private String breed;
    
        public Dog() {
    
        }
    
        public Dog(String name, String breed) {
            setName(name);
            setBreed(breed);
        }
    
        public String getBreed() {
            return breed;
        }
    
        public void setBreed(String breed) {
            this.breed = breed;
        }
    }
    
    public class Cat extends Animal {
    
        public String getFavoriteToy() {
            return favoriteToy;
        }
    
        public Cat() {}
    
        public Cat(String name, String favoriteToy) {
            setName(name);
            setFavoriteToy(favoriteToy);
        }
    
        public void setFavoriteToy(String favoriteToy) {
            this.favoriteToy = favoriteToy;
        }
    
        private String favoriteToy;
    
    }
    

    As you can see, there is nothing special for Cat and Dog, the only one that know about them is the abstract class Animal, so when deserializing, you'll target to Animal and the ObjectMapper will return the actual instance as you can see in the following test:

    public class Test {
    
        public static void main(String[] args) {
    
            ObjectMapper objectMapper = new ObjectMapper();
    
            Animal myDog = new Dog("ruffus","english shepherd");
    
            Animal myCat = new Cat("goya", "mice");
    
            try {
                String dogJson = objectMapper.writeValueAsString(myDog);
    
                System.out.println(dogJson);
    
                Animal deserializedDog = objectMapper.readValue(dogJson, Animal.class);
    
                System.out.println("Deserialized dogJson Class: " + deserializedDog.getClass().getSimpleName());
    
                String catJson = objectMapper.writeValueAsString(myCat);
    
                Animal deseriliazedCat = objectMapper.readValue(catJson, Animal.class);
    
                System.out.println("Deserialized catJson Class: " + deseriliazedCat.getClass().getSimpleName());
    
    
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    }
    

    Output after running the Test class:

    {"@type":"Dog","name":"ruffus","breed":"english shepherd"}

    Deserialized dogJson Class: Dog

    {"@type":"Cat","name":"goya","favoriteToy":"mice"}

    Deserialized catJson Class: Cat

    Hope this helps,

    Jose Luis

    Regex for empty string or white space

    The \ (backslash) in the .match call is not properly escaped. It would be easier to use a regex literal though. Either will work:

    var regex = "^\\s+$";
    var regex = /^\s+$/;
    

    Also note that + will require at least one space. You may want to use *.

    Re-assign host access permission to MySQL user

    The accepted answer only renamed the user but the privileges were left behind.

    I'd recommend using:

    RENAME USER 'foo'@'1.2.3.4' TO 'foo'@'1.2.3.5';
    

    According to MySQL documentation:

    RENAME USER causes the privileges held by the old user to be those held by the new user.

    How to check if a line has one of the strings in a list?

    strings = ("string1", "string2", "string3")
    for line in file:
        if any(s in line for s in strings):
            print "yay!"
    

    ASP.NET page life cycle explanation

    This acronym might help you to remember the ASP.NET life cycle stages which I wrote about in the below blog post.

    R-SIL-VP-RU

    1. Request
    2. Start
    3. Initialization
    4. Load
    5. Validation
    6. Post back handling
    7. Rendering
    8. Unload

    From my blog: Understand ASP.NET Page life cycle and remember stages in easy way
    18 May 2014

    How do I pick 2 random items from a Python set?

    Use the random module: http://docs.python.org/library/random.html

    import random
    random.sample(set([1, 2, 3, 4, 5, 6]), 2)
    

    This samples the two values without replacement (so the two values are different).

    How to trigger SIGUSR1 and SIGUSR2?

    They are signals that application developers use. The kernel shouldn't ever send these to a process. You can send them using kill(2) or using the utility kill(1).

    If you intend to use signals for synchronization you might want to check real-time signals (there's more of them, they are queued, their delivery order is guaranteed etc).

    Checking on a thread / remove from list

    The answer has been covered, but for simplicity...

    # To filter out finished threads
    threads = [t for t in threads if t.is_alive()]
    
    # Same thing but for QThreads (if you are using PyQt)
    threads = [t for t in threads if t.isRunning()]
    

    Only allow specific characters in textbox

    Intercept the KeyPressed event is in my opinion a good solid solution. Pay attention to trigger code characters (e.KeyChar lower then 32) if you use a RegExp.

    But in this way is still possible to inject characters out of range whenever the user paste text from the clipboard. Unfortunately I did not found correct clipboard events to fix this.

    So a waterproof solution is to intercept TextBox.TextChanged. Here is sometimes the original out of range character visible, for a short time. I recommend to implement both.

    using System.Text.RegularExpressions;

    private void Form1_Shown(object sender, EventArgs e)
    {
        filterTextBoxContent(textBox1);
    }
    
    
    string pattern = @"[^0-9^+^\-^/^*^(^)]";
    
    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if(e.KeyChar >= 32 && Regex.Match(e.KeyChar.ToString(), pattern).Success) { e.Handled = true; }
    }
    
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        filterTextBoxContent(textBox1);
    }
    
    private bool filterTextBoxContent(TextBox textBox)
    {
        string text = textBox.Text;
    
        MatchCollection matches = Regex.Matches(text, pattern);
        bool matched = false;
    
        int selectionStart = textBox.SelectionStart;
        int selectionLength = textBox.SelectionLength;
    
        int leftShift = 0;
        foreach (Match match in matches)
        {
            if (match.Success && match.Captures.Count > 0)
            {
                matched = true;
                Capture capture = match.Captures[0];
    
                int captureLength = capture.Length;
                int captureStart = capture.Index - leftShift;
                int captureEnd = captureStart + captureLength;
    
                int selectionEnd = selectionStart + selectionLength;
    
                text = text.Substring(0, captureStart) + text.Substring(captureEnd, text.Length - captureEnd);
    
                textBox.Text = text;
    
                int boundSelectionStart = selectionStart < captureStart ? -1 : (selectionStart < captureEnd ? 0 : 1);
                int boundSelectionEnd = selectionEnd < captureStart ? -1 : (selectionEnd < captureEnd ? 0 : 1);
    
                if (boundSelectionStart == -1)
                {
                    if (boundSelectionEnd == 0)
                    {
                        selectionLength -= selectionEnd - captureStart;
                    }
                    else if (boundSelectionEnd == 1)
                    {
                        selectionLength -= captureLength;
                    }
                }
                else if (boundSelectionStart == 0)
                {
                    if (boundSelectionEnd == 0)
                    {
                        selectionStart = captureStart;
                        selectionLength = 0;
                    }
                    else if (boundSelectionEnd == 1)
                    {
                        selectionStart = captureStart;
                        selectionLength -= captureEnd - selectionStart;
                    }
                }
                else if (boundSelectionStart == 1)
                {
                    selectionStart -= captureLength;
                }
    
                leftShift++;
            }
        }
    
        textBox.SelectionStart = selectionStart;
        textBox.SelectionLength = selectionLength;
    
        return matched;
    }
    

    How to make a website secured with https

    For business data, if the data is private I would use a secured connection, otherwise a forms authentication is sufficient.

    If you do decide to use a secured connection, please note that I do not have experience with securing websites, I am just recanting off what I encountered during my own personal experience. If I am wrong in anyway, please feel free to correct me.

    What should I do to prepare my website for https. (Do I need to alter the code / Config)

    In order to enable SSL (Secure Sockets Layer) for your website, you would need to set-up a certificate, code or config is not altered.

    I have enabled SSL for an internal web-server, by using OpenSSL and ActivePerl from this online tutorial. If this is used for a larger audience (my audience was less than 10 people) and is in the public domain, I suggest seeking professional alternatives.

    Is SSL and https one and the same...

    Not exactly, but they go hand in hand! SSL ensures that data is encrypted and decrypted back and forth while you are viewing the website, https is the URI that is need to access the secure website. You will notice when you try to access http://secure.mydomain.com it displays an error message.

    Do I need to apply with someone to get some license or something.

    You would not need to obtain a license, but rather a certificate. You can look into companies that offer professional services with securing websites, such as VeriSign as an example.

    Do I need to make all my pages secured or only the login page...

    Once your certificate is enabled for mydomain.com every page that falls under *.mydomain.com will be secured.

    How to style a div to have a background color for the entire width of the content, and not just for the width of the display?

    The width is being restricted by the size of the body. If you make the width of the body larger you will see it stays on one line with the background color.

    To maintain the minimum width: min-width:100%

    Why is there no tuple comprehension in Python?

    As another poster macm mentioned, the fastest way to create a tuple from a generator is tuple([generator]).


    Performance Comparison

    • List comprehension:

      $ python3 -m timeit "a = [i for i in range(1000)]"
      10000 loops, best of 3: 27.4 usec per loop
      
    • Tuple from list comprehension:

      $ python3 -m timeit "a = tuple([i for i in range(1000)])"
      10000 loops, best of 3: 30.2 usec per loop
      
    • Tuple from generator:

      $ python3 -m timeit "a = tuple(i for i in range(1000))"
      10000 loops, best of 3: 50.4 usec per loop
      
    • Tuple from unpacking:

      $ python3 -m timeit "a = *(i for i in range(1000)),"
      10000 loops, best of 3: 52.7 usec per loop
      

    My version of python:

    $ python3 --version
    Python 3.6.3
    

    So you should always create a tuple from a list comprehension unless performance is not an issue.

    Change URL parameters

    I just wrote a simple module to deal with reading and updating the current url query params.

    Example usage:

    import UrlParams from './UrlParams'
    
    UrlParams.remove('foo') //removes all occurences of foo=?
    UrlParams.set('foo', 'bar') //set all occurences of foo equal to bar
    UrlParams.add('foo', 'bar2') //add bar2 to foo result: foo=bar&foo=bar2
    UrlParams.get('foo') //returns bar
    UrlParams.get('foo', true) //returns [bar, bar2]
    

    Here is my code named UrlParams.(js/ts):

    class UrlParams {
    
        /**
         * Get params from current url
         * 
         * @returns URLSearchParams
         */
        static getParams(){
            let url = new URL(window.location.href)
            return new URLSearchParams(url.search.slice(1))
        }
    
        /**
         * Update current url with params
         * 
         * @param params URLSearchParams
         */
        static update(params){
            if(`${params}`){
                window.history.replaceState({}, '', `${location.pathname}?${params}`)
            } else {
                window.history.replaceState({}, '', `${location.pathname}`)
            }
        }
    
        /**
         * Remove key from url query
         * 
         * @param param string
         */
        static remove(param){
            let params = this.getParams()
            if(params.has(param)){
                params.delete(param)
                this.update(params)
            }
        }
    
        /**
         * Add key value pair to current url
         * 
         * @param key string
         * @param value string
         */
        static add(key, value){
            let params = this.getParams()
            params.append(key, value)
            this.update(params)
        }
    
        /**
         * Get value or values of key
         * 
         * @param param string
         * @param all string | string[]
         */
        static get(param, all=false){
            let params = this.getParams()
            if(all){
                return params.getAll(param)
            }
            return params.get(param)
        }
    
        /**
         * Set value of query param
         * 
         * @param key string
         * @param value string
         */
        static set(key, value){
            let params = this.getParams()
            params.set(key, value)
            this.update(params)
        }
    
    }
    export default UrlParams
    export { UrlParams }
    

    Set a button background image iPhone programmatically

    Code for background image of a Button in Swift 3.0

    buttonName.setBackgroundImage(UIImage(named: "facebook.png"), for: .normal)

    Hope this will help someone.

    sql searching multiple words in a string

    Oracle SQL :

    select * 
    from MY_TABLE
    where REGEXP_LIKE (company , 'Microsodt industry | goglge auto car | oracles    database')
    
    • company - is the database column name.
    • results - this SQL will show you if company column rows contain one of those companies (OR phrase) please note that : no wild characters are needed, it's built in.

    more info at : http://www.techonthenet.com/oracle/regexp_like.php

    How to open every file in a folder

    Os

    You can list all files in the current directory using os.listdir:

    import os
    for filename in os.listdir(os.getcwd()):
       with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
          # do your stuff
    

    Glob

    Or you can list only some files, depending on the file pattern using the glob module:

    import glob
    for filename in glob.glob('*.txt'):
       with open(os.path.join(os.cwd(), filename), 'r') as f: # open in readonly mode
          # do your stuff
    

    It doesn't have to be the current directory you can list them in any path you want:

    path = '/some/path/to/file'
    for filename in glob.glob(os.path.join(path, '*.txt')):
       with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
          # do your stuff
    

    Pipe Or you can even use the pipe as you specified using fileinput

    import fileinput
    for line in fileinput.input():
        # do your stuff
    

    And then use it with piping:

    ls -1 | python parse.py
    

    How can JavaScript save to a local file?

    So, your real question is: "How can JavaScript save to a local file?"

    Take a look at http://www.tiddlywiki.com/

    They save their HTML page locally after you have "changed" it internally.

    [ UPDATE 2016.01.31 ]

    TiddlyWiki original version saved directly. It was quite nice, and saved to a configurable backup directory with the timestamp as part of the backup filename.

    TiddlyWiki current version just downloads it as any file download. You need to do your own backup management. :(

    [ END OF UPDATE

    The trick is, you have to open the page as file:// not as http:// to be able to save locally.

    The security on your browser will not let you save to _someone_else's_ local system, only to your own, and even then it isn't trivial.

    -Jesse

    Creating a .p12 file

    The openssl documentation says that file supplied as the -in argument must be in PEM format.

    Turns out that, contrary to the CA's manual, the certificate returned by the CA which I stored in myCert.cer is not PEM format rather it is PKCS7.

    In order to create my .p12, I had to first convert the certificate to PEM:

    openssl pkcs7 -in myCert.cer -print_certs -out certs.pem
    

    and then execute

    openssl pkcs12 -export -out keyStore.p12 -inkey myKey.pem -in certs.pem
    

    How do I copy an object in Java?

    Just follow as below:

    public class Deletable implements Cloneable{
    
        private String str;
        public Deletable(){
        }
        public void setStr(String str){
            this.str = str;
        }
        public void display(){
            System.out.println("The String is "+str);
        }
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }
    

    and wherever you want to get another object, simple perform cloning. e.g:

    Deletable del = new Deletable();
    Deletable delTemp = (Deletable ) del.clone(); // this line will return you an independent
                                     // object, the changes made to this object will
                                     // not be reflected to other object
    

    AcquireConnection method call to the connection manager <Excel Connection Manager> failed with error code 0xC0202009

    In my case the problem was the 32/64 bit driver which I solved by configuring the properties of the sql server job:

    enter image description here

    J2ME/Android/BlackBerry - driving directions, route between two locations

    J2ME Map Route Provider

    maps.google.com has a navigation service which can provide you route information in KML format.

    To get kml file we need to form url with start and destination locations:

    public static String getUrl(double fromLat, double fromLon,
                                double toLat, double toLon) {// connect to map web service
        StringBuffer urlString = new StringBuffer();
        urlString.append("http://maps.google.com/maps?f=d&hl=en");
        urlString.append("&saddr=");// from
        urlString.append(Double.toString(fromLat));
        urlString.append(",");
        urlString.append(Double.toString(fromLon));
        urlString.append("&daddr=");// to
        urlString.append(Double.toString(toLat));
        urlString.append(",");
        urlString.append(Double.toString(toLon));
        urlString.append("&ie=UTF8&0&om=0&output=kml");
        return urlString.toString();
    }
    

    Next you will need to parse xml (implemented with SAXParser) and fill data structures:

    public class Point {
        String mName;
        String mDescription;
        String mIconUrl;
        double mLatitude;
        double mLongitude;
    }
    
    public class Road {
        public String mName;
        public String mDescription;
        public int mColor;
        public int mWidth;
        public double[][] mRoute = new double[][] {};
        public Point[] mPoints = new Point[] {};
    }
    

    Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

     public static String getUrl(double fromLat, double fromLon,
         double toLat, double toLon)
    

    then create connection with this url and get InputStream.
    Then pass this InputStream and get parsed data structure:

     public static Road getRoute(InputStream is) 
    

    Full source code RoadProvider.java

    BlackBerry

    class MapPathScreen extends MainScreen {
        MapControl map;
        Road mRoad = new Road();
        public MapPathScreen() {
            double fromLat = 49.85, fromLon = 24.016667;
            double toLat = 50.45, toLon = 30.523333;
            String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
            InputStream is = getConnection(url);
            mRoad = RoadProvider.getRoute(is);
            map = new MapControl();
            add(new LabelField(mRoad.mName));
            add(new LabelField(mRoad.mDescription));
            add(map);
        }
        protected void onUiEngineAttached(boolean attached) {
            super.onUiEngineAttached(attached);
            if (attached) {
                map.drawPath(mRoad);
            }
        }
        private InputStream getConnection(String url) {
            HttpConnection urlConnection = null;
            InputStream is = null;
            try {
                urlConnection = (HttpConnection) Connector.open(url);
                urlConnection.setRequestMethod("GET");
                is = urlConnection.openInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return is;
        }
    }
    

    See full code on J2MEMapRouteBlackBerryEx on Google Code

    Android

    Android G1 screenshot

    public class MapRouteActivity extends MapActivity {
        LinearLayout linearLayout;
        MapView mapView;
        private Road mRoad;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            mapView = (MapView) findViewById(R.id.mapview);
            mapView.setBuiltInZoomControls(true);
            new Thread() {
                @Override
                public void run() {
                    double fromLat = 49.85, fromLon = 24.016667;
                    double toLat = 50.45, toLon = 30.523333;
                    String url = RoadProvider
                            .getUrl(fromLat, fromLon, toLat, toLon);
                    InputStream is = getConnection(url);
                    mRoad = RoadProvider.getRoute(is);
                    mHandler.sendEmptyMessage(0);
                }
            }.start();
        }
    
        Handler mHandler = new Handler() {
            public void handleMessage(android.os.Message msg) {
                TextView textView = (TextView) findViewById(R.id.description);
                textView.setText(mRoad.mName + " " + mRoad.mDescription);
                MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
                List<Overlay> listOfOverlays = mapView.getOverlays();
                listOfOverlays.clear();
                listOfOverlays.add(mapOverlay);
                mapView.invalidate();
            };
        };
    
        private InputStream getConnection(String url) {
            InputStream is = null;
            try {
                URLConnection conn = new URL(url).openConnection();
                is = conn.getInputStream();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return is;
        }
        @Override
        protected boolean isRouteDisplayed() {
            return false;
        }
    }
    

    See full code on J2MEMapRouteAndroidEx on Google Code

    HTTPS connection Python

    Python 2.x: docs.python.org/2/library/httplib.html:

    Note: HTTPS support is only available if the socket module was compiled with SSL support.

    Python 3.x: docs.python.org/3/library/http.client.html:

    Note HTTPS support is only available if Python was compiled with SSL support (through the ssl module).

    #!/usr/bin/env python
    
    import httplib
    c = httplib.HTTPSConnection("ccc.de")
    c.request("GET", "/")
    response = c.getresponse()
    print response.status, response.reason
    data = response.read()
    print data
    # => 
    # 200 OK
    # <!DOCTYPE html ....
    

    To verify if SSL is enabled, try:

    >>> import socket
    >>> socket.ssl
    <function ssl at 0x4038b0>
    

    Display PDF within web browser

    You can also have this simple GoogleDoc approach.

    <a  style="color: green;" href="http://docs.google.com/gview?url=http://domain//docs/<?php echo $row['docname'] ;?>" target="_blank">View</a>
    

    This would create a new page for you to view the doc without distorting your flow.

    Getting the difference between two repositories

    In repo_a:

    git remote add -f b path/to/repo_b.git
    git remote update
    git diff master remotes/b/master
    git remote rm b
    

    How to identify which columns are not "NA" per row in a matrix?

    Try:

    which( !is.na(p), arr.ind=TRUE)
    

    Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

    > apply(p, 1, function(x) which(!is.na(x)) )
    [[1]]
    [1] 2 3
    
    [[2]]
    [1] 4 7
    
    [[3]]
    integer(0)
    
    [[4]]
    [1] 5
    
    [[5]]
    integer(0)
    

    Or even with smushing together with paste:

    lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
    

    The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

    > which( !is.na(p), arr.ind=TRUE)
         row col
    [1,]   1   2
    [2,]   1   3
    [3,]   2   4
    [4,]   4   5
    [5,]   2   7
    

    Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

    > which( !is.na(p) )
    [1]  6 11 17 24 32
    

    What is the "Upgrade-Insecure-Requests" HTTP header?

    Short answer: it's closely related to the Content-Security-Policy: upgrade-insecure-requests response header, indicating that the browser supports it (and in fact prefers it).

    It took me 30mins of Googling, but I finally found it buried in the W3 spec.

    The confusion comes because the header in the spec was HTTPS: 1, and this is how Chromium implemented it, but after this broke lots of websites that were poorly coded (particularly WordPress and WooCommerce) the Chromium team apologized:

    "I apologize for the breakage; I apparently underestimated the impact based on the feedback during dev and beta."
    — Mike West, in Chrome Issue 501842

    Their fix was to rename it to Upgrade-Insecure-Requests: 1, and the spec has since been updated to match.

    Anyway, here is the explanation from the W3 spec (as it appeared at the time)...

    The HTTPS HTTP request header field sends a signal to the server expressing the client’s preference for an encrypted and authenticated response, and that it can successfully handle the upgrade-insecure-requests directive in order to make that preference as seamless as possible to provide.

    ...

    When a server encounters this preference in an HTTP request’s headers, it SHOULD redirect the user to a potentially secure representation of the resource being requested.

    When a server encounters this preference in an HTTPS request’s headers, it SHOULD include a Strict-Transport-Security header in the response if the request’s host is HSTS-safe or conditionally HSTS-safe [RFC6797].

    $.widget is not a function

    I got this error recently by introducing an old plugin to wordpress. It loaded an older version of jquery, which happened to be placed before the jquery mouse file. There was no jquery widget file loaded with the second version, which caused the error.

    No error for using the extra jquery library -- that's a problem especially if a silent fail might have happened, causing a not so silent fail later on.

    A potential way around it for wordpress might be to be explicit about the dependencies that way the jquery mouse would follow the widget which would follow the correct core leaving the other jquery to be loaded afterwards. Still might cause a production error later if you don't catch that and change the default function for jquery for the second version in all the files associated with it.

    Struct Constructor in C++?

    All the above answers technically answer the asker's question, but just thought I'd point out a case where you might encounter problems.

    If you declare your struct like this:

    typedef struct{
    int x;
    foo(){};
    } foo;
    

    You will have problems trying to declare a constructor. This is of course because you haven't actually declared a struct named "foo", you've created an anonymous struct and assigned it the alias "foo". This also means you will not be able to use "foo" with a scoping operator in a cpp file:

    foo.h:

    typedef struct{
    int x;
    void myFunc(int y);
    } foo;
    

    foo.cpp:

    //<-- This will not work because the struct "foo" was never declared.
    void foo::myFunc(int y)
    {
      //do something...
    }
    

    To fix this, you must either do this:

    struct foo{
    int x;
    foo(){};
    };
    

    or this:

    typedef struct foo{
    int x;
    foo(){};
    } foo;
    

    Where the latter creates a struct called "foo" and gives it the alias "foo" so you don't have to use the struct keyword when referencing it.

    Write a formula in an Excel Cell using VBA

    Treb, Matthieu's problem was caused by using Excel in a non-English language. In many language versions ";" is the correct separator. Even functions are translated (SUM can be SOMMA, SUMME or whatever depending on what language you work in). Excel will generally understand these differences and if a French-created workbook is opened by a Brazilian they will normally not have any problem. But VBA speaks only US English so for those of us working in one (or more) foreign langauges, this can be a headache. You and CharlesB both gave answers that would have been OK for a US user but Mikko understod the REAL problem and gave the correct answer (which was also the correct one for me too - I'm a Brit working in Italy for a German-speaking company).

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

    import java.util.Scanner;
    
    class CalculateGCD 
    {   
      public static int calGCD(int a, int b) 
      { 
       int c=0,d=0;  
       if(a>b){c=b;} 
       else{c=a;}  
       for(int i=c; i>0; i--) 
       { 
        if(((a%i)+(b%i))==0) 
        { 
         d=i; 
         break; 
        } 
       } 
       return d;  
      }  
    
      public static void main(String args[]) 
      { 
       Scanner sc=new Scanner(System.in); 
       System.out.println("Enter the nos whose GCD is to be calculated:"); 
       int a=sc.nextInt(); 
       int b=sc.nextInt(); 
       System.out.println(calGCD(a,b));  
      } 
     } 
    

    Make <body> fill entire screen?

    Try using viewport (vh, vm) units of measure at the body level

    html, body { margin: 0; padding: 0; } body { min-height: 100vh; }

    Use vh units for horizontal margins, paddings, and borders on the body and subtract them from the min-height value.

    I've had bizarre results using vh,vm units on elements within the body, especially when re-sizing.

    Converting a view to Bitmap without displaying it in Android?

    there is a way to do this. you have to create a Bitmap and a Canvas and call view.draw(canvas);

    here is the code:

    public static Bitmap loadBitmapFromView(View v) {
        Bitmap b = Bitmap.createBitmap( v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888);                
        Canvas c = new Canvas(b);
        v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
        v.draw(c);
        return b;
    }
    

    if the view wasn't displayed before the size of it will be zero. Its possible to measure it like this:

    if (v.getMeasuredHeight() <= 0) {
        v.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        Bitmap b = Bitmap.createBitmap(v.getMeasuredWidth(), v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
        v.draw(c);
        return b;
    }
    

    EDIT: according to this post, Passing WRAP_CONTENT as value to makeMeasureSpec() doesn't to do any good (although for some view classes it does work), and the recommended method is:

    // Either this
    int specWidth = MeasureSpec.makeMeasureSpec(parentWidth, MeasureSpec.AT_MOST);
    // Or this
    int specWidth = MeasureSpec.makeMeasureSpec(0 /* any */, MeasureSpec.UNSPECIFIED);
    view.measure(specWidth, specWidth);
    int questionWidth = view.getMeasuredWidth();
    

    Can Mockito stub a method without regard to the argument?

    http://site.mockito.org/mockito/docs/1.10.19/org/mockito/Matchers.html

    anyObject() should fit your needs.

    Also, you can always consider implementing hashCode() and equals() for the Bazoo class. This would make your code example work the way you want.

    IE Enable/Disable Proxy Settings via Registry

    modifying the proxy value under

    [HKEY_USERS\<your SID>\Software\Microsoft\Windows\CurrentVersion\Internet Settings]
    

    doesnt need to restart ie

    How can I run a PHP script in the background after a form is submitted?

    And why not making a HTTP Request on the script and ignoring the response ?

    http://php.net/manual/en/function.httprequest-send.php

    If you make your request on the script you need to call your webserver will run it in background and you can (in your main script) show a message telling the user that the script is running.

    How to check if a text field is empty or not in swift

    Easy way to Check

    if TextField.stringValue.isEmpty {
    
    }
    

    Find in Files: Search all code in Team Foundation Server

    Another solution is to use "ctrl+shift+F". You can change the search location to a local directory rather than a solution or project. This will just take the place of the desktop search and you'll still need to get the latest code, but it will allow you to remain within Visual Studio to do your searching.

    Using find to locate files that match one of multiple patterns

    find MyDir -iname "*.[j][p][g]"
    +
    find MyDir -iname "*.[b][m][p]"
    =
    find MyDir -iname "*.[jb][pm][gp]"
    

    sqlplus how to find details of the currently connected database session

    select * from v$session
    where sid = to_number(substr(dbms_session.unique_session_id,1,4),'XXXX')
    

    git remote add with other SSH port

    Rather than using the ssh:// protocol prefix, you can continue using the conventional URL form for accessing git over SSH, with one small change. As a reminder, the conventional URL is:

    git@host:path/to/repo.git
    

    To specify an alternative port, put brackets around the user@host part, including the port:

    [git@host:port]:path/to/repo.git
    

    But if the port change is merely temporary, you can tell git to use a different SSH command instead of changing your repository’s remote URL:

    export GIT_SSH_COMMAND='ssh -p port'
    git clone git@host:path/to/repo.git # for instance
    

    How to count total lines changed by a specific author in a Git repository?

    The Answer from AaronM using the shell one-liner is good, but actually, there is yet another bug, where spaces will corrupt the user names if there are different amounts of white spaces between the user name and the date. The corrupted user names will give multiple rows for user counts and you have to sum them up yourself.

    This small change fixed the issue for me:

    git ls-files -z | xargs -0n1 git blame -w --show-email | perl -n -e '/^.*?\((.*?)\s+[\d]{4}/; print $1,"\n"' | sort -f | uniq -c | sort -n
    

    Notice the + after \s which will consume all whitespaces from the name to the date.

    Actually adding this answer as much for my own rememberance as for helping anyone else, since this is at least the second time I google the subject :)

    • Edit 2019-01-23 Added --show-email to git blame -w to aggregate on email instead, since some people use different Name formats on different computers, and sometimes two people with the same name are working in the same git.

    What is the use of ObservableCollection in .net?

    it is a collection which is used to notify mostly UI to change in the collection , it supports automatic notification.

    Mainly used in WPF ,

    Where say suppose you have UI with a list box and add button and when you click on he button an object of type suppose person will be added to the obseravablecollection and you bind this collection to the ItemSource of Listbox , so as soon as you added a new item in the collection , Listbox will update itself and add one more item in it.

    How to retrieve the LoaderException property?

    Another Alternative for those who are probing around and/or in interactive mode:

    $Error[0].Exception.LoaderExceptions

    Note: [0] grabs the most recent Error from the stack

    finding and replacing elements in a list

    On long lists and rare occurrences its about 3x faster using list.index() - compared to single step iteration methods presented in the other answers.

    def list_replace(lst, old=1, new=10):
        """replace list elements (inplace)"""
        i = -1
        try:
            while 1:
                i = lst.index(old, i + 1)
                lst[i] = new
        except ValueError:
            pass
    

    Image encryption/decryption using AES256 symmetric block ciphers

    Warning: This answer contains code you should not use as it is insecure (using SHA1PRNG for key derivation and using AES in ECB mode)

    Instead (as of 2016), use PBKDF2WithHmacSHA1 for key derivation and AES in CBC or GCM mode (GCM provides both privacy and integrity)

    You could use functions like these:

    private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(clear);
        return encrypted;
    }
    
    private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
    }
    

    And invoke them like this:

    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    bm.compress(Bitmap.CompressFormat.PNG, 100, baos); // bm is the bitmap object   
    byte[] b = baos.toByteArray();  
    
    byte[] keyStart = "this is a key".getBytes();
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(keyStart);
    kgen.init(128, sr); // 192 and 256 bits may not be available
    SecretKey skey = kgen.generateKey();
    byte[] key = skey.getEncoded();    
    
    // encrypt
    byte[] encryptedData = encrypt(key,b);
    // decrypt
    byte[] decryptedData = decrypt(key,encryptedData);
    

    This should work, I use similar code in a project right now.

    What is the difference between a Shared Project and a Class Library in Visual Studio 2015?

    I found some more information from this blog.

    • In a Class Library, when code is compiled, assemblies (dlls) are generated for each library. But with Shared Project it will not contain any header information so when you have a Shared Project reference it will be compiled as part of the parent application. There will not be separate dlls created.
    • In class library you are only allowed to write C# code while shared project can have any thing like C# code files, XAML files or JavaScript files etc.

    How to remove first 10 characters from a string?

    str = "hello world!";
    str.Substring(10, str.Length-10)
    

    you will need to perform the length checks else this would throw an error

    How to get the user input in Java?

    Here is a more developed version of the accepted answer that addresses two common needs:

    • Collecting user input repeatedly until an exit value has been entered
    • Dealing with invalid input values (non-integers in this example)

    Code

    package inputTest;
    
    import java.util.Scanner;
    import java.util.InputMismatchException;
    
    public class InputTest {
        public static void main(String args[]) {
            Scanner reader = new Scanner(System.in);
            System.out.println("Please enter integers. Type 0 to exit.");
    
            boolean done = false;
            while (!done) {
                System.out.print("Enter an integer: ");
                try {
                    int n = reader.nextInt();
                    if (n == 0) {
                        done = true;
                    }
                    else {
                        // do something with the input
                        System.out.println("\tThe number entered was: " + n);
                    }
                }
                catch (InputMismatchException e) {
                    System.out.println("\tInvalid input type (must be an integer)");
                    reader.nextLine();  // Clear invalid input from scanner buffer.
                }
            }
            System.out.println("Exiting...");
            reader.close();
        }
    }
    

    Example

    Please enter integers. Type 0 to exit.
    Enter an integer: 12
        The number entered was: 12
    Enter an integer: -56
        The number entered was: -56
    Enter an integer: 4.2
        Invalid input type (must be an integer)
    Enter an integer: but i hate integers
        Invalid input type (must be an integer)
    Enter an integer: 3
        The number entered was: 3
    Enter an integer: 0
    Exiting...
    

    Note that without nextLine(), the bad input will trigger the same exception repeatedly in an infinite loop. You might want to use next() instead depending on the circumstance, but know that input like this has spaces will generate multiple exceptions.

    Does Python support short-circuiting?

    Yes. Try the following in your python interpreter:

    and

    >>>False and 3/0
    False
    >>>True and 3/0
    ZeroDivisionError: integer division or modulo by zero
    

    or

    >>>True or 3/0
    True
    >>>False or 3/0
    ZeroDivisionError: integer division or modulo by zero
    

    Multiple files upload in Codeigniter

    _x000D_
    _x000D_
    <?php
    
    if(isset($_FILES[$input_name]) && is_array($_FILES[$input_name]['name'])){
                $image_path = array();          
                $count = count($_FILES[$input_name]['name']);   
                for($key =0; $key <$count; $key++){     
                    $_FILES['file']['name']     = $_FILES[$input_name]['name'][$key]; 
                    $_FILES['file']['type']     = $_FILES[$input_name]['type'][$key]; 
                    $_FILES['file']['tmp_name'] = $_FILES[$input_name]['tmp_name'][$key]; 
                    $_FILES['file']['error']     = $_FILES[$input_name]['error'][$key]; 
                    $_FILES['file']['size']     = $_FILES[$input_name]['size'][$key]; 
                        
                    $config['file_name'] = $_FILES[$input_name]['name'][$key];                      
                    $this->upload->initialize($config); 
                    
                    if($this->upload->do_upload('file')) {
                        $data = $this->upload->data();
                        $image_path[$key] = $path ."$data[file_name]";                  
                    }else{
                        $error =  $this->upload->display_errors();
                    $this->session->set_flashdata('msg_error',"image upload! ".$error);
                    }   
                }
                return json_encode($image_path);
            }
        
        
       ?>
    _x000D_
    _x000D_
    _x000D_

    MySQL: selecting rows where a column is null

    As all are given answers I want to add little more. I had also faced the same issue.

    Why did your query fail? You have,

    SELECT pid FROM planets WHERE userid = NULL;
    

    This will not give you the expected result, because from mysql doc

    In SQL, the NULL value is never true in comparison to any other value, even NULL. An expression that contains NULL always produces a NULL value unless otherwise indicated in the documentation for the operators and functions involved in the expression.

    Emphasis mine.

    To search for column values that are NULL, you cannot use an expr = NULL test. The following statement returns no rows, because expr = NULL is never true for any expression

    Solution

    SELECT pid FROM planets WHERE userid IS NULL; 
    

    To test for NULL, use the IS NULL and IS NOT NULL operators.

    How do I use regex in a SQLite query?

    SQLite3 supports the REGEXP operator:

    WHERE x REGEXP <regex>
    

    http://www.sqlite.org/lang_expr.html#regexp

    How to change the default GCC compiler in Ubuntu?

    This is the great description and step-by-step instruction how to create and manage master and slave (gcc and g++) alternatives.

    Shortly it's:

    sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 60 --slave /usr/bin/g++ g++ /usr/bin/g++-4.6
    sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.7 40 --slave /usr/bin/g++ g++ /usr/bin/g++-4.7
    sudo update-alternatives --config gcc
    

    Onclick on bootstrap button

    <a class="btn btn-large btn-success" id="fire" href="http://twitter.github.io/bootstrap/examples/marketing-narrow.html#">Send Email</a>
    
    $('#fire').on('click', function (e) {
    
         //your awesome code here
    
    })
    

    Change background colour for Visual Studio

    This is the only one right answer on this whole page as people answered about "Visual Studio", not "Visual Studio Code":

    To change color theme in "Visual Studio Code", use:

    File -> Preferences -> Color Theme -> select any color theme you like

    You can also download other custom themes as extensions. To do that, open extensions tab on sidebar and type "theme" into the search field to filter extensions only to themes related ones. Click any you like, click "download" and then "install". After installation and restarting VSC, you can find newly installed themes next to default themes in the same place:

    File -> Preferences -> Color Theme -> select newly downloaded color theme

    PS - Microsoft made bad naming decision by calling this new editor Visual Studio Code, it's terrible how many wrong links we have in google and stackoverflow. They should rename it to VSCode or something.

    Where is HttpContent.ReadAsAsync?

    Just right click in your project go Manage NuGet Packages search for Microsoft.AspNet.WebApi.Client install it and you will have access to the extension method.

    What causes a java.lang.StackOverflowError

    I created a program with hibernate, in which I created two POJO classes, both with an object of each other as data members. When in the main method I tried to save them in the database I also got this error.

    This happens because both of the classes are referring each other, hence creating a loop which causes this error.

    So, check whether any such kind of relationships exist in your program.

    SQL Server: SELECT only the rows with MAX(DATE)

    rownumber() over(...) is working but I didn't like this solution for 2 reasons. - This function is not available when you using older version of SQL like SQL2000 - Dependency on function and is not really readable.

    Another solution is:

    SELECT tmpall.[OrderNO] ,
           tmpall.[PartCode] ,
           tmpall.[Quantity] ,
    FROM   (SELECT [OrderNO],
                   [PartCode],
                   [Quantity],
                   [DateEntered]
            FROM   you_table) AS tmpall
           INNER JOIN (SELECT [OrderNO],
                              Max([DateEntered]) AS _max_date
                       FROM   your_table
                       GROUP  BY OrderNO ) AS tmplast
                   ON tmpall.[OrderNO] = tmplast.[OrderNO]
                      AND tmpall.[DateEntered] = tmplast._max_date
    

    How to add a named sheet at the end of all Excel sheets?

    This is a quick and simple add of a named tab to the current worksheet:

    Sheets.Add.Name = "Tempo"
    

    How does EL empty operator work in JSF?

    From EL 2.2 specification (get the one below "Click here to download the spec for evaluation"):

    1.10 Empty Operator - empty A

    The empty operator is a prefix operator that can be used to determine if a value is null or empty.

    To evaluate empty A

    • If A is null, return true
    • Otherwise, if A is the empty string, then return true
    • Otherwise, if A is an empty array, then return true
    • Otherwise, if A is an empty Map, return true
    • Otherwise, if A is an empty Collection, return true
    • Otherwise return false

    So, considering the interfaces, it works on Collection and Map only. In your case, I think Collection is the best option. Or, if it's a Javabean-like object, then Map. Either way, under the covers, the isEmpty() method is used for the actual check. On interface methods which you can't or don't want to implement, you could throw UnsupportedOperationException.

    NSString property: copy or retain?

    Through this example copy and retain can be explained like:

    NSMutableString *someName = [NSMutableString stringWithString:@"Chris"];
    
    Person *p = [[[Person alloc] init] autorelease];
    p.name = someName;
    
    [someName setString:@"Debajit"];
    

    if the property is of type copy then ,

    a new copy will be created for the [Person name] string that will hold the contents of someName string. Now any operation on someName string will have no effect on [Person name].

    [Person name] and someName strings will have different memory addresses.

    But in case of retain,

    both the [Person name] will hold the same memory address as of somename string, just the retain count of somename string will be incremented by 1.

    So any change in somename string will be reflected in [Person name] string.

    How do you find out the type of an object (in Swift)?

    If you simply need to check whether the variable is of type X, or that it conforms to some protocol, then you can use is, or as? as in the following:

    var unknownTypeVariable = …
    
    if unknownTypeVariable is <ClassName> {
        //the variable is of type <ClassName>
    } else {
        //variable is not of type <ClassName>
    }
    

    This is equivalent of isKindOfClass in Obj-C.

    And this is equivalent of conformsToProtocol, or isMemberOfClass

    var unknownTypeVariable = …
    
    if let myClass = unknownTypeVariable as? <ClassName or ProtocolName> {
        //unknownTypeVarible is of type <ClassName or ProtocolName>
    } else {
        //unknownTypeVariable is not of type <ClassName or ProtocolName>
    }
    

    git clone through ssh

    Disclaimer: This is just a copy of a comment by bobbaluba made more visible for future visitors. It helped me more than any other answer.


    You have to drop the ssh:// prefix when using git clone as an example

    git clone [email protected]:owner/repo.git
    

    Sum values from an array of key-value pairs in JavaScript

    where 0 is initial value

    Array.reduce((currentValue, value) => currentValue +value,0)
    

    or

    Array.reduce((currentValue, value) =>{ return currentValue +value},0)
    

    or

    [1,3,4].reduce(function(currentValue, value) { return currentValue + value},0)
    

    Proxy Error 502 : The proxy server received an invalid response from an upstream server

    The HTTP 502 "Bad Gateway" response is generated when Apache web server does not receive a valid HTTP response from the upstream server, which in this case is your Tomcat web application.

    Some reasons why this might happen:

    • Tomcat may have crashed
    • The web application did not respond in time and the request from Apache timed out
    • The Tomcat threads are timing out
    • A network device is blocking the request, perhaps as some sort of connection timeout or DoS attack prevention system

    If the problem is related to timeout settings, you may be able to resolve it by investigating the following:

    • ProxyTimeout directive of Apache's mod_proxy
    • Connector config of Apache Tomcat
    • Your network device's manual

    How to watch for a route change in AngularJS?

    This is for the total beginner... like me:

    HTML:

      <ul>
        <li>
          <a href="#"> Home </a>
        </li>
        <li>
          <a href="#Info"> Info </a>
        </li>
      </ul>
    
      <div ng-app="myApp" ng-controller="MainCtrl">
        <div ng-view>
    
        </div>
      </div>
    

    Angular:

    //Create App
    var app = angular.module("myApp", ["ngRoute"]);
    
    //Configure routes
    app.config(function ($routeProvider) {
        $routeProvider
          .otherwise({ template: "<p>Coming soon</p>" })
          .when("/", {
            template: "<p>Home information</p>"
          })
          .when("/Info", {
            template: "<p>Basic information</p>"
            //templateUrl: "/content/views/Info.html"
          });
    });
    
    //Controller
    app.controller('MainCtrl', function ($scope, $rootScope, $location) {
      $scope.location = $location.path();
      $rootScope.$on('$routeChangeStart', function () {
        console.log("routeChangeStart");
       //Place code here:....
       });
    });
    

    Hope this helps a total beginner like me. Here is the full working sample:

    _x000D_
    _x000D_
    <html>_x000D_
    <head>_x000D_
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>_x000D_
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-route.min.js"></script>_x000D_
    </head>_x000D_
    <body>_x000D_
      <ul>_x000D_
        <li>_x000D_
          <a href="#"> Home </a>_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#Info"> Info </a>_x000D_
        </li>_x000D_
      </ul>_x000D_
    _x000D_
      <div ng-app="myApp" ng-controller="MainCtrl">_x000D_
        <div ng-view>_x000D_
    _x000D_
        </div>_x000D_
      </div>_x000D_
      <script>_x000D_
    //Create App_x000D_
    var app = angular.module("myApp", ["ngRoute"]);_x000D_
    _x000D_
    //Configure routes_x000D_
    app.config(function ($routeProvider) {_x000D_
        $routeProvider_x000D_
          .otherwise({ template: "<p>Coming soon</p>" })_x000D_
          .when("/", {_x000D_
            template: "<p>Home information</p>"_x000D_
          })_x000D_
          .when("/Info", {_x000D_
            template: "<p>Basic information</p>"_x000D_
            //templateUrl: "/content/views/Info.html"_x000D_
          });_x000D_
    });_x000D_
    _x000D_
    //Controller_x000D_
    app.controller('MainCtrl', function ($scope, $rootScope, $location) {_x000D_
      $scope.location = $location.path();_x000D_
      $rootScope.$on('$routeChangeStart', function () {_x000D_
        console.log("routeChangeStart");_x000D_
       //Place code here:...._x000D_
       });_x000D_
    });_x000D_
      </script>_x000D_
    </body>_x000D_
    </html>
    _x000D_
    _x000D_
    _x000D_

    Easy way to print Perl array? (with a little formatting)

    # better than Dumper --you're ready for the WWW....
    
    use JSON::XS;
    print encode_json \@some_array
    

    Java naming convention for static final variables

    Well that's a very interesting question. I would divide the two constants in your question according to their type. int MAX_COUNT is a constant of primitive type while Logger log is a non-primitive type.

    When we are making use of a constant of a primitive types, we are mutating the constant only once in our code public static final in MAX_COUNT = 10 and we are just accessing the value of the constant elsewhere for(int i = 0; i<MAX_COUNT; i++). This is the reason we are comfortable with using this convention.

    While in the case of non-primitive types, although, we initialize the constant in only one place private static final Logger log = Logger.getLogger(MyClass.class);, we are expected to mutate or call a method on this constant elsewhere log.debug("Problem"). We guys don't like to put a dot operator after the capital characters. After all we have to put a function name after the dot operator which is surely going to be a camel-case name. That's why LOG.debug("Problem") would look awkward.

    Same is the case with String types. We are usually not mutating or calling a method on a String constant in our code and that's why we use the capital naming convention for a String type object.

    XPath to select element based on childs child value

    Almost there. In your predicate, you want a relative path, so change

    ./book[/author/name = 'John'] 
    

    to either

    ./book[author/name = 'John'] 
    

    or

    ./book[./author/name = 'John'] 
    

    and you will match your element. Your current predicate goes back to the root of the document to look for an author.

    How to save traceback / sys.exc_info() values in a variable?

    Use traceback.extract_stack() if you want convenient access to module and function names and line numbers.

    Use ''.join(traceback.format_stack()) if you just want a string that looks like the traceback.print_stack() output.

    Notice that even with ''.join() you will get a multi-line string, since the elements of format_stack() contain \n. See output below.

    Remember to import traceback.

    Here's the output from traceback.extract_stack(). Formatting added for readability.

    >>> traceback.extract_stack()
    [
       ('<string>', 1, '<module>', None),
       ('C:\\Python\\lib\\idlelib\\run.py', 126, 'main', 'ret = method(*args, **kwargs)'),
       ('C:\\Python\\lib\\idlelib\\run.py', 353, 'runcode', 'exec(code, self.locals)'),
       ('<pyshell#1>', 1, '<module>', None)
    ]
    

    Here's the output from ''.join(traceback.format_stack()). Formatting added for readability.

    >>> ''.join(traceback.format_stack())
    '  File "<string>", line 1, in <module>\n
       File "C:\\Python\\lib\\idlelib\\run.py", line 126, in main\n
           ret = method(*args, **kwargs)\n
       File "C:\\Python\\lib\\idlelib\\run.py", line 353, in runcode\n
           exec(code, self.locals)\n  File "<pyshell#2>", line 1, in <module>\n'
    

    cc1plus: error: unrecognized command line option "-std=c++11" with g++

    Seeing from your G++ version, you need to update it badly. C++11 has only been available since G++ 4.3. The most recent version is 4.7.

    In versions pre-G++ 4.7, you'll have to use -std=c++0x, for more recent versions you can use -std=c++11.

    How do I change the default application icon in Java?

    Or place the image in a location relative to a class and you don't need all that package/path info in the string itself.

    com.xyz.SomeClassInThisPackage.class.getResource( "resources/camera.png" );
    

    That way if you move the class to a different package, you dont have to find all the strings, you just move the class and its resources directory.

    fast way to copy formatting in excel

    For me, you can't. But if that suits your needs, you could have speed and formatting by copying the whole range at once, instead of looping:

    range("B2:B5002").Copy Destination:=Sheets("Output").Cells(startrow, 2)
    

    And, by the way, you can build a custom range string, like Range("B2:B4, B6, B11:B18")


    edit: if your source is "sparse", can't you just format the destination at once when the copy is finished ?

    jQuery: selecting each td in a tr

    Fully example to demonstrate how jQuery query all data in HTML table.

    Assume there is a table like the following in your HTML code.

    <table id="someTable">
      <thead>
        <tr>
          <td>title 0</td>
          <td>title 1</td>
          <td>title 2</td>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>row 0 td 0</td>
          <td>row 0 td 1</td>
          <td>row 0 td 2</td>
        </tr>
        <tr>
          <td>row 1 td 0</td>
          <td>row 1 td 1</td>
          <td>row 1 td 2</td>
        </tr>
        <tr>
          <td>row 2 td 0</td>
          <td>row 2 td 1</td>
          <td>row 2 td 2</td>
        </tr>
        <tr> ... </tr>
        <tr> ... </tr>
        ...
        <tr> ... </tr>
        <tr>
          <td>row n td 0</td>
          <td>row n td 1</td>
          <td>row n td 2</td>
        </tr>
      </tbody>
    </table>
    

    Then, The Answer, the code to print all row all column, should like this

    $('#someTable tbody tr').each( (tr_idx,tr) => {
        $(tr).children('td').each( (td_idx, td) => {
            console.log( '[' +tr_idx+ ',' +td_idx+ '] => ' + $(td).text());
        });                 
    });
    

    After running the code, the result will show

    [0,0] => row 0 td 0
    [0,1] => row 0 td 1
    [0,2] => row 0 td 2
    [1,0] => row 1 td 0
    [1,1] => row 1 td 1
    [1,2] => row 1 td 2
    [2,0] => row 2 td 0
    [2,1] => row 2 td 1
    [2,2] => row 2 td 2
    ...
    [n,0] => row n td 0
    [n,1] => row n td 1
    [n,2] => row n td 2
    

    Summary.
    In the code,
    tr_idx is the row index start from 0.
    td_idx is the column index start from 0.

    From this double-loop code,
    you can get all loop-index and data in each td cell after comparing the Answer's source code and the output result.

    How to check is Apache2 is stopped in Ubuntu?

    You can also type "top" and look at the list of running processes.

    Get the contents of a table row with a button click

    The selector ".nr:first" is specifically looking for the first, and only the first, element having class "nr" within the selected table element. If you instead call .find(".nr") you will get all of the elements within the table having class "nr". Once you have all of those elements, you could use the .each method to iterate over them. For example:

    $(".use-address").click(function() {
        $("#choose-address-table").find(".nr").each(function(i, nrElt) {
            var id = nrElt.text();
            $("#resultas").append("<p>" + id + "</p>"); // Testing: append the contents of the td to a div
        });
    });
    

    However, that would get you all of the td.nr elements in the table, not just the one in the row that was clicked. To further limit your selection to the row containing the clicked button, use the .closest method, like so:

    $(".use-address").click(function() {
        $(this).closest("tr").find(".nr").each(function(i, nrElt) {
            var id = nrElt.text();
            $("#resultas").append("<p>" + id + "</p>"); // Testing: append the contents of the td to a div
        });
    });
    

    Remove 'standalone="yes"' from generated XML

    I'm using Java 1.8 and JAXB 2.3.1

    First, be sure to be using java 1.8 in pom.xml

    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    

    Then in source code I used: (the key was the internal part)

    // remove standalone=yes
    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
    marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    

    How can I remove a key and its value from an associative array?

    You may need two or more loops depending on your array:

    $arr[$key1][$key2][$key3]=$value1; // ....etc
    
    foreach ($arr as $key1 => $values) {
      foreach ($key1 as $key2 => $value) {
      unset($arr[$key1][$key2]);
      }
    }
    

    Google maps responsive resize

    After few years, I moved to leaflet map and I have fixed this issue completely, the following could be applied to google maps too:

        var headerHeight = $("#navMap").outerHeight();
        var footerHeight = $("footer").outerHeight();
        var windowHeight = window.innerHeight;
        var mapContainerHeight = headerHeight + footerHeight;
        var totalMapHeight = windowHeight - mapContainerHeight;
        $("#map").css("margin-top", headerHeight);
        $("#map").height(totalMapHeight);
    
        $(window).resize(function(){
            var headerHeight = $("#navMap").outerHeight();
            var footerHeight = $("footer").outerHeight();
            var windowHeight = window.innerHeight;
            var mapContainerHeight = headerHeight + footerHeight;
            var totalMapHeight = windowHeight - mapContainerHeight;
            $("#map").css("margin-top", headerHeight);
            $("#map").height(totalMapHeight);
            map.fitBounds(group1.getBounds());
        });
    

    Automapper missing type map configuration or unsupported mapping - Error

    Notice the Categoies_7314E98C41152985A4218174DDDF658046BC82AB0ED9E1F0440514D79052F84D class in the exception? That's an Entity Framework proxy. I would recommend you disposing of your EF context to ensure that all your objects are eagerly loaded from the database and no such proxies exist:

    [HttpPost]
    public ActionResult _EditCategory(CategoriesViewModel viewModel)
    {
        Categoies category = null;
        using (var ctx = new MyentityFrameworkContext())
        {
            category = ctx.Categoies.Find(viewModel.Id);
        }
        AutoMapper.Mapper.Map<CategoriesViewModel, Categoies>(viewModel, category);
        //category = AutoMapper.Mapper.Map<CategoriesViewModel, Categoies>(viewModel, category);
        entity.SaveChanges();
    }
    

    If the entity retrieval is performed inside a data access layer (which of course is the correct way) make sure you dispose your EF context before returning instances from your DAL.

    How can I rename a single column in a table at select?

    There is no need to use AS, just use:

    SELECT table1.price Table1 Price, table2.price Table2 Price, .....
    

    Java Does Not Equal (!=) Not Working?

    if (!"success".equals(statusCheck))
    

    How do I remove  from the beginning of a file?

    Same problem, different solution.

    One line in the PHP file was printing out XML headers (which use the same begin/end tags as PHP). Looks like the code within these tags set the encoding, and was executed within PHP which resulted in the strange characters. Either way here's the solution:

    # Original
    $xml_string = "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;";
    
    # fixed
    $xml_string = "<" . "?xml version=\"1.0\" encoding=\"UTF-8\"?" . ">";
    

    Javascript Append Child AFTER Element

    You can use:

    if (parentGuest.nextSibling) {
      parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);
    }
    else {
      parentGuest.parentNode.appendChild(childGuest);
    }
    

    But as Pavel pointed out, the referenceElement can be null/undefined, and if so, insertBefore behaves just like appendChild. So the following is equivalent to the above:

    parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);
    

    Making a flex item float right

    You can't use float inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle.

    So if you want to position child element to right of parent element you can use margin-left: auto but now child element will also push other div to the right as you can see here Fiddle.

    What you can do now is change order of elements and set order: 2 on child element so it doesn't affect second div

    _x000D_
    _x000D_
    .parent {_x000D_
      display: flex;_x000D_
    }_x000D_
    .child {_x000D_
      margin-left: auto;_x000D_
      order: 2;_x000D_
    }
    _x000D_
    <div class="parent">_x000D_
      <div class="child">Ignore parent?</div>_x000D_
      <div>another child</div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    How to select the nth row in a SQL database table?

    SELECT * FROM emp a
    WHERE  n = (SELECT COUNT( _rowid)
                  FROM emp b
                 WHERE a. _rowid >= b. _rowid);
    

    How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

    in SQL*Plus you could also use a REFCURSOR variable:

    SQL> VARIABLE x REFCURSOR
    SQL> DECLARE
      2   V_Sqlstatement Varchar2(2000);
      3  BEGIN
      4   V_Sqlstatement := 'SELECT * FROM DUAL';
      5   OPEN :x for v_Sqlstatement;
      6  End;
      7  /
    
    ProcÚdure PL/SQL terminÚe avec succÞs.
    
    SQL> print x;
    
    D
    -
    X
    

    How to access ssis package variables inside script component

    I had the same problem as the OP except I remembered to declare the ReadOnlyVariables.

    After some playing around, I discovered it was the name of my variable that was the issue. "File_Path" in SSIS somehow got converted to "FilePath". C# does not play nicely with underscores in variable names.

    So to access the variable, I type

    string fp = Variables.FilePath;
    

    In the PreExecute() method of the Script Component.

    Sending HTTP Post request with SOAP action using org.apache.http

    This is a full working example :

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost; 
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;
    
    public void callWebService(String soapAction, String soapEnvBody)  throws IOException {
        // Create a StringEntity for the SOAP XML.
        String body ="<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://example.com/v1.0/Records\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><SOAP-ENV:Body>"+soapEnvBody+"</SOAP-ENV:Body></SOAP-ENV:Envelope>";
        StringEntity stringEntity = new StringEntity(body, "UTF-8");
        stringEntity.setChunked(true);
    
        // Request parameters and other properties.
        HttpPost httpPost = new HttpPost("http://example.com?soapservice");
        httpPost.setEntity(stringEntity);
        httpPost.addHeader("Accept", "text/xml");
        httpPost.addHeader("SOAPAction", soapAction);
    
        // Execute and get the response.
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
    
        String strResponse = null;
        if (entity != null) {
            strResponse = EntityUtils.toString(entity);
        }
    }
    

    correct way to use super (argument passing)

    If you're going to have a lot of inheritence (that's the case here) I suggest you to pass all parameters using **kwargs, and then pop them right after you use them (unless you need them in upper classes).

    class First(object):
        def __init__(self, *args, **kwargs):
            self.first_arg = kwargs.pop('first_arg')
            super(First, self).__init__(*args, **kwargs)
    
    class Second(First):
        def __init__(self, *args, **kwargs):
            self.second_arg = kwargs.pop('second_arg')
            super(Second, self).__init__(*args, **kwargs)
    
    class Third(Second):
        def __init__(self, *args, **kwargs):
            self.third_arg = kwargs.pop('third_arg')
            super(Third, self).__init__(*args, **kwargs)
    

    This is the simplest way to solve those kind of problems.

    third = Third(first_arg=1, second_arg=2, third_arg=3)
    

    MySQL: can't access root account

    I got the same problem when accessing mysql with root. The problem I found is that some database files does not have permission by the mysql user, which is the user that started the mysql server daemon.

    We can check this with ls -l /var/lib/mysql command, if the mysql user does not have permission of reading or writing on some files or directories, that might cause problem. We can change the owner or mode of those files or directories with chown/chmod commands.

    After these changes, restart the mysqld daemon and login with root with command:

    mysql -u root
    

    Then change passwords or create other users for logging into mysql.

    HTH

    Why does pycharm propose to change method to static

    The reason why Pycharm make it as a warning because Python will pass self as the first argument when calling a none static method (not add @staticmethod). Pycharm knows it.

    Example:

    class T:
        def test():
            print "i am a normal method!"
    
    t = T()
    t.test()
    output:
    Traceback (most recent call last):
      File "F:/Workspace/test_script/test.py", line 28, in <module>
        T().test()
    TypeError: test() takes no arguments (1 given)
    

    I'm from Java, in Java "self" is called "this", you don't need write self(or this) as argument in class method. You can just call self as you need inside the method. But Python "has to" pass self as a method argument.

    By understanding this you don't need any Workaround as @BobStein answer.

    Java Calendar, getting current month value, clarification needed

    as others said Calendar.MONTH returns int and is zero indexed.

    to get the current month as a String use SimpleDateFormat.format() method

    Calendar cal = Calendar.getInstance();
    System.out.println(new SimpleDateFormat("MMM").format(cal.getTime()));
    
    returns NOV
    

    Does MS SQL Server's "between" include the range boundaries?

    The BETWEEN operator is inclusive.

    From Books Online:

    BETWEEN returns TRUE if the value of test_expression is greater than or equal to the value of begin_expression and less than or equal to the value of end_expression.

    DateTime Caveat

    NB: With DateTimes you have to be careful; if only a date is given the value is taken as of midnight on that day; to avoid missing times within your end date, or repeating the capture of the following day's data at midnight in multiple ranges, your end date should be 3 milliseconds before midnight on of day following your to date. 3 milliseconds because any less than this and the value will be rounded up to midnight the next day.

    e.g. to get all values within June 2016 you'd need to run:

    where myDateTime between '20160601' and DATEADD(millisecond, -3, '20160701')

    i.e.

    where myDateTime between '20160601 00:00:00.000' and '20160630 23:59:59.997'

    datetime2 and datetimeoffset

    Subtracting 3 ms from a date will leave you vulnerable to missing rows from the 3 ms window. The correct solution is also the simplest one:

    where myDateTime >= '20160601' AND myDateTime < '20160701'
    

    Upload files with FTP using PowerShell

    Easiest way

    The most trivial way to upload a binary file to an FTP server using PowerShell is using WebClient.UploadFile:

    $client = New-Object System.Net.WebClient
    $client.Credentials = New-Object System.Net.NetworkCredential("username", "password")
    $client.UploadFile("ftp://ftp.example.com/remote/path/file.zip", "C:\local\path\file.zip")
    

    Advanced options

    If you need a greater control, that WebClient does not offer (like TLS/SSL encryption, etc), use FtpWebRequest. Easy way is to just copy a FileStream to FTP stream using Stream.CopyTo:

    $request = [Net.WebRequest]::Create("ftp://ftp.example.com/remote/path/file.zip")
    $request.Credentials = New-Object System.Net.NetworkCredential("username", "password")
    $request.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile 
    
    $fileStream = [System.IO.File]::OpenRead("C:\local\path\file.zip")
    $ftpStream = $request.GetRequestStream()
    
    $fileStream.CopyTo($ftpStream)
    
    $ftpStream.Dispose()
    $fileStream.Dispose()
    

    Progress monitoring

    If you need to monitor an upload progress, you have to copy the contents by chunks yourself:

    $request = [Net.WebRequest]::Create("ftp://ftp.example.com/remote/path/file.zip")
    $request.Credentials = New-Object System.Net.NetworkCredential("username", "password")
    $request.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile 
    
    $fileStream = [System.IO.File]::OpenRead("C:\local\path\file.zip")
    $ftpStream = $request.GetRequestStream()
    
    $buffer = New-Object Byte[] 10240
    while (($read = $fileStream.Read($buffer, 0, $buffer.Length)) -gt 0)
    {
        $ftpStream.Write($buffer, 0, $read)
        $pct = ($fileStream.Position / $fileStream.Length)
        Write-Progress `
            -Activity "Uploading" -Status ("{0:P0} complete:" -f $pct) `
            -PercentComplete ($pct * 100)
    }
    
    $ftpStream.Dispose()
    $fileStream.Dispose()
    

    Uploading folder

    If you want to upload all files from a folder, see
    PowerShell Script to upload an entire folder to FTP

    How can I change or remove HTML5 form validation default error messages?

    you can change them via constraint validation api: http://www.w3.org/TR/html5/constraints.html#dom-cva-setcustomvalidity

    if you want an easy solution, you can rock out civem.js, Custom Input Validation Error Messages JavaScript lib download here: https://github.com/javanto/civem.js live demo here: http://jsfiddle.net/hleinone/njSbH/

    Detecting negative numbers

    I assume that the main idea is to find if number is negative and display it in correct format.

    For those who use PHP5.3 might be interested in using Number Formatter Class - http://php.net/manual/en/class.numberformatter.php. This function, as well as range of other useful things, can format your number.

    $profitLoss = 25000 - 55000;
    
    $a= new \NumberFormatter("en-UK", \NumberFormatter::CURRENCY); 
    $a->formatCurrency($profitLoss, 'EUR');
    // would display (€30,000.00)
    

    Here also a reference to why brackets are used for negative numbers: http://www.open.edu/openlearn/money-management/introduction-bookkeeping-and-accounting/content-section-1.7

    Frequency table for a single variable

    Maybe .value_counts()?

    >>> import pandas
    >>> my_series = pandas.Series([1,2,2,3,3,3, "fred", 1.8, 1.8])
    >>> my_series
    0       1
    1       2
    2       2
    3       3
    4       3
    5       3
    6    fred
    7     1.8
    8     1.8
    >>> counts = my_series.value_counts()
    >>> counts
    3       3
    2       2
    1.8     2
    fred    1
    1       1
    >>> len(counts)
    5
    >>> sum(counts)
    9
    >>> counts["fred"]
    1
    >>> dict(counts)
    {1.8: 2, 2: 2, 3: 3, 1: 1, 'fred': 1}
    

    How to attach a process in gdb

    The first argument should be the path to the executable program. So

    gdb progname 12271
    

    Why does corrcoef return a matrix?

    Consider using matplotlib.cbook pieces

    for example:

    import matplotlib.cbook as cbook
    segments = cbook.pieces(np.arange(20), 3)
    for s in segments:
         print s
    

    Event handlers for Twitter Bootstrap dropdowns?

    Here you go, options have values, label and css classes that gets reflected on parent element upon selection.

    _x000D_
    _x000D_
    $(document).on('click','.update_app_status', function (e) {
                let $div = $(this).parent().parent(); 
                let $btn = $div.find('.vBtnMain');
                let $btn2 = $div.find('.vBtnArrow');
                let cssClass = $(this).data('status_class');
                let status_value = $(this).data('status_value');
                let status_label = $(this).data('status_label');
                $btn.html(status_label);
                $btn.removeClass();
                $btn2.removeClass();
                $btn.addClass('btn btn-sm vBtnMain '+cssClass);
                $btn2.addClass('btn btn-sm vBtnArrow dropdown-toggle dropdown-toggle-split '+cssClass);
                $div.removeClass('show');
                $div.find('.dropdown-menu').removeClass('show');
                e.preventDefault();
                return false;
        });
    _x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
    
    
      
    
       <div class="btn-group">
       <button type="button" class="btn btn-sm vBtnMain btn-warning">Awaiting Review</button>
       <button type="button" class="btn btn-sm vBtnArrow btn-warning dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
           <span class="sr-only">Toggle Dropdown</span>
       </button>
       <div class="dropdown-menu dropdown-menu-right">
         <a class="dropdown-item update_app_status" data-status_class="btn-warning" data-status_value="1" data-status_label="Awaiting Review" href="#">Awaiting Review</a>
         <a class="dropdown-item update_app_status" data-status_class="btn-info" data-status_value="2" data-status_label="Reviewed" href="#">Reviewed</a>
         <a class="dropdown-item update_app_status" data-status_class="btn-dark" data-status_value="3" data-status_label="Contacting" href="#">Contacting</a>
         <a class="dropdown-item update_app_status" data-status_class="btn-success" data-status_value="4" data-status_label="Hired" href="#">Hired</a>
         <a class="dropdown-item update_app_status" data-status_class="btn-danger" data-status_value="5" data-status_label="Rejected" href="#">Rejected</a>
       </div>
       </div>
    _x000D_
    _x000D_
    _x000D_

    How to send a POST request using volley with string body?

    I created a function for a Volley Request. You just need to pass the arguments :

    public void callvolly(final String username, final String password){
        RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
        String url = "http://your_url.com/abc.php"; // <----enter your post url here
        StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                //This code is executed if the server responds, whether or not the response contains data.
                //The String 'response' contains the server's response.
            }
        }, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
            @Override
            public void onErrorResponse(VolleyError error) {
                //This code is executed if there is an error.
            }
        }) {
            protected Map<String, String> getParams() {
                Map<String, String> MyData = new HashMap<String, String>();
                MyData.put("username", username);             
                MyData.put("password", password);                
                return MyData;
            }
        };
    
    
        MyRequestQueue.add(MyStringRequest);
    }
    

    How can I pad an int with leading zeros when using cout << operator?

    Another way to achieve this is using old printf() function of C language

    You can use this like

    int dd = 1, mm = 9, yy = 1;
    printf("%02d - %02d - %04d", mm, dd, yy);
    

    This will print 09 - 01 - 0001 on the console.

    You can also use another function sprintf() to write formatted output to a string like below:

    int dd = 1, mm = 9, yy = 1;
    char s[25];
    sprintf(s, "%02d - %02d - %04d", mm, dd, yy);
    cout << s;
    

    Don't forget to include stdio.h header file in your program for both of these functions

    Thing to be noted:

    You can fill blank space either by 0 or by another char (not number).
    If you do write something like %24d format specifier than this will not fill 2 in blank spaces. This will set pad to 24 and will fill blank spaces.

    Removing body margin in CSS

    The right answer for this question is "css reset".

    * {
        margin: 0;
        padding: 0;
    }
    

    It removes all default margin and padding for every object on the page, no holds barred, regardless of browser.

    Bootstrap 3 Slide in Menu / Navbar on Mobile

    Bootstrap 4

    Create a responsive navbar sidebar "drawer" in Bootstrap 4?
    Bootstrap horizontal menu collapse to sidemenu

    Bootstrap 3

    I think what you're looking for is generally known as an "off-canvas" layout. Here is the standard off-canvas example from the official Bootstrap docs: http://getbootstrap.com/examples/offcanvas/

    The "official" example uses a right-side sidebar the toggle off and on separately from the top navbar menu. I also found these off-canvas variations that slide in from the left and may be closer to what you're looking for..

    http://www.bootstrapzero.com/bootstrap-template/off-canvas-sidebar http://www.bootstrapzero.com/bootstrap-template/facebook

    How to call shell commands from Ruby

    The way I like to do this is using the %x literal, which makes it easy (and readable!) to use quotes in a command, like so:

    directorylist = %x[find . -name '*test.rb' | sort]
    

    Which, in this case, will populate file list with all test files under the current directory, which you can process as expected:

    directorylist.each do |filename|
      filename.chomp!
      # work with file
    end
    

    URL encode sees “&” (ampersand) as “&amp;” HTML entity

    If you did literally this:

    encodeURIComponent('&')
    

    Then the result is %26, you can test it here. Make sure the string you are encoding is just & and not &amp; to begin with...otherwise it is encoding correctly, which is likely the case. If you need a different result for some reason, you can do a .replace(/&amp;/g,'&') before the encoding.

    Map implementation with duplicate keys

    I used this:

    java.util.List<java.util.Map.Entry<String,Integer>> pairList= new java.util.ArrayList<>();

    How to call a function from another controller in angularjs?

    I wouldn't use function from one controller into another. A better approach would be to move the common function to a service and then inject the service in both controllers.

    How to convert a string to integer in C?

    Ok, I had the same problem.I came up with this solution.It worked for me the best.I did try atoi() but didn't work well for me.So here is my solution:

    void splitInput(int arr[], int sizeArr, char num[])
    {
        for(int i = 0; i < sizeArr; i++)
            // We are subtracting 48 because the numbers in ASCII starts at 48.
            arr[i] = (int)num[i] - 48;
    }
    

    Pause in Python

    One way is to leave a raw_input() at the end so the script waits for you to press Enter before it terminates.

    Oracle: how to add minutes to a timestamp?

    If the data type of the field is date or timestamp, Oracle should always give the correct result if you add the correct number given in number of days (or a the correct fraction of a day in your case). So if you are trying to bump the value in 30 minutes, you should use :

    select field + 0.5/24 from table;
    

    Based on the information you provided, I believe this is what you tried to do and I am quite sure it works.

    Java2D: Increase the line width

    You should use setStroke to set a stroke of the Graphics2D object.

    The example at http://www.java2s.com gives you some code examples.

    The following code produces the image below:

    import java.awt.*;
    import java.awt.geom.Line2D;
    import javax.swing.*;
    
    public class FrameTest {
        public static void main(String[] args) {
            JFrame jf = new JFrame("Demo");
            Container cp = jf.getContentPane();
            cp.add(new JComponent() {
                public void paintComponent(Graphics g) {
                    Graphics2D g2 = (Graphics2D) g;
                    g2.setStroke(new BasicStroke(10));
                    g2.draw(new Line2D.Float(30, 20, 80, 90));
                }
            });
            jf.setSize(300, 200);
            jf.setVisible(true);
        }
    }
    

    enter image description here

    (Note that the setStroke method is not available in the Graphics object. You have to cast it to a Graphics2D object.)


    This post has been rewritten as an article here.

    How to get a tab character?

    Posting another alternative to be more complete. When I tried the "pre" based answers, they added extra vertical line breaks as well.

    Each tab can be converted to a sequence non-breaking spaces which require no wrapping.

    "&nbsp;&nbsp;&nbsp;&nbsp;" 
    

    This is not recommended for repeated/extensive use within a page. A div margin/padding approach would appear much cleaner.

    font-weight is not working properly?

    I removed the text-transform: uppercase; and then set it to bold/bolder, and this seemed to work.

    How to un-commit last un-pushed git commit without losing the changes

    2020 simple way :

    git reset <commit_hash>
    

    Commit hash of the last commit you want to keep.

    Return Max Value of range that is determined by an Index & Match lookup

    You don't need an index match formula. You can use this array formula. You have to press CTL + SHIFT + ENTER after you enter the formula.

    =MAX(IF((A1:A6=A10)*(B1:B6=B10),C1:F6))
    

    SNAPSHOT

    enter image description here

    How to Iterate over a Set/HashSet without an Iterator?

    Enumeration(?):

    Enumeration e = new Vector(set).elements();
    while (e.hasMoreElements())
        {
            System.out.println(e.nextElement());
        }
    

    Another way (java.util.Collections.enumeration()):

    for (Enumeration e1 = Collections.enumeration(set); e1.hasMoreElements();)
        {
            System.out.println(e1.nextElement());
        }
    

    Java 8:

    set.forEach(element -> System.out.println(element));
    

    or

    set.stream().forEach((elem) -> {
        System.out.println(elem);
    });
    

    How to convert milliseconds into human readable form?

    I'm not able to comment first answer to your question, but there's a small mistake. You should use parseInt or Math.floor to convert floating point numbers to integer, i

    var days, hours, minutes, seconds, x;
    x = ms / 1000;
    seconds = Math.floor(x % 60);
    x /= 60;
    minutes = Math.floor(x % 60);
    x /= 60;
    hours = Math.floor(x % 24);
    x /= 24;
    days = Math.floor(x);
    

    Personally, I use CoffeeScript in my projects and my code looks like that:

    getFormattedTime : (ms)->
            x = ms / 1000
            seconds = Math.floor x % 60
            x /= 60
            minutes = Math.floor x % 60
            x /= 60
            hours = Math.floor x % 24
            x /= 24
            days = Math.floor x
            formattedTime = "#{seconds}s"
            if minutes then formattedTime = "#{minutes}m " + formattedTime
            if hours then formattedTime = "#{hours}h " + formattedTime
            formattedTime 
    

    insert/delete/update trigger in SQL server

    I use that for all status (update, insert and delete)

    CREATE TRIGGER trg_Insert_Test
    ON [dbo].[MyTable]
    AFTER UPDATE, INSERT, DELETE 
    AS
    BEGIN
    SET NOCOUNT ON;
    
    DECLARE @Activity  NVARCHAR (50)
    
    -- update
    IF EXISTS (SELECT * FROM inserted) AND EXISTS (SELECT * FROM deleted)
    BEGIN
        SET @Activity = 'UPDATE'
    END
    
    -- insert
    IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS(SELECT * FROM deleted)
    BEGIN
        SET @Activity = 'INSERT'
    END
    
    -- delete
    IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS(SELECT * FROM inserted)
    BEGIN
        SET @Activity = 'DELETE'
    END
    
    
    
    -- delete temp table
    IF OBJECT_ID('tempdb..#tmpTbl') IS NOT NULL DROP TABLE #tmpTbl
    
    -- get last 1 row
    SELECT * INTO #tmpTbl FROM (SELECT TOP 1 * FROM (SELECT * FROM inserted
                                                     UNION 
                                                     SELECT * FROM deleted
                                                     ) AS A ORDER BY A.Date DESC
                                ) AS T
    
    
    -- try catch
    BEGIN TRY 
    
        INSERT INTO MyTable  (
               [Code]
              ,[Name]
               .....
              ,[Activity])
        SELECT [Code]
              ,[Name]
              ,@Activity 
        FROM #tmpTbl
    
    END TRY BEGIN CATCH END CATCH
    
    
    -- delete temp table
    IF OBJECT_ID('tempdb..#tmpTbl') IS NOT NULL DROP TABLE #tmpTbl
    
    SET NOCOUNT OFF;
    END
    

    Get local IP address in Node.js

    For Linux and macOS uses, if you want to get your IP addresses by a synchronous way, try this:

    var ips = require('child_process').execSync("ifconfig | grep inet | grep -v inet6 | awk '{gsub(/addr:/,\"\");print $2}'").toString().trim().split("\n");
    console.log(ips);
    

    The result will be something like this:

    ['192.168.3.2', '192.168.2.1']
    

    Laravel: getting a a single value from a MySQL query

    Edit:

    Sorry i forgot about pluck() as many have commented : Easiest way is :

    return DB::table('users')->where('username', $username)->pluck('groupName');
    

    Which will directly return the only the first result for the requested row as a string.

    Using the fluent query builder you will obtain an array anyway. I mean The Query Builder has no idea how many rows will come back from that query. Here is what you can do to do it a bit cleaner

    $result = DB::table('users')->select('groupName')->where('username', $username)->first();
    

    The first() tells the queryBuilder to return only one row so no array, so you can do :

    return $result->groupName;
    

    Hope it helps

    How to download files using axios

    Axios.post solution with IE and other browsers

    I've found some incredible solutions here. But they frequently don't take into account problems with IE browser. Maybe it will save some time to somebody else.

     axios.post("/yourUrl"
                    , data,
                    {responseType: 'blob'}
                ).then(function (response) {
                        let fileName = response.headers["content-disposition"].split("filename=")[1];
                        if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE variant
                            window.navigator.msSaveOrOpenBlob(new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}),
                                fileName);
                        } else {
                            const url = window.URL.createObjectURL(new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}));
                            const link = document.createElement('a');
                            link.href = url;
                            link.setAttribute('download', response.headers["content-disposition"].split("filename=")[1]);
                            document.body.appendChild(link);
                            link.click();
                        }
                    }
                );
    

    example above is for excel files, but with little changes can be applied to any format.

    And on server I've done this to send an excel file.

    response.contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    
    response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=exceptions.xlsx")
    

    How to insert data into elasticsearch

    To avoid using curl or Chrome plugins you can just use the the built in windows Powershell. From the Powershell command window run

    Invoke-WebRequest -UseBasicParsing "http://127.0.0.1:9200/sampleindex/sampleType/" -
    Method POST -ContentType "application/json" -Body '{
    "user" : "Test",
    "post_date" : "2017/11/13 11:07:00",
    "message" : "trying out Elasticsearch"
    }'
    

    Note the Index name MUST be in lowercase.

    Capture keyboardinterrupt in Python without try-except

    If someone is in search for a quick minimal solution,

    import signal
    
    # The code which crashes program on interruption
    
    signal.signal(signal.SIGINT, call_this_function_if_interrupted)
    
    # The code skipped if interrupted
    

    How do I set multipart in axios with react?

    Here's how I do file upload in react using axios

    import React from 'react'
    import axios, { post } from 'axios';
    
    class SimpleReactFileUpload extends React.Component {
    
      constructor(props) {
        super(props);
        this.state ={
          file:null
        }
        this.onFormSubmit = this.onFormSubmit.bind(this)
        this.onChange = this.onChange.bind(this)
        this.fileUpload = this.fileUpload.bind(this)
      }
    
      onFormSubmit(e){
        e.preventDefault() // Stop form submit
        this.fileUpload(this.state.file).then((response)=>{
          console.log(response.data);
        })
      }
    
      onChange(e) {
        this.setState({file:e.target.files[0]})
      }
    
      fileUpload(file){
        const url = 'http://example.com/file-upload';
        const formData = new FormData();
        formData.append('file',file)
        const config = {
            headers: {
                'content-type': 'multipart/form-data'
            }
        }
        return  post(url, formData,config)
      }
    
      render() {
        return (
          <form onSubmit={this.onFormSubmit}>
            <h1>File Upload</h1>
            <input type="file" onChange={this.onChange} />
            <button type="submit">Upload</button>
          </form>
       )
      }
    }
    
    
    
    export default SimpleReactFileUpload
    

    Source

    How to convert an Object {} to an Array [] of key-value pairs in JavaScript

    Object.entries() returns an array whose elements are arrays corresponding to the enumerable property [key, value] pairs found directly upon object. The ordering of the properties is the same as that given by looping over the property values of the object manually.

    - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries#Description

    The Object.entries function returns almost the exact output you're asking for, except the keys are strings instead of numbers.

    _x000D_
    _x000D_
    const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};_x000D_
    _x000D_
    console.log(Object.entries(obj));
    _x000D_
    _x000D_
    _x000D_

    If you need the keys to be numbers, you could map the result to a new array with a callback function that replaces the key in each pair with a number coerced from it.

    _x000D_
    _x000D_
    const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};_x000D_
    _x000D_
    const toNumericPairs = input => {_x000D_
        const entries = Object.entries(input);_x000D_
        return entries.map(entry => Object.assign(entry, { 0: +entry[0] }));_x000D_
    }_x000D_
    _x000D_
    console.log(toNumericPairs(obj));
    _x000D_
    _x000D_
    _x000D_

    I use an arrow function and Object.assign for the map callback in the example above so that I can keep it in one instruction by leveraging the fact that Object.assign returns the object being assigned to, and a single instruction arrow function's return value is the result of the instruction.

    This is equivalent to:

    entry => {
        entry[0] = +entry[0];
        return entry;
    }
    

    As mentioned by @TravisClarke in the comments, the map function could be shortened to:

    entry => [ +entry[0], entry[1] ]
    

    However, that would create a new array for each key-value pair, instead of modifying the existing array in place, hence doubling the amount of key-value pair arrays created. While the original entries array is still accessible, it and its entries will not be garbage collected.

    Now, even though using our in-place method still uses two arrays that hold the key-value pairs (the input and the output arrays), the total number of arrays only changes by one. The input and output arrays aren't actually filled with arrays, but rather references to arrays and those references take up a negligible amount of space in memory.

    • Modifying each key-value pair in-place results in a negligible amount of memory growth, but requires typing a few more characters.
    • Creating a new array for each key-value pair results in doubling the amount of memory required, but requires typing a few less characters.

    You could go one step further and eliminate growth altogether by modifying the entries array in-place instead of mapping it to a new array:

    _x000D_
    _x000D_
    const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};_x000D_
    _x000D_
    const toNumericPairs = input => {_x000D_
      const entries = Object.entries(obj);_x000D_
      entries.forEach(entry => entry[0] = +entry[0]);_x000D_
      return entries;_x000D_
    }_x000D_
    _x000D_
    console.log(toNumericPairs(obj));
    _x000D_
    _x000D_
    _x000D_

    Defining a HTML template to append using JQuery

    Old question, but since the question asks "using jQuery", I thought I'd provide an option that lets you do this without introducing any vendor dependency.

    While there are a lot of templating engines out there, many of their features have fallen in to disfavour recently, with iteration (<% for), conditionals (<% if) and transforms (<%= myString | uppercase %>) seen as microlanguage at best, and anti-patterns at worst. Modern templating practices encourage simply mapping an object to its DOM (or other) representation, e.g. what we see with properties mapped to components in ReactJS (especially stateless components).

    Templates Inside HTML

    One property you can rely on for keeping the HTML for your template next to the rest of your HTML, is by using a non-executing <script> type, e.g. <script type="text/template">. For your case:

    <script type="text/template" data-template="listitem">
        <a href="${url}" class="list-group-item">
            <table>
                <tr>
                    <td><img src="${img}"></td>
                    <td><p class="list-group-item-text">${title}</p></td>
                </tr>
            </table>
        </a>
    </script>
    

    On document load, read your template and tokenize it using a simple String#split

    var itemTpl = $('script[data-template="listitem"]').text().split(/\$\{(.+?)\}/g);
    

    Notice that with our token, you get it in the alternating [text, property, text, property] format. This lets us nicely map it using an Array#map, with a mapping function:

    function render(props) {
      return function(tok, i) { return (i % 2) ? props[tok] : tok; };
    }
    

    Where props could look like { url: 'http://foo.com', img: '/images/bar.png', title: 'Lorem Ipsum' }.

    Putting it all together assuming you've parsed and loaded your itemTpl as above, and you have an items array in-scope:

    $('.search').keyup(function () {
      $('.list-items').append(items.map(function (item) {
        return itemTpl.map(render(item)).join('');
      }));
    });
    

    This approach is also only just barely jQuery - you should be able to take the same approach using vanilla javascript with document.querySelector and .innerHTML.

    jsfiddle

    Templates inside JS

    A question to ask yourself is: do you really want/need to define templates as HTML files? You can always componentize + re-use a template the same way you'd re-use most things you want to repeat: with a function.

    In es7-land, using destructuring, template strings, and arrow-functions, you can write downright pretty looking component functions that can be easily loaded using the $.fn.html method above.

    const Item = ({ url, img, title }) => `
      <a href="${url}" class="list-group-item">
        <div class="image">
          <img src="${img}" />
        </div>
        <p class="list-group-item-text">${title}</p>
      </a>
    `;
    

    Then you could easily render it, even mapped from an array, like so:

    $('.list-items').html([
      { url: '/foo', img: 'foo.png', title: 'Foo item' },
      { url: '/bar', img: 'bar.png', title: 'Bar item' },
    ].map(Item).join(''));
    

    Oh and final note: don't forget to sanitize your properties passed to a template, if they're read from a DB, or someone could pass in HTML (and then run scripts, etc.) from your page.

    How to print Boolean flag in NSLog?

    Apple's FixIt supplied %hhd, which correctly gave me the value of my BOOL.

    How to initialize/instantiate a custom UIView class with a XIB file in Swift

    Swift 3 Answer: In my case, I wanted to have an outlet in my custom class that I could modify:

    class MyClassView: UIView {
        @IBOutlet weak var myLabel: UILabel!
    
        class func createMyClassView() -> MyClass {
            let myClassNib = UINib(nibName: "MyClass", bundle: nil)
            return myClassNib.instantiate(withOwner: nil, options: nil)[0] as! MyClassView
        }
    }
    

    When in the .xib, make sure that the Custom Class field is MyClassView. Don't bother with the File's Owner.

    Make sure Custom Class is MyClassView

    Also, make sure that you connect the outlet in MyClassView to the label: Outlet for myLabel

    To instantiate it:

    let myClassView = MyClassView.createMyClassView()
    myClassView.myLabel.text = "Hello World!"
    

    PHP passing $_GET in linux command prompt

    Typically, for passing arguments to a command line script, you will use either argv global variable or getopt:

    // bash command:
    //   php -e myscript.php hello
    echo $argv[1]; // prints hello
    
    // bash command:
    //   php -e myscript.php -f=world
    $opts = getopt('f:');
    echo $opts['f']; // prints world
    

    $_GET refers to the HTTP GET method parameters, which are unavailable in command line, since they require a web server to populate.

    If you really want to populate $_GET anyway, you can do this:

    // bash command:
    //   export QUERY_STRING="var=value&arg=value" ; php -e myscript.php
    parse_str($_SERVER['QUERY_STRING'], $_GET);
    print_r($_GET);
    /* outputs:
         Array(
            [var] => value
            [arg] => value
         )
    */
    

    You can also execute a given script, populate $_GET from the command line, without having to modify said script:

    export QUERY_STRING="var=value&arg=value" ; \
    php -e -r 'parse_str($_SERVER["QUERY_STRING"], $_GET); include "index.php";'
    

    Note that you can do the same with $_POST and $_COOKIE as well.

    Python module for converting PDF to text

    PDFminer gave me perhaps one line [page 1 of 7...] on every page of a pdf file I tried with it.

    The best answer I have so far is pdftoipe, or the c++ code it's based on Xpdf.

    see my question for what the output of pdftoipe looks like.

    How to use count and group by at the same select statement

    I know this is an old post, in SQL Server:

    select  isnull(town,'TOTAL') Town, count(*) cnt
    from    user
    group by town WITH ROLLUP
    
    Town         cnt
    Copenhagen   58
    NewYork      58
    Athens       58
    TOTAL        174