Programs & Examples On #Mysql error 1222

Error #1222 - The used SELECT statements have a different number of columns

How to read input with multiple lines in Java

 public class Sol {

   public static void main(String[] args) {

   Scanner sc = new Scanner(System.in); 

   while(sc.hasNextLine()){

   System.out.println(sc.nextLine());

  }
 }
}

How can I list ALL grants a user received?

Sorry guys, but selecting from all_tab_privs_recd where grantee = 'your user' will not give any output except public grants and current user grants if you run the select from a different (let us say, SYS) user. As documentation says,

ALL_TAB_PRIVS_RECD describes the following types of grants:

Object grants for which the current user is the grantee
Object grants for which an enabled role or PUBLIC is the grantee

So, if you're a DBA and want to list all object grants for a particular (not SYS itself) user, you can't use that system view.

In this case, you must perform a more complex query. Here is one taken (traced) from TOAD to select all object grants for a particular user:

select tpm.name privilege,
       decode(mod(oa.option$,2), 1, 'YES', 'NO') grantable,
       ue.name grantee,
       ur.name grantor,
       u.name owner,
       decode(o.TYPE#, 0, 'NEXT OBJECT', 1, 'INDEX', 2, 'TABLE', 3, 'CLUSTER',
                       4, 'VIEW', 5, 'SYNONYM', 6, 'SEQUENCE',
                       7, 'PROCEDURE', 8, 'FUNCTION', 9, 'PACKAGE',
                       11, 'PACKAGE BODY', 12, 'TRIGGER',
                       13, 'TYPE', 14, 'TYPE BODY',
                       19, 'TABLE PARTITION', 20, 'INDEX PARTITION', 21, 'LOB',
                       22, 'LIBRARY', 23, 'DIRECTORY', 24, 'QUEUE',
                       28, 'JAVA SOURCE', 29, 'JAVA CLASS', 30, 'JAVA RESOURCE',
                       32, 'INDEXTYPE', 33, 'OPERATOR',
                       34, 'TABLE SUBPARTITION', 35, 'INDEX SUBPARTITION',
                       40, 'LOB PARTITION', 41, 'LOB SUBPARTITION',
                       42, 'MATERIALIZED VIEW',
                       43, 'DIMENSION',
                       44, 'CONTEXT', 46, 'RULE SET', 47, 'RESOURCE PLAN',
                       66, 'JOB', 67, 'PROGRAM', 74, 'SCHEDULE',
                       48, 'CONSUMER GROUP',
                       51, 'SUBSCRIPTION', 52, 'LOCATION',
                       55, 'XML SCHEMA', 56, 'JAVA DATA',
                       57, 'EDITION', 59, 'RULE',
                       62, 'EVALUATION CONTEXT',
                       'UNDEFINED') object_type,
       o.name object_name,
       '' column_name
        from sys.objauth$ oa, sys.obj$ o, sys.user$ u, sys.user$ ur, sys.user$ ue,
             table_privilege_map tpm
        where oa.obj# = o.obj#
          and oa.grantor# = ur.user#
          and oa.grantee# = ue.user#
          and oa.col# is null
          and oa.privilege# = tpm.privilege
          and u.user# = o.owner#
          and o.TYPE# in (2, 4, 6, 9, 7, 8, 42, 23, 22, 13, 33, 32, 66, 67, 74, 57)
  and ue.name = 'your user'
  and bitand (o.flags, 128) = 0
union all -- column level grants
select tpm.name privilege,
       decode(mod(oa.option$,2), 1, 'YES', 'NO') grantable,
       ue.name grantee,
       ur.name grantor,
       u.name owner,
       decode(o.TYPE#, 2, 'TABLE', 4, 'VIEW', 42, 'MATERIALIZED VIEW') object_type,
       o.name object_name,
       c.name column_name
from sys.objauth$ oa, sys.obj$ o, sys.user$ u, sys.user$ ur, sys.user$ ue,
     sys.col$ c, table_privilege_map tpm
where oa.obj# = o.obj#
  and oa.grantor# = ur.user#
  and oa.grantee# = ue.user#
  and oa.obj# = c.obj#
  and oa.col# = c.col#
  and bitand(c.property, 32) = 0 /* not hidden column */
  and oa.col# is not null
  and oa.privilege# = tpm.privilege
  and u.user# = o.owner#
  and o.TYPE# in (2, 4, 42)
  and ue.name = 'your user'
  and bitand (o.flags, 128) = 0;

This will list all object grants (including column grants) for your (specified) user. If you don't want column level grants then delete all part of the select beginning with 'union' clause.

UPD: Studying the documentation I found another view that lists all grants in much simpler way:

select * from DBA_TAB_PRIVS where grantee = 'your user';

Bear in mind that there's no DBA_TAB_PRIVS_RECD view in Oracle.

C# Linq Group By on multiple columns

var consolidatedChildren =
    from c in children
    group c by new
    {
        c.School,
        c.Friend,
        c.FavoriteColor,
    } into gcs
    select new ConsolidatedChild()
    {
        School = gcs.Key.School,
        Friend = gcs.Key.Friend,
        FavoriteColor = gcs.Key.FavoriteColor,
        Children = gcs.ToList(),
    };

var consolidatedChildren =
    children
        .GroupBy(c => new
        {
            c.School,
            c.Friend,
            c.FavoriteColor,
        })
        .Select(gcs => new ConsolidatedChild()
        {
            School = gcs.Key.School,
            Friend = gcs.Key.Friend,
            FavoriteColor = gcs.Key.FavoriteColor,
            Children = gcs.ToList(),
        });

JQuery datepicker language

Include js files of datepicker and language (locales)

'resource/bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js',
'resource/bower_components/bootstrap-datepicker/dist/locales/bootstrap-datepicker.sv.min.js',

In the options of the datepicker, set the language as below:

$('.datepicker').datepicker({'language' : 'sv'});

Regular expressions inside SQL Server

In order to match a digit, you can use [0-9].

So you could use 5[0-9][0-9][0-9][0-9][0-9][0-9] and [0-9][0-9][0-9][0-9]7[0-9][0-9][0-9]. I do this a lot for zip codes.

converting CSV/XLS to JSON?

If you can't find an existing solution it's pretty easy to build a basic one in Java. I just wrote one for a client and it took only a couple hours including researching tools.

Apache POI will read the Excel binary. http://poi.apache.org/

JSONObject will build the JSON

After that it's just a matter of iterating through the rows in the Excel data and building a JSON structure. Here's some pseudo code for the basic usage.

FileInputStream inp = new FileInputStream( file );
Workbook workbook = WorkbookFactory.create( inp );

// Get the first Sheet.
Sheet sheet = workbook.getSheetAt( 0 );

    // Start constructing JSON.
    JSONObject json = new JSONObject();

    // Iterate through the rows.
    JSONArray rows = new JSONArray();
    for ( Iterator<Row> rowsIT = sheet.rowIterator(); rowsIT.hasNext(); )
    {
        Row row = rowsIT.next();
        JSONObject jRow = new JSONObject();

        // Iterate through the cells.
        JSONArray cells = new JSONArray();
        for ( Iterator<Cell> cellsIT = row.cellIterator(); cellsIT.hasNext(); )
        {
            Cell cell = cellsIT.next();
            cells.put( cell.getStringCellValue() );
        }
        jRow.put( "cell", cells );
        rows.put( jRow );
    }

    // Create the JSON.
    json.put( "rows", rows );

// Get the JSON text.
return json.toString();

Twitter Bootstrap scrollable table rows and fixed header

Just stack two bootstrap tables; one for columns, the other for content. No plugins, just pure bootstrap (and that ain't no bs, haha!)

  <table id="tableHeader" class="table" style="table-layout:fixed">
        <thead>
            <tr>
                <th>Col1</th>
                ...
            </tr>
        </thead>
  </table>
  <div style="overflow-y:auto;">
    <table id="tableData" class="table table-condensed" style="table-layout:fixed">
        <tbody>
            <tr>
                <td>data</td>
                ...
            </tr>
        </tbody>
    </table>
 </div>

Demo JSFiddle

The content table div needs overflow-y:auto, for vertical scroll bars. Had to use table-layout:fixed, otherwise, columns did not line up. Also, had to put the whole thing inside a bootstrap panel to eliminate space between the tables.

Have not tested with custom column widths, but provided you keep the widths consistent between the tables, it should work.

    // ADD THIS JS FUNCTION TO MATCH UP COL WIDTHS
    $(function () {

        //copy width of header cells to match width of cells with data
        //so they line up properly
        var tdHeader = document.getElementById("tableHeader").rows[0].cells;
        var tdData = document.getElementById("tableData").rows[0].cells;

        for (var i = 0; i < tdData.length; i++)
            tdHeader[i].style.width = tdData[i].offsetWidth + 'px';

    });

Java: Finding the highest value in an array

You can write like this.

import java.util.Scanner;
class   BigNoArray{

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter how many array element");
        int n=sc.nextInt();
        int[] ar= new int[n];
        System.out.println("enter "+n+" values");
        for(int i=0;i<ar.length;i++){
            ar[i]=sc.nextInt();
        }
        int fbig=ar[0];
        int sbig=ar[1];
        int tbig=ar[3];
            for(int i=1;i<ar.length;i++){
                if(fbig<ar[i]){
                    sbig=fbig;
                    fbig=ar[i];
                }
                else if(sbig<ar[i]&&ar[i]!=fbig){
                    sbig=ar[i];
                }
                else if(tbig<ar[i]&&ar[i]!=fbig){
                    tbig=ar[i];
                }
            }
        System.out.println("first big number is "+fbig);
        System.out.println("second big number is "+sbig);
        System.out.println("third big number is "+tbig);
    }
}

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

How to reset db in Django? I get a command 'reset' not found error

reset has been replaced by flush with Django 1.5, see:

python manage.py help flush

ERROR 1148: The used command is not allowed with this MySQL version

SpringBoot 2.1 with Default MySQL connector

To Solve this please follow the instructions

1. SET GLOBAL local_infile = 1;

to set this global variable please follow the instruction provided in MySQL documentation https://dev.mysql.com/doc/refman/8.0/en/load-data-local.html

2. Change the MySQL Connector String

allowLoadLocalInfile=true Example : jdbc:mysql://localhost:3306/xxxx?useSSL=false&useUnicode=yes&characterEncoding=UTF-8&allowLoadLocalInfile=true

Eclipse error: "The import XXX cannot be resolved"

I didn't understand the reasoning behind this but this solved the same problem I was facing. You may require these steps before executing steps mentioned in above solutions (Clean all projects and Build automatically).

right click project -> Properties -> Project Facets -> select Java -> Apply

Div not expanding even with content inside

Floated elements don’t take up any vertical space in their containing element.

All of your elements inside #albumhold are floated, apart from #albumhead, which doesn’t look like it’d take up much space.

However, if you add overflow: hidden; to #albumhold (or some other CSS to clear floats inside it), it will expand its height to encompass its floated children.

tar: Error is not recoverable: exiting now

Try to get your archive using wget, I had the same issue when I was downloading archive through browser. Than I just copy archive link and in terminal use the command:

wget http://PATH_TO_ARCHIVE

What's the Use of '\r' escape sequence?

The '\r' stands for "Carriage Return" - it's a holdover from the days of typewriters and really old printers. The best example is in Windows and other DOSsy OSes, where a newline is given as "\r\n". These are the instructions sent to an old printer to start a new line: first move the print head back to the beginning, then go down one.

Different OSes will use other newline sequences. Linux and OSX just use '\n'. Older Mac OSes just use '\r'. Wikipedia has a more complete list, but those are the important ones.

Hope this helps!

PS: As for why you get that weird output... Perhaps the console is moving the "cursor" back to the beginning of the line, and then overwriting the first bit with spaces or summat.

Tracking Google Analytics Page Views with AngularJS

If you're using ng-view in your Angular app you can listen for the $viewContentLoaded event and push a tracking event to Google Analytics.

Assuming you've set up your tracking code in your main index.html file with a name of var _gaq and MyCtrl is what you've defined in the ng-controller directive.

function MyCtrl($scope, $location, $window) {
  $scope.$on('$viewContentLoaded', function(event) {
    $window._gaq.push(['_trackPageView', $location.url()]);
  });
}

UPDATE: for new version of google-analytics use this one

function MyCtrl($scope, $location, $window) {
  $scope.$on('$viewContentLoaded', function(event) {
    $window.ga('send', 'pageview', { page: $location.url() });
  });
}

Get path from open file in Python

I had the exact same issue. If you are using a relative path os.path.dirname(path) will only return the relative path. os.path.realpath does the trick:

>>> import os
>>> f = open('file.txt')
>>> os.path.realpath(f.name)

implements Closeable or implements AutoCloseable

The try-with-resources Statement.

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}

In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:

static String readFirstLineFromFileWithFinallyBlock(String path)
                                                     throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }

}

Please refer to the docs.

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

Well, the <head> tag has nothing to do with the <header> tag. In the head comes all the metadata and stuff, while the header is just a layout component.
And layout comes into body. So I disagree with you.

How to emulate a do-while loop in Python?

If you're in a scenario where you are looping while a resource is unavaliable or something similar that throws an exception, you could use something like

import time

while True:
    try:
       f = open('some/path', 'r')
    except IOError:
       print('File could not be read. Retrying in 5 seconds')   
       time.sleep(5)
    else:
       break

Change default timeout for mocha

By default Mocha will read a file named test/mocha.opts that can contain command line arguments. So you could create such a file that contains:

--timeout 5000

Whenever you run Mocha at the command line, it will read this file and set a timeout of 5 seconds by default.

Another way which may be better depending on your situation is to set it like this in a top level describe call in your test file:

describe("something", function () {
    this.timeout(5000); 

    // tests...
});

This would allow you to set a timeout only on a per-file basis.

You could use both methods if you want a global default of 5000 but set something different for some files.


Note that you cannot generally use an arrow function if you are going to call this.timeout (or access any other member of this that Mocha sets for you). For instance, this will usually not work:

describe("something", () => {
    this.timeout(5000); //will not work

    // tests...
});

This is because an arrow function takes this from the scope the function appears in. Mocha will call the function with a good value for this but that value is not passed inside the arrow function. The documentation for Mocha says on this topic:

Passing arrow functions (“lambdas”) to Mocha is discouraged. Due to the lexical binding of this, such functions are unable to access the Mocha context.

Is there a Google Chrome-only CSS hack?

Only Chrome CSS hack:

@media all and (-webkit-min-device-pixel-ratio:0) and (min-resolution: .001dpcm) {
    #selector {
        background: red;
    }
}

Declaring variables inside loops, good practice or bad practice?

Declaring variables inside or outside of a loop, It's the result of JVM specifications But in the name of best coding practice it is recommended to declare the variable in the smallest possible scope (in this example it is inside the loop, as this is the only place where the variable is used). Declaring objects in the smallest scope improve readability. The scope of local variables should always be the smallest possible. In your example I presume str is not used outside of the while loop, otherwise you would not be asking the question, because declaring it inside the while loop would not be an option, since it would not compile.

Does it make a difference if I declare variables inside or outside a , Does it make a difference if I declare variables inside or outside a loop in Java? Is this for(int i = 0; i < 1000; i++) { int At the level of the individual variable there is no significant difference in effeciency, but if you had a function with 1000 loops and 1000 variables (never mind the bad style implied) there could be systemic differences because all the lives of all the variables would be the same instead of overlapped.

Declaring Loop Control Variables Inside the for Loop, When you declare a variable inside a for loop, there is one important point to remember: the scope of that variable ends when the for statement does. (That is, the scope of the variable is limited to the for loop.) This Java Example shows how to declare multiple variables in Java For loop using declaration block.

How do I get data from a table?

use Json & jQuery. It's way easier than oldschool javascript

function savedata1() { 

var obj = $('#myTable tbody tr').map(function() {
var $row = $(this);
var t1 = $row.find(':nth-child(1)').text();
var t2 = $row.find(':nth-child(2)').text();
var t3 = $row.find(':nth-child(3)').text();
return {
    td_1: $row.find(':nth-child(1)').text(),
    td_2: $row.find(':nth-child(2)').text(),
    td_3: $row.find(':nth-child(3)').text()
   };
}).get();

How can I capture the result of var_dump to a string?

Use output buffering:

<?php
ob_start();
var_dump($someVar);
$result = ob_get_clean();
?>

Create a symbolic link of directory in Ubuntu

This is the behavior of ln if the second arg is a directory. It places a link to the first arg inside it. If you want /etc/nginx to be the symlink, you should remove that directory first and run that same command.

Moving matplotlib legend outside of the axis makes it cutoff by the figure box

Added: I found something that should do the trick right away, but the rest of the code below also offers an alternative.

Use the subplots_adjust() function to move the bottom of the subplot up:

fig.subplots_adjust(bottom=0.2) # <-- Change the 0.02 to work for your plot.

Then play with the offset in the legend bbox_to_anchor part of the legend command, to get the legend box where you want it. Some combination of setting the figsize and using the subplots_adjust(bottom=...) should produce a quality plot for you.

Alternative: I simply changed the line:

fig = plt.figure(1)

to:

fig = plt.figure(num=1, figsize=(13, 13), dpi=80, facecolor='w', edgecolor='k')

and changed

lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,0))

to

lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,-0.02))

and it shows up fine on my screen (a 24-inch CRT monitor).

Here figsize=(M,N) sets the figure window to be M inches by N inches. Just play with this until it looks right for you. Convert it to a more scalable image format and use GIMP to edit if necessary, or just crop with the LaTeX viewport option when including graphics.

How to convert a datetime to string in T-SQL

There are 3 different methods depending on what I is my requirement and which version I am using.

Here are the methods..

1) Using Convert

DECLARE @DateTime DATETIME = GETDATE();
--Using Convert
SELECT
    CONVERT(NVARCHAR, @DateTime,120) AS 'myDateTime'
    ,CONVERT(NVARCHAR(10), @DateTime, 120) AS 'myDate'
    ,RIGHT(CONVERT(NVARCHAR, @DateTime, 120),8) AS 'myTime'

2) Using Cast (SQL Server 2008 and beyond)

SELECT
    CAST(@DateTime AS DATETIME2) AS 'myDateTime'
    ,CAST(@DateTime AS DATETIME2(3)) AS 'myDateTimeWithPrecision'
    ,CAST(@DateTime AS DATE) AS 'myDate'
    ,CAST(@DateTime AS TIME) AS 'myTime'
    ,CAST(@DateTime AS TIME(3)) AS 'myTimeWithPrecision'

3) Using Fixed-length character data type

DECLARE @myDateTime NVARCHAR(20) = CONVERT(NVARCHAR, @DateTime, 120);
DECLARE @myDate NVARCHAR(10) = CONVERT(NVARCHAR, @DateTime, 120);

SELECT
    @myDateTime AS 'myDateTime'
    ,@myDate AS 'myDate'

How to create a TextArea in Android

All of the answers are good but not complete. Use this.

 <EditText
      android:layout_width="match_parent"
      android:layout_height="0dp"
      android:layout_marginTop="12dp"
      android:layout_marginBottom="12dp"
      android:background="@drawable/text_area_background"
      android:gravity="start|top"
      android:hint="@string/write_your_comments"
      android:imeOptions="actionDone"
      android:importantForAutofill="no"
      android:inputType="textMultiLine"
      android:padding="12dp" />

Xcode Debugger: view value of variable

This gets a little complicated. These objects are custom classes or structs, and looking inside them is not as easy on Xcode as in other development environments.

If I were you, I'd NSLog the values you want to see, with some description.

i.e:

NSLog(@"Description of object & time: %i", indexPath.row);

How to allow users to check for the latest app version from inside the app?

Here's how to find the current and latest available versions:

       try {
            String curVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
            String newVersion = curVersion;
            newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + getPackageName() + "&hl=en")
                    .timeout(30000)
                    .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                    .referrer("http://www.google.com")
                    .get()
                    .select("div.hAyfc:nth-child(4) .IQ1z0d .htlgb")
                    .first()
                    .ownText();
            Log.d("Curr Version" , curVersion);
            Log.d("New Version" , newVersion);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

Why does the Google Play store say my Android app is incompatible with my own device?

To give an extra solution to the above 'This app is incompatible with your...' problem, let me share my solution for a different problem cause. I tried installing an app on a low-end Samsung Galaxy Y (GT-S6350) device and got this error from the Play store. To test various AndroidManifest configurations, I created an account and followed the routine as described in https://stackoverflow.com/a/5449397/372838 until my device showed up in the supported device list.

It turned out that a lot of devices become incompatible when you use the Camera permission:

<uses-permission android:name="android.permission.CAMERA" />

When I removed that specific permission, the application was available for 1180 devices instead of 870. Hope it will help someone

Linux: is there a read or recv from socket with timeout?

LINUX

struct timeval tv;
tv.tv_sec = 30;        // 30 Secs Timeout
tv.tv_usec = 0;        // Not init'ing this can cause strange errors
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv,sizeof(struct timeval));

WINDOWS

DWORD timeout = SOCKET_READ_TIMEOUT_SEC * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout));

NOTE: You have put this setting before bind() function call for proper run

Print "hello world" every X seconds

For small applications it is fine to use Timer and TimerTask as Rohit mentioned but in web applications I would use Quartz Scheduler to schedule jobs and to perform such periodic jobs.

See tutorials for Quartz scheduling.

Pandas: drop a level from a multi-level column index?

I have struggled with this problem since I don’t know why my droplevel() function does not work. Work through several and learn that ‘a’ in your table is columns name and ‘b’, ‘c’ are index. Do like this will help

df.columns.name = None
df.reset_index() #make index become label

iOS 10 - Changes in asking permissions of Camera, microphone and Photo Library causing application to crash

Please find below codes for ios 10 request permission sample for info.plist.
You can modify for your custom message.

    <key>NSCameraUsageDescription</key>
    <string>${PRODUCT_NAME} Camera Usage</string>

    <key>NSBluetoothPeripheralUsageDescription</key>
    <string>${PRODUCT_NAME} BluetoothPeripheral</string>

    <key>NSCalendarsUsageDescription</key>
    <string>${PRODUCT_NAME} Calendar Usage</string>

    <key>NSContactsUsageDescription</key>
    <string>${PRODUCT_NAME} Contact fetch</string>

    <key>NSHealthShareUsageDescription</key>
    <string>${PRODUCT_NAME} Health Description</string>

    <key>NSHealthUpdateUsageDescription</key>
    <string>${PRODUCT_NAME} Health Updates</string>

    <key>NSHomeKitUsageDescription</key>
    <string>${PRODUCT_NAME} HomeKit Usage</string>

    <key>NSLocationAlwaysUsageDescription</key>
    <string>${PRODUCT_NAME} Use location always</string>

    <key>NSLocationUsageDescription</key>
    <string>${PRODUCT_NAME} Location Updates</string>

    <key>NSLocationWhenInUseUsageDescription</key>
    <string>${PRODUCT_NAME} WhenInUse Location</string>

    <key>NSAppleMusicUsageDescription</key>
    <string>${PRODUCT_NAME} Music Usage</string>

    <key>NSMicrophoneUsageDescription</key>
    <string>${PRODUCT_NAME} Microphone Usage</string>

    <key>NSMotionUsageDescription</key>
    <string>${PRODUCT_NAME} Motion Usage</string>

    <key>kTCCServiceMediaLibrary</key>
    <string>${PRODUCT_NAME} MediaLibrary Usage</string>

    <key>NSPhotoLibraryUsageDescription</key>
    <string>${PRODUCT_NAME} PhotoLibrary Usage</string>

    <key>NSRemindersUsageDescription</key>
    <string>${PRODUCT_NAME} Reminder Usage</string>

    <key>NSSiriUsageDescription</key>
    <string>${PRODUCT_NAME} Siri Usage</string>

    <key>NSSpeechRecognitionUsageDescription</key>
    <string>${PRODUCT_NAME} Speech Recognition Usage</string>

    <key>NSVideoSubscriberAccountUsageDescription</key>
    <string>${PRODUCT_NAME} Video Subscribe Usage</string>

iOS 11 and plus, If you want to add photo/image to your library then you must add this key

    <key>NSPhotoLibraryAddUsageDescription</key>
    <string>${PRODUCT_NAME} library Usage</string>

What does "make oldconfig" do exactly in the Linux kernel makefile?

It's torture. Instead of including a generic conf file, they make you hit return 9000 times to generate one.

How to pass an event object to a function in Javascript?

I would change your binding to be:

<button type="button" value="click me" onclick="check_me" />

I would then change your check_me() function declaration to be:

function check_me() {   
  //event.preventDefault();
  var hello = document.myForm.username.value;
  var err = '';

  if(hello == '' || hello == null) {
    err = 'User name required';
  }

  if(err != '') { 
     alert(err); 
     $('username').focus(); 
     event.preventDefault(); 
   } else { 
    return true; }
}

How to create an ArrayList from an Array in PowerShell?

Probably the shortest version:

[System.Collections.ArrayList]$someArray

It is also faster because it does not call relatively expensive New-Object.

jQuery get the id/value of <li> element after click function

If you change your html code a bit - remove the ids

<ul id='myid'>  
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
<li>Fifth</li>
</ul>

Then the jquery code you want is...

$("#myid li").click(function() {
    alert($(this).prevAll().length+1);
});?

You don't need to place any ids, just keep on adding li items.

Take a look at demo

Useful links

How do you subtract Dates in Java?

Here's the basic approach,

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

Date beginDate = dateFormat.parse("2013-11-29");
Date endDate = dateFormat.parse("2013-12-4");

Calendar beginCalendar = Calendar.getInstance();
beginCalendar.setTime(beginDate);

Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);

There is simple way to implement it. We can use Calendar.add method with loop. The minus days between beginDate and endDate, and the implemented code as below,

int minusDays = 0;
while (true) {
  minusDays++;

  // Day increasing by 1
  beginCalendar.add(Calendar.DAY_OF_MONTH, 1);

  if (dateFormat.format(beginCalendar.getTime()).
            equals(dateFormat.format(endCalendar).getTime())) {
    break;
  }
}
System.out.println("The subtraction between two days is " + (minusDays + 1));**

Error when trying to access XAMPP from a network

This answer is for XAMPP on Ubuntu.

The manual for installation and download is on (site official)

http://www.apachefriends.org/it/xampp-linux.html

After to start XAMPP simply call this command:

sudo /opt/lampp/lampp start

You should now see something like this on your screen:

Starting XAMPP 1.8.1...
LAMPP: Starting Apache...
LAMPP: Starting MySQL...
LAMPP started.

If you have this

Starting XAMPP for Linux 1.8.1...                                                             
XAMPP: Another web server daemon is already running.                                          
XAMPP: Another MySQL daemon is already running.                                               
XAMPP: Starting ProFTPD...                                                                    
XAMPP for Linux started

. The solution is

sudo /etc/init.d/apache2 stop
sudo /etc/init.d/mysql stop

And the restast with sudo //opt/lampp/lampp restart

You to fix most of the security weaknesses simply call the following command:

/opt/lampp/lampp security

After the change this file

sudo kate //opt/lampp/etc/extra/httpd-xampp.conf

Find and replace on

    #
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
    Order deny,allow
    Deny from all
    Allow from ::1 127.0.0.0/8 
    Allow from all
    #\
    #   fc00::/7 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 \
    #   fe80::/10 169.254.0.0/16

    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

Responsive width Facebook Page Plugin

Hi everybody!

My version with a live demonstration(native JavaScript):

1). Javascript code in a separate file (the best solution):

Codepen

_x000D_
_x000D_
/* Vanilla JS */_x000D_
function setupFBframe(frame) {_x000D_
  var container = frame.parentNode;_x000D_
_x000D_
  var containerWidth = container.offsetWidth;_x000D_
  var containerHeight = container.offsetHeight;_x000D_
_x000D_
  var src =_x000D_
    "https://www.facebook.com/plugins/page.php" +_x000D_
    "?href=https%3A%2F%2Fwww.facebook.com%2Ffacebook" +_x000D_
    "&tabs=timeline" +_x000D_
    "&width=" +_x000D_
    containerWidth +_x000D_
    "&height=" +_x000D_
    containerHeight +_x000D_
    "&small_header=false" +_x000D_
    "&adapt_container_width=false" +_x000D_
    "&hide_cover=true" +_x000D_
    "&hide_cta=true" +_x000D_
    "&show_facepile=true" +_x000D_
    "&appId";_x000D_
_x000D_
  frame.width = containerWidth;_x000D_
  frame.height = containerHeight;_x000D_
  frame.src = src;_x000D_
}_x000D_
_x000D_
/* begin Document Ready                                _x000D_
############################################ */_x000D_
_x000D_
document.addEventListener('DOMContentLoaded', function() {_x000D_
  var facebookIframe = document.querySelector('#facebook_iframe');_x000D_
  setupFBframe(facebookIframe);_x000D_
 _x000D_
  /* begin Window Resize                                _x000D_
  ############################################ */_x000D_
  _x000D_
  // Why resizeThrottler? See more : https://developer.mozilla.org/ru/docs/Web/Events/resize_x000D_
  (function() {_x000D_
    window.addEventListener("resize", resizeThrottler, false);_x000D_
_x000D_
    var resizeTimeout;_x000D_
_x000D_
    function resizeThrottler() {_x000D_
      if (!resizeTimeout) {_x000D_
        resizeTimeout = setTimeout(function() {_x000D_
          resizeTimeout = null;_x000D_
          actualResizeHandler();_x000D_
        }, 66);_x000D_
      }_x000D_
    }_x000D_
_x000D_
    function actualResizeHandler() {_x000D_
      document.querySelector('#facebook_iframe').removeAttribute('src');_x000D_
      setupFBframe(facebookIframe);_x000D_
    }_x000D_
  })();_x000D_
  /* end Window Resize_x000D_
  ############################################ */_x000D_
});_x000D_
/* end Document Ready                                _x000D_
############################################ */
_x000D_
@import url('https://fonts.googleapis.com/css?family=Indie+Flower');_x000D_
body {_x000D_
  font-family: 'Indie Flower', cursive;_x000D_
}_x000D_
.container {_x000D_
  max-width: 1170px;_x000D_
  width: 100%;_x000D_
  margin-left: auto;_x000D_
  margin-right: auto;_x000D_
}_x000D_
.content {_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
.left_sidebar {_x000D_
  position: relative;_x000D_
  float: left;_x000D_
  width: 30%;_x000D_
  max-width: 300px;_x000D_
}_x000D_
_x000D_
.main_content {_x000D_
  position: relative;_x000D_
  float: left;_x000D_
  width: 70%;_x000D_
  background-color: #DDEFF7;_x000D_
}_x000D_
/* ------- begin Widget Facebook -------------- */_x000D_
.widget--facebook--container {_x000D_
  padding: 10px;_x000D_
  border: 1px solid #000;_x000D_
}_x000D_
_x000D_
.widget-facebook {_x000D_
  height: 500px;_x000D_
}_x000D_
_x000D_
.widget-facebook .facebook_iframe {_x000D_
  border: none;_x000D_
}_x000D_
_x000D_
/* ---------- end Widget Facebook---------------- */_x000D_
_x000D_
/* ----------------- no need -------------------- */_x000D_
.block {_x000D_
  color: #fff;_x000D_
  height: 300px;_x000D_
  background-color: #00A7F7;_x000D_
  border: 1px solid #005dff;_x000D_
}_x000D_
_x000D_
.block h3 {_x000D_
  line-height: 300px;_x000D_
  text-align: center;_x000D_
}
_x000D_
<!-- Min. responsive 180px -->_x000D_
<div class="container">_x000D_
  <div class="content">_x000D_
    <div class="left_sidebar">_x000D_
      <aside class="block">_x000D_
        <h3>Content</h3>_x000D_
      </aside>_x000D_
      <!-- begin Widget Facebook_x000D_
    ========================================= -->_x000D_
      <aside class="widget--facebook--container">_x000D_
        <div class="widget-facebook">_x000D_
          <iframe id="facebook_iframe" class="facebook_iframe"></iframe>_x000D_
        </div>_x000D_
      </aside>_x000D_
      <!-- end Widget Facebook_x000D_
      ========================================= -->_x000D_
      <aside class="block">_x000D_
        <h3>Content</h3>_x000D_
      </aside>_x000D_
    </div>_x000D_
    <div class="main_content">_x000D_
      <h1>Responsive width Facebook Page Plugin</h1>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

2). Javascript code is written in HTML:

Codepen

_x000D_
_x000D_
@import url('https://fonts.googleapis.com/css?family=Indie+Flower');_x000D_
body {_x000D_
  font-family: 'Indie Flower', cursive;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  max-width: 1170px;_x000D_
  width: 100%;_x000D_
  margin-left: auto;_x000D_
  margin-right: auto;_x000D_
}_x000D_
_x000D_
.content {_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
.left_sidebar {_x000D_
  position: relative;_x000D_
  float: left;_x000D_
  width: 30%;_x000D_
  max-width: 300px;_x000D_
}_x000D_
_x000D_
.main_content {_x000D_
  position: relative;_x000D_
  float: left;_x000D_
  width: 70%;_x000D_
  background-color: #DDEFF7;_x000D_
}_x000D_
_x000D_
_x000D_
/* ------- begin Widget Facebook -------------- */_x000D_
_x000D_
.widget--facebook--container {_x000D_
  padding: 10px;_x000D_
  border: 1px solid #000;_x000D_
}_x000D_
_x000D_
.widget-facebook {_x000D_
  height: 500px;_x000D_
}_x000D_
_x000D_
.widget-facebook .facebook_iframe {_x000D_
  border: none;_x000D_
}_x000D_
_x000D_
_x000D_
/* ---------- end Widget Facebook---------------- */_x000D_
_x000D_
_x000D_
/* ----------------- no need -------------------- */_x000D_
_x000D_
.block {_x000D_
  color: #fff;_x000D_
  height: 300px;_x000D_
  background-color: #00A7F7;_x000D_
  border: 1px solid #005dff;_x000D_
}_x000D_
_x000D_
.block h3 {_x000D_
  line-height: 300px;_x000D_
  text-align: center;_x000D_
}
_x000D_
<!-- Vanilla JS -->_x000D_
<!-- Min. responsive 180px -->_x000D_
<div class="container">_x000D_
  <div class="content">_x000D_
    <div class="left_sidebar">_x000D_
      <aside class="block">_x000D_
        <h3>Content</h3>_x000D_
      </aside>_x000D_
      <!-- begin Widget Facebook_x000D_
      ========================================= -->_x000D_
      <aside class="widget--facebook--container">_x000D_
        <div class="widget-facebook">_x000D_
          <script>_x000D_
            function setupFBframe(frame) {_x000D_
              if (frame.src) return; // already set up_x000D_
_x000D_
              var container = frame.parentNode;_x000D_
              console.log(frame.parentNode);_x000D_
_x000D_
              var containerWidth = container.offsetWidth;_x000D_
              var containerHeight = container.offsetHeight;_x000D_
_x000D_
              var src =_x000D_
                "https://www.facebook.com/plugins/page.php" +_x000D_
                "?href=https%3A%2F%2Fwww.facebook.com%2Ffacebook" +_x000D_
                "&tabs=timeline" +_x000D_
                "&width=" +_x000D_
                containerWidth +_x000D_
                "&height=" +_x000D_
                containerHeight +_x000D_
                "&small_header=false" +_x000D_
                "&adapt_container_width=false" +_x000D_
                "&hide_cover=true" +_x000D_
                "&hide_cta=true" +_x000D_
                "&show_facepile=true" +_x000D_
                "&appId";_x000D_
_x000D_
              frame.width = containerWidth;_x000D_
              frame.height = containerHeight;_x000D_
              frame.src = src;_x000D_
            }_x000D_
_x000D_
            var facebookIframe;_x000D_
_x000D_
            /* begin Window Resize                                _x000D_
            ############################################ */_x000D_
_x000D_
            // Why resizeThrottler? See more : https://developer.mozilla.org/ru/docs/Web/Events/resize_x000D_
            (function() {_x000D_
              window.addEventListener("resize", resizeThrottler, false);_x000D_
_x000D_
              var resizeTimeout;_x000D_
_x000D_
              function resizeThrottler() {_x000D_
                if (!resizeTimeout) {_x000D_
                  resizeTimeout = setTimeout(function() {_x000D_
                    resizeTimeout = null;_x000D_
                    actualResizeHandler();_x000D_
                  }, 66);_x000D_
                }_x000D_
              }_x000D_
_x000D_
              function actualResizeHandler() {_x000D_
                document.querySelector('#facebook_iframe').removeAttribute('src');_x000D_
                setupFBframe(facebookIframe);_x000D_
              }_x000D_
            })();_x000D_
            /* end Window Resize_x000D_
            ############################################ */_x000D_
          </script>_x000D_
          <iframe id="facebook_iframe" class="facebook_iframe" onload="facebookIframe = this; setupFBframe(facebookIframe)"></iframe>_x000D_
        </div>_x000D_
      </aside>_x000D_
      <!-- end Widget Facebook_x000D_
      ========================================= -->_x000D_
      <aside class="block">_x000D_
        <h3>Content</h3>_x000D_
      </aside>_x000D_
    </div>_x000D_
    <div class="main_content">_x000D_
      <h1>Responsive width Facebook Page Plugin</h1>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Thanks storsoc!

All the best to you all and have a nice day!

How to get a list of MySQL views?

SHOW FULL TABLES IN database_name WHERE TABLE_TYPE LIKE 'VIEW';

MySQL query to find all views in a database

Taking screenshot on Emulator from Android Studio

Besides using Android Studio, you can also take a screenshot with adb which is faster.

adb shell screencap -p /sdcard/screen.png
adb pull /sdcard/screen.png
adb shell rm /sdcard/screen.png

Shorter one line alternative in Unix/OSX

adb shell screencap -p | perl -pe 's/\x0D\x0A/\x0A/g' > screen.png

Original blog post: Grab Android screenshot to computer via ADB

where is gacutil.exe?

gacutil comes with Visual Studio, not with VSTS. It is part of Windows SDK and can be download separately at http://www.microsoft.com/downloads/details.aspx?FamilyId=F26B1AA4-741A-433A-9BE5-FA919850BDBF&displaylang=en . This installation will have gacutil.exe included. But first check it here

C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin

you might have it installed.

As @devi mentioned

If you decide to grab gacutil files from existing installation, note that from .NET 4.0 is three files: gacutil.exe gacutil.exe.config and 1033/gacutlrc.dll

Java 8 stream reverse order

General Question:

Stream does not store any elements.

So iterating elements in the reverse order is not possible without storing the elements in some intermediate collection.

Stream.of("1", "2", "20", "3")
      .collect(Collectors.toCollection(ArrayDeque::new)) // or LinkedList
      .descendingIterator()
      .forEachRemaining(System.out::println);

Update: Changed LinkedList to ArrayDeque (better) see here for details

Prints:

3

20

2

1

By the way, using sort method is not correct as it sorts, NOT reverses (assuming stream may have unordered elements)

Specific Question:

I found this simple, easier and intuitive(Copied @Holger comment)

IntStream.iterate(to - 1, i -> i - 1).limit(to - from)

Embed a PowerPoint presentation into HTML

Try PowerPoint ActiveX 2.4. This is an ActiveX component that embeds PowerPoint into an OCX.

Since you are using just Internet Explorer 6 and Internet Explorer 7 you can embed this component into the HTML.

How do I find where JDK is installed on my windows machine?

I have improved munsingh's answer above by testing for the registry key in 64-bit and 32-bit registries, if needed:

::- Test for the registry location  
SET VALUE=CurrentVersion
SET KEY_1="HKLM\SOFTWARE\JavaSoft\Java Development Kit"
SET KEY_2=HKLM\SOFTWARE\JavaSoft\JDK
SET REG_1=reg.exe
SET REG_2="C:\Windows\sysnative\reg.exe"
SET REG_3="C:\Windows\syswow64\reg.exe"

SET KEY=%KEY_1%
SET REG=%REG_1%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value

SET KEY=%KEY_2%
SET REG=%REG_1%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value

::- %REG_2% is for 64-bit installations, using "C:\Windows\sysnative"
SET KEY=%KEY_1%
SET REG=%REG_2%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value

SET KEY=%KEY_2%
SET REG=%REG_2%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value

::- %REG_3% is for 32-bit installations on a 64-bit system, using "C:\Windows\syswow64"
SET KEY=%KEY_1%
SET REG=%REG_3%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value

SET KEY=%KEY_2%
SET REG=%REG_3%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value

:_set_value
FOR /F "tokens=2,*" %%a IN ('%REG% QUERY %KEY% /v %VALUE%') DO (
    SET JDK_VERSION=%%b
)
SET KEY=%KEY%\%JDK_VERSION%
SET VALUE=JavaHome
FOR /F "tokens=2,*" %%a IN ('%REG% QUERY %KEY% /v %VALUE%') DO (
    SET JAVAHOME=%%b
)
ECHO "%JAVAHOME%"
::- SETX JAVA_HOME "%JAVAHOME%"

reference for access to the 64-bit registry

Python read-only property

That's my workaround.

@property
def language(self):
    return self._language
@language.setter
def language(self, value):
    # WORKAROUND to get a "getter-only" behavior
    # set the value only if the attribute does not exist
    try:
        if self.language == value:
            pass
        print("WARNING: Cannot set attribute \'language\'.")
    except AttributeError:
        self._language = value

Migration: Cannot add foreign key constraint

In my case it did not work until I ran the command

composer dump-autoload

that way you can leave the foreign keys inside the create Schema

public function up()
{
    //
     Schema::create('priorities', function($table) {
        $table->increments('id', true);
        $table->integer('user_id');
        $table->foreign('user_id')->references('id')->on('users');
        $table->string('priority_name');
        $table->smallInteger('rank');
        $table->text('class');
        $table->timestamps('timecreated');
    });
 }

 /**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    //
    Schema::drop('priorities');
}

Case statement in MySQL

Yes, something like this:

SELECT
    id,
    action_heading,
    CASE
        WHEN action_type = 'Income' THEN action_amount
        ELSE NULL
    END AS income_amt,
    CASE
        WHEN action_type = 'Expense' THEN action_amount
        ELSE NULL
    END AS expense_amt

FROM tbl_transaction;

As other answers have pointed out, MySQL also has the IF() function to do this using less verbose syntax. I generally try to avoid this because it is a MySQL-specific extension to SQL that isn't generally supported elsewhere. CASE is standard SQL and is much more portable across different database engines, and I prefer to write portable queries as much as possible, only using engine-specific extensions when the portable alternative is considerably slower or less convenient.

LOAD DATA INFILE Error Code : 13

CentOS 7+ Minimal Secure Solution: (should work with RedHat too)

chcon -Rv --type=mysqld_db_t /YOUR/PATH/

Explanation:

Knowing that you applied the good practice of using secure-file-priv=/YOUR/PATH/ in my.cnf in order to use load data infile sql statement, you still see the following:

ERROR 13 (HY000): Can't get stat of '/YOUR/PATH/FILE.EXT' (Errcode: 13 "Permission denied")

That's caused by SELinux Enforcing mode, it's not secure to change the mode to Permissive or disable SELinux.
In short,

chcon change SELinux security context of a file or files/directories in a similar way to how 'chown' or 'chmod' may be used to change the ownership or standard file permissions of a file.

SELinux Enforcing mode prevents mysqld from accessing directories with secure-context-type default_t, hence we need to change the secure-context-type of our path to mysqld_db_t. To see the current secure-context-type use the command:

ls --directory --scontext /YOUR/PATH/

In case you want to reset/undo the solution, then apply below command:

restorecon -Rv /YOUR/PATH/

The solution I shared is referenced in below links:

https://wiki.centos.org/HowTos/SELinux
https://mariadb.com/kb/en/selinux/
https://linux.die.net/man/8/mysqld_selinux

PHP, pass array through POST

Why are you sending it through a post if you already have it on the server (PHP) side?

Why not just save the array to s $_SESSION variable so you can use it when the form gets submitted, that might make it more "secure" since then the client cannot change the variables by editing the source.

It all depends on what you really want to do.

Common elements comparison between 2 lists

>>> list1 = [1,2,3,4,5,6]
>>> list2 = [3, 5, 7, 9]
>>> list(set(list1).intersection(list2))
[3, 5]

How can my iphone app detect its own version number?

If you need a combination of both version and build num, here's a short way using Swift 3:

let appVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"]!
let buildNum = Bundle.main.infoDictionary!["CFBundleVersion"]!
let versionInfo = "\(appVersion) (build \(buildNum))"
// versionInfo is now something like "2.3.0 (build 17)"

Add an as! String to the end of either the appVersion or buildNum line to get only that portion as a String object. No need for that though if you're looking for the full versionInfo.

I hope this helps!

Trigger event on body load complete js/jquery

$(document).ready(function() {
    // do needed things
});

This will trigger once the DOM structure is ready.

When to use static methods

Static: Obj.someMethod

Use static when you want to provide class level access to a method, i.e. where the method should be callable without an instance of the class.

git recover deleted file where no commit was made after the delete

You've staged the deletion so you need to do:

git checkout HEAD cc.properties store/README store/cc.properties

git checkout . only checks out from the index where the deletion has already been staged.

Creating C formatted strings (not printing them)

I haven't done this, so I'm just going to point at the right answer.

C has provisions for functions that take unspecified numbers of operands, using the <stdarg.h> header. You can define your function as void log_out(const char *fmt, ...);, and get the va_list inside the function. Then you can allocate memory and call vsprintf() with the allocated memory, format, and va_list.

Alternately, you could use this to write a function analogous to sprintf() that would allocate memory and return the formatted string, generating it more or less as above. It would be a memory leak, but if you're just logging out it may not matter.

How do I format date in jQuery datetimepicker?

You can use the format option, as described in the documentation

$("#timePicker").datetimepicker({
  format: 'Y-m-d H:i'
});

Changing :hover to touch/click for mobile devices

I got the same trouble, in mobile device with Microsoft's Edge browser. I can solve the problem with: aria-haspopup="true". It need to add to the div and the :hover, :active, :focus for the other mobile browsers.

Example html:

<div class="left_bar" aria-haspopup="true">

CSS:

.left_bar:hover, .left_bar:focus, .left_bar:active{
    left: 0%;
    }

How to declare a type as nullable in TypeScript?

type MyProps = {
  workoutType: string | null;
};

Adding null values to arraylist

Yes, you can always use null instead of an object. Just be careful because some methods might throw error.

It would be 1.

also nulls would be factored in in the for loop, but you could use

 for(Item i : itemList) {
        if (i!= null) {
               //code here
        }
 }

No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. when updating to Support Library 26.0.0

when you try to change targetSDKVersion 26 to 25 that time occurred i was found solution of No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. when updating to Support Library 26.0.0

Just Chage This code from Your Build.gradle

configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support') {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion '26.0.1'
            }
        }
    }
}

to

configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support') {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion '25.2.0'
            }
        }
    }
}

Using FileUtils in eclipse

I have come accross the above issue. I have solved it as below. Its working fine for me.

  1. Download the 'org.apache.commons.io.jar' file on navigating to [org.apache.commons.io.FileUtils] [ http://www.java2s.com/Code/Jar/o/Downloadorgapachecommonsiojar.htm ]

  2. Extract the downloaded zip file to a specified folder.

  3. Update the project properties by using below navigation Right click on project>Select Properties>Select Java Build Path> Click Libraries tab>Click Add External Class Folder button>Select the folder where zip file is extracted for org.apache.commons.io.FileUtils.zip file.

  4. Now access the File Utils.

How do I copy a version of a single file from one git branch to another?

Following madlep's answer you can also just copy one directory from another branch with the directory blob.

git checkout other-branch app/**

As to the op's question if you've only changed one file in there this will work fine ^_^

How do you divide each element in a list by an int?

The abstract version can be:

import numpy as np
myList = [10, 20, 30, 40, 50, 60, 70, 80, 90]
myInt = 10
newList  = np.divide(myList, myInt)

ViewPager and fragments — what's the right way to store fragment's state?

What is that BasePagerAdapter? You should use one of the standard pager adapters -- either FragmentPagerAdapter or FragmentStatePagerAdapter, depending on whether you want Fragments that are no longer needed by the ViewPager to either be kept around (the former) or have their state saved (the latter) and re-created if needed again.

Sample code for using ViewPager can be found here

It is true that the management of fragments in a view pager across activity instances is a little complicated, because the FragmentManager in the framework takes care of saving the state and restoring any active fragments that the pager has made. All this really means is that the adapter when initializing needs to make sure it re-connects with whatever restored fragments there are. You can look at the code for FragmentPagerAdapter or FragmentStatePagerAdapter to see how this is done.

how to loop through rows columns in excel VBA Macro

Try this:

Create A Macro with the following thing inside:

Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(-1, 1).Select
Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(0, -1).Select

That particular macro will copy the current cell (place your cursor in the VOL cell you wish to copy) down one row and then copy the CAP cell also.

This is only a single loop so you can automate copying VOL and CAP of where your current active cell (where your cursor is) to down 1 row.

Just put it inside a For loop statement to do it x number of times. like:

For i = 1 to 100 'Do this 100 times
    Selection.Copy
    ActiveCell.Offset(1, 0).Select
    ActiveSheet.Paste
    ActiveCell.Offset(-1, 1).Select
    Selection.Copy
    ActiveCell.Offset(1, 0).Select
    ActiveSheet.Paste
    ActiveCell.Offset(0, -1).Select
Next i

Can I set max_retries for requests.request?

This will not only change the max_retries but also enable a backoff strategy which makes requests to all http:// addresses sleep for a period of time before retrying (to a total of 5 times):

import requests
from urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter

s = requests.Session()

retries = Retry(total=5,
                backoff_factor=0.1,
                status_forcelist=[ 500, 502, 503, 504 ])

s.mount('http://', HTTPAdapter(max_retries=retries))

s.get('http://httpstat.us/500')

As per documentation for Retry: if the backoff_factor is 0.1, then sleep() will sleep for [0.1s, 0.2s, 0.4s, ...] between retries. It will also force a retry if the status code returned is 500, 502, 503 or 504.

Various other options to Retry allow for more granular control:

  • total – Total number of retries to allow.
  • connect – How many connection-related errors to retry on.
  • read – How many times to retry on read errors.
  • redirect – How many redirects to perform.
  • method_whitelist – Set of uppercased HTTP method verbs that we should retry on.
  • status_forcelist – A set of HTTP status codes that we should force a retry on.
  • backoff_factor – A backoff factor to apply between attempts.
  • raise_on_redirect – Whether, if the number of redirects is exhausted, to raise a MaxRetryError, or to return a response with a response code in the 3xx range.
  • raise_on_status – Similar meaning to raise_on_redirect: whether we should raise an exception, or return a response, if status falls in status_forcelist range and retries have been exhausted.

NB: raise_on_status is relatively new, and has not made it into a release of urllib3 or requests yet. The raise_on_status keyword argument appears to have made it into the standard library at most in python version 3.6.

To make requests retry on specific HTTP status codes, use status_forcelist. For example, status_forcelist=[503] will retry on status code 503 (service unavailable).

By default, the retry only fires for these conditions:

  • Could not get a connection from the pool.
  • TimeoutError
  • HTTPException raised (from http.client in Python 3 else httplib). This seems to be low-level HTTP exceptions, like URL or protocol not formed correctly.
  • SocketError
  • ProtocolError

Notice that these are all exceptions that prevent a regular HTTP response from being received. If any regular response is generated, no retry is done. Without using the status_forcelist, even a response with status 500 will not be retried.

To make it behave in a manner which is more intuitive for working with a remote API or web server, I would use the above code snippet, which forces retries on statuses 500, 502, 503 and 504, all of which are not uncommon on the web and (possibly) recoverable given a big enough backoff period.

EDITED: Import Retry class directly from urllib3.

How do I build a graphical user interface in C++?

It's easy to create a .NET Windows GUI in C++.

See the following tutorial from MSDN. You can download everything you need (Visual C++ Express) for free.

Of course you tie yourself to .NET, but if you're just playing around or only need a Windows application you'll be fine (most people still have Windows...for now).

What's the best way to parse command line arguments?

consoleargs deserves to be mentioned here. It is very easy to use. Check it out:

from consoleargs import command

@command
def main(url, name=None):
  """
  :param url: Remote URL 
  :param name: File name
  """
  print """Downloading url '%r' into file '%r'""" % (url, name)

if __name__ == '__main__':
  main()

Now in console:

% python demo.py --help
Usage: demo.py URL [OPTIONS]

URL:    Remote URL 

Options:
    --name -n   File name

% python demo.py http://www.google.com/
Downloading url ''http://www.google.com/'' into file 'None'

% python demo.py http://www.google.com/ --name=index.html
Downloading url ''http://www.google.com/'' into file ''index.html''

How to avoid pressing Enter with getchar() for reading a single character only?

On a linux system, you can modify terminal behaviour using the stty command. By default, the terminal will buffer all information until Enter is pressed, before even sending it to the C program.

A quick, dirty, and not-particularly-portable example to change the behaviour from within the program itself:

#include<stdio.h>
#include<stdlib.h>

int main(void){
  int c;
  /* use system call to make terminal send all keystrokes directly to stdin */
  system ("/bin/stty raw");
  while((c=getchar())!= '.') {
    /* type a period to break out of the loop, since CTRL-D won't work raw */
    putchar(c);
  }
  /* use system call to set terminal behaviour to more normal behaviour */
  system ("/bin/stty cooked");
  return 0;
}

Please note that this isn't really optimal, since it just sort of assumes that stty cooked is the behaviour you want when the program exits, rather than checking what the original terminal settings were. Also, since all special processing is skipped in raw mode, many key sequences (such as CTRL-C or CTRL-D) won't actually work as you expect them to without explicitly processing them in the program.

You can man stty for more control over the terminal behaviour, depending exactly on what you want to achieve.

MySQL query finding values in a comma separated string

The classic way would be to add commas to the left and right:

select * from shirts where CONCAT(',', colors, ',') like '%,1,%'

But find_in_set also works:

select * from shirts where find_in_set('1',colors) <> 0

java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

I have had the same problem in my project. I used an IntelliJ Idea 14 and Maven 8. And what I've noticed is that when I added a tomcat destination to to IDE it automaticly linked two jars from tomcat lib directory, they were servlet-api and jsp-api. Also I had them in my pom.xml. I killed a whole day trying to figure out why I'm getting java.lang.ClassNotFoundException: org.apache.jsp.index_jsp. And kewpiedoll99 is right. That is because there are dependency conflicts. When I added provided to those two jars in my pom.xml I found a happiness :)

Pandas df.to_csv("file.csv" encode="utf-8") still gives trash characters for minus sign

Your "bad" output is UTF-8 displayed as CP1252.

On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:

df.to_csv('file.csv',encoding='utf-8-sig')

That encoder will add the BOM.

Remove spaces from std::string in C++

I'm afraid it's the best solution that I can think of. But you can use reserve() to pre-allocate the minimum required memory in advance to speed up things a bit. You'll end up with a new string that will probably be shorter but that takes up the same amount of memory, but you'll avoid reallocations.

EDIT: Depending on your situation, this may incur less overhead than jumbling characters around.

You should try different approaches and see what is best for you: you might not have any performance issues at all.

Specifying row names when reading in a file

If you used read.table() (or one of it's ilk, e.g. read.csv()) then the easy fix is to change the call to:

read.table(file = "foo.txt", row.names = 1, ....)

where .... are the other arguments you needed/used. The row.names argument takes the column number of the data file from which to take the row names. It need not be the first column. See ?read.table for details/info.

If you already have the data in R and can't be bothered to re-read it, or it came from another route, just set the rownames attribute and remove the first variable from the object (assuming obj is your object)

rownames(obj) <- obj[, 1]  ## set rownames
obj <- obj[, -1]           ## remove the first variable

StringStream in C#

Since your Print() method presumably deals with Text data, could you rewrite it to accept a TextWriter parameter?

The library provides a StringWriter: TextWriter but not a StringStream. I suppose you could create one by wrapping a MemoryStream, but is it really necessary?


After the Update:

void Main() 
{
  string myString;  // outside using

  using (MemoryStream stream = new MemoryStream ())
  {
     Print(stream);
     myString = Encoding.UTF8.GetString(stream.ToArray());
  }
  ... 

}

You may want to change UTF8 to ASCII, depending on the encoding used by Print().

How to show all privileges from a user in oracle?

There are various scripts floating around that will do that depending on how crazy you want to get. I would personally use Pete Finnigan's find_all_privs script.

If you want to write it yourself, the query gets rather challenging. Users can be granted system privileges which are visible in DBA_SYS_PRIVS. They can be granted object privileges which are visible in DBA_TAB_PRIVS. And they can be granted roles which are visible in DBA_ROLE_PRIVS (roles can be default or non-default and can require a password as well, so just because a user has been granted a role doesn't mean that the user can necessarily use the privileges he acquired through the role by default). But those roles can, in turn, be granted system privileges, object privileges, and additional roles which can be viewed by looking at ROLE_SYS_PRIVS, ROLE_TAB_PRIVS, and ROLE_ROLE_PRIVS. Pete's script walks through those relationships to show all the privileges that end up flowing to a user.

Unix - copy contents of one directory to another

Try this:

cp Folder1/* Folder2/

How to query first 10 rows and next time query other 10 rows from table

for first 10 rows...

SELECT * FROM msgtable WHERE cdate='18/07/2012' LIMIT 0,10

for next 10 rows

SELECT * FROM msgtable WHERE cdate='18/07/2012' LIMIT 10,10

Correct way to use get_or_create?

get_or_create returns a tuple.

customer.source, created = Source.objects.get_or_create(name="Website")

How to style a JSON block in Github Wiki?

I encountered the same problem. So, I tried representing the JSON in different Language syntax formats.But all time favorites are Perl, js, python, & elixir.

This is how it looks.

The following screenshots are from the Gitlab in a markdown file. This may vary based on the colors using for syntax in MARKDOWN files.

JsonasPerl

JsonasPython

JsonasJs

JsonasElixir

How to solve error "Missing `secret_key_base` for 'production' environment" (Rails 4.1)

Add config/secrets.yml to version control and deploy again. You might need to remove a line from .gitignore so that you can commit the file.

I had this exact same issue and it just turned out that the boilerplate .gitignore Github created for my Rails application included config/secrets.yml.

Padding characters in printf

This one is even simpler and execs no external commands.

$ PROC_NAME="JBoss"
$ PROC_STATUS="UP"
$ printf "%-.20s [%s]\n" "${PROC_NAME}................................" "$PROC_STATUS"

JBoss............... [UP]

How to remove all white spaces from a given text file

Much simpler to my opinion:

sed -r 's/\s+//g' filename

How to pass arguments to addEventListener listener function?

someVar value should be accessible only in some_function() context, not from listener's. If you like to have it within listener, you must do something like:

someObj.addEventListener("click",
                         function(){
                             var newVar = someVar;
                             some_function(someVar);
                         },
                         false);

and use newVar instead.

The other way is to return someVar value from some_function() for using it further in listener (as a new local var):

var someVar = some_function(someVar);

Pretty Printing a pandas dataframe

I've just found a great tool for that need, it is called tabulate.

It prints tabular data and works with DataFrame.

from tabulate import tabulate
import pandas as pd

df = pd.DataFrame({'col_two' : [0.0001, 1e-005 , 1e-006, 1e-007],
                   'column_3' : ['ABCD', 'ABCD', 'long string', 'ABCD']})
print(tabulate(df, headers='keys', tablefmt='psql'))

+----+-----------+-------------+
|    |   col_two | column_3    |
|----+-----------+-------------|
|  0 |    0.0001 | ABCD        |
|  1 |    1e-05  | ABCD        |
|  2 |    1e-06  | long string |
|  3 |    1e-07  | ABCD        |
+----+-----------+-------------+

Note:

To suppress row indices for all types of data, pass showindex="never" or showindex=False.

How to run a program automatically as admin on Windows 7 at startup?

You need to plug it into the task scheduler, such that it is launched after login of a user, using a user account that has administrative access on the system, with the highest privileges that are afforded to processes launched by that account.

This is the implementation that is used to autostart processes with administrative privileges when logging in as an ordinary user.

I've used it to launch the 'OpenVPN GUI' helper process which needs elevated privileges to work correctly, and thus would not launch properly from the registry key.

From the command line, you can create the task from an XML description of what you want to accomplish; so for example we have this, exported from my system, which would start notepad with the highest privileges when i log in:

<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2015-01-27T18:30:34</Date>
    <Author>Pete</Author>
  </RegistrationInfo>
  <Triggers>
    <LogonTrigger>
      <StartBoundary>2015-01-27T18:30:00</StartBoundary>
      <Enabled>true</Enabled>
    </LogonTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>CHUMBAWUMBA\Pete</UserId>
      <LogonType>InteractiveToken</LogonType>
      <RunLevel>HighestAvailable</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>"c:\windows\system32\notepad.exe"</Command>
    </Exec>
  </Actions>
</Task>

and it's registered by an administrator command prompt using:

schtasks /create /tn "start notepad on login" /xml startnotepad.xml

this answer should really be moved over to one of the other stackexchange sites, as it's not actually a programming question per se.

Excel VBA: function to turn activecell to bold

A UDF will only return a value it won't allow you to change the properties of a cell/sheet/workbook. Move your code to a Worksheet_Change event or similar to change properties.

Eg

Private Sub worksheet_change(ByVal target As Range)
  target.Font.Bold = True
End Sub

Delete keychain items when an app is uninstalled

@amro's answer translated to Swift 4.0:

if UserDefaults.standard.object(forKey: "FirstInstall") == nil {
    UserDefaults.standard.set(false, forKey: "FirstInstall")
    UserDefaults.standard.synchronize()
}

Default argument values in JavaScript functions

You have to check if the argument is undefined:

function func(a, b) {
    if (a === undefined) a = "default value";
    if (b === undefined) b = "default value";
}

Also note that this question has been answered before.

How do I remove objects from an array in Java?

You can always do:

int i, j;
for (i = j = 0; j < foo.length; ++j)
  if (!"a".equals(foo[j])) foo[i++] = foo[j];
foo = Arrays.copyOf(foo, i);

javac: file not found: first.java Usage: javac <options> <source files>

I had the same issue and it was to do with my file name. If you set the file location using CD in CMD, and then type DIR it will list the files in that directory. Check that the file name appears and check that the spelling and filename ending is correct.

It should be .java but mine was .java.txt. The instructions on the Java tutorials website state that you should select "Save as Type Text Documents" but for me that always adds .txt onto the end of the file name. If I change it to "Save as Type All Documents" it correctly saved the file name.

CMD DIR Example

Repeat each row of data.frame the number of times specified in a column

Use expandRows() from the splitstackshape package:

library(splitstackshape)
expandRows(df, "freq")

Simple syntax, very fast, works on data.frame or data.table.

Result:

    var1 var2
1      a    d
2      b    e
2.1    b    e
3      c    f
3.1    c    f
3.2    c    f

Are there such things as variables within an Excel formula?

You could define a name for the VLOOKUP part of the formula.

  1. Highlight the cell that contains this formula
  2. On the Insert menu, go Name, and click Define
  3. Enter a name for your variable (e.g. 'Value')
  4. In the Refers To box, enter your VLOOKUP formula: =VLOOKUP(A1,B:B, 1, 0)
  5. Click Add, and close the dialog
  6. In your original formula, replace the VLOOKUP parts with the name you just defined: =IF( Value > 10, Value - 10, Value )

Step (1) is important here: I guess on the second row, you want Excel to use VLOOKUP(A2,B:B, 1, 0), the third row VLOOKUP(A3,B:B, 1, 0), etc. Step (4) achieves this by using relative references (A1 and B:B), not absolute references ($A$1 and $B:$B).

Note:

  1. For newer Excel versions with the ribbon, go to Formulas ribbon -> Define Name. It's the same after that. Also, to use your name, you can do "Use in Formula", right under Define Name, while editing the formula, or else start typing it, and Excel will suggest the name (credits: Michael Rusch)

  2. Shortened steps: 1. Right click a cell and click Define name... 2. Enter a name and the formula which you want to associate with that name/local variable 3. Use variable (credits: Jens Bodal)

Check difference in seconds between two times

I use this to avoid negative interval.

var seconds = (date1< date2)? (date2- date1).TotalSeconds: (date1 - date2).TotalSeconds;

How to use timeit module

import timeit


def oct(x):
   return x*x


timeit.Timer("for x in range(100): oct(x)", "gc.enable()").timeit()

How do I consume the JSON POST data in an Express application

_x000D_
_x000D_
const express = require('express');_x000D_
let app = express();_x000D_
app.use(express.json());
_x000D_
_x000D_
_x000D_

This app.use(express.json) will now let you read the incoming post JSON object

What are enums and why are they useful?

In my experience I have seen Enum usage sometimes cause systems to be very difficult to change. If you are using an Enum for a set of domain-specific values that change frequently, and it has a lot of other classes and components that depend on it, you might want to consider not using an Enum.

For example, a trading system that uses an Enum for markets/exchanges. There are a lot of markets out there and it's almost certain that there will be a lot of sub-systems that need to access this list of markets. Every time you want a new market to be added to your system, or if you want to remove a market, it's possible that everything under the sun will have to be rebuilt and released.

A better example would be something like a product category type. Let's say your software manages inventory for a department store. There are a lot of product categories, and many reasons why this list of categories could change. Managers may want to stock a new product line, get rid of other product lines, and possibly reorganize the categories from time to time. If you have to rebuild and redeploy all of your systems simply because users want to add a product category, then you've taken something that should be simple and fast (adding a category) and made it very difficult and slow.

Bottom line, Enums are good if the data you are representing is very static over time and has a limited number of dependencies. But if the data changes a lot and has a lot of dependencies, then you need something dynamic that isn't checked at compile time (like a database table).

Netbeans installation doesn't find JDK

We managed installation of netbeans 6.8 under windows 8 successfully the following way:

  • Don't execute but unzip netbeans-6.8-ml-windows.exe with 7zip (or other unzipper) in an emtpy folder
  • execute cmd.exe as administrator
  • cd to the folder in which you unzipped the installer
  • execute 'java org.netbeans.installer.Installer'

-> installation executes without any errors

Java: Multiple class declarations in one file

My suggested name for this technique (including multiple top-level classes in a single source file) would be "mess". Seriously, I don't think it's a good idea - I'd use a nested type in this situation instead. Then it's still easy to predict which source file it's in. I don't believe there's an official term for this approach though.

As for whether this actually changes between implementations - I highly doubt it, but if you avoid doing it in the first place, you'll never need to care :)

Node.js global variables

You can just use the global object.

var X = ['a', 'b', 'c'];
global.x = X;

console.log(x);
//['a', 'b', 'c']

What bitrate is used for each of the youtube video qualities (360p - 1080p), in regards to flowplayer?

Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:

                   240p       360p        480p        720p        1080p
Resolution      426 x 240   640 x 360   854x480     1280x720    1920x1080
Video Bitrates                   
Maximum         700 Kbps    1000 Kbps   2000 Kbps   4000 Kbps   6000 Kbps
Recommended     400 Kbps    750 Kbps    1000 Kbps   2500 Kbps   4500 Kbps
Minimum         300 Kbps    400 Kbps    500 Kbps    1500 Kbps   3000 Kbps

It would appear as though this is the case, although the numbers dont sync up to the google table above:

// the bitrates, video width and file names for this clip
      bitrates: [
        { url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
        { url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
        { url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
      ],

use current date as default value for a column

Select Table Column Name where you want to get default value of Current date

 ALTER TABLE 
 [dbo].[Table_Name]
 ADD  CONSTRAINT [Constraint_Name] 
 DEFAULT (getdate()) FOR [Column_Name]

Alter Table Query

Alter TABLE [dbo].[Table_Name](
    [PDate] [datetime] Default GetDate())

Use '=' or LIKE to compare strings in SQL?

To see the performance difference, try this:

SELECT count(*)
FROM master..sysobjects as A
JOIN tempdb..sysobjects as B
on A.name = B.name

SELECT count(*)
FROM master..sysobjects as A
JOIN tempdb..sysobjects as B
on A.name LIKE B.name

Comparing strings with '=' is much faster.

How to implement a FSM - Finite State Machine in Java

You can implement Finite State Machine in two different ways.

Option 1:

Finite State machine with a pre-defined workflow : Recommended if you know all states in advance and state machine is almost fixed without any changes in future

  1. Identify all possible states in your application

  2. Identify all the events in your application

  3. Identify all the conditions in your application, which may lead state transition

  4. Occurrence of an event may cause transitions of state

  5. Build a finite state machine by deciding a workflow of states & transitions.

    e.g If an event 1 occurs at State 1, the state will be updated and machine state may still be in state 1.

    If an event 2 occurs at State 1, on some condition evaluation, the system will move from State 1 to State 2

This design is based on State and Context patterns.

Have a look at Finite State Machine prototype classes.

Option 2:

Behavioural trees: Recommended if there are frequent changes to state machine workflow. You can dynamically add new behaviour without breaking the tree.

enter image description here

The base Task class provides a interface for all these tasks, the leaf tasks are the ones just mentioned, and the parent tasks are the interior nodes that decide which task to execute next.

The Tasks have only the logic they need to actually do what is required of them, all the decision logic of whether a task has started or not, if it needs to update, if it has finished with success, etc. is grouped in the TaskController class, and added by composition.

The decorators are tasks that “decorate” another class by wrapping over it and giving it additional logic.

Finally, the Blackboard class is a class owned by the parent AI that every task has a reference to. It works as a knowledge database for all the leaf tasks

Have a look at this article by Jaime Barrachina Verdia for more details

How to save a new sheet in an existing excel file, using Pandas?

A simple example for writing multiple data to excel at a time. And also when you want to append data to a sheet on a written excel file (closed excel file).

When it is your first time writing to an excel. (Writing "df1" and "df2" to "1st_sheet" and "2nd_sheet")

import pandas as pd 
from openpyxl import load_workbook

df1 = pd.DataFrame([[1],[1]], columns=['a'])
df2 = pd.DataFrame([[2],[2]], columns=['b'])
df3 = pd.DataFrame([[3],[3]], columns=['c'])

excel_dir = "my/excel/dir"

with pd.ExcelWriter(excel_dir, engine='xlsxwriter') as writer:    
    df1.to_excel(writer, '1st_sheet')   
    df2.to_excel(writer, '2nd_sheet')   
    writer.save()    

After you close your excel, but you wish to "append" data on the same excel file but another sheet, let's say "df3" to sheet name "3rd_sheet".

book = load_workbook(excel_dir)
with pd.ExcelWriter(excel_dir, engine='openpyxl') as writer:
    writer.book = book
    writer.sheets = dict((ws.title, ws) for ws in book.worksheets)    

    ## Your dataframe to append. 
    df3.to_excel(writer, '3rd_sheet')  

    writer.save()     

Be noted that excel format must not be xls, you may use xlsx one.

Warning about `$HTTP_RAW_POST_DATA` being deprecated

; always_populate_raw_post_data = -1 in php.init remove comment of this line .. always_populate_raw_post_data = -1

Drop Down Menu/Text Field in one

You can use the <datalist> tag instead of the <select> tag.

<input list="browsers" name="browser" id="browser">
<datalist id="browsers">
  <option value="Edge">
  <option value="Firefox">
  <option value="Chrome">
  <option value="Opera">
  <option value="Safari">
</datalist>

How to get text with Selenium WebDriver in Python

You can use:

element = driver.find_element_by_class_name("class_name").text

This will return the text within the element and will allow you to verify it after that.

How can you profile a Python script?

When i'm not root on the server, I use lsprofcalltree.py and run my program like this:

python lsprofcalltree.py -o callgrind.1 test.py

Then I can open the report with any callgrind-compatible software, like qcachegrind

iFrame Height Auto (CSS)

You should note that div tag behaves like nothing and just let you to put something in it. It means that if you insert a paragraph with 100 lines of text within a div tag, it shows all the text but its height won't change to contain all the text.

So you have to use a CSS & HTML trick to handle this issue. This trick is very simple. you must use an empty div tag with class="clear" and then you will have to add this class to your CSS. Also note that your have #wrap in your CSS file but you don't have any tag with this id. In summary you have to change you code to something like below:

HTML Code:

    <!-- Change "id" from "container" to "wrap" -->
    <div id="wrap">    
        <div id="header">
        </div>

        <div id="navigation"> 
            <a href="/" class="navigation">home</a>
            <a href="about.php" class="navigation">about</a>
            <a href="fanlisting.php" class="navigation">fanlisting</a>
            <a href="reasons.php" class="navigation">100 reasons</a>
            <a href="letter.php" class="navigation">letter</a>
        </div>
        <div id="content" >
            <h1>Update Information</h1>
            <iframe name="frame" id="frame" src="http://website.org/update.php" allowtransparency="true" frameborder="0"></iframe>

            <!-- Add this line -->
            <div class="clear"></div>
        </div>
        <div id="footer">
        </div>

        <!-- Add this line -->
        <div class="clear"></div>
    </div>

And also add this line to your CSS file:

.clear{ display: block; clear: both;}

What's a "static method" in C#?

The static keyword, when applied to a class, tells the compiler to create a single instance of that class. It is not then possible to 'new' one or more instance of the class. All methods in a static class must themselves be declared static.

It is possible, And often desirable, to have static methods of a non-static class. For example a factory method when creates an instance of another class is often declared static as this means that a particular instance of the class containing the factor method is not required.

For a good explanation of how, when and where see MSDN

mysqli or PDO - what are the pros and cons?

There's one thing to keep in mind.

Mysqli does not support fetch_assoc() function which would return the columns with keys representing column names. Of course it's possible to write your own function to do that, it's not even very long, but I had really hard time writing it (for non-believers: if it seems easy to you, try it on your own some time and don't cheat :) )

Centering a button vertically in table cell, using Twitter Bootstrap

So why is td default set to vertical-align: top;? I really don't know that yet. I would not dare to touch it. Instead add this to your stylesheet. It alters the buttons in the tables.

table .btn{
  vertical-align: top;
}

Uninstall all installed gems, in OSX?

If you like doing it using ruby:

ruby -e "`gem list`.split(/$/).each { |line| puts `gem uninstall -Iax #{line.split(' ')[0]}` unless line.strip.empty? }"

Cheers

How can I list the contents of a directory in Python?

import os
os.listdir("path") # returns list

Reading specific columns from a text file in python

It may help:

import csv
with open('csv_file','r') as f:
    # Printing Specific Part of CSV_file
    # Printing last line of second column
    lines = list(csv.reader(f, delimiter = ' ', skipinitialspace = True))
    print(lines[-1][1])
    # For printing a range of rows except 10 last rows of second column
    for i in range(len(lines)-10):
        print(lines[i][1])

How do I find the mime-type of a file with php?

i got very good results using a user function from http://php.net/manual/de/function.mime-content-type.php @''john dot howard at prismmg dot com 26-Oct-2009 03:43''

function get_mime_type($filename, $mimePath = '../etc') { ...

which doesnt use finfo, exec or deprecated function

works well also with remote ressources!

Decompile Python 2.7 .pyc

Here is a great tool to decompile pyc files.

It was coded by me and supports python 1.0 - 3.3

Its based on uncompyle2 and decompyle++

http://sourceforge.net/projects/easypythondecompiler/

COALESCE Function in TSQL

Here is the way I look at COALESCE...and hopefully it makes sense...

In a simplistic form….

Coalesce(FieldName, 'Empty')

So this translates to…If "FieldName" is NULL, populate the field value with the word "EMPTY".

Now for mutliple values...

Coalesce(FieldName1, FieldName2, Value2, Value3)

If the value in Fieldname1 is null, fill it with the value in Fieldname2, if FieldName2 is NULL, fill it with Value2, etc.

This piece of test code for the AdventureWorks2012 sample database works perfectly & gives a good visual explanation of how COALESCE works:

SELECT Name, Class, Color, ProductNumber,
COALESCE(Class, Color, ProductNumber) AS FirstNotNull
FROM Production.Product

Angular checkbox and ng-click

cardeal's answer was really helpful. Took it a little further and figured it may help others some where down the line. Here is the fiddle:

https://jsfiddle.net/vtL5x0wh/

And the code:

<body ng-app="checkboxExample">
  <script>
  angular.module('checkboxExample', [])
    .controller('ExampleController', ['$scope', function($scope) {

    $scope.value0 = "none";
    $scope.value1 = "none";
    $scope.value2 = "none";
    $scope.value3 = "none";

    $scope.checkboxModel = {
        critical1: {selected: true, id: 'C1', error:'critical' , score:20},
        critical2: {selected: false, id: 'C2', error:'critical' , score:30},
        critical3: {selected: false, id: 'C3', error:'critical' , score:40},

       myClick : function($event) { 
          $scope.value0 = $event.selected;
          $scope.value1 = $event.id;
          $scope.value2 = $event.error;
          $scope.value3 = $event.score;
        }
    };

   }]);
</script>
<form name="myForm" ng-controller="ExampleController">
  <label>


    Value1:
    <input type="checkbox" ng-model="checkboxModel.critical1.selected" ng-change="checkboxModel.myClick(checkboxModel.critical1)">
  </label><br/>
  <label>Value2:
    <input type="checkbox" ng-model="checkboxModel.critical2.selected" ng-change="checkboxModel.myClick(checkboxModel.critical2)">
   </label><br/>
     <label>Value3:
    <input type="checkbox" ng-model="checkboxModel.critical3.selected" ng-change="checkboxModel.myClick(checkboxModel.critical3)">
   </label><br/><br/><br/><br/>
  <tt>selected = {{value0}}</tt><br/>
  <tt>id = {{value1}}</tt><br/>
  <tt>error = {{value2}}</tt><br/>
  <tt>score = {{value3}}</tt><br/>
 </form>

How to detect when a youtube video finishes playing?

This can be done through the youtube player API:

http://jsfiddle.net/7Gznb/

Working example:

    <div id="player"></div>

    <script src="http://www.youtube.com/player_api"></script>

    <script>

        // create youtube player
        var player;
        function onYouTubePlayerAPIReady() {
            player = new YT.Player('player', {
              width: '640',
              height: '390',
              videoId: '0Bmhjf0rKe8',
              events: {
                onReady: onPlayerReady,
                onStateChange: onPlayerStateChange
              }
            });
        }

        // autoplay video
        function onPlayerReady(event) {
            event.target.playVideo();
        }

        // when video ends
        function onPlayerStateChange(event) {        
            if(event.data === 0) {          
                alert('done');
            }
        }

    </script>

How to put/get multiple JSONObjects to JSONArray?

Once you have put the values into the JSONObject then put the JSONObject into the JSONArray staright after.

Something like this maybe:

jsonObj.put("value1", 1);
jsonObj.put("value2", 900);
jsonObj.put("value3", 1368349);
jsonArray.put(jsonObj);

Then create new JSONObject, put the other values into it and add it to the JSONArray:

jsonObj.put("value1", 2);
jsonObj.put("value2", 1900);
jsonObj.put("value3", 136856);
jsonArray.put(jsonObj);

Refresh/reload the content in Div using jquery/ajax

When this method executes, it retrieves the content of location.href, but then jQuery parses the returned document to find the element with divId. This element, along with its contents, is inserted into the element with an ID (divId) of result, and the rest of the retrieved document is discarded.

$("#divId").load(location.href + " #divId>*", "");

hope this may help someone to understand

In PowerShell, how can I test if a variable holds a numeric value?

If you want to check if a string has a numeric value, use this code:

$a = "44.4"
$b = "ad"
$rtn = ""
[double]::TryParse($a,[ref]$rtn)
[double]::TryParse($b,[ref]$rtn)

Credits go here

Android Studio Run/Debug configuration error: Module not specified

If you can't find your settings.gradle file in your project directory

  1. Add settings.gradle file

  2. Add include ':app' inside the settings.gradle file

  3. Rebuild or sync your project

Your app module should appear in your configuration file.

Jenkins Slave port number for firewall

I have a similar scenario, and had no problem connecting after setting the JNLP port as you describe, and adding a single firewall rule allowing a connection on the server using that port. Granted it is a randomly selected client port going to a known server port (a host:ANY -> server:1 rule is needed).

From my reading of the source code, I don't see a way to set the local port to use when making the request from the slave. It's unfortunate, it would be a nice feature to have.

Alternatives:

Use a simple proxy on your client that listens on port N and then does forward all data to the actual Jenkins server on the remote host using a constant local port. Connect your slave to this local proxy instead of the real Jenkins server.

Create a custom Jenkins slave build that allows an option to specify the local port to use.

Remember also if you are using HTTPS via a self-signed certificate, you must alter the configuration jenkins-slave.xml file on the slave to specify the -noCertificateCheck option on the command line.

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive

Just had this in VS 2010.

Fixed by editing the .sln file and changing the TargetFrameworkMoniker to have the value ".NETFramework,Version%3Dv4.0" assigned to it.

How to keep footer at bottom of screen

HTML

<div id="footer"></div>

CSS

#footer {
   position:absolute;
   bottom:0;
   width:100%;
   height:100px;   
   background:blue;//optional
}

Undo a Git merge that hasn't been pushed yet

You can use only two commands to revert a merge or restart by a specific commit:

  1. git reset --hard commitHash (you should use the commit that you want to restart, eg. 44a587491e32eafa1638aca7738)
  2. git push origin HEAD --force (Sending the new local master branch to origin/master)

Good luck and go ahead!

Capturing browser logs with Selenium WebDriver using Java

Driver manager logs can be used to get console logs from browser and it will help to identify errors appears in console.

   import org.openqa.selenium.logging.LogEntries;
   import org.openqa.selenium.logging.LogEntry;

    public List<LogEntry> getBrowserConsoleLogs()
    {
    LogEntries log= driver.manage().logs().get("browser")
    List<LogEntry> logs=log.getAll();
    return logs;
    }

Keeping it simple and how to do multiple CTE in a query

You certainly are able to have multiple CTEs in a single query expression. You just need to separate them with a comma. Here is an example. In the example below, there are two CTEs. One is named CategoryAndNumberOfProducts and the second is named ProductsOverTenDollars.

WITH CategoryAndNumberOfProducts (CategoryID, CategoryName, NumberOfProducts) AS
(
   SELECT
      CategoryID,
      CategoryName,
      (SELECT COUNT(1) FROM Products p
       WHERE p.CategoryID = c.CategoryID) as NumberOfProducts
   FROM Categories c
),

ProductsOverTenDollars (ProductID, CategoryID, ProductName, UnitPrice) AS
(
   SELECT
      ProductID,
      CategoryID,
      ProductName,
      UnitPrice
   FROM Products p
   WHERE UnitPrice > 10.0
)

SELECT c.CategoryName, c.NumberOfProducts,
      p.ProductName, p.UnitPrice
FROM ProductsOverTenDollars p
   INNER JOIN CategoryAndNumberOfProducts c ON
      p.CategoryID = c.CategoryID
ORDER BY ProductName

HTTP Content-Type Header and JSON

The Content-Type header is just used as info for your application. The browser doesn't care what it is. The browser just returns you the data from the AJAX call. If you want to parse it as JSON, you need to do that on your own.

The header is there so your app can detect what data was returned and how it should handle it. You need to look at the header, and if it's application/json then parse it as JSON.

This is actually how jQuery works. If you don't tell it what to do with the result, it uses the Content-Type to detect what to do with it.

Nginx: Permission denied for nginx on Ubuntu

Make sure you are running the test as a superuser.

sudo nginx -t

Or the test wont have all the permissions needed to complete the test properly.

Redirect using AngularJS

Don't forget to inject $location into controller.

Creating InetAddress object in Java

The api is fairly easy to use.

// Lookup the dns, if the ip exists.
 if (!ip.isEmpty()) {
     InetAddress inetAddress = InetAddress.getByName(ip);
     dns = inetAddress.getCanonicalHostName(); 
 }

SQL - IF EXISTS UPDATE ELSE INSERT Syntax Error

In this approach only one statement is executed when the UPDATE is successful.

-- For each row in source
BEGIN TRAN    

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

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

COMMIT

Get all dates between two dates in SQL Server

This can be considered as bit tricky way as in my situation, I can't use a CTE table, so decided to join with sys.all_objects and then created row numbers and added that to start date till it reached the end date.

See the code below where I generated all dates in Jul 2018. Replace hard coded dates with your own variables (tested in SQL Server 2016):

select top (datediff(dd, '2018-06-30', '2018-07-31')) ROW_NUMBER() 
over(order by a.name) as SiNo, 
Dateadd(dd, ROW_NUMBER() over(order by a.name) , '2018-06-30') as Dt from sys.all_objects a

Convert list into a pandas data frame

You need convert list to numpy array and then reshape:

df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

How to get response as String using retrofit without using GSON or any other library in android

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

Example interface --

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

Pass data from Activity to Service using an Intent

This is a much better and secured way. Working like a charm!

   private void startFloatingWidgetService() {
        startService(new Intent(MainActivity.this,FloatingWidgetService.class)
                .setAction(FloatingWidgetService.ACTION_PLAY));
    }

instead of :

 private void startFloatingWidgetService() {
        startService(new Intent(FloatingWidgetService.ACTION_PLAY));
    }

Because when you try 2nd one then you get an error saying : java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.floatingwidgetchathead_demo.SampleService.ACTION_START }

Then your Service be like this :

static final String ACTION_START = "com.floatingwidgetchathead_demo.SampleService.ACTION_START";
    static final String ACTION_PLAY = "com.floatingwidgetchathead_demo.SampleService.ACTION_PLAY";
    static final String ACTION_PAUSE = "com.floatingwidgetchathead_demo.SampleService.ACTION_PAUSE";
    static final String ACTION_DESTROY = "com.yourcompany.yourapp.SampleService.ACTION_DESTROY";

 @SuppressLint("LogConditional")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    String action = intent.getAction();
    //System.out.println("ACTION: "+action);
    switch (action){
        case ACTION_START:
            Log.d(TAG, "onStartCommand: "+action);
            break;
        case ACTION_PLAY:
            Log.d(TAG, "onStartCommand: "+action);
           addRemoveView();
           addFloatingWidgetView();
            break;
        case ACTION_PAUSE:
            Log.d(TAG, "onStartCommand: "+action);
            break;
        case ACTION_DESTROY:
            Log.d(TAG, "onStartCommand: "+action);
            break;
    }
    return START_STICKY;

}

Full width image with fixed height

If you don't want to lose the ratio of your image, then don't bother with height:300px; and just use width:100%;.

If the image is too large, then you will have to crop it using an image editor.

How to append elements at the end of ArrayList in Java?

I ran into a similar problem and just passed the end of the array to the ArrayList.add() index param like so:

public class Stack {

    private ArrayList<String> stringList = new ArrayList<String>();

    RandomStringGenerator rsg = new RandomStringGenerator();

    private void push(){
        String random = rsg.randomStringGenerator();
        stringList.add(stringList.size(), random);
    }

}

How can I increment a date by one day in Java?

It's very simple, trying to explain in a simple word. get the today's date as below

Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime());// print today's date
calendar.add(Calendar.DATE, 1);

Now set one day ahead with this date by calendar.add method which takes (constant, value). Here constant could be DATE, hours, min, sec etc. and value is the value of constant. Like for one day, ahead constant is Calendar.DATE and its value are 1 because we want one day ahead value.

System.out.println(calendar.getTime());// print modified date which is tomorrow's date

Thanks

Understanding Fragment's setRetainInstance(boolean)

setRetaininstance is only useful when your activity is destroyed and recreated due to a configuration change because the instances are saved during a call to onRetainNonConfigurationInstance. That is, if you rotate the device, the retained fragments will remain there(they're not destroyed and recreated.) but when the runtime kills the activity to reclaim resources, nothing is left. When you press back button and exit the activity, everything is destroyed.

Usually I use this function to saved orientation changing Time.Say I have download a bunch of Bitmaps from server and each one is 1MB, when the user accidentally rotate his device, I certainly don't want to do all the download work again.So I create a Fragment holding my bitmaps and add it to the manager and call setRetainInstance,all the Bitmaps are still there even if the screen orientation changes.

Sending HTML email using Python

You might try using my mailer module.

from mailer import Mailer
from mailer import Message

message = Message(From="[email protected]",
                  To="[email protected]")
message.Subject = "An HTML Email"
message.Html = """<p>Hi!<br>
   How are you?<br>
   Here is the <a href="http://www.python.org">link</a> you wanted.</p>"""

sender = Mailer('smtp.example.com')
sender.send(message)

CAML query with nested ANDs and ORs for multiple fields

Since you are not allowed to put more than two conditions in one condition group (And | Or) you have to create an extra nested group (MSDN). The expression A AND B AND C looks like this:

<And>
    A
    <And>
        B
        C
    </And>
</And>

Your SQL like sample translated to CAML (hopefully with matching XML tags ;) ):

<Where>
    <And>
        <Or>
            <Eq>
                <FieldRef Name='FirstName' />
                <Value Type='Text'>John</Value>
            </Eq>
            <Or>
                <Eq>
                    <FieldRef Name='LastName' />
                    <Value Type='Text'>John</Value>
                </Eq>
                <Eq>
                    <FieldRef Name='Profile' />
                    <Value Type='Text'>John</Value>
                </Eq>
            </Or>
        </Or>
        <And>       
            <Or>
                <Eq>
                    <FieldRef Name='FirstName' />
                    <Value Type='Text'>Doe</Value>
                </Eq>
                <Or>
                    <Eq>
                        <FieldRef Name='LastName' />
                        <Value Type='Text'>Doe</Value>
                    </Eq>
                    <Eq>
                        <FieldRef Name='Profile' />
                        <Value Type='Text'>Doe</Value>
                    </Eq>
                </Or>
            </Or>
            <Or>
                <Eq>
                    <FieldRef Name='FirstName' />
                    <Value Type='Text'>123</Value>
                </Eq>
                <Or>
                    <Eq>
                        <FieldRef Name='LastName' />
                        <Value Type='Text'>123</Value>
                    </Eq>
                    <Eq>
                        <FieldRef Name='Profile' />
                        <Value Type='Text'>123</Value>
                    </Eq>
                </Or>
            </Or>
        </And>
    </And>
</Where>

IOCTL Linux device driver

An ioctl, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.

An alternative is the sysfs interface, where you set up a file under /sys/ and read/write that to get information from and to the driver. An example of how to set this up:

static ssize_t mydrvr_version_show(struct device *dev,
        struct device_attribute *attr, char *buf)
{
    return sprintf(buf, "%s\n", DRIVER_RELEASE);
}

static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);

And during driver setup:

device_create_file(dev, &dev_attr_version);

You would then have a file for your device in /sys/, for example, /sys/block/myblk/version for a block driver.

Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl or libnl3 libraries.

Bootstrap combining rows (rowspan)

Check this one. hope it will help full for you.

http://jsfiddle.net/j6amM/

.row-fix { margin-bottom:20px;}

.row-fix > [class*="span"]{ height:100px; background:#f1f1f1;}

.row-fix .two-col{ background:none;}

.two-col > [class*="col"]{ height:40px; background:#ccc;}

.two-col > .col1{margin-bottom:20px;}

How do I import an existing Java keystore (.jks) file into a Java installation?

Ok, so here was my process:

keytool -list -v -keystore permanent.jks - got me the alias.

keytool -export -alias alias_name -file certificate_name -keystore permanent.jks - got me the certificate to import.

Then I could import it with the keytool:

keytool -import -alias alias_name -file certificate_name -keystore keystore location

As @Christian Bongiorno says the alias can't already exist in your keystore.

how to refresh Select2 dropdown menu after ajax loading different content?

Select 3.*

Please see Update select2 data without rebuilding the control as this may be a duplicate. Another way is to destroy and then recreate the select2 element.

$("#dropdown").select2("destroy");

$("#dropdown").select2();

If you are having problems with resetting the state/region on country change try clearing the current value with

$("#dropdown").select2("val", "");

You can view the documentation here http://ivaynberg.github.io/select2/ that outlines nearly/all features. Select2 supports events such as change that can be used to update the subsequent dropdowns.

$("#dropdown").on("change", function(e) {});

Select 4.* Update

You can now update the data/list without rebuilding the control using:

fooBarDropdown.select2({
    data: fromAccountData
});

How to capture no file for fs.readFileSync()?

The JavaScript try…catch mechanism cannot be used to intercept errors generated by asynchronous APIs. A common mistake for beginners is to try to use throw inside an error-first callback:

// THIS WILL NOT WORK:
const fs = require('fs');

try {
  fs.readFile('/some/file/that/does-not-exist', (err, data) => {
    // Mistaken assumption: throwing here...
    if (err) {
      throw err;
    }
  });
} catch (err) {
  // This will not catch the throw!
  console.error(err);
}

This will not work because the callback function passed to fs.readFile() is called asynchronously. By the time the callback has been called, the surrounding code, including the try…catch block, will have already exited. Throwing an error inside the callback can crash the Node.js process in most cases. If domains are enabled, or a handler has been registered with process.on('uncaughtException'), such errors can be intercepted.

reference: https://nodejs.org/api/errors.html

What's the proper way to install pip, virtualenv, and distribute for Python?

I've had various problems (see below) installing upgraded SSL modules, even inside a virtualenv, on top of older OS-provided Python versions, so I now use pyenv.

pyenv makes it very easy to install new Python versions and supports virtualenvs. Getting started is much easier than the recipes for virtualenv listed in other answers:

  • On Mac, type brew install pyenv and on Linux, use pyenv-installer
  • this gets you built-in virtualenv support as well as Python version switching (if required)
  • works well with Python 2 or 3, can have many versions installed at once

This works very well to insulate the "new Python" version and virtualenv from system Python. Because you can easily use a more recent Python (post 2.7.9), the SSL modules are already upgraded, and of course like any modern virtualenv setup you are insulated from the system Python modules.

A couple of nice tutorials:

The pyenv-virtualenv plugin is now built in - type pyenv commands | grep virtualenv to check. I wouldn't use the pyenv-virtualenvwrapper plugin to start with - see how you get on with pyenv-virtualenv which is more integrated into pyenv, as this covers most of what virtualenvwrapper does.

pyenv is modelled on rbenv (a good tool for Ruby version switching) and its only dependency is bash.

  • pyenv is unrelated to the very similarly named pyvenv - that is a virtualenv equivalent that's part of recent Python 3 versions, and doesn't handle Python version switching

Caveats

Two warnings about pyenv:

  1. It only works from a bash or similar shell - or more specifically, the pyenv-virtualenv plugin doesn't like dash, which is /bin/sh on Ubuntu or Debian.
  2. It must be run from an interactive login shell (e.g. bash --login using a terminal), which is not always easy to achieve with automation tools such as Ansible.

Hence pyenv is best for interactive use, and less good for scripting servers.

Older distributions - SSL module problems

One reason to use pyenv was that there were often problems with upgrading Python SSL modules when using older system-provided Python versions. This may be less of a problem now that current Linux distributions support Python 3.x.

Get and Set a Single Cookie with Node.js HTTP Server

You can use the "cookies" npm module, which has a comprehensive set of features.

Documentation and examples at:
https://github.com/jed/cookies

1067 error on attempt to start MySQL

in my case innodb_data_home_dir was no longer correct because I had shuffled some drive letters around when I added a new drive to my system

No module named MySQLdb

I have tried methods above, but still no module named 'MySQLdb', finally, I succeed with

easy_install mysql-python

my env is unbuntu 14.04

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

return, return None, and no return at all?

As other have answered, the result is exactly the same, None is returned in all cases.

The difference is stylistic, but please note that PEP8 requires the use to be consistent:

Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None, and an explicit return statement should be present at the end of the function (if reachable).

Yes:

def foo(x):
    if x >= 0:
        return math.sqrt(x)
    else:
        return None

def bar(x):
    if x < 0:
        return None
    return math.sqrt(x)

No:

def foo(x):
    if x >= 0:
        return math.sqrt(x)

def bar(x):
    if x < 0:
        return
    return math.sqrt(x)

https://www.python.org/dev/peps/pep-0008/#programming-recommendations


Basically, if you ever return non-None value in a function, it means the return value has meaning and is meant to be caught by callers. So when you return None, it must also be explicit, to convey None in this case has meaning, it is one of the possible return values.

If you don't need return at all, you function basically works as a procedure instead of a function, so just don't include the return statement.

If you are writing a procedure-like function and there is an opportunity to return earlier (i.e. you are already done at that point and don't need to execute the remaining of the function) you may use empty an returns to signal for the reader it is just an early finish of execution and the None value returned implicitly doesn't have any meaning and is not meant to be caught (the procedure-like function always returns None anyway).

How do I set up a private Git repository on GitHub? Is it even possible?

Update (2019, latest)

Since Jan 2019, GitHub allows private repositories for up to three collaborators.

Previous answer:

Here is the comparison for free plans listed by tree main Git Cloud based solutions:

Enter image description here

Here is the comparison for paid plans listed by tree main Git Cloud based solutions:

Enter image description here

Conclusion:

I'm not seeing people mentioning GitLab here, but it seems like the best free private plan for me. I myself am using it with no problems.

GitHub: If you have a student account or want to pay for $7 monthly, GitHub has the biggest community and you can take advantage of it's public repositories, forks, etc.

Bitbucket: If you use other products from Atlassian like Jira or Confluence, Bitbucket works great with them.

GitLab: Everything that I care about (free private repository, number of private repositories, number of collaborators, etc.) are offered for free. This seems like the best choice for me.

How can I backup a Docker-container with its data-volumes?

The following command will run tar in a container with all named data volumes mounted, and redirect the output into a file:

docker run --rm `docker volume list -q | egrep -v '^.{64}$' | awk '{print "-v " $1 ":/mnt/" $1}'` alpine tar -C /mnt -cj . > data-volumes.tar.bz2

Make sure to test the resulting archive in case something went wrong:

tar -tjf data-volumes.tar.bz2

Convert Java String to sql.Timestamp

Here's the intended way to convert a String to a Date:

String timestamp = "2011-10-02-18.48.05.123";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-kk.mm.ss.SSS");
Date parsedDate = df.parse(timestamp);

Admittedly, it only has millisecond resolution, but in all services slower than Twitter, that's all you'll need, especially since most machines don't even track down to the actual nanoseconds.

How can I check if a string contains ANY letters from the alphabet?

You can use islower() on your string to see if it contains some lowercase letters (amongst other characters). or it with isupper() to also check if contains some uppercase letters:

below: letters in the string: test yields true

>>> z = "(555) 555 - 5555 ext. 5555"
>>> z.isupper() or z.islower()
True

below: no letters in the string: test yields false.

>>> z= "(555).555-5555"
>>> z.isupper() or z.islower()
False
>>> 

Not to be mixed up with isalpha() which returns True only if all characters are letters, which isn't what you want.

Note that Barm's answer completes mine nicely, since mine doesn't handle the mixed case well.

filename and line number of Python script

Here's what works for me to get the line number in Python 3.7.3 in VSCode 1.39.2 (dmsg is my mnemonic for debug message):

import inspect

def dmsg(text_s):
    print (str(inspect.currentframe().f_back.f_lineno) + '| ' + text_s)

To call showing a variable name_s and its value:

name_s = put_code_here
dmsg('name_s: ' + name_s)

Output looks like this:

37| name_s: value_of_variable_at_line_37

Can you use @Autowired with static fields?

In short, no. You cannot autowire or manually wire static fields in Spring. You'll have to write your own logic to do this.

How to print all session variables currently set?

You could use the following code.

print_r($_SESSION);

How to remove &quot; from my Json in javascript?

Presumably you have it in a variable and are using JSON.parse(data);. In which case, use:

JSON.parse(data.replace(/&quot;/g,'"'));

You might want to fix your JSON-writing script though, because &quot; is not valid in a JSON object.

GIT vs. Perforce- Two VCS will enter... one will leave

The command that sold me on git personally was bisect. I don't think that this feature is available in any other version control system as of now.

That being said, if people are used to a GUI client for source control they are not going to be impressed with git. Right now the only full-featured client is command-line.

Get the ID of a drawable in ImageView

Even easier: just store the R.drawable id in the view's id: use v.setId(). Then get it back with v.getId().

What does this format means T00:00:00.000Z?

As one person may have already suggested,

I passed the ISO 8601 date string directly to moment like so...

`moment.utc('2019-11-03T05:00:00.000Z').format('MM/DD/YYYY')`

or

`moment('2019-11-03T05:00:00.000Z').utc().format('MM/DD/YYYY')`

either of these solutions will give you the same result.

`console.log(moment('2019-11-03T05:00:00.000Z').utc().format('MM/DD/YYYY')) // 11/3/2019`

docker build with --build-arg with multiple arguments

If you want to use environment variable during build. Lets say setting username and password.

username= Ubuntu
password= swed24sw

Dockerfile

FROM ubuntu:16.04
ARG SMB_PASS
ARG SMB_USER
# Creates a new User
RUN useradd -ms /bin/bash $SMB_USER
# Enters the password twice.
RUN echo "$SMB_PASS\n$SMB_PASS" | smbpasswd -a $SMB_USER

Terminal Command

docker build --build-arg SMB_PASS=swed24sw --build-arg SMB_USER=Ubuntu . -t IMAGE_TAG

How to use HTTP_X_FORWARDED_FOR properly?

If you use it in a database, this is a good way:

Set the ip field in database to varchar(250), and then use this:

$theip = $_SERVER["REMOTE_ADDR"];

if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
    $theip .= '('.$_SERVER["HTTP_X_FORWARDED_FOR"].')';
}

if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
    $theip .= '('.$_SERVER["HTTP_CLIENT_IP"].')';
}

$realip = substr($theip, 0, 250);

Then you just check $realip against the database ip field

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

Changing the tmp folder of mysql

You can also set the TMPDIR environment variable.

In some situations (Docker in my case) it's more convenient to set an environment variable than to update a config file.

Bind event to right mouse click

To disable right click context menu on all images of a page simply do this with following:

jQuery(document).ready(function(){
    // Disable context menu on images by right clicking
    for(i=0;i<document.images.length;i++) {
        document.images[i].onmousedown = protect;
    }
});

function protect (e) {
    //alert('Right mouse button not allowed!');
    this.oncontextmenu = function() {return false;};
}

Why does javascript replace only first instance when using replace?

You can use:

String.prototype.replaceAll = function(search, replace) {
if (replace === undefined) {
    return this.toString();
}
return this.split(search).join(replace);
}

How to grant all privileges to root user in MySQL 8.0

1. grant privileges

mysql> GRANT ALL PRIVILEGES ON . TO 'root'@'%'WITH GRANT OPTION;

mysql> FLUSH PRIVILEGES

2. check user table:

mysql> use mysql

mysql> select host,user from user enter image description here

3.Modify the configuration file

mysql default bind ip:127.0.0.1, if we want to remote visit services,just delete config

#Modify the configuration file
vi /usr/local/etc/my.cnf

#Comment out the ip-address option
[mysqld]
# Only allow connections from localhost
#bind-address = 127.0.0.1

4.finally restart the services

brew services restart mysql

Create a HTML table where each TR is a FORM

If all of these rows are related and you need to alter the tabular data ... why not just wrap the entire table in a form, and change GET to POST (unless you know that you're not going to be sending more than the max amount of data a GET request can send).

I cannot wrap the entire table in a form, because some input fields of each row are input type="file" and files may be large. When the user submits the form, I want to POST only fields of current row, not all fields of the all rows which may have unneeded huge files, causing form to submit very slowly.

So, I tried incorrect nesting: tr/form and form/tr. However, it works only when one does not try to add new inputs dynamically into the form. Dynamically added inputs will not belong to incorrectly nested form, thus won't get submitted. (valid form/table dynamically inputs are submitted just fine).

Nesting div[display:table]/form/div[display:table-row]/div[display:table-cell] produced non-uniform widths of grid columns. I managed to get uniform layout when I replaced div[display:table-row] to form[display:table-row] :

div.grid {
    display: table;
}

div.grid > form {
    display: table-row;


div.grid > form > div {
    display: table-cell;
}
div.grid > form > div.head {
    text-align: center;
    font-weight: 800;
}

For the layout to be displayed correctly in IE8:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
...
<meta http-equiv="X-UA-Compatible" content="IE=8, IE=9, IE=10" />

Sample of output:

<div class="grid" id="htmlrow_grid_item">
<form>
    <div class="head">Title</div>
    <div class="head">Price</div>
    <div class="head">Description</div>
    <div class="head">Images</div>
    <div class="head">Stock left</div>
    <div class="head">Action</div>
</form>
<form action="/index.php" enctype="multipart/form-data" method="post">
    <div title="Title"><input required="required" class="input_varchar" name="add_title" type="text" value="" /></div>

It would be much harder to make this code work in IE6/7, however.

How to call getResources() from a class which has no context?

This always works for me:

import android.app.Activity;
import android.content.Context;

public class yourClass {

 Context ctx;

 public yourClass (Handler handler, Context context) {
 super(handler);
    ctx = context;
 }

 //Use context (ctx) in your code like this:
 block1 = new Droid(BitmapFactory.decodeResource(ctx.getResources(), R.drawable.birdpic), 100, 10);
 //OR
 builder.setLargeIcon(BitmapFactory.decodeResource(ctx.getResources(), R.drawable.birdpic));
 //OR
 final Intent intent = new Intent(ctx, MainActivity.class);
 //OR
 NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
 //ETC...

}

Not related to this question but example using a Fragment to access system resources/activity like this:

public boolean onQueryTextChange(String newText) {
 Activity activity = getActivity();
 Context context = activity.getApplicationContext();
 returnSomething(newText);
 return false;
}

View customerInfo = getActivity().getLayoutInflater().inflate(R.layout.main_layout_items, itemsLayout, false);
 itemsLayout.addView(customerInfo);

react change class name on state change

Below is a fully functional example of what I believe you're trying to do (with a functional snippet).

Explanation

Based on your question, you seem to be modifying 1 property in state for all of your elements. That's why when you click on one, all of them are being changed.

In particular, notice that the state tracks an index of which element is active. When MyClickable is clicked, it tells the Container its index, Container updates the state, and subsequently the isActive property of the appropriate MyClickables.

Example

_x000D_
_x000D_
class Container extends React.Component {_x000D_
  state = {_x000D_
    activeIndex: null_x000D_
  }_x000D_
_x000D_
  handleClick = (index) => this.setState({ activeIndex: index })_x000D_
_x000D_
  render() {_x000D_
    return <div>_x000D_
      <MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />_x000D_
      <MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>_x000D_
      <MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>_x000D_
    </div>_x000D_
  }_x000D_
}_x000D_
_x000D_
class MyClickable extends React.Component {_x000D_
  handleClick = () => this.props.onClick(this.props.index)_x000D_
  _x000D_
  render() {_x000D_
    return <button_x000D_
      type='button'_x000D_
      className={_x000D_
        this.props.isActive ? 'active' : 'album'_x000D_
      }_x000D_
      onClick={ this.handleClick }_x000D_
    >_x000D_
      <span>{ this.props.name }</span>_x000D_
    </button>_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Container />, document.getElementById('app'))
_x000D_
button {_x000D_
  display: block;_x000D_
  margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
.album>span:after {_x000D_
  content: ' (an album)';_x000D_
}_x000D_
_x000D_
.active {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.active>span:after {_x000D_
  content: ' ACTIVE';_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

Update: "Loops"

In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.

// New render method for `Container`
render() {
  const clickables = [
    { name: "a" },
    { name: "b" },
    { name: "c" },
  ]

  return <div>
      { clickables.map(function(clickable, i) {
          return <MyClickable key={ clickable.name }
            name={ clickable.name }
            index={ i }
            isActive={ this.state.activeIndex === i }
            onClick={ this.handleClick }
          />
        } )
      }
  </div>
}

What does 'URI has an authority component' mean?

An authority is a portion of a URI. Your error suggests that it was not expecting one. The authority section is shown below, it is what is known as the website part of the url.

From RFC3986 on URIs:

The following is an example URI and its component parts:

     foo://example.com:8042/over/there?name=ferret#nose
     \_/   \______________/\_________/ \_________/ \__/
      |           |            |            |        |
   scheme     authority       path        query   fragment
      |   _____________________|__
     / \ /                        \
     urn:example:animal:ferret:nose

So there are two formats, one with an authority and one not. Regarding slashes:

"When authority is not present, the path cannot begin with two slash
characters ("//")."

Source: https://tools.ietf.org/rfc/rfc3986.txt (search for text 'authority is not present, the path cannot begin with two slash')

How to exit git log or git diff

You can press q to exit.

git hist is using a pager tool so you can scroll up and down the results before returning to the console.

Postgres: How to convert a json string to text?

In 9.4.4 using the #>> operator works for me:

select to_json('test'::text) #>> '{}';

To use with a table column:

select jsoncol #>> '{}' from mytable;

How to Convert the value in DataTable into a string array in c#

 
            string[] result = new string[table.Columns.Count];
            DataRow dr = table.Rows[0];
            for (int i = 0; i < dr.ItemArray.Length; i++)
            {
                result[i] = dr[i].ToString();
            }
            foreach (string str in result)
                Console.WriteLine(str);

Create a temporary table in a SELECT statement without a separate CREATE TABLE

Engine must be before select:

CREATE TEMPORARY TABLE temp1 ENGINE=MEMORY 
as (select * from table1)

How do I remove all HTML tags from a string without knowing which tags are in it?

You can use the below code on your string and you will get the complete string without html part.

string title = "<b> Hulk Hogan's Celebrity Championship Wrestling &nbsp;&nbsp;&nbsp;<font color=\"#228b22\">[Proj # 206010]</font></b>&nbsp;&nbsp;&nbsp; (Reality Series, &nbsp;)".Replace("&nbsp;",string.Empty);            
        string s = Regex.Replace(title, "<.*?>", String.Empty);

How to generate keyboard events?

I tried lib keyboard and it works good on Windows, Mac and Linux. Below line helps me switch tabs in browser:

keyboard.press_and_release('ctrl+tab')
    

How to force garbage collector to run?

It is not recommended to call gc explicitly, but if you call

GC.Collect();
GC.WaitForPendingFinalizers();

It will call GC explicitly throughout your code, don't forget to call GC.WaitForPendingFinalizers(); after GC.Collect().

javascript unexpected identifier

In such cases, you are better off re-adding the whitespace which makes the syntax error immediate apparent:

function(){
  if(xmlhttp.readyState==4&&xmlhttp.status==200){
    document.getElementById("content").innerHTML=xmlhttp.responseText;
  }
}
xmlhttp.open("GET","data/"+id+".html",true);xmlhttp.send();
}

There's a } too many. Also, after the closing } of the function, you should add a ; before the xmlhttp.open()

And finally, I don't see what that anonymous function does up there. It's never executed or referenced. Are you sure you pasted the correct code?

How to utilize date add function in Google spreadsheet?

=TO_DATE(TO_PURE_NUMBER(Insert Date cell, i.e. AM4)+[how many days to add in numbers, e.g. 3 days])

Looks like in practice:

=TO_DATE(TO_PURE_NUMBER(AM4)+3)

Essentially you are converting the date into a pure number and back into a date again.

How can I symlink a file in Linux?

ln -s TARGET LINK_NAME

Where the -s makes it symbolic.

How to use sbt from behind proxy?

For Windows users, enter the following command :

set JAVA_OPTS=-Dhttp.proxySet=true -Dhttp.proxyHost=[Your Proxy server] -Dhttp.proxyPort=8080

load external URL into modal jquery ui dialog

var page = "http://somurl.com/asom.php.aspx";

var $dialog = $('<div></div>')
               .html('<iframe style="border: 0px; " src="' + page + '" width="100%" height="100%"></iframe>')
               .dialog({
                   autoOpen: false,
                   modal: true,
                   height: 625,
                   width: 500,
                   title: "Some title"
               });
$dialog.dialog('open');

Use this inside a function. This is great if you really want to load an external URL as an IFRAME. Also make sure that in you custom jqueryUI you have the dialog.

GCC -fPIC option

The link to a function in a dynamic library is resolved when the library is loaded or at run time. Therefore, both the executable file and dynamic library are loaded into memory when the program is run. The memory address at which a dynamic library is loaded cannot be determined in advance, because a fixed address might clash with another dynamic library requiring the same address.


There are two commonly used methods for dealing with this problem:

1.Relocation. All pointers and addresses in the code are modified, if necessary, to fit the actual load address. Relocation is done by the linker and the loader.

2.Position-independent code. All addresses in the code are relative to the current position. Shared objects in Unix-like systems use position-independent code by default. This is less efficient than relocation if program run for a long time, especially in 32-bit mode.


The name "position-independent code" actually implies following:

  • The code section contains no absolute addresses that need relocation, but only self relative addresses. Therefore, the code section can be loaded at an arbitrary memory address and shared between multiple processes.

  • The data section is not shared between multiple processes because it often contains writeable data. Therefore, the data section may contain pointers or addresses that need relocation.

  • All public functions and public data can be overridden in Linux. If a function in the main executable has the same name as a function in a shared object, then the version in main will take precedence, not only when called from main, but also when called from the shared object. Likewise, when a global variable in main has the same name as a global variable in the shared object, then the instance in main will be used, even when accessed from the shared object.


This so-called symbol interposition is intended to mimic the behavior of static libraries.

A shared object has a table of pointers to its functions, called procedure linkage table (PLT) and a table of pointers to its variables called global offset table (GOT) in order to implement this "override" feature. All accesses to functions and public variables go through this tables.

p.s. Where dynamic linking cannot be avoided, there are various ways to avoid the timeconsuming features of the position-independent code.

You can read more from this article: http://www.agner.org/optimize/optimizing_cpp.pdf

How to Set focus to first text input in a bootstrap modal after shown

I think the most correct answer, assuming the use of jQuery, is a consolidation of aspects of all the answers in this page, plus the use of the event that Bootstrap passes:

$(document).on('shown.bs.modal', function(e) {
  $('input:visible:enabled:first', e.target).focus();
});

It also would work changing $(document) to $('.modal') or to add a class to the modal that signals that this focus should occur, like $('.modal.focus-on-first-input')