Programs & Examples On #Tweepy

An easy-to-use Python library for accessing the Twitter API. It can be used with Python (2.6, 2.7, and 3.x).

How to extract hours and minutes from a datetime.datetime object?

If the time is 11:03, then the accepted answer will print 11:3.

You could zero-pad the minutes:

"Created at {:d}:{:02d}".format(tdate.hour, tdate.minute)

Or go another way and use tdate.time() and only take the hour/minute part:

str(tdate.time())[0:5]

How to use Sublime over SSH

You can try something that I've been working on called 'xeno'. It will allow you to open up files/folders in Sublime Text (or any local editor really) over an SSH connection and automatically synchronize changes to the remote machine. It should work on almost all POSIX systems (I myself use it from OS X to connect to Linux machines and edit files in Sublime Text). It's free and open source. I'd love some feedback.

For more information: it's basically a Git/SSH mashup written in Python that allows you to edit files and folders on a remote machine in a local editor. You don't have to configure kernel modules, you don't need to have a persistent connection, it's all automatic, and it won't interfere with existing source control because it uses an out-of-worktree Git repository. Also, because it's built on Git, it's extremely fast and supports automatic merging of files that might be changing on both ends, unlike SSHFS/SFTP which will just clobber any files with older timestamps.

How to clear mysql screen console in windows?

just type \system cls

took me a couple hours to get it jejej

Converting a double to an int in C#

Because Convert.ToInt32 rounds:

Return Value: rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.

...while the cast truncates:

When you convert from a double or float value to an integral type, the value is truncated.

Update: See Jeppe Stig Nielsen's comment below for additional differences (which however do not come into play if score is a real number as is the case here).

Why do I have to "git push --set-upstream origin <branch>"?

If you forgot to add the repository HTTPS link then put it with git push <repo HTTPS>

RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol

You can match those three groups separately, and make sure that they all present. Also, [^\w] seems a bit too broad, but if that's what you want you might want to replace it with \W.

add column to mysql table if it does not exist

If you are on MariaDB, no need to use stored procedures. Just use, for example:

ALTER TABLE table_name ADD COLUMN IF NOT EXISTS column_name tinyint(1) DEFAULT 0;

See here

Jquery array.push() not working

another workaround:

var myarray = [];
$("#test").click(function() {
    myarray[index]=$("#drop").val();
    alert(myarray);
});

i wanted to add all checked checkbox to array. so example, if .each is used:

var vpp = [];
var incr=0;
$('.prsn').each(function(idx) {
   if (this.checked) {
       var p=$('.pp').eq(idx).val();
       vpp[incr]=(p);
       incr++;
   }
});
//do what ever with vpp array;

How to skip over an element in .map()?

Here is a updated version of the code provided by @theprtk. It is a cleaned up a little to show the generalized version whilst having an example.

Note: I'd add this as a comment to his post but I don't have enough reputation yet

/**
 * @see http://clojure.com/blog/2012/05/15/anatomy-of-reducer.html
 * @description functions that transform reducing functions
 */
const transduce = {
  /** a generic map() that can take a reducing() & return another reducing() */
  map: changeInput => reducing => (acc, input) =>
    reducing(acc, changeInput(input)),
  /** a generic filter() that can take a reducing() & return */
  filter: predicate => reducing => (acc, input) =>
    predicate(input) ? reducing(acc, input) : acc,
  /**
   * a composing() that can take an infinite # transducers to operate on
   *  reducing functions to compose a computed accumulator without ever creating
   *  that intermediate array
   */
  compose: (...args) => x => {
    const fns = args;
    var i = fns.length;
    while (i--) x = fns[i].call(this, x);
    return x;
  },
};

const example = {
  data: [{ src: 'file.html' }, { src: 'file.txt' }, { src: 'file.json' }],
  /** note: `[1,2,3].reduce(concat, [])` -> `[1,2,3]` */
  concat: (acc, input) => acc.concat([input]),
  getSrc: x => x.src,
  filterJson: x => x.src.split('.').pop() !== 'json',
};

/** step 1: create a reducing() that can be passed into `reduce` */
const reduceFn = example.concat;
/** step 2: transforming your reducing function by mapping */
const mapFn = transduce.map(example.getSrc);
/** step 3: create your filter() that operates on an input */
const filterFn = transduce.filter(example.filterJson);
/** step 4: aggregate your transformations */
const composeFn = transduce.compose(
  filterFn,
  mapFn,
  transduce.map(x => x.toUpperCase() + '!'), // new mapping()
);

/**
 * Expected example output
 *  Note: each is wrapped in `example.data.reduce(x, [])`
 *  1: ['file.html', 'file.txt', 'file.json']
 *  2:  ['file.html', 'file.txt']
 *  3: ['FILE.HTML!', 'FILE.TXT!']
 */
const exampleFns = {
  transducers: [
    mapFn(reduceFn),
    filterFn(mapFn(reduceFn)),
    composeFn(reduceFn),
  ],
  raw: [
    (acc, x) => acc.concat([x.src]),
    (acc, x) => acc.concat(x.src.split('.').pop() !== 'json' ? [x.src] : []),
    (acc, x) => acc.concat(x.src.split('.').pop() !== 'json' ? [x.src.toUpperCase() + '!'] : []),
  ],
};
const execExample = (currentValue, index) =>
  console.log('Example ' + index, example.data.reduce(currentValue, []));

exampleFns.raw.forEach(execExample);
exampleFns.transducers.forEach(execExample);

Disable Button in Angular 2

I tried use [disabled]="!editmode" but it not work in my case.

This is my solution [disabled]="!editmode ? 'disabled': null" , I share for whom concern.

<button [disabled]="!editmode ? 'disabled': null" 
    (click)='loadChart()'>
            <div class="btn-primary">Load Chart</div>
    </button>

Stackbliz https://stackblitz.com/edit/angular-af55ep

Why Response.Redirect causes System.Threading.ThreadAbortException?

I had that problem too.

Try using Server.Transfer instead of Response.Redirect

Worked for me.

Plot a horizontal line using matplotlib

Use matplotlib.pyplot.hlines:

  • Plot multiple horizontal lines by passing a list to the y parameter.
  • y can be passed as a single location: y=40
  • y can be passed as multiple locations: y=[39, 40, 41]
  • If you're a plotting a figure with something like fig, ax = plt.subplots(), then replace plt.hlines or plt.axhline with ax.hlines or ax.axhline, respectively.
  • matplotlib.pyplot.axhline can only plot a single location (e.g. y=40)

plt.plot

import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(1, 21, 200)

plt.figure(figsize=(6, 3))
plt.hlines(y=39.5, xmin=100, xmax=175, colors='aqua', linestyles='-', lw=2, label='Single Short Line')
plt.hlines(y=[39, 40, 41], xmin=[0, 25, 50], xmax=[len(xs)], colors='purple', linestyles='--', lw=2, label='Multiple Lines')
plt.legend(bbox_to_anchor=(1.04,0.5), loc="center left", borderaxespad=0)

enter image description here

ax.plot

import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(1, 21, 200)
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(6, 6))

ax1.hlines(y=40, xmin=0, xmax=len(xs), colors='r', linestyles='--', lw=2)
ax1.set_title('One Line')

ax2.hlines(y=[39, 40, 41], xmin=0, xmax=len(xs), colors='purple', linestyles='--', lw=2)
ax2.set_title('Multiple Lines')

plt.tight_layout()
plt.show()

enter image description here

Time Series Axis

  • xmin and xmax will accept a date like '2020-09-10' or datetime(2020, 9, 10)
    • xmin=datetime(2020, 9, 10), xmax=datetime(2020, 9, 10) + timedelta(days=3)
    • Given date = df.index[9], xmin=date, xmax=date + pd.Timedelta(days=3), where the index is a DatetimeIndex.
import pandas_datareader as web  # conda or pip install this; not part of pandas
import pandas as pd
import matplotlib.pyplot as plt

# get test data
df = web.DataReader('^gspc', data_source='yahoo', start='2020-09-01', end='2020-09-28').iloc[:, :2]

# plot dataframe
ax = df.plot(figsize=(9, 6), title='S&P 500', ylabel='Price')

# add horizontal line
ax.hlines(y=3450, xmin='2020-09-10', xmax='2020-09-17', color='purple', label='test')

ax.legend()
plt.show()

enter image description here

  • Sample time series data if web.DataReader doesn't work.
data = {pd.Timestamp('2020-09-01 00:00:00'): {'High': 3528.03, 'Low': 3494.6}, pd.Timestamp('2020-09-02 00:00:00'): {'High': 3588.11, 'Low': 3535.23}, pd.Timestamp('2020-09-03 00:00:00'): {'High': 3564.85, 'Low': 3427.41}, pd.Timestamp('2020-09-04 00:00:00'): {'High': 3479.15, 'Low': 3349.63}, pd.Timestamp('2020-09-08 00:00:00'): {'High': 3379.97, 'Low': 3329.27}, pd.Timestamp('2020-09-09 00:00:00'): {'High': 3424.77, 'Low': 3366.84}, pd.Timestamp('2020-09-10 00:00:00'): {'High': 3425.55, 'Low': 3329.25}, pd.Timestamp('2020-09-11 00:00:00'): {'High': 3368.95, 'Low': 3310.47}, pd.Timestamp('2020-09-14 00:00:00'): {'High': 3402.93, 'Low': 3363.56}, pd.Timestamp('2020-09-15 00:00:00'): {'High': 3419.48, 'Low': 3389.25}, pd.Timestamp('2020-09-16 00:00:00'): {'High': 3428.92, 'Low': 3384.45}, pd.Timestamp('2020-09-17 00:00:00'): {'High': 3375.17, 'Low': 3328.82}, pd.Timestamp('2020-09-18 00:00:00'): {'High': 3362.27, 'Low': 3292.4}, pd.Timestamp('2020-09-21 00:00:00'): {'High': 3285.57, 'Low': 3229.1}, pd.Timestamp('2020-09-22 00:00:00'): {'High': 3320.31, 'Low': 3270.95}, pd.Timestamp('2020-09-23 00:00:00'): {'High': 3323.35, 'Low': 3232.57}, pd.Timestamp('2020-09-24 00:00:00'): {'High': 3278.7, 'Low': 3209.45}, pd.Timestamp('2020-09-25 00:00:00'): {'High': 3306.88, 'Low': 3228.44}, pd.Timestamp('2020-09-28 00:00:00'): {'High': 3360.74, 'Low': 3332.91}}

df = pd.DataFrame.from_dict(data, 'index')

Java HashMap: How to get a key and value by index?

Here is the general solution if you really only want the first key's value

Object firstKey = myHashMap.keySet().toArray()[0];
Object valueForFirstKey = myHashMap.get(firstKey);

How do I get a file name from a full path with PHP?

You're looking for basename.

The example from the PHP manual:

<?php
$path = "/home/httpd/html/index.php";
$file = basename($path);         // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
?>

Preventing console window from closing on Visual Studio C/C++ Console application

Either use:

  1. cin.get();

or

  1. system("pause");

Make sure to make either of them at the end of main() function and before the return statement.

Right query to get the current number of connections in a PostgreSQL DB

From looking at the source code, it seems like the pg_stat_database query gives you the number of connections to the current database for all users. On the other hand, the pg_stat_activity query gives the number of connections to the current database for the querying user only.

What is the Windows equivalent of the diff command?

Well, on Windows I happily run diff and many other of the GNU tools. You can do it with cygwin, but I personally prefer GnuWin32 because it is a much lighter installation experience.

So, my answer is that the Windows equivalent of diff, is none other than diff itself!

/usr/bin/codesign failed with exit code 1

Update:
The Technical Note in my original answer is now deprecated. Apple posted a collection of code signing problems (and some solutions) in a new document: Technical Note TN2407 Code Signing Troubleshooting Index

Check the CODE_SIGN_IDENTITY property in your build settings. Is your provisioning profile selected there?
You also need to enter a valid bundle identifier in your apps .plist.
The identifier has to match the one you provided when generating the profile.
Apple has a technote about that here.

get selected value in datePicker and format it

var dateObject = $("#datePickerInput").datepicker('getDate');
$.datepicker.formatDate('dd MM, yy', dateObject);

Add to python path mac os x

Setting the $PYTHONPATH environment variable does not seem to affect the Spyder IDE's iPython terminals on a Mac. However, Spyder's application menu contains a "PYTHONPATH manager." Adding my path here solved my problem. The "PYTHONPATH manager" is also persistent across application restarts.

This is specific to a Mac, because setting the PYTHONPATH environment variable on my Windows PC gives the expected behavior (modules are found) without using the PYTHONPATH manager in Spyder.

Pass Array Parameter in SqlCommand

Passing an array of items as a collapsed parameter to the WHERE..IN clause will fail since query will take form of WHERE Age IN ("11, 13, 14, 16").

But you can pass your parameter as an array serialized to XML or JSON:

Using nodes() method:

StringBuilder sb = new StringBuilder();

foreach (ListItem item in ddlAge.Items)
  if (item.Selected)
    sb.Append("<age>" + item.Text + "</age>"); // actually it's xml-ish

sqlComm.CommandText = @"SELECT * from TableA WHERE Age IN (
    SELECT Tab.col.value('.', 'int') as Age from @Ages.nodes('/age') as Tab(col))";
sqlComm.Parameters.Add("@Ages", SqlDbType.NVarChar);
sqlComm.Parameters["@Ages"].Value = sb.ToString();

Using OPENXML method:

using System.Xml.Linq;
...
XElement xml = new XElement("Ages");

foreach (ListItem item in ddlAge.Items)
  if (item.Selected)
    xml.Add(new XElement("age", item.Text);

sqlComm.CommandText = @"DECLARE @idoc int;
    EXEC sp_xml_preparedocument @idoc OUTPUT, @Ages;
    SELECT * from TableA WHERE Age IN (
    SELECT Age from OPENXML(@idoc, '/Ages/age') with (Age int 'text()')
    EXEC sp_xml_removedocument @idoc";
sqlComm.Parameters.Add("@Ages", SqlDbType.Xml);
sqlComm.Parameters["@Ages"].Value = xml.ToString();

That's a bit more on the SQL side and you need a proper XML (with root).

Using OPENJSON method (SQL Server 2016+):

using Newtonsoft.Json;
...
List<string> ages = new List<string>();

foreach (ListItem item in ddlAge.Items)
  if (item.Selected)
    ages.Add(item.Text);

sqlComm.CommandText = @"SELECT * from TableA WHERE Age IN (
    select value from OPENJSON(@Ages))";
sqlComm.Parameters.Add("@Ages", SqlDbType.NVarChar);
sqlComm.Parameters["@Ages"].Value = JsonConvert.SerializeObject(ages);

Note that for the last method you also need to have Compatibility Level at 130+.

Error: Argument is not a function, got undefined

If you are in a submodule, don't forget to declare the module in main app. ie :

<scrip>
angular.module('mainApp', ['subModule1', 'subModule2']);

angular.module('subModule1')
   .controller('MyController', ['$scope', function($scope) {
      $scope.moduleName = 'subModule1';
   }]);
</script>
...
<div ng-app="mainApp">
   <div ng-controller="MyController">
   <span ng-bind="moduleName"></span>
</div>

If you don't declare subModule1 in mainApp, you will got a "[ng:areq] Argument "MyController" is not a function, got undefined.

Working with $scope.$emit and $scope.$on

Scope(s) can be used to propagate, dispatch event to the scope children or parent.

$emit - propagates the event to parent. $broadcast - propagates the event to children. $on - method to listen the events, propagated by $emit and $broadcast.

example index.html:

<div ng-app="appExample" ng-controller="EventCtrl">
      Root(Parent) scope count: {{count}}
  <div>
      <button ng-click="$emit('MyEvent')">$emit('MyEvent')</button>
      <button ng-click="$broadcast('MyEvent')">$broadcast('MyEvent')</button><br>

      Childrent scope count: {{count}} 
  </div>
</div>

example app.js:

angular.module('appExample', [])
.controller('EventCtrl', ['$scope', function($scope) {
  $scope.count = 0;
  $scope.$on('MyEvent', function() {
    $scope.count++;
  });
}]);

Here u can test code: http://jsfiddle.net/zp6v0rut/41/

Why is the Java main method static?

The main() method in C++, C# and Java are static
Because they can then be invoked by the runtime engine without having to instantiate any objects then the code in the body of main() will do the rest.

Notepad++ incrementally replace

I was looking for the same feature today but couldn't do this in Notepad++. However, we have TextPad to our rescue. It worked for me.

In TextPad's replace dialog, turn on regex; then you could try replacing

<row id="1"/>

by

<row id="\i"/>

Have a look at this link for further amazing replace features of TextPad - http://sublimetext.userecho.com/topic/106519-generate-a-sequence-of-numbers-increment-replace/

Trust Anchor not found for Android SSL Connection

The solution of @Chrispix is dangerous! Trusting all certificates allows anybody to do a man in the middle attack! Just send ANY certificate to the client and it will accept it!

Add your certificate(s) to a custom trust manager like described in this post: Trusting all certificates using HttpClient over HTTPS

Although it is a bit more complex to establish a secure connection with a custom certificate, it will bring you the wanted ssl encryption security without the danger of man in the middle attack!

Can I scroll a ScrollView programmatically in Android?

There are a lot of good answers here, but I only want to add one thing. It sometimes happens that you want to scroll your ScrollView to a specific view of the layout, instead of a full scroll to the top or the bottom.

A simple example: in a registration form, if the user tap the "Signup" button when a edit text of the form is not filled, you want to scroll to that specific edit text to tell the user that he must fill that field.

In that case, you can do something like that:

scrollView.post(new Runnable() { 
        public void run() { 
             scrollView.scrollTo(0, editText.getBottom());
        } 
});

or, if you want a smooth scroll instead of an instant scroll:

scrollView.post(new Runnable() { 
            public void run() { 
                 scrollView.smoothScrollTo(0, editText.getBottom());
            } 
    });

Obviously you can use any type of view instead of Edit Text. Note that getBottom() returns the coordinates of the view based on its parent layout, so all the views used inside the ScrollView should have only a parent (for example a Linear Layout).

If you have multiple parents inside the child of the ScrollView, the only solution i've found is to call requestChildFocus on the parent view:

editText.getParent().requestChildFocus(editText, editText);

but in this case you cannot have a smooth scroll.

I hope this answer can help someone with the same problem.

How to generate XML from an Excel VBA macro?

This one more version - this will help in generic

Public strSubTag As String
Public iStartCol As Integer
Public iEndCol As Integer
Public strSubTag2 As String
Public iStartCol2 As Integer
Public iEndCol2 As Integer

Sub Create()
Dim strFilePath As String
Dim strFileName As String

'ThisWorkbook.Sheets("Sheet1").Range("C3").Activate
'strTag = ActiveCell.Offset(0, 1).Value
strFilePath = ThisWorkbook.Sheets("Sheet1").Range("B4").Value
strFileName = ThisWorkbook.Sheets("Sheet1").Range("B5").Value
strSubTag = ThisWorkbook.Sheets("Sheet1").Range("F3").Value
iStartCol = ThisWorkbook.Sheets("Sheet1").Range("F4").Value
iEndCol = ThisWorkbook.Sheets("Sheet1").Range("F5").Value

strSubTag2 = ThisWorkbook.Sheets("Sheet1").Range("G3").Value
iStartCol2 = ThisWorkbook.Sheets("Sheet1").Range("G4").Value
iEndCol2 = ThisWorkbook.Sheets("Sheet1").Range("G5").Value

Dim iCaptionRow As Integer
iCaptionRow = ThisWorkbook.Sheets("Sheet1").Range("B3").Value
'strFileName = ThisWorkbook.Sheets("Sheet1").Range("B4").Value
MakeXML iCaptionRow, iCaptionRow + 1, strFilePath, strFileName

End Sub


Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFilePath As String, sOutputFileName As String)
    Dim Q As String
    Dim sOutputFileNamewithPath As String
    Q = Chr$(34)

    Dim sXML As String


    'sXML = sXML & "<rows>"

'    ''--determine count of columns
    Dim iColCount As Integer
    iColCount = 1

    While Trim$(Cells(iCaptionRow, iColCount)) > ""
        iColCount = iColCount + 1
    Wend


    Dim iRow As Integer
    Dim iCount  As Integer
    iRow = iDataStartRow
    iCount = 1
    While Cells(iRow, 1) > ""
        'sXML = sXML & "<row id=" & Q & iRow & Q & ">"
        sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
        For iCOl = 1 To iColCount - 1
          If (iStartCol = iCOl) Then
               sXML = sXML & "<" & strSubTag & ">"
          End If
          If (iEndCol = iCOl) Then
               sXML = sXML & "</" & strSubTag & ">"
          End If
         If (iStartCol2 = iCOl) Then
               sXML = sXML & "<" & strSubTag2 & ">"
          End If
          If (iEndCol2 = iCOl) Then
               sXML = sXML & "</" & strSubTag2 & ">"
          End If
           sXML = sXML & "<" & Trim$(Cells(iCaptionRow, iCOl)) & ">"
           sXML = sXML & Trim$(Cells(iRow, iCOl))
           sXML = sXML & "</" & Trim$(Cells(iCaptionRow, iCOl)) & ">"
        Next

        'sXML = sXML & "</row>"
        Dim nDestFile As Integer, sText As String

    ''Close any open text files
        Close

    ''Get the number of the next free text file
        nDestFile = FreeFile
        sOutputFileNamewithPath = sOutputFilePath & sOutputFileName & iCount & ".XML"
    ''Write the entire file to sText
        Open sOutputFileNamewithPath For Output As #nDestFile
        Print #nDestFile, sXML

        iRow = iRow + 1
        sXML = ""
        iCount = iCount + 1
    Wend
    'sXML = sXML & "</rows>"

    Close
End Sub

How do you write a migration to rename an ActiveRecord model and its table in Rails?

Here's an example:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def self.up
    rename_table :old_table_name, :new_table_name
  end

  def self.down
    rename_table :new_table_name, :old_table_name
  end
end

I had to go and rename the model declaration file manually.

Edit:

In Rails 3.1 & 4, ActiveRecord::Migration::CommandRecorder knows how to reverse rename_table migrations, so you can do this:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def change
    rename_table :old_table_name, :new_table_name
  end 
end

(You still have to go through and manually rename your files.)

Jquery Ajax Posting json to webservice

Please follow this to by ajax call to webservice of java var param = { feildName: feildValue }; JSON.stringify({data : param})

$.ajax({
            dataType    : 'json',
            type        : 'POST',
            contentType : 'application/json',
            url         : '<%=request.getContextPath()%>/rest/priceGroups',
            data        : JSON.stringify({data : param}),
            success     : function(res) {
                if(res.success == true){
                    $('#alertMessage').html('Successfully price group created.').addClass('alert alert-success fade in');
                    $('#alertMessage').removeClass('alert-danger alert-info');
                    initPriceGroupsList();
                    priceGroupId = 0;
                    resetForm();                                                                    
                }else{                          
                    $('#alertMessage').html(res.message).addClass('alert alert-danger fade in');
                }
                $('#alertMessage').alert();         
                window.setTimeout(function() { 
                    $('#alertMessage').removeClass('in');
                    document.getElementById('message').style.display = 'none';
                }, 5000);
            }
        });

How to set the project name/group/version, plus {source,target} compatibility in the same file?

gradle.properties:

theGroup=some.group
theName=someName
theVersion=1.0
theSourceCompatibility=1.6

settings.gradle:

rootProject.name = theName

build.gradle:

apply plugin: "java"

group = theGroup
version = theVersion
sourceCompatibility = theSourceCompatibility

Converting <br /> into a new line for use in a text area

Here is another approach.

class orbisius_custom_string {
    /**
     * The reverse of nl2br. Handles <br/> <br/> <br />
     * usage: orbisius_custom_string::br2nl('Your buffer goes here ...');
     * @param str $buff
     * @return str
     * @author Slavi Marinov | http://orbisius.com
     */
    public static function br2nl($buff = '') {
        $buff = preg_replace('#<br[/\s]*>#si', "\n", $buff);
        $buff = trim($buff);

        return $buff;
    }
}

Test iOS app on device without apple developer program or jailbreak

With Xcode 7 you are no longer required to have a developer account in order to test your apps on your device:

enter image description here

Check it out here.

Please notice that this is the officially supported by Apple, so there's no need of jailbroken devices or testing on the simulator, but you'll have to use Xcode 7 (currently in beta by the time of this post) or later.

I successfully deployed an app to my iPhone without a developer account. You'll have to use your iCloud account to solve the provisioning profile issues. Just add your iCloud account and assign it in the Team dropdown (in the Identity menu) and the Fix Issue button should do the rest.


UPDATE:

Some people are having problems with iOS 8.4, here is how to fix it.

Automating the InvokeRequired code pattern

You could write an extension method:

public static void InvokeIfRequired(this Control c, Action<Control> action)
{
    if(c.InvokeRequired)
    {
        c.Invoke(new Action(() => action(c)));
    }
    else
    {
        action(c);
    }
}

And use it like this:

object1.InvokeIfRequired(c => { c.Visible = true; });

EDIT: As Simpzon points out in the comments you could also change the signature to:

public static void InvokeIfRequired<T>(this T c, Action<T> action) 
    where T : Control

How to send and receive JSON data from a restful webservice using Jersey API

The above problem can be solved by adding the following dependencies in your project, as i was facing the same problem.For more detail answer to this solution please refer link SEVERE:MessageBodyWriter not found for media type=application/xml type=class java.util.HashMap

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.0</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.2</version>
    </dependency>   


    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>2.25</version>
    </dependency>

How to empty a file using Python

Alternate form of the answer by @rumpel

with open(filename, 'w'): pass

Error launching Eclipse 4.4 "Version 1.6.0_65 of the JVM is not suitable for this product."

Please check if you got the x64 edition of eclipse. Someone answered this just a few hours ago.

Binding a generic list to a repeater - ASP.NET

Code Behind:

public class Friends
{
    public string   ID      { get; set; }
    public string   Name    { get; set; }
    public string   Image   { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
        List <Friends> friendsList = new List<Friends>();

        foreach (var friend  in friendz)
        {
            friendsList.Add(
                new Friends { ID = friend.id, Name = friend.name }    
            );

        }

        this.rptFriends.DataSource = friendsList;
        this.rptFriends.DataBind();
}

.aspx Page

<asp:Repeater ID="rptFriends" runat="server">
            <HeaderTemplate>
                <table border="0" cellpadding="0" cellspacing="0">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                        </tr>
                    </thead>
                    <tbody>
            </HeaderTemplate>
            <ItemTemplate>
                    <tr>
                        <td><%# Eval("ID") %></td>
                        <td><%# Eval("Name") %></td>
                    </tr>
            </ItemTemplate>
            <FooterTemplate>
                    </tbody>
                </table>
            </FooterTemplate>
        </asp:Repeater>

MVC Redirect to View from jQuery with parameters

This would also work I believe:

$('#results').on('click', '.item', function () {
            var NestId = $(this).data('id');
            var url = '@Html.Raw(Url.Action("Artists", new { NestId = @NestId }))';
            window.location.href = url; 
        })

.bashrc at ssh login

I had similar situation like Hobhouse. I wanted to use command

 ssh myhost.com 'some_command'

and 'some_command' exists in '/var/some_location' so I tried to append '/var/some_location' in PATH environment by editing '$HOME/.bashrc'

but that wasn't working. because default .bashrc(Ubuntu 10.4 LTS) prevent from sourcing by code like below

# If not running interactively, don't do anything
[ -z "$PS1" ] && return

so If you want to change environment for ssh non-login shell. you should add code above that line.

Javascript - Regex to validate date format

Try this:

^\d\d[./-]\d\d[./-]\d\d\d\d$

How to declare a global variable in React?

Maybe it's using a sledge-hammer to crack a nut, but using environment variables (with Dotenv https://www.npmjs.com/package/dotenv) you can also provide values throughout your React app. And that without any overhead code where they are used.

I came here because I found that some of the variables defined in my env files where static throughout the different envs, so I searched for a way to move them out of the env files. But honestly I don't like any of the alternatives I found here. I don't want to set up and use a context everytime I need those values.

I am not experienced when it comes to environments, so please, if there is a downside to this approach, let me know.

How to change Jquery UI Slider handle

The CSS class that can be changed to add a image to the JQuery slider handle is called ".ui-slider-horizontal .ui-slider-handle".

The following code shows a demo:

<!DOCTYPE html>
<html>
<head>
  <link type="text/css" href="http://jqueryui.com/latest/themes/base/ui.all.css" rel="stylesheet" />
  <script type="text/javascript" src="http://jqueryui.com/latest/jquery-1.3.2.js"></script>
  <script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.core.js"></script>
  <script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.slider.js"></script>
  <style type="text/css">
  .ui-slider-horizontal .ui-state-default {background: white url(http://stackoverflow.com/content/img/so/vote-arrow-down.png) no-repeat scroll 50% 50%;}
  </style>
  <script type="text/javascript">
  $(document).ready(function(){
    $("#slider").slider();
  });
  </script>
</head>
<body>
<div id="slider"></div>
</body>
</html>

I think registering a handle option was the old way of doing it and no longer supported in JQuery-ui 1.7.2?

Set selected item in Android BottomNavigationView

I you don't want to modify your code. If so, I recommended you to try BottomNavigationViewEx?

You just need replace call a method setCurrentItem(index); and getCurrentItem()?

Click here to view the image

Adb install failure: INSTALL_CANCELED_BY_USER

I tried all the steps described above but failed.

Like, connect to the internet with Data connection, Turning off the MIUI optimization and reboot, Turning on Install via USB from Security settings etc.

Then I found a solution.

Steps:

  • Install PlexVPN.
  • set China-Shanghai server
  • Try turning on Install via USB from Developer option.

That's all.

Can I disable a CSS :hover effect via JavaScript?

I'd recommend to replace all :hover properties to :active when you detect that device supports touch. Just call this function when you do so as touch().

function touch() {
  if ('ontouchstart' in document.documentElement) {
    for (var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
      var sheet = document.styleSheets[sheetI];
      if (sheet.cssRules) {
        for (var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
          var rule = sheet.cssRules[ruleI];

          if (rule.selectorText) {
            rule.selectorText = rule.selectorText.replace(':hover', ':active');
          }
        }
      }
    }
  }
}

Parse query string in JavaScript

Here is a fast and easy way of parsing query strings in JavaScript:

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (decodeURIComponent(pair[0]) == variable) {
            return decodeURIComponent(pair[1]);
        }
    }
    console.log('Query variable %s not found', variable);
}

Now make a request to page.html?x=Hello:

console.log(getQueryVariable('x'));

Smooth GPS data

Going back to the Kalman Filters ... I found a C implementation for a Kalman filter for GPS data here: http://github.com/lacker/ikalman I haven't tried it out yet, but it seems promising.

Why doesn't margin:auto center an image?

Because your image is an inline-block element. You could change it to a block-level element like this:

<img src="queuedError.jpg" style="margin:auto; width:200px;display:block" />

and it will be centered.

MySQL error 2006: mysql server has gone away

There is an easier way if you are using XAMPP. Open the XAMPP control panel, and click on the config button in mysql section.
enter image description here

Now click on the my.ini and it will open in the editor. Update the max_allowed_packet to your required size.

enter image description here

Then restart the mysql service. Click on stop on the Mysql service click start again. Wait for a few minutes. enter image description here enter image description here

Then try to run your Mysql query again. Hope it will work.

How to find Max Date in List<Object>?

troubleshooting-friendly style

You should not call .get() directly. Optional<>, that Stream::max returns, was designed to benefit from .orElse... inline handling.

If you are sure your arguments have their size of 2+:

list.stream()
    .map(u -> u.date)
    .max(Date::compareTo)
    .orElseThrow(() -> new IllegalArgumentException("Expected 'list' to be of size: >= 2. Was: 0"));

If you support empty lists, then return some default value, for example:

list.stream()
    .map(u -> u.date)
    .max(Date::compareTo)
    .orElse(new Date(Long.MIN_VALUE));

CREDITS to: @JimmyGeers, @assylias from the accepted answer.

How can I find the product GUID of an installed MSI setup?

There is also a very helpful GUI tool called Product Browser which appears to be made by Microsoft or at least an employee of Microsoft.

It can be found on Github here Product Browser

I personally had a very easy time locating the GUID I needed with this.

How to clear radio button in Javascript?

If you have a radio button with same id, then you can clear the selection

Radio Button definition :

<input type="radio" name="paymentType" id="paymentType" value="CASH" /> CASH
<input type="radio" name="paymentType" id="paymentType" value="CHEQUE" /> CHEQUE
<input type="radio" name="paymentType" id="paymentType" value="DD" /> DD

Clearing all values of radio button:

document.formName.paymentType[0].checked = false;
document.formName.paymentType[1].checked = false;
document.formName.paymentType[2].checked = false;
...

Set background image according to screen resolution

I know it's too old question but thought to answer, it might will help someone. If you see twitter, you will find something very tricky but pure css approach to achieve this.

<div class="background"><img src="home-bg.png" /></div>
Applied CSS
.background {
    background: none repeat scroll 0 0 #FFFFFF;
    height: 200%;
    left: -50%;
    position: fixed;
    width: 200%;}

.background img{
    bottom: 0;
    display: block;
    left: 0;
    margin: auto;
    min-height: 50%;
    min-width: 50%;
    right: 0;
    top: 0;}

This background images fits to all size. even portrait view of ipad. it always adjust the image in center. if you zoom out; image will remain the same.

Python string.join(list) on object array rather than string array

I know this is a super old post, but I think what is missed is overriding __repr__, so that __repr__ = __str__, which is the accepted answer of this question marked duplicate.

Ruby objects and JSON serialization (without Rails)

What version of Ruby are you using? ruby -v will tell you.

If it's 1.9.2, JSON is included in the standard library.

If you're on 1.8.something then do gem install json and it'll install. Then, in your code do:

require 'rubygems'
require 'json'

Then append to_json to an object and you're good to go:

asdf = {'a' => 'b'} #=> {"a"=>"b"}
asdf.to_json #=> "{"a":"b"}"

How to align footer (div) to the bottom of the page?

Your title and comments imply that you weren't looking for a sticky footer (stuck to the bottom of the window as content scrolls below it). I assume you were looking for a footer that would be forced to the bottom of the window if the content does not fill the window, and push down to the bottom of the content if the content exceeds the window boundary.

You can accomplish this with the following.

<style>
html,
body {
    margin:0;
    padding:0;
    height:100%;
}
#container {
    min-height:100%;
    position:relative;
}
#header {
    background:#ff0;
    padding:10px;
}
#body {
    padding:10px;
    padding-bottom:60px;   /* Height of the footer */
}
#footer {
    position:absolute;
    bottom:0;
    width:100%;
    height:60px;   /* Height of the footer */
    background:#6cf;
}
</style>

<div id="container">
    <div id="header">header</div>
    <div id="body">body</div>
    <div id="footer">footer</div>
</div>

Source: How to keep footers at the bottom of the page

Java - Reading XML file

Avoid hardcoding try making the code that is dynamic below is the code it will work for any xml I have used SAX Parser you can use dom,xpath it's upto you I am storing all the tags name and values in the map after that it becomes easy to retrieve any values you want I hope this helps
SAMPLE XML:

<parent>
<child >
    <child1> value 1 </child1>
    <child2> value 2 </child2>
    <child3> value 3 </child3>
    </child>
    <child >
     <child4> value 4 </child4>
    <child5> value 5</child5>
    <child6> value 6 </child6>
    </child>
  </parent>

JAVA CODE:

 import java.io.File;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.LinkedHashMap;
    import java.util.Map;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;


    public class saxParser {
           static Map<String,String> tmpAtrb=null;
           static Map<String,String> xmlVal= new LinkedHashMap<String, String>();
        public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, VerifyError {

            /**
             * We can pass the class name of the XML parser
             * to the SAXParserFactory.newInstance().
             */

            //SAXParserFactory saxDoc = SAXParserFactory.newInstance("com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl", null);

            SAXParserFactory saxDoc = SAXParserFactory.newInstance();
            SAXParser saxParser = saxDoc.newSAXParser();

            DefaultHandler handler = new DefaultHandler() {
                String tmpElementName = null;
                String tmpElementValue = null;


                @Override
                public void startElement(String uri, String localName, String qName, 
                                                                    Attributes attributes) throws SAXException {
                    tmpElementValue = "";
                    tmpElementName = qName;
                    tmpAtrb=new HashMap();
                    //System.out.println("Start Element :" + qName);
                    /**
                     * Store attributes in HashMap
                     */
                    for (int i=0; i<attributes.getLength(); i++) {
                        String aname = attributes.getLocalName(i);
                        String value = attributes.getValue(i);
                        tmpAtrb.put(aname, value);
                    }

                }

                @Override
                public void endElement(String uri, String localName, String qName) 
                                                            throws SAXException { 

                    if(tmpElementName.equals(qName)){
                        System.out.println("Element Name :"+tmpElementName);
                    /**
                     * Retrive attributes from HashMap
                     */                    for (Map.Entry<String, String> entrySet : tmpAtrb.entrySet()) {
                            System.out.println("Attribute Name :"+ entrySet.getKey() + "Attribute Value :"+ entrySet.getValue());
                        }
                        System.out.println("Element Value :"+tmpElementValue);
                        xmlVal.put(tmpElementName, tmpElementValue);
                        System.out.println(xmlVal);
                      //Fetching The Values From The Map
                        String getKeyValues=xmlVal.get(tmpElementName);
                        System.out.println("XmlTag:"+tmpElementName+":::::"+"ValueFetchedFromTheMap:"+getKeyValues);   
                    }   
                }
                @Override
                public void characters(char ch[], int start, int length) throws SAXException {
                    tmpElementValue = new String(ch, start, length) ;  
                } 
            };
            /**
             * Below two line used if we use SAX 2.0
             * Then last line not needed.
             */

            //saxParser.setContentHandler(handler);
            //saxParser.parse(new InputSource("c:/file.xml"));
            saxParser.parse(new File("D:/Test _ XML/file.xml"), handler);
        }  
    }

OUTPUT:

Element Name :child1
Element Value : value 1 
XmlTag:<child1>:::::ValueFetchedFromTheMap: value 1 
Element Name :child2
Element Value : value 2 
XmlTag:<child2>:::::ValueFetchedFromTheMap: value 2 
Element Name :child3
Element Value : value 3 
XmlTag:<child3>:::::ValueFetchedFromTheMap: value 3 
Element Name :child4
Element Value : value 4 
XmlTag:<child4>:::::ValueFetchedFromTheMap: value 4 
Element Name :child5
Element Value : value 5
XmlTag:<child5>:::::ValueFetchedFromTheMap: value 5
Element Name :child6
Element Value : value 6 
XmlTag:<child6>:::::ValueFetchedFromTheMap: value 6 
Values Inside The Map:{child1= value 1 , child2= value 2 , child3= value 3 , child4= value 4 , child5= value 5, child6= value 6 }

What is the path that Django uses for locating and loading templates?

For Django 1.6.6:

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = os.path.join(BASE_DIR, 'templates')

Also static and media for debug and production mode:

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
if DEBUG:
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
else:
    STATIC_ROOT = %REAL_PATH_TO_PRODUCTION_STATIC_FOLDER%
    MEDIA_ROOT = %REAL_PATH_TO_PRODUCTION_MEDIA_FOLDER%

Into urls.py you must add:

from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings

from news.views import Index

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    ...
    )

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

In Django 1.8 you can set template paths, backend and other parameters for templates in one dictionary (settings.py):

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            path.join(BASE_DIR, 'templates')
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Official docs.

How can I print literal curly-brace characters in a string and also use .format on it?

If you are going to be doing this a lot, it might be good to define a utility function that will let you use arbitrary brace substitutes instead, like

def custom_format(string, brackets, *args, **kwargs):
    if len(brackets) != 2:
        raise ValueError('Expected two brackets. Got {}.'.format(len(brackets)))
    padded = string.replace('{', '{{').replace('}', '}}')
    substituted = padded.replace(brackets[0], '{').replace(brackets[1], '}')
    formatted = substituted.format(*args, **kwargs)
    return formatted

>>> custom_format('{{[cmd]} process 1}', brackets='[]', cmd='firefox.exe')
'{{firefox.exe} process 1}'

Note that this will work either with brackets being a string of length 2 or an iterable of two strings (for multi-character delimiters).

Using bind variables with dynamic SELECT INTO clause in PL/SQL

No you can't use bind variables that way. In your second example :into_bind in v_query_str is just a placeholder for value of variable v_num_of_employees. Your select into statement will turn into something like:

SELECT COUNT(*) INTO  FROM emp_...

because the value of v_num_of_employees is null at EXECUTE IMMEDIATE.

Your first example presents the correct way to bind the return value to a variable.

Edit

The original poster has edited the second code block that I'm referring in my answer to use OUT parameter mode for v_num_of_employees instead of the default IN mode. This modification makes the both examples functionally equivalent.

Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

Many people have answered the mechanical details already, but it's worth noting: This is a poor design choice, by Java.

Java's asList method is documented as "Returns a fixed-size list...". If you take its result and call (say) the .add method, it throws an UnsupportedOperationException. This is unintuitive behavior! If a method says it returns a List, the standard expectation is that it returns an object which supports the methods of interface List. A developer shouldn't have to memorize which of the umpteen util.List methods create Lists that don't actually support all the List methods.

If they had named the method asImmutableList, it would make sense. Or if they just had the method return an actual List (and copy the backing array), it would make sense. They decided to favor both runtime-performance and short names, at the expense of violating both the Principle of Least Surprise and the good-O.O. practice of avoiding UnsupportedOperationExceptions.

(Also, the designers might have made a interface ImmutableList, to avoid a plethora of UnsupportedOperationExceptions.)

How to define and use function inside Jenkins Pipeline config?

Solved! The call build job: project, parameters: params fails with an error java.lang.UnsupportedOperationException: must specify $class with an implementation of interface java.util.List when params = [:]. Replacing it with params = null solved the issue. Here the working code below.

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1')
    }
}

How to change xampp localhost to another folder ( outside xampp folder)?

steps :

  1. run your xampp control panel
  2. click the button saying config
  3. select apache( httpd.conf )
  4. find document root

replace

DocumentRoot "C:/xampp/htdocs"
<Directory "C:/xampp/htdocs">

Those 2 lines

| C:/xampp/htdocs == current location for root |

|change C:/xampp/htdocs with any location you want|

  1. save it

DONE: start apache and go to the localhost see in action [ watch video click here ]

How to make a class property?

Here's how I would do this:

class ClassPropertyDescriptor(object):

    def __init__(self, fget, fset=None):
        self.fget = fget
        self.fset = fset

    def __get__(self, obj, klass=None):
        if klass is None:
            klass = type(obj)
        return self.fget.__get__(obj, klass)()

    def __set__(self, obj, value):
        if not self.fset:
            raise AttributeError("can't set attribute")
        type_ = type(obj)
        return self.fset.__get__(obj, type_)(value)

    def setter(self, func):
        if not isinstance(func, (classmethod, staticmethod)):
            func = classmethod(func)
        self.fset = func
        return self

def classproperty(func):
    if not isinstance(func, (classmethod, staticmethod)):
        func = classmethod(func)

    return ClassPropertyDescriptor(func)


class Bar(object):

    _bar = 1

    @classproperty
    def bar(cls):
        return cls._bar

    @bar.setter
    def bar(cls, value):
        cls._bar = value


# test instance instantiation
foo = Bar()
assert foo.bar == 1

baz = Bar()
assert baz.bar == 1

# test static variable
baz.bar = 5
assert foo.bar == 5

# test setting variable on the class
Bar.bar = 50
assert baz.bar == 50
assert foo.bar == 50

The setter didn't work at the time we call Bar.bar, because we are calling TypeOfBar.bar.__set__, which is not Bar.bar.__set__.

Adding a metaclass definition solves this:

class ClassPropertyMetaClass(type):
    def __setattr__(self, key, value):
        if key in self.__dict__:
            obj = self.__dict__.get(key)
        if obj and type(obj) is ClassPropertyDescriptor:
            return obj.__set__(self, value)

        return super(ClassPropertyMetaClass, self).__setattr__(key, value)

# and update class define:
#     class Bar(object):
#        __metaclass__ = ClassPropertyMetaClass
#        _bar = 1

# and update ClassPropertyDescriptor.__set__
#    def __set__(self, obj, value):
#       if not self.fset:
#           raise AttributeError("can't set attribute")
#       if inspect.isclass(obj):
#           type_ = obj
#           obj = None
#       else:
#           type_ = type(obj)
#       return self.fset.__get__(obj, type_)(value)

Now all will be fine.

How to have click event ONLY fire on parent DIV, not children?

My case is similar but this is occasion when you have few foobar-s, and you want to close only one - per one click:

Find parent case

$(".foobar-close-button-class").on("click", function () {
    $(this).parents('.foobar').fadeOut( 100 );
    // 'this' - means that you finding some parent class from '.foobar-close-button-class'
    // '.parents' -means that you finding parent class with name '.foobar'
});

Find child case

$(".foobar-close-button-class").on("click", function () {
    $(this).child('.foobar-close-button-child-class').fadeOut( 100 );
    // 'this' - means that you finding some child class from '.foobar-close-button-class'
    // '.child' -means that you finding child class with name '.foobar-close-button-child-class'
});

Python Traceback (most recent call last)

In Python2, input is evaluated, input() is equivalent to eval(raw_input()). When you enter klj, Python tries to evaluate that name and raises an error because that name is not defined.

Use raw_input to get a string from the user in Python2.

Demo 1: klj is not defined:

>>> input()
klj
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'klj' is not defined

Demo 2: klj is defined:

>>> klj = 'hi'
>>> input()
klj
'hi'

Demo 3: getting a string with raw_input:

>>> raw_input()
klj
'klj'

Database design for a survey

Given the proper index your second solution is normalized and good for a traditional relational database system.

I don't know how huge is huge but it should hold without problem a couple million answers.

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

Pls, check if DataGridComboBoxColumn xaml below would work for you:

<DataGridComboBoxColumn 
    SelectedValueBinding="{Binding CompanyID}" 
    DisplayMemberPath="Name" 
    SelectedValuePath="ID">

    <DataGridComboBoxColumn.ElementStyle>
        <Style TargetType="{x:Type ComboBox}">
            <Setter Property="ItemsSource" Value="{Binding Path=DataContext.CompanyItems, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
        </Style>
    </DataGridComboBoxColumn.ElementStyle>
    <DataGridComboBoxColumn.EditingElementStyle>
        <Style TargetType="{x:Type ComboBox}">
            <Setter Property="ItemsSource" Value="{Binding Path=DataContext.CompanyItems, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
        </Style>
    </DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>

Here you can find another solution for the problem you're facing: Using combo boxes with the WPF DataGrid

Is it possible to use jQuery .on and hover?

The jQuery plugin hoverIntent http://cherne.net/brian/resources/jquery.hoverIntent.html goes much further than the naive approaches listed here. While they certainly work, they might not necessarily behave how users expect.

The strongest reason to use hoverIntent is the timeout feature. It allows you to do things like prevent a menu from closing because a user drags their mouse slightly too far to the right or left before they click the item they want. It also provides capabilities for not activating hover events in a barrage and waits for focused hovering.

Usage example:

var config = {    
 sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
 interval: 200, // number = milliseconds for onMouseOver polling interval    
 over: makeTall, // function = onMouseOver callback (REQUIRED)    
 timeout: 500, // number = milliseconds delay before onMouseOut    
 out: makeShort // function = onMouseOut callback (REQUIRED)
};
$("#demo3 li").hoverIntent( config )

Further explaination of this can be found on https://stackoverflow.com/a/1089381/37055

Convert Xml to Table SQL Server

This is the answer, hope it helps someone :)

First there are two variations on how the xml can be written:

1

<row>
    <IdInvernadero>8</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>8</IdCaracteristica1>
    <IdCaracteristica2>8</IdCaracteristica2>
    <Cantidad>25</Cantidad>
    <Folio>4568457</Folio>
</row>
<row>
    <IdInvernadero>3</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>1</IdCaracteristica1>
    <IdCaracteristica2>2</IdCaracteristica2>
    <Cantidad>72</Cantidad>
    <Folio>4568457</Folio>
</row>

Answer:

SELECT  
       Tbl.Col.value('IdInvernadero[1]', 'smallint'),  
       Tbl.Col.value('IdProducto[1]', 'smallint'),  
       Tbl.Col.value('IdCaracteristica1[1]', 'smallint'),
       Tbl.Col.value('IdCaracteristica2[1]', 'smallint'),
       Tbl.Col.value('Cantidad[1]', 'int'),
       Tbl.Col.value('Folio[1]', 'varchar(7)')
FROM   @xml.nodes('//row') Tbl(Col)  

2.

<row IdInvernadero="8" IdProducto="3" IdCaracteristica1="8" IdCaracteristica2="8" Cantidad ="25" Folio="4568457" />                         
<row IdInvernadero="3" IdProducto="3" IdCaracteristica1="1" IdCaracteristica2="2" Cantidad ="72" Folio="4568457" />

Answer:

SELECT  
       Tbl.Col.value('@IdInvernadero', 'smallint'),  
       Tbl.Col.value('@IdProducto', 'smallint'),  
       Tbl.Col.value('@IdCaracteristica1', 'smallint'),
       Tbl.Col.value('@IdCaracteristica2', 'smallint'),
       Tbl.Col.value('@Cantidad', 'int'),
       Tbl.Col.value('@Folio', 'varchar(7)')

FROM   @xml.nodes('//row') Tbl(Col)

Taken from:

  1. http://kennyshu.blogspot.com/2007/12/convert-xml-file-to-table-in-sql-2005.html

  2. http://msdn.microsoft.com/en-us/library/ms345117(SQL.90).aspx

How may I sort a list alphabetically using jQuery?

$(".list li").sort(asc_sort).appendTo('.list');
//$("#debug").text("Output:");
// accending sort
function asc_sort(a, b){
    return ($(b).text()) < ($(a).text()) ? 1 : -1;    
}

// decending sort
function dec_sort(a, b){
    return ($(b).text()) > ($(a).text()) ? 1 : -1;    
}

live demo : http://jsbin.com/eculis/876/edit

$(document).ready(function(){ Uncaught ReferenceError: $ is not defined

Remember that you must first load jquery script and then the script js

<script type="text/javascript" src="http://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="example.js"></script>

Html is read sequentially!

Oracle SQL: Update a table with data from another table

This is called a correlated update

UPDATE table1 t1
   SET (name, desc) = (SELECT t2.name, t2.desc
                         FROM table2 t2
                        WHERE t1.id = t2.id)
 WHERE EXISTS (
    SELECT 1
      FROM table2 t2
     WHERE t1.id = t2.id )

Assuming the join results in a key-preserved view, you could also

UPDATE (SELECT t1.id, 
               t1.name name1,
               t1.desc desc1,
               t2.name name2,
               t2.desc desc2
          FROM table1 t1,
               table2 t2
         WHERE t1.id = t2.id)
   SET name1 = name2,
       desc1 = desc2

Loading scripts after page load?

http://jsfiddle.net/c725wcn9/2/embedded

You will need to inspect the DOM to check this works. Jquery is needed.

$(document).ready(function(){
   var el = document.createElement('script');
   el.type = 'application/ld+json';
   el.text = JSON.stringify({ "@context": "http://schema.org",  "@type": "Recipe", "name": "My recipe name" });

   document.querySelector('head').appendChild(el);
});

Setting up Eclipse with JRE Path

You can add this line to eclipse.ini :

-vm 
D:/work/Java/jdk1.6.0_13/bin/javaw.exe  <-- change to your JDK actual path
-vmargs <-- needs to be after -vm <path>

But it's worth setting JAVA_HOME and JRE_HOME anyway because it may not work as if the path environment points to a different java version.

Because the next one to complain will be Maven, etc.

Spring JUnit: How to Mock autowired component in autowired component

You could use Mockito. I am not sure with PostConstruct specifically, but this generally works:

// Create a mock of Resource to change its behaviour for testing
@Mock
private Resource resource;

// Testing instance, mocked `resource` should be injected here 
@InjectMocks
@Resource
private TestedClass testedClass;

@Before
public void setUp() throws Exception {
    // Initialize mocks created above
    MockitoAnnotations.initMocks(this);
    // Change behaviour of `resource`
    when(resource.getSomething()).thenReturn("Foo");   
}

Why do we need C Unions?

I used union when I was coding for embedded devices. I have C int that is 16 bit long. And I need to retrieve the higher 8 bits and the lower 8 bits when I need to read from/store to EEPROM. So I used this way:

union data {
    int data;
    struct {
        unsigned char higher;
        unsigned char lower;
    } parts;
};

It doesn't require shifting so the code is easier to read.

On the other hand, I saw some old C++ stl code that used union for stl allocator. If you are interested, you can read the sgi stl source code. Here is a piece of it:

union _Obj {
    union _Obj* _M_free_list_link;
    char _M_client_data[1];    /* The client sees this.        */
};

Get Today's date in Java at midnight time

private static Date truncateTime(Calendar cal) {
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return new Date(cal.getTime().getTime());
}
 public static void main(String[] args) throws Exception{
        Date d2 = new Date();
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(d2);
        Date d1 = truncateTime( cal );
        System.out.println(d1.toString());
        System.out.println(d2.toString());
}

Compute elapsed time

First, you can always grab the current time by

var currentTime = new Date();

Then you could check out this "pretty date" example at http://www.zachleat.com/Lib/jquery/humane.js

If that doesn't work for you, just google "javascript pretty date" and you'll find dozens of example scripts.

Good luck.

How does cellForRowAtIndexPath work?

1) The function returns a cell for a table view yes? So, the returned object is of type UITableViewCell. These are the objects that you see in the table's rows. This function basically returns a cell, for a table view. But you might ask, how the function would know what cell to return for what row, which is answered in the 2nd question

2)NSIndexPath is essentially two things-

  • Your Section
  • Your row

Because your table might be divided to many sections and each with its own rows, this NSIndexPath will help you identify precisely which section and which row. They are both integers. If you're a beginner, I would say try with just one section.

It is called if you implement the UITableViewDataSource protocol in your view controller. A simpler way would be to add a UITableViewController class. I strongly recommend this because it Apple has some code written for you to easily implement the functions that can describe a table. Anyway, if you choose to implement this protocol yourself, you need to create a UITableViewCell object and return it for whatever row. Have a look at its class reference to understand re-usablity because the cells that are displayed in the table view are reused again and again(this is a very efficient design btw).

As for when you have two table views, look at the method. The table view is passed to it, so you should not have a problem with respect to that.

What does "implements" do on a class?

Interfaces are implemented through classes. They are purely abstract classes, if you will.

In PHP when a class implements from an interface, the methods defined in that interface are to be strictly followed. When a class inherits from a parent class, method parameters may be altered. That is not the case for interfaces:

interface ImplementMeStrictly {
   public function foo($a, $b);
}

class Obedient implements ImplementMeStrictly {
   public function foo($a, $b, $c) 
      {
      }
}

will cause an error, because the interface wasn't implemented as defined. Whereas:

class InheritMeLoosely {
   public function foo($a)
      {
      }
}

class IDoWhateverWithFoo extends InheritMeLoosely {
   public function foo()
      {
      }
}

Is allowed.

jQuery UI Tabs - How to Get Currently Selected Tab Index

$( "#tabs" ).tabs( "option", "active" )

then you will have the index of tab from 0

simple

How to properly create composite primary keys - MYSQL

I would use a composite (multi-column) key.

CREATE TABLE INFO (
    t1ID INT,
    t2ID INT,
    PRIMARY KEY (t1ID, t2ID)
) 

This way you can have t1ID and t2ID as foreign keys pointing to their respective tables as well.

remove all variables except functions

I wrote this to remove all objects apart from functions from the current environment (Programming language used is R with IDE R-Studio):

    remove_list=c()                             # create a vector

      for(i in 1:NROW(ls())){                   # repeat over all objects in environment
        if(class(get(ls()[i]))!="function"){    # if object is *not* a function
         remove_list=c(remove_list,ls()[i])     # ..add to vector remove_list
         }    
      }

    rm(list=remove_list)                        # remove all objects named in remove_list

Notes-

The argument "list" in rm(list=) must be a character vector.

The name of an object in position i of the current environment is returned from ls()[i] and the object itself from get(ls()[i]). Therefore the class of an object is returned from class(get(ls()[i]))

How can I get my Android device country code without using GPS?

There isn't any need to call any API. You can get the country code from your device where it is located. Just use this function:

 fun getUserCountry(context: Context): String? {
    try {
        val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        val simCountry = tm.simCountryIso
        if (simCountry != null && simCountry.length == 2) { // SIM country code is available
            return simCountry.toLowerCase(Locale.US)
        } 
        else if (tm.phoneType != TelephonyManager.PHONE_TYPE_CDMA) { // Device is not 3G (would be unreliable)
            val networkCountry = tm.networkCountryIso
            if (networkCountry != null && networkCountry.length == 2) { // network country code is available
                return networkCountry.toLowerCase(Locale.US)
            }
        }
    }
    catch (e: Exception) {
    }
    return null
}

How to set the margin or padding as percentage of height of parent container?

This is a very interesting bug. (In my opinion, it is a bug anyway) Nice find!

Regarding how to set it, I would recommend Camilo Martin's answer. But as to why, I'd like to explain this a bit if you guys don't mind.


In the CSS specs I found:

'padding'
Percentages: refer to width of containing block

… which is weird, but okay.

So, with a parent width: 210px and a child padding-top: 50%, I get a calculated/computed value of padding-top: 96.5px – which is not the expected 105px.

That is because in Windows (I'm not sure about other OSs), the size of common scrollbars is per default 17px × 100% (or 100% × 17px for horizontal bars). Those 17px are substracted before calculating the 50%, hence 50% of 193px = 96.5px.

How do I view the Explain Plan in Oracle Sql developer?

Explain only shows how the optimizer thinks the query will execute.

To show the real plan, you will need to run the sql once. Then use the same session run the following:

@yoursql 
select * from table(dbms_xplan.display_cursor()) 

This way can show the real plan used during execution. There are several other ways in showing plan using dbms_xplan. You can Google with term "dbms_xplan".

Could not find an implementation of the query pattern

I had a similar issue with generated strongly typed datasets, the full error message was:

Could not find an implementation of the query pattern for source type 'MyApp.InvcHeadDataTable'. 'Where' not found. Consider explicitly specifying the type of the range variable 'row'.

From my code:

        var x =
            from row in ds.InvcHead
            where row.Company == Session.CompanyID
            select row;

So I did as it suggested and explicitly specified the type:

        var x =
            from MyApp.InvcHeadRow row in ds.InvcHead
            where row.Company == Session.CompanyID
            select row;

Which worked a treat.

pandas: find percentile stats of a given column

You can even give multiple columns with null values and get multiple quantile values (I use 95 percentile for outlier treatment)

my_df[['field_A','field_B']].dropna().quantile([0.0, .5, .90, .95])

WCF service startup error "This collection already contains an address with scheme http"

I came by the same error on an old 2010 Exchange Server. A service(Exchange mailbox replication service) was giving out the above error and the migration process could not be continued. Searching through the internet, i came by this link which stated the below:

The Exchange GRE fails to open when installed for the first time or if any changes are made to the IIS server. It fails with snap-in error and when you try to open the snap-in page, the following content is displayed:

This collection already contains an address with scheme http.  There can be at most one address per scheme in this collection. If your service is being hosted in IIS you can fix the problem by setting 'system.serviceModel/serviceHostingEnvironment/multipleSiteBindingsEnabled' to true or specifying 'system.serviceModel/serviceHostingEnvironment/baseAddressPrefixFilters'."

Cause: This error occurs because http port number 443 is already in use by another application and the IIS server is not configured to handle multiple binding to the same port.

Solution: Configure IIS server to handle multiple port bindings. Contact the vendor (Microsoft) to configure it.

Since these services were offered from an IIS Web Server, checking the Bindings on the Root Site fixed the problem. Someone had messed up the Site Bindings, defining rules that were overlapping themselves and messed up the services.

Fixing the correct Bindings resolved the problem, in my case, and i did not have to configure the Web.Config.

C++ String Concatenation operator<<

nametext is an std::string but these do not have the stream insertion operator (<<) like output streams do.

To concatenate strings you can use the append member function (or its equivalent, +=, which works in the exact same way) or the + operator, which creates a new string as a result of concatenating the previous two.

Conditional logic in AngularJS template

You could use the ngSwitch directive:

  <div ng-switch on="selection" >
    <div ng-switch-when="settings">Settings Div</div>
    <span ng-switch-when="home">Home Span</span>
    <span ng-switch-default>default</span>
  </div>

If you don't want the DOM to be loaded with empty divs, you need to create your custom directive using $http to load the (sub)templates and $compile to inject it in the DOM when a certain condition has reached.

This is just an (untested) example. It can and should be optimized:

HTML:

<conditional-template ng-model="element" template-url1="path/to/partial1" template-url2="path/to/partial2"></div>

Directive:

app.directive('conditionalTemplate', function($http, $compile) {
   return {
      restrict: 'E',
      require: '^ngModel',
      link: function(sope, element, attrs, ctrl) {
        // get template with $http
        // check model via ctrl.$viewValue
        // compile with $compile
        // replace element with element.replaceWith()
      }
   };
});

oracle sql: update if exists else insert

MERGE doesn't need "multiple tables", but it does need a query as the source. Something like this should work:

MERGE INTO mytable d
USING (SELECT 1 id, 'x' name from dual) s
ON (d.id = s.id)
WHEN MATCHED THEN UPDATE SET d.name = s.name
WHEN NOT MATCHED THEN INSERT (id, name) VALUES (s.id, s.name);

Alternatively you can do this in PL/SQL:

BEGIN
  INSERT INTO mytable (id, name) VALUES (1, 'x');
EXCEPTION
  WHEN DUP_VAL_ON_INDEX THEN
    UPDATE mytable
    SET    name = 'x'
    WHERE id = 1;
END;

How do you sort a dictionary by value?

Sort and print:

var items = from pair in players_Dic
                orderby pair.Value descending
                select pair;

// Display results.
foreach (KeyValuePair<string, int> pair in items)
{
    Debug.Log(pair.Key + " - " + pair.Value);
}

Change descending to acending to change sort order

How to convert POJO to JSON and vice versa?

Use GSON for converting POJO to JSONObject. Refer here.

For converting JSONObject to POJO, just call the setter method in the POJO and assign the values directly from the JSONObject.

Full-screen responsive background image

for Full-screen responsive background image

set css height ( height:100vh )

example :

.main-header {
    background-image: url(../img/bb-background2.png);
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
    width: 100%;
    height:100vh;  /* responsive height */
}

Get elements by attribute when querySelectorAll is not available without using libraries?

I played a bit around and ended up with this crude solution:

function getElementsByAttribute(attribute, context) {
  var nodeList = (context || document).getElementsByTagName('*');
  var nodeArray = [];
  var iterator = 0;
  var node = null;

  while (node = nodeList[iterator++]) {
    if (node.hasAttribute(attribute)) nodeArray.push(node);
  }

  return nodeArray;
}

The usage is quite simple, and works even in IE8:

getElementsByAttribute('data-foo');
// or with parentNode
getElementsByAttribute('data-foo', document);

http://fiddle.jshell.net/9xaxf6jr/

But I recommend to use querySelector / All for this (and to support older browsers use a polyfill):

document.querySelectorAll('[data-foo]');

Take n rows from a spark dataframe and pass to toPandas()

You could get first rows of Spark DataFrame with head and then create Pandas DataFrame:

l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])

df_pandas = pd.DataFrame(df.head(3), columns=df.columns)

In [4]: df_pandas
Out[4]: 
     name  age
0   Alice    1
1     Jim    2
2  Sandra    3

Lua string to int

local a = "10"
print(type(a))
local num = tonumber(a)
print(type(num))

Output

   string                                                                                                                                                                          
   number

How to rotate a 3D object on axis three.js?

Here are the two functions I use. They are based on matrix rotations. and can rotate around arbitrary axes. To rotate using the world's axes you would want to use the second function rotateAroundWorldAxis().

// Rotate an object around an arbitrary axis in object space
var rotObjectMatrix;
function rotateAroundObjectAxis(object, axis, radians) {
    rotObjectMatrix = new THREE.Matrix4();
    rotObjectMatrix.makeRotationAxis(axis.normalize(), radians);

    // old code for Three.JS pre r54:
    // object.matrix.multiplySelf(rotObjectMatrix);      // post-multiply
    // new code for Three.JS r55+:
    object.matrix.multiply(rotObjectMatrix);

    // old code for Three.js pre r49:
    // object.rotation.getRotationFromMatrix(object.matrix, object.scale);
    // old code for Three.js r50-r58:
    // object.rotation.setEulerFromRotationMatrix(object.matrix);
    // new code for Three.js r59+:
    object.rotation.setFromRotationMatrix(object.matrix);
}

var rotWorldMatrix;
// Rotate an object around an arbitrary axis in world space       
function rotateAroundWorldAxis(object, axis, radians) {
    rotWorldMatrix = new THREE.Matrix4();
    rotWorldMatrix.makeRotationAxis(axis.normalize(), radians);

    // old code for Three.JS pre r54:
    //  rotWorldMatrix.multiply(object.matrix);
    // new code for Three.JS r55+:
    rotWorldMatrix.multiply(object.matrix);                // pre-multiply

    object.matrix = rotWorldMatrix;

    // old code for Three.js pre r49:
    // object.rotation.getRotationFromMatrix(object.matrix, object.scale);
    // old code for Three.js pre r59:
    // object.rotation.setEulerFromRotationMatrix(object.matrix);
    // code for r59+:
    object.rotation.setFromRotationMatrix(object.matrix);
}

So you should call these functions within your anim function (requestAnimFrame callback), resulting in a rotation of 90 degrees on the x-axis:

var xAxis = new THREE.Vector3(1,0,0);
rotateAroundWorldAxis(mesh, xAxis, Math.PI / 180);

invalid_grant trying to get oAuth token from google

There are two major reasons for invalid_grant error which you have to take care prior to the POST request for Refresh Token and Access Token.

  1. Request header must contain "content-type: application/x-www-form-urlencoded"
  2. Your request payload should be url encoded Form Data, don't send as json object.

RFC 6749 OAuth 2.0 defined invalid_grant as: The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.

I found another good article, here you will find many other reasons for this error.

https://blog.timekit.io/google-oauth-invalid-grant-nightmare-and-how-to-fix-it-9f4efaf1da35

What uses are there for "placement new"?

It is useful if you are building a kernel - where do you place the kernel code you read from disk or the pagetable? You need to know where to jump to.

Or in other, very rare circumstances such as when you have loads of allocated room and want to place a few structures behind each other. They can be packed this way without the need for the offsetof() operator. There are other tricks for that too, though.

I also believe some STL implementations make use of placement new, like std::vector. They allocate room for 2^n elements that way and don't need to always realloc.

JavaScript replace/regex

You need to double escape any RegExp characters (once for the slash in the string and once for the regexp):

  "$TESTONE $TESTONE".replace( new RegExp("\\$TESTONE","gm"),"foo")

Otherwise, it looks for the end of the line and 'TESTONE' (which it never finds).

Personally, I'm not a big fan of building regexp's using strings for this reason. The level of escaping that's needed could lead you to drink. I'm sure others feel differently though and like drinking when writing regexes.

Visual Studio popup: "the operation could not be completed"

enter image description hereRestart the visual studio as Admin will work on in many cases.

referenced before assignment error in python

def inside():
   global var
   var = 'info'
inside()
print(var)

>>>'info'

problem ended

Is mongodb running?

I know this is for php, but I got here looking for a solution for node. Using mongoskin:

mongodb.admin().ping(function(err) {
    if(err === null)
        // true - you got a conntion, congratulations
    else if(err.message.indexOf('failed to connect') !== -1)
        // false - database isn't around
    else
        // actual error, do something about it
})

With other drivers, you can attempt to make a connection and if it fails, you know the mongo server's down. Mongoskin needs to actually make some call (like ping) because it connects lazily. For php, you can use the try-to-connect method. Make a script!

PHP:

$dbIsRunning = true
try {
  $m = new MongoClient('localhost:27017');
} catch($e) {
  $dbIsRunning = false
}

How to inject JPA EntityManager using spring

Yes, although it's full of gotchas, since JPA is a bit peculiar. It's very much worth reading the documentation on injecting JPA EntityManager and EntityManagerFactory, without explicit Spring dependencies in your code:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-jpa

This allows you to either inject the EntityManagerFactory, or else inject a thread-safe, transactional proxy of an EntityManager directly. The latter makes for simpler code, but means more Spring plumbing is required.

How to check if the docker engine and a docker container are running?

You can check with this command systemctl status docker it will show the status of the docker. If you want to start you can use systemctl start docker instead of systemctl you can try also with service, service docker status and service docker start respectively.

Convert varchar to float IF ISNUMERIC

..extending Mikaels' answers

SELECT
  CASE WHEN ISNUMERIC(QTY + 'e0') = 1 THEN CAST(QTY AS float) ELSE null END AS MyFloat
  CASE WHEN ISNUMERIC(QTY + 'e0') = 0 THEN QTY ELSE null END AS MyVarchar
FROM
  ...
  • Two data types requires two columns
  • Adding e0 fixes some ISNUMERIC issues (such as + - . and empty string being accepted)

How to check if a string "StartsWith" another string?

var str = 'hol';
var data = 'hola mundo';
if (data.length >= str.length && data.substring(0, str.length) == str)
    return true;
else
    return false;

Is there a MySQL option/feature to track history of changes to records?

Here is how we solved it

a Users table looked like this

Users
-------------------------------------------------
id | name | address | phone | email | created_on | updated_on

And the business requirement changed and we were in a need to check all previous addresses and phone numbers a user ever had. new schema looks like this

Users (the data that won't change over time)
-------------
id | name

UserData (the data that can change over time and needs to be tracked)
-------------------------------------------------
id | id_user | revision | city | address | phone | email | created_on
 1 |   1     |    0     | NY   | lake st | 9809  | @long | 2015-10-24 10:24:20
 2 |   1     |    2     | Tokyo| lake st | 9809  | @long | 2015-10-24 10:24:20
 3 |   1     |    3     | Sdny | lake st | 9809  | @long | 2015-10-24 10:24:20
 4 |   2     |    0     | Ankr | lake st | 9809  | @long | 2015-10-24 10:24:20
 5 |   2     |    1     | Lond | lake st | 9809  | @long | 2015-10-24 10:24:20

To find the current address of any user, we search for UserData with revision DESC and LIMIT 1

To get the address of a user between a certain period of time we can use created_on bewteen (date1 , date 2)

Cannot find module '@angular/compiler'

Uninstall the Angular CLI and install the latest version of it.

npm uninstall angular-cli

npm install --save-dev @angular/cli@latest

Slice indices must be integers or None or have __index__ method

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))

What does iterator->second mean?

The type of the elements of an std::map (which is also the type of an expression obtained by dereferencing an iterator of that map) whose key is K and value is V is std::pair<const K, V> - the key is const to prevent you from interfering with the internal sorting of map values.

std::pair<> has two members named first and second (see here), with quite an intuitive meaning. Thus, given an iterator i to a certain map, the expression:

i->first

Which is equivalent to:

(*i).first

Refers to the first (const) element of the pair object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression:

i->second

Which is equivalent to:

(*i).second

Refers to the second element of the pair - i.e. to the corresponding value in the map.

React fetch data in server before render

What you're looking for is componentWillMount.

From the documentation:

Invoked once, both on the client and server, immediately before the initial rendering occurs. If you call setState within this method, render() will see the updated state and will be executed only once despite the state change.

So you would do something like this:

componentWillMount : function () {
    var data = this.getData();
    this.setState({data : data});
},

This way, render() will only be called once, and you'll have the data you're looking for in the initial render.

How can I list (ls) the 5 last modified files in a directory?

Try using head or tail. If you want the 5 most-recently modified files:

ls -1t | head -5

The -1 (that's a one) says one file per line and the head says take the first 5 entries.

If you want the last 5 try

ls -1t | tail -5

MySQL error - #1062 - Duplicate entry ' ' for key 2

As it was said you have a unique index.

However, when I added most of the list yesterday I didn't get this error once even though a lot of the entries I added yesterday have a blank cell in column 2 as well. Whats going on?

That means that all these entries contain value NULL, not empty string ''. Mysql lets you have multiple NULL values in unique fields.

Android Studio: Unable to start the daemon process

Not sure this will fix the problem for everyone , But uninstalling java, java SDK and installing the latest version (Version 8) fixed the issue for me ..

EditText underline below text property

You have to use a different background image, not color, for each state of the EditText (focus, enabled, activated).

http://android-holo-colors.com/

In the site above, you can get images from a lot of components in the Holo theme. Just select "EditText" and the color you want. You can see a preview at the bottom of the page.

Download the .zip file, and copy paste the resources in your project (images and the XML).

if your XML is named: apptheme_edit_text_holo_light.xml (or something similar):

  1. Go to your XML "styles.xml" and add the custom EditText style:

    <style name="EditTextCustomHolo" parent="android:Widget.EditText">
       <item name="android:background">@drawable/apptheme_edit_text_holo_light</item>
       <item name="android:textColor">#ffffff</item>
    </style>
    
  2. Just do this in your EditText:

    <EditText
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       style="@style/EditTextCustomHolo"/>
    

And that's it, I hope it helps you.

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
    

How should I declare default values for instance variables in Python?

You can also declare class variables as None which will prevent propagation. This is useful when you need a well defined class and want to prevent AttributeErrors. For example:

>>> class TestClass(object):
...     t = None
... 
>>> test = TestClass()
>>> test.t
>>> test2 = TestClass()
>>> test.t = 'test'
>>> test.t
'test'
>>> test2.t
>>>

Also if you need defaults:

>>> class TestClassDefaults(object):
...    t = None
...    def __init__(self, t=None):
...       self.t = t
... 
>>> test = TestClassDefaults()
>>> test.t
>>> test2 = TestClassDefaults([])
>>> test2.t
[]
>>> test.t
>>>

Of course still follow the info in the other answers about using mutable vs immutable types as the default in __init__.

php get values from json encode

json_decode will return the same array that was originally encoded. For instanse, if you

$array = json_decode($json, true);
echo $array['countryId'];

OR

$obj= json_decode($json);

echo $obj->countryId;

These both will echo 84. I think json_encode and json_decode function names are self-explanatory...

What Makes a Method Thread-safe? What are the rules?

If a method only accesses local variables, it's thread safe. Is that it?

Absolultely not. You can write a program with only a single local variable accessed from a single thread that is nevertheless not threadsafe:

https://stackoverflow.com/a/8883117/88656

Does that apply for static methods as well?

Absolutely not.

One answer, provided by @Cybis, was: "Local variables cannot be shared among threads because each thread gets its own stack."

Absolutely not. The distinguishing characteristic of a local variable is that it is only visible from within the local scope, not that it is allocated on the temporary pool. It is perfectly legal and possible to access the same local variable from two different threads. You can do so by using anonymous methods, lambdas, iterator blocks or async methods.

Is that the case for static methods as well?

Absolutely not.

If a method is passed a reference object, does that break thread safety?

Maybe.

I've done some research, and there is a lot out there about certain cases, but I was hoping to be able to define, by using just a few rules, guidelines to follow to make sure a method is thread safe.

You are going to have to learn to live with disappointment. This is a very difficult subject.

So, I guess my ultimate question is: "Is there a short list of rules that define a thread-safe method?

Nope. As you saw from my example earlier an empty method can be non-thread-safe. You might as well ask "is there a short list of rules that ensures a method is correct". No, there is not. Thread safety is nothing more than an extremely complicated kind of correctness.

Moreover, the fact that you are asking the question indicates your fundamental misunderstanding about thread safety. Thread safety is a global, not a local property of a program. The reason why it is so hard to get right is because you must have a complete knowledge of the threading behaviour of the entire program in order to ensure its safety.

Again, look at my example: every method is trivial. It is the way that the methods interact with each other at a "global" level that makes the program deadlock. You can't look at every method and check it off as "safe" and then expect that the whole program is safe, any more than you can conclude that because your house is made of 100% non-hollow bricks that the house is also non-hollow. The hollowness of a house is a global property of the whole thing, not an aggregate of the properties of its parts.

Safari 3rd party cookie iframe trick no longer working?

I have also been suffering from this problem, but finally got the solution, Initially directly the load the iframe url in browser like small popup then only access the session values inside the iframe.

Removing nan values from an array

As shown by others

x[~numpy.isnan(x)]

works. But it will throw an error if the numpy dtype is not a native data type, for example if it is object. In that case you can use pandas.

x[~pandas.isna(x)] or x[~pandas.isnull(x)]

Stretch image to fit full container width bootstrap

First of all if the size of the image is smaller than the container, then only "img-fluid" class will not solve your problem. you have to set the width of image to 100%, for that you can use Bootstrap class "w-100". keep in mind that "container-fluid" and "col-12" class sets left and right padding to 15px and "row" class sets left and right margin to "-15px" by default. make sure to set them to 0.

Note: "px-0" is a bootstrap class which sets left and right padding to 0 and
"mx-0" is a bootstrap class which sets left and right margin to 0

P.S. i am using Bootstrap 4.0 version.

 <div class="container-fluid px-0">
        <div class="row mx-0">
            <div class="col-12 px-0">
            <img src="images/top.jpg" class="img-fluid w-100">
            </div>
        </div>
    </div>

Jquery find nearest matching element

var otherInput = $(this).closest('.row').find('.inputQty');

That goes up to a row level, then back down to .inputQty.

Writing a string to a cell in excel

replace Range("A1") = "Asdf" with Range("A1").value = "Asdf"

Instantiating a generic type

You cannot do new T() due to type erasure. The default constructor can only be

public Navigation() {     this("", "", null); } 

​ You can create other constructors to provide default values for trigger and description. You need an concrete object of T.

How to clear/delete the contents of a Tkinter Text widget?

this works

import tkinter as tk
inputEdit.delete("1.0",tk.END)

PDOException “could not find driver”

$DB_TYPE = 'mysql'; //Type of database<br>
$DB_HOST = 'localhost'; //Host name<br>
$DB_USER = 'root'; //Host Username<br>
$DB_PASS = ''; //Host Password<br>
$DB_NAME = 'database_name'; //Database name<br><br>

$dbh = new PDO("$DB_TYPE:host=$DB_HOST; dbname=$DB_NAME;", $DB_USER, $DB_PASS); // PDO Connection

This worked for me.

ListView with Add and Delete Buttons in each Row in android

public class UserCustomAdapter extends ArrayAdapter<User> {
 Context context;
 int layoutResourceId;
 ArrayList<User> data = new ArrayList<User>();

 public UserCustomAdapter(Context context, int layoutResourceId,
   ArrayList<User> data) {
  super(context, layoutResourceId, data);
  this.layoutResourceId = layoutResourceId;
  this.context = context;
  this.data = data;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  View row = convertView;
  UserHolder holder = null;

  if (row == null) {
   LayoutInflater inflater = ((Activity) context).getLayoutInflater();
   row = inflater.inflate(layoutResourceId, parent, false);
   holder = new UserHolder();
   holder.textName = (TextView) row.findViewById(R.id.textView1);
   holder.textAddress = (TextView) row.findViewById(R.id.textView2);
   holder.textLocation = (TextView) row.findViewById(R.id.textView3);
   holder.btnEdit = (Button) row.findViewById(R.id.button1);
   holder.btnDelete = (Button) row.findViewById(R.id.button2);
   row.setTag(holder);
  } else {
   holder = (UserHolder) row.getTag();
  }
  User user = data.get(position);
  holder.textName.setText(user.getName());
  holder.textAddress.setText(user.getAddress());
  holder.textLocation.setText(user.getLocation());
  holder.btnEdit.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Edit Button Clicked", "**********");
    Toast.makeText(context, "Edit button Clicked",
      Toast.LENGTH_LONG).show();
   }
  });
  holder.btnDelete.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Delete Button Clicked", "**********");
    Toast.makeText(context, "Delete button Clicked",
      Toast.LENGTH_LONG).show();
   }
  });
  return row;

 }

 static class UserHolder {
  TextView textName;
  TextView textAddress;
  TextView textLocation;
  Button btnEdit;
  Button btnDelete;
 }
}

Hey Please have a look here-

I have same answer here on my blog ..

How to run Nginx within a Docker container without halting?

It is also good idea to use supervisord or runit[1] for service management.

[1] https://github.com/phusion/baseimage-docker

Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

The instances of the new HttpHeader class are immutable objects. Invoking class methods will return a new instance as result. So basically, you need to do the following:

let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');

or

const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});

Update: adding multiple headers

let headers = new HttpHeaders();
headers = headers.set('h1', 'v1').set('h2','v2');

or

const headers = new HttpHeaders({'h1':'v1','h2':'v2'});

Update: accept object map for HttpClient headers & params

Since 5.0.0-beta.6 is now possible to skip the creation of a HttpHeaders object an directly pass an object map as argument. So now its possible to do the following:

http.get('someurl',{
   headers: {'header1':'value1','header2':'value2'}
});

C++ Object Instantiation

There's no reason to new (on the heap) when you can allocate on the stack (unless for some reason you've got a small stack and want to use the heap.

You might want to consider using a shared_ptr (or one of its variants) from the standard library if you do want to allocate on the heap. That'll handle doing the delete for you once all references to the shared_ptr have gone out of existance.

Avoid dropdown menu close on click inside

The simplest working solution for me is:

  • adding keep-open class to elements that should not cause dropdown closing
  • and this piece of code do the rest:
$('.dropdown').on('click', function(e) {
    var target = $(e.target);
    var dropdown = target.closest('.dropdown');
    return !dropdown.hasClass('open') || !target.hasClass('keep-open');
});

How can I get phone serial number (IMEI)

pls refer this https://stackoverflow.com/a/1972404/951045

 TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); 
  mngr.getDeviceId();

add READ_PHONE_STATE permission to AndroidManifest.xml

Put buttons at bottom of screen with LinearLayout?

You can use a RelativeLayout and align it to the bottom with android:layout_alignParentBottom="true"

How to make php display \t \n as tab and new line instead of characters

"\n" = new line
'\n' = \n
"\t" = tab
'\t' = \t

Xcode 5.1 - No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=i386)

My problem was that the Pods project was targeting OS X, despite my Podfile having platform :ios. I'm using cocoapods 0.35.0.rc2.

To fix it, select the Pods project in the project navigator, and check that the Pods PROJECT node (mind you, not the Pods target) is targeting iOS. That is, the architectures build settings should be:

  • Architectures: $(ARCHS_STANDARD)
  • Base SDK: iOS 8.1
  • Supported Platforms: iOS
  • Valid architectures: $(ARCHS_STANDARD)

I also wanted to build all architectures, so I added the following to the Podfile:

post_install do | installer |
    installer.project.build_configurations.each do |config|
        config.build_settings['ONLY_ACTIVE_ARCH'] = 'NO'
    end
end

Why use Ruby's attr_accessor, attr_reader and attr_writer?

You don't always want your instance variables to be fully accessible from outside of the class. There are plenty of cases where allowing read access to an instance variable makes sense, but writing to it might not (e.g. a model that retrieves data from a read-only source). There are cases where you want the opposite, but I can't think of any that aren't contrived off the top of my head.

How to get JSON from URL in JavaScript?

//Resolved
const fetchPromise1 = fetch(url);
    fetchPromise1.then(response => {
      console.log(response);
    });


//Pending
const fetchPromise = fetch(url);
console.log(fetchPromise);

Reshape an array in NumPy

numpy has a great tool for this task ("numpy.reshape") link to reshape documentation

a = [[ 0  1]
 [ 2  3]
 [ 4  5]
 [ 6  7]
 [ 8  9]
 [10 11]
 [12 13]
 [14 15]
 [16 17]]

`numpy.reshape(a,(3,3))`

you can also use the "-1" trick

`a = a.reshape(-1,3)`

the "-1" is a wild card that will let the numpy algorithm decide on the number to input when the second dimension is 3

so yes.. this would also work: a = a.reshape(3,-1)

and this: a = a.reshape(-1,2) would do nothing

and this: a = a.reshape(-1,9) would change the shape to (2,9)

Asus Zenfone 5 not detected by computer

This should solve your problem.

  1. Download the Asus USB Driver for Zenfone 5 here
  2. Extract the rar file
  3. Go to your Device Manager if you're on Windows (Make sure you've connected your phone to your computer)
  4. Choose update driver then browse the path to where the extracted rar file is. It should prompt something on your phone, just accept it
  5. Try it on your IDE, just select run configurations

SQL WITH clause example

This has been fully answered here.

See Oracle's docs on SELECT to see how subquery factoring works, and Mark's example:

WITH employee AS (SELECT * FROM Employees)
SELECT * FROM employee WHERE ID < 20
UNION ALL
SELECT * FROM employee WHERE Sex = 'M'

How to update only one field using Entity Framework?

Ladislav's answer updated to use DbContext (introduced in EF 4.1):

public void ChangePassword(int userId, string password)
{
    var user = new User() { Id = userId, Password = password };
    using (var db = new MyEfContextName())
    {
        db.Users.Attach(user);
        db.Entry(user).Property(x => x.Password).IsModified = true;
        db.SaveChanges();
    }
}

Solution to "subquery returns more than 1 row" error

When one gets the error 'sub-query returns more than 1 row', the database is actually telling you that there is an unresolvable circular reference. It's a bit like using a spreadsheet and saying cell A1 = B1 and then saying B1 = A1. This error is typically associated with a scenario where one needs to have a double nested sub-query. I would recommend you look up a thing called a 'cross-tab query' this is the type of query one normally needs to solve this problem. It's basically an outer join (left or right) nested inside a sub-query or visa versa. One can also solve this problem with a double join (also considered to be a type of cross-tab query) such as below:

CREATE DEFINER=`root`@`localhost` PROCEDURE `SP_GET_VEHICLES_IN`(
    IN P_email VARCHAR(150),
    IN P_credentials VARCHAR(150)
)
BEGIN
    DECLARE V_user_id INT(11);
    SET V_user_id = (SELECT user_id FROM users WHERE email = P_email AND credentials = P_credentials LIMIT 1);
    SELECT vehicles_in.vehicle_id, vehicles_in.make_id, vehicles_in.model_id, vehicles_in.model_year,
    vehicles_in.registration, vehicles_in.date_taken, make.make_label, model.model_label
    FROM make
    LEFT OUTER JOIN vehicles_in ON vehicles_in.make_id = make.make_id
    LEFT OUTER JOIN model ON model.make_id = make.make_id AND vehicles_in.model_id = model.model_id
    WHERE vehicles_in.user_id = V_user_id;
END

In the code above notice that there are three tables in amongst the SELECT clause and these three tables show up after the FROM clause and after the two LEFT OUTER JOIN clauses, these three tables must be distinct amongst the FROM and LEFT OUTER JOIN clauses to be syntactically correct.

It is noteworthy that this is a very important construct to know as a developer especially if you're writing periodical report queries and it's probably the most important skill for any complex cross referencing, so all developers should study these constructs (cross-tab and double join).

Another thing I must warn about is: If you are going to use a cross-tab as a part of a working system and not just a periodical report, you must check the record count and reconfigure the join conditions until the minimum records are returned, otherwise large tables and cross-tabs can grind your server to a halt. Hope this helps.

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

I had similar issue when I entered very big port here: enter image description here

But when I corrected it to something smaller which is in offset range: enter image description here

Issue was resolved.

PowerShell and the -contains operator

The -Contains operator doesn't do substring comparisons and the match must be on a complete string and is used to search collections.

From the documentation you linked to:

-Contains Description: Containment operator. Tells whether a collection of reference values includes a single test value.

In the example you provided you're working with a collection containing just one string item.

If you read the documentation you linked to you'll see an example that demonstrates this behaviour:

Examples:

PS C:\> "abc", "def" -Contains "def"
True

PS C:\> "Windows", "PowerShell" -Contains "Shell"
False  #Not an exact match

I think what you want is the -Match operator:

"12-18" -Match "-"

Which returns True.

Important: As pointed out in the comments and in the linked documentation, it should be noted that the -Match operator uses regular expressions to perform text matching.

Python Binomial Coefficient

For everyone looking for the log of the binomial coefficient (Theano calls this binomln), this answer has it:

from numpy import log
from scipy.special import betaln

def binomln(n, k):
    "Log of scipy.special.binom calculated entirely in the log domain"
    return -betaln(1 + n - k, 1 + k) - log(n + 1)

(And if your language/library lacks betaln but has gammaln, like Go, have no fear, since betaln(a, b) is just gammaln(a) + gammaln(b) - gammaln(a + b), per MathWorld.)

Encode html entities in javascript

one of the Easy Way for Encode Or Decode HTML-entities
just Call a Function with one argument...

Decode HTML-entities

function decodeHTMLEntities(text) {
  var textArea = document.createElement('textarea');
  textArea.innerHTML = text;
  return textArea.value;
}

Decode HTML-entities (JQuery)

function decodeHTMLEntities(text) {
  return $("<textarea/>").html(text).text();
}

Encode HTML-entities

function encodeHTMLEntities(text) {
  var textArea = document.createElement('textarea');
  textArea.innerText = text;
  return textArea.innerHTML;
}

Encode HTML-entities (JQuery)

function encodeHTMLEntities(text) {
  return $("<textarea/>").text(text).html();
}

PHP - remove <img> tag from string

I would suggest using the strip_tags method.

Git push error: Unable to unlink old (Permission denied)

FWIW - I had a similar problem and I'm not sure if this alleviated it (beyond the permission mod): Closing Eclipse that was using the branch with this problem.

LINQ query to select top five

Additional information

Sometimes it is necessary to bind a model into a view models and give a type conversion error. In this situation you should use ToList() method.

var list = (from t in ctn.Items
       where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
       orderby t.Delivery.SubmissionDate
       select t).Take(5).ToList();

php return 500 error but no error log

What happened for me when this was an issue, was that the site had used too much memory, so I'm guessing that it couldn't write to an error log or displayed the error. For clarity, it was a Wordpress site that did this. Upping the memory limit on the server showed the site again.

How can I get the average (mean) of selected columns

Here are some examples:

> z$mean <- rowMeans(subset(z, select = c(x, y)), na.rm = TRUE)
> z
  w x  y mean
1 5 1  1    1
2 6 2  2    2
3 7 3  3    3
4 8 4 NA    4

weighted mean

> z$y <- rev(z$y)
> z
  w x  y mean
1 5 1 NA    1
2 6 2  3    2
3 7 3  2    3
4 8 4  1    4
> 
> weight <- c(1, 2) # x * 1/3 + y * 2/3
> z$wmean <- apply(subset(z, select = c(x, y)), 1, function(d) weighted.mean(d, weight, na.rm = TRUE))
> z
  w x  y mean    wmean
1 5 1 NA    1 1.000000
2 6 2  3    2 2.666667
3 7 3  2    3 2.333333
4 8 4  1    4 2.000000

How can I loop through a C++ map of maps?

use std::map< std::string, std::map<std::string, std::string> >::const_iterator when map is const.

How can I send an inner <div> to the bottom of its parent <div>?

A flexbox way.

HTML:

<div class="parent">
  <div>Images, text, buttons oh my!</div>
  <div>Bottom</div>
</div>

CSS:

.parent {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

/*  not necessary, just to visualize it */

.parent {
  height: 500px;
  border: 1px solid black;
}


.parent div {
  border: 1px solid red;
}

enter image description here

Edit:

Source - Flexbox Guide

Browser support for flexbox - Caniuse

How to check for file lock?

You can see if the file is locked by trying to read or lock it yourself first.

Please see my answer here for more information.

ISO C++ forbids comparison between pointer and integer [-fpermissive]| [c++]

char a[2] defines an array of char's. a is a pointer to the memory at the beginning of the array and using == won't actually compare the contents of a with 'ab' because they aren't actually the same types, 'ab' is integer type. Also 'ab' should be "ab" otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.

Something that might be illustrative is looking at the typeid of 'ab':

#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
    int some_int =5;
    std::cout << typeid('ab').name() << std::endl;
    std::cout << typeid(some_int).name() << std::endl;
    return 0;
}

on my system this returns:

i
i

showing that 'ab' is actually evaluated as an int.

If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator == overloaded and will do a comparison check when called this way.

If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:

#include <iostream>
#include <string>
using namespace std;
int main(){
    string a;
    cout<<"enter ab ";
    cin>>a;
    if(a=="ab"){
         cout<<"correct";
    }
    return 0;
}

This one is due to:

if(a=='ab') , here, a is const char* type (ie : array of char)

'ab' is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.

Since char is a primitive type inherited from C, no operator == is defined.

the good code should be:

if(strcmp(a,"ab")==0) , then you'll compare a const char* to another const char* using strcmp.

How to implement class constructor in Visual Basic?

Not sure what you mean with "class constructor" but I'd assume you mean one of the ones below.

Instance constructor:

Public Sub New()

End Sub

Shared constructor:

Shared Sub New()

End Sub

Batch File; List files in directory, only filenames?

  • Why not use where instead dir?

In command line:

for /f tokens^=* %i in ('where .:*')do @"%~nxi"

In bat/cmd file:

@echo off 

for /f tokens^=* %%i in ('where .:*')do %%~nxi
  • Output:

file_0003.xlsx
file_0001.txt
file_0002.log
where .:*
  • Output:

G:\SO_en-EN\Q23228983\file_0003.xlsx
G:\SO_en-EN\Q23228983\file_0001.txt
G:\SO_en-EN\Q23228983\file_0002.log

For recursively:

where /r . *
  • Output:

G:\SO_en-EN\Q23228983\file_0003.xlsx
G:\SO_en-EN\Q23228983\file_0001.txt
G:\SO_en-EN\Q23228983\file_0002.log
G:\SO_en-EN\Q23228983\Sub_dir_001\file_0004.docx
G:\SO_en-EN\Q23228983\Sub_dir_001\file_0005.csv
G:\SO_en-EN\Q23228983\Sub_dir_001\file_0006.odt
  • For loop get path and name:

  • In command line:
for /f tokens^=* %i in ('where .:*')do @echo/ Path: %~dpi ^| Name: %~nxi
  • In bat/cmd file:
@echo off 

for /f tokens^=* %%i in ('where .:*')do echo/ Path: %%~dpi ^| Name: %%~nxi
  • Output:

 Path: G:\SO_en-EN\Q23228983\ | Name: file_0003.xlsx
 Path: G:\SO_en-EN\Q23228983\ | Name: file_0001.txt
 Path: G:\SO_en-EN\Q23228983\ | Name: file_0002.log

  • For loop get path and name recursively:

In command line:

for /f tokens^=* %i in ('where /r . *')do @echo/ Path: %~dpi ^| Name: %~nxi

In bat/cmd file:

@echo off 

for /f tokens^=* %%i in ('where /r . *')do echo/ Path: %%~dpi ^| Name: %%~nxi
  • Output:

 Path: G:\SO_en-EN\Q23228983\ | Name: file_0003.xlsx
 Path: G:\SO_en-EN\Q23228983\ | Name: file_0001.txt
 Path: G:\SO_en-EN\Q23228983\ | Name: file_0002.log
 Path: G:\SO_en-EN\Q23228983\Sub_dir_001\ | Name: file_0004.docx
 Path: G:\SO_en-EN\Q23228983\Sub_dir_001\ | Name: file_0005.csv
 Path: G:\SO_en-EN\Q23228983\Sub_dir_001\ | Name: file_0006.odt

Flutter - Wrap text on overflow, like insert ellipsis or fade

You should wrap your Container in a Flexible to let your Row know that it's ok for the Container to be narrower than its intrinsic width. Expanded will also work.

screenshot

Flexible(
  child: new Container(
    padding: new EdgeInsets.only(right: 13.0),
    child: new Text(
      'Text largeeeeeeeeeeeeeeeeeeeeeee',
      overflow: TextOverflow.ellipsis,
      style: new TextStyle(
        fontSize: 13.0,
        fontFamily: 'Roboto',
        color: new Color(0xFF212121),
        fontWeight: FontWeight.bold,
      ),
    ),
  ),
),

Check if value already exists within list of dictionaries?

Perhaps a function along these lines is what you're after:

 def add_unique_to_dict_list(dict_list, key, value):
  for d in dict_list:
     if key in d:
        return d[key]

  dict_list.append({ key: value })
  return value

How to render a PDF file in Android

There is no anyway to preview pdf document in Android webview.If you want to preview base64 pdf. It requires to third-party library.

build.Gradle

compile 'com.github.barteksc:android-pdf-viewer:2.7.0'

dialog_pdf_viewer

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/dialog_pdf_viewer_close"
        style="@style/ExitButtonImageViewStyle"
        android:src="@drawable/popup_exit" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@color/white"
        android:orientation="vertical">

        <com.github.barteksc.pdfviewer.PDFView
            android:id="@+id/pdfView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>

    <View style="@style/HorizontalLine" />

    <com.pozitron.commons.customviews.ButtonFont
        android:id="@+id/dialog_pdf_viewer_button"
        style="@style/ButtonPrimary2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="15dp"
        android:text="@string/agreed" />

</LinearLayout>

DailogPDFViewer.java

public class DialogPdfViewer extends Dialog {
    PDFView pdfView;
    byte[] decodedString;

    public interface OnDialogPdfViewerListener {
        void onAgreeClick(DialogPdfViewer dialogFullEula);

        void onCloseClick(DialogPdfViewer dialogFullEula);
    }

    public DialogPdfViewer(Context context, String base64, final DialogPdfViewer.OnDialogPdfViewerListener onDialogPdfViewerListener) {
        super(context);

        setContentView(R.layout.dialog_pdf_viewer);
        findViewById(R.id.dialog_pdf_viewer_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onDialogPdfViewerListener.onCloseClick(DialogPdfViewer.this);
            }
        });

        findViewById(R.id.dialog_pdf_viewer_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onDialogPdfViewerListener.onAgreeClick(DialogPdfViewer.this);
            }
        });

        decodedString = Base64.decode(base64.toString(), Base64.DEFAULT);

        pdfView = ((PDFView) findViewById(R.id.pdfView));
        pdfView.fromBytes(decodedString).load();

        setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    onDialogPdfViewerListener.onCloseClick(DialogPdfViewer.this);
                }
                return true;
            }
        });

    }
}

How to overload functions in javascript?

Check this out:

http://www.codeproject.com/Articles/688869/Overloading-JavaScript-Functions

Basically in your class, you number your functions that you want to be overloaded and then with one function call you add function overloading, fast and easy.

Android, Java: HTTP POST Request

You can reuse the implementation I added to ACRA: http://code.google.com/p/acra/source/browse/tags/REL-3_1_0/CrashReport/src/org/acra/HttpUtils.java?r=236

(See the doPost(Map, Url) method, working over http and https even with self signed certs)

How to use SqlClient in ASP.NET Core?

I think you may have missed this part in the tutorial:

Instead of referencing System.Data and System.Data.SqlClient you need to grab from Nuget:

System.Data.Common and System.Data.SqlClient.

Currently this creates dependency in project.json –> aspnetcore50 section to these two libraries.

"aspnetcore50": {
       "dependencies": {
           "System.Runtime": "4.0.20-beta-22523",
           "System.Data.Common": "4.0.0.0-beta-22605",
           "System.Data.SqlClient": "4.0.0.0-beta-22605"
       }
}

Try getting System.Data.Common and System.Data.SqlClient via Nuget and see if this adds the above dependencies for you, but in a nutshell you are missing System.Runtime.

Edit: As per Mozarts answer, if you are using .NET Core 3+, reference Microsoft.Data.SqlClient instead.

Return None if Dictionary key is not available

I was thrown aback by what was possible in python2 vs python3. I will answer it based on what I ended up doing for python3. My objective was simple: check if a json response in dictionary format gave an error or not. My dictionary is called "token" and my key that I am looking for is "error". I am looking for key "error" and if it was not there setting it to value of None, then checking is the value is None, if so proceed with my code. An else statement would handle if I do have the key "error".

if ((token.get('error', None)) is None):
    do something

Simple way to calculate median with MySQL

The following SQL Code will help you to calculate the median in MySQL using user defined variables.

_x000D_
_x000D_
create table employees(salary int);_x000D_
_x000D_
insert into employees values(8);_x000D_
insert into employees values(23);_x000D_
insert into employees values(45);_x000D_
insert into employees values(123);_x000D_
insert into employees values(93);_x000D_
insert into employees values(2342);_x000D_
insert into employees values(2238);_x000D_
_x000D_
select * from employees;_x000D_
_x000D_
Select salary from employees  order by salary;_x000D_
_x000D_
set @rowid=0;_x000D_
set @cnt=(select count(*) from employees);_x000D_
set @middle_no=ceil(@cnt/2);_x000D_
set @odd_even=null;_x000D_
_x000D_
select AVG(salary) from _x000D_
(select salary,@rowid:=@rowid+1 as rid, (CASE WHEN(mod(@cnt,2)=0) THEN @odd_even:=1 ELSE @odd_even:=0 END) as odd_even_status  from employees  order by salary) as tbl where tbl.rid=@middle_no or tbl.rid=(@middle_no+@odd_even);
_x000D_
_x000D_
_x000D_

If you are looking for detailed explanation, please refer this blog.

Using column alias in WHERE clause of MySQL query produces an error

Standard SQL disallows references to column aliases in a WHERE clause. This restriction is imposed because when the WHERE clause is evaluated, the column value may not yet have been determined. For example, the following query is illegal:

SELECT id, COUNT(*) AS cnt FROM tbl_name WHERE cnt > 0 GROUP BY id;

Split data frame string column into multiple columns

The subject is almost exhausted, I 'd like though to offer a solution to a slightly more general version where you don't know the number of output columns, a priori. So for example you have

before = data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2', 'foo_and_bar_2_and_bar_3', 'foo_and_bar'))
  attr                    type
1    1             foo_and_bar
2   30           foo_and_bar_2
3    4 foo_and_bar_2_and_bar_3
4    6             foo_and_bar

We can't use dplyr separate() because we don't know the number of the result columns before the split, so I have then created a function that uses stringr to split a column, given the pattern and a name prefix for the generated columns. I hope the coding patterns used, are correct.

split_into_multiple <- function(column, pattern = ", ", into_prefix){
  cols <- str_split_fixed(column, pattern, n = Inf)
  # Sub out the ""'s returned by filling the matrix to the right, with NAs which are useful
  cols[which(cols == "")] <- NA
  cols <- as.tibble(cols)
  # name the 'cols' tibble as 'into_prefix_1', 'into_prefix_2', ..., 'into_prefix_m' 
  # where m = # columns of 'cols'
  m <- dim(cols)[2]

  names(cols) <- paste(into_prefix, 1:m, sep = "_")
  return(cols)
}

We can then use split_into_multiple in a dplyr pipe as follows:

after <- before %>% 
  bind_cols(split_into_multiple(.$type, "_and_", "type")) %>% 
  # selecting those that start with 'type_' will remove the original 'type' column
  select(attr, starts_with("type_"))

>after
  attr type_1 type_2 type_3
1    1    foo    bar   <NA>
2   30    foo  bar_2   <NA>
3    4    foo  bar_2  bar_3
4    6    foo    bar   <NA>

And then we can use gather to tidy up...

after %>% 
  gather(key, val, -attr, na.rm = T)

   attr    key   val
1     1 type_1   foo
2    30 type_1   foo
3     4 type_1   foo
4     6 type_1   foo
5     1 type_2   bar
6    30 type_2 bar_2
7     4 type_2 bar_2
8     6 type_2   bar
11    4 type_3 bar_3

adding .css file to ejs

Your problem is not actually specific to ejs.

2 things to note here

  1. style.css is an external css file. So you dont need style tags inside that file. It should only contain the css.

  2. In your express app, you have to mention the public directory from which you are serving the static files. Like css/js/image

it can be done by

app.use(express.static(__dirname + '/public'));

assuming you put the css files in public folder from in your app root. now you have to refer to the css files in your tamplate files, like

<link href="/css/style.css" rel="stylesheet" type="text/css">

Here i assume you have put the css file in css folder inside your public folder.

So folder structure would be

.
./app.js
./public
    /css
        /style.css

Print string and variable contents on the same line in R

{glue} offers much better string interpolation, see my other answer. Also, as Dainis rightfully mentions, sprintf() is not without problems.

There's also sprintf():

sprintf("Current working dir: %s", wd)

To print to the console output, use cat() or message():

cat(sprintf("Current working dir: %s\n", wd))
message(sprintf("Current working dir: %s\n", wd))

Eclipse Generate Javadoc Wizard: what is "Javadoc Command"?

Yes, presumably it wants the path to the javadoc command line tool that comes with the JDK (in the bin directory, same as java and javac).

Eclipse should be able to find it automatically; are you perhaps running it on a JRE? That would explain the request.

Correct way to handle conditional styling in React

Another way, using inline style and the spread operator

style={{
  ...completed ? { textDecoration: completed } : {}
}}

That way be useful in some situations where you want to add a bunch of properties at the same time base on the condition.

How to detect Adblock on my website?

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>var adb=true;</script>
<script src="./getbanner.cfm?"></script>
<script>
$(document).ready(function(){if(adb)alert('AdBlock!');});
</script>

and in getbanner.cfm file:

adb = false;

I think it's easiest way to detect adblock.

CSS/HTML: Create a glowing border around an Input Field

I combined two of the previous answers (jsfiddle).

input {
    /* round the corners */
    border-radius: 4px;
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;    
}

input:focus { 
    outline:none;
    border: 1px solid #4195fc; 
    /* create a BIG glow */
    box-shadow: 0px 0px 14px #4195fc; 
    -moz-box-shadow: 0px 0px 14px #4195fc;
    -webkit-box-shadow: 0px 0px 14px #4195fc;  
}?

Python - Get Yesterday's date as a string in YYYY-MM-DD format

You Just need to subtract one day from today's date. In Python datetime.timedelta object lets you create specific spans of time as a timedelta object.

datetime.timedelta(1) gives you the duration of "one day" and is subtractable from a datetime object. After you subtracted the objects you can use datetime.strftime in order to convert the result --which is a date object-- to string format based on your format of choice:

>>> from datetime import datetime, timedelta
>>> yesterday = datetime.now() - timedelta(1)

>>> type(yesterday)                                                                                                                                                                                    
>>> datetime.datetime    

>>> datetime.strftime(yesterday, '%Y-%m-%d')
'2015-05-26'

Note that instead of calling the datetime.strftime function, you can also directly use strftime method of datetime objects:

>>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
'2015-05-26'

As a function:

def yesterday(string=False):
    yesterday = datetime.now() - timedelta(1)
    if string:
        return yesterday.strftime('%Y-%m-%d')
    return yesterday

SQL split values to multiple rows

If you can create a numbers table, that contains numbers from 1 to the maximum fields to split, you could use a solution like this:

select
  tablename.id,
  SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) name
from
  numbers inner join tablename
  on CHAR_LENGTH(tablename.name)
     -CHAR_LENGTH(REPLACE(tablename.name, ',', ''))>=numbers.n-1
order by
  id, n

Please see fiddle here.

If you cannot create a table, then a solution can be this:

select
  tablename.id,
  SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) name
from
  (select 1 n union all
   select 2 union all select 3 union all
   select 4 union all select 5) numbers INNER JOIN tablename
  on CHAR_LENGTH(tablename.name)
     -CHAR_LENGTH(REPLACE(tablename.name, ',', ''))>=numbers.n-1
order by
  id, n

an example fiddle is here.

How can I access "static" class variables within class methods in Python?

Instead of bar use self.bar or Foo.bar. Assigning to Foo.bar will create a static variable, and assigning to self.bar will create an instance variable.

Create MSI or setup project with Visual Studio 2012

I think that Deploying an Office Solution by Using ClickOnce (MSDN) can be useful.

After creating an Outlook plugin for Office 2010 the problem was to install it on the customer's computer, without using ISLE or other complex tools (or expensive).

The solution was to use the publish instrument of the Visual Studio project, as described in the link. Just two things to be done before the setup will work:

How do I set the default schema for a user in MySQL

There is no default database for user. There is default database for current session.

You can get it using DATABASE() function -

SELECT DATABASE();

And you can set it using USE statement -

USE database1;

You should set it manually - USE db_name, or in the connection string.

How to terminate a window in tmux?

Kent's response fully answered your question, however if you are looking to change tmux's configuration to be similar to GNU Screen, here's a tmux.conf that I've used to accomplish this:

# Prefix key
set -g prefix C-a
unbind C-b
bind C-a send-prefix

# Keys
bind k confirm kill-window
bind K confirm kill-server
bind % split-window -h
bind : split-window -v
bind < resize-pane -L 1
bind > resize-pane -R 1
bind - resize-pane -D 1
bind + resize-pane -U 1
bind . command-prompt
bind a last-window
bind space command-prompt -p index "select-window"
bind r source-file ~/.tmux.conf

# Options
set -g bell-action none
set -g set-titles on
set -g set-titles-string "tmux (#I:#W)"
set -g base-index 1
set -g status-left ""
set -g status-left-attr bold
set -g status-right "tmux"
set -g pane-active-border-bg black
set -g pane-active-border-fg black
set -g default-terminal "screen-256color"

# Window options
setw -g monitor-activity off
setw -g automatic-rename off

# Colors
setw -g window-status-current-fg colour191
set -g status-bg default
set -g status-fg white
set -g message-bg default
set -g message-fg colour191

How to horizontally center an element

If width of the content is unknown you can use the following method. Suppose we have these two elements:

  • .outer -- full width
  • .inner -- no width set (but a max-width could be specified)

Suppose the computed width of the elements are 1000 pixels and 300 pixels respectively. Proceed as follows:

  1. Wrap .inner inside .center-helper
  2. Make .center-helper an inline block; it becomes the same size as .inner making it 300 pixels wide.
  3. Push .center-helper 50% right relative to its parent; this places its left at 500 pixels wrt. outer.
  4. Push .inner 50% left relative to its parent; this places its left at -150 pixels wrt. center helper which means its left is at 500 - 150 = 350 pixels wrt. outer.
  5. Set overflow on .outer to hidden to prevent horizontal scrollbar.

Demo:

_x000D_
_x000D_
body {_x000D_
  font: medium sans-serif;_x000D_
}_x000D_
_x000D_
.outer {_x000D_
  overflow: hidden;_x000D_
  background-color: papayawhip;_x000D_
}_x000D_
_x000D_
.center-helper {_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
  left: 50%;_x000D_
  background-color: burlywood;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
  left: -50%;_x000D_
  background-color: wheat;_x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="center-helper">_x000D_
    <div class="inner">_x000D_
      <h1>A div with no defined width</h1>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br>_x000D_
          Duis condimentum sem non turpis consectetur blandit.<br>_x000D_
          Donec dictum risus id orci ornare tempor.<br>_x000D_
          Proin pharetra augue a lorem elementum molestie.<br>_x000D_
          Nunc nec justo sit amet nisi tempor viverra sit amet a ipsum.</p>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to add new column to MYSQL table?

your table:

q1 | q2 | q3 | q4 | q5

you can also do

ALTER TABLE yourtable ADD q6 VARCHAR( 255 ) after q5

Deep-Learning Nan loss reasons

If using integers as targets, makes sure they aren't symmetrical at 0.

I.e., don't use classes -1, 0, 1. Use instead 0, 1, 2.

What are the differences between struct and class in C++?

Not in the specification, no. The main difference is in programmer expectations when they read your code in 2 years. structs are often assumed to be POD. Structs are also used in template metaprogramming when you're defining a type for purposes other than defining objects.

How do I set vertical space between list items?

Old question but I think it lacked an answer. I would use an adjacent siblings selector. This way we only write "one" line of CSS and take into consideration the space at the end or beginning, which most of the answers lacks.

li + li {
  margin-top: 10px;
}

ORA-00979 not a group by expression

If you do grouping by virtue of including GROUP BY clause, any expression in SELECT, which is not group function (or aggregate function or aggregated column) such as COUNT, AVG, MIN, MAX, SUM and so on (List of Aggregate functions) should be present in GROUP BY clause.

Example (correct way) (here employee_id is not group function (non-aggregated column), so it must appear in GROUP BY. By contrast, sum(salary) is a group function (aggregated column), so it is not required to appear in the GROUP BYclause.

   SELECT employee_id, sum(salary) 
   FROM employees
   GROUP BY employee_id; 

Example (wrong way) (here employee_id is not group function and it does not appear in GROUP BY clause, which will lead to the ORA-00979 Error .

   SELECT employee_id, sum(salary) 
   FROM employees;

To correct you need to do one of the following :

  • Include all non-aggregated expressions listed in SELECT clause in the GROUP BY clause
  • Remove group (aggregate) function from SELECT clause.

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

The answer is not efficiency. Non-reentrant mutexes lead to better code.

Example: A::foo() acquires the lock. It then calls B::bar(). This worked fine when you wrote it. But sometime later someone changes B::bar() to call A::baz(), which also acquires the lock.

Well, if you don't have recursive mutexes, this deadlocks. If you do have them, it runs, but it may break. A::foo() may have left the object in an inconsistent state before calling bar(), on the assumption that baz() couldn't get run because it also acquires the mutex. But it probably shouldn't run! The person who wrote A::foo() assumed that nobody could call A::baz() at the same time - that's the entire reason that both of those methods acquired the lock.

The right mental model for using mutexes: The mutex protects an invariant. When the mutex is held, the invariant may change, but before releasing the mutex, the invariant is re-established. Reentrant locks are dangerous because the second time you acquire the lock you can't be sure the invariant is true any more.

If you are happy with reentrant locks, it is only because you have not had to debug a problem like this before. Java has non-reentrant locks these days in java.util.concurrent.locks, by the way.

How to convert column with string type to int form in pyspark data frame?

from pyspark.sql.types import IntegerType
data_df = data_df.withColumn("Plays", data_df["Plays"].cast(IntegerType()))
data_df = data_df.withColumn("drafts", data_df["drafts"].cast(IntegerType()))

You can run loop for each column but this is the simplest way to convert string column into integer.

Could not open input file: composer.phar

I had the same issue when trying to use php composer install in a local directory on my Apache server for a laravel project I cloned from Github. My problem was I had already setup composer globally on my Ubuntu 18 machine.
Adding sudo instead of php started the install of a whole slew of packages listed in the json.lock file i.e. sudo composer install.

React Native fetch() Network Request Failed

if you using localhost just change it :

from :http://localhost:3030 to :http://10.0.2.2:3030

bash script read all the files in directory

To write it with a while loop you can do:

ls -f /var | while read -r file; do cmd $file; done

The primary disadvantage of this is that cmd is run in a subshell, which causes some difficulty if you are trying to set variables. The main advantages are that the shell does not need to load all of the filenames into memory, and there is no globbing. When you have a lot of files in the directory, those advantages are important (that's why I use -f on ls; in a large directory ls itself can take several tens of seconds to run and -f speeds that up appreciably. In such cases 'for file in /var/*' will likely fail with a glob error.)

Div side by side without float

I am currently working on this, and i have already a number of solutions. It is nice to have a high quality site, that i can use also for my convenience. Because if you do not write these things down, you will eventually forget some parts. And i can also recommend writing some basic's down if you are starting any kind of new programming/design.

So if the float functions are causing problems there is a couple of options you can try.

One is modify the div alignment in the div tag it self like so <div class="kosher" align=left> If this does not suit you then there is another option with margin like so.

.leftdiv {
    display: inline-block;
    width: 40%;
    float: left;
}
.rightdiv {
    display: block;
    margin-right: 20px;
    margin-left: 45%;
}

Don't forget to remove the <div align=left>.