Programs & Examples On #Sablecc

How to create new folder?

You probably want os.makedirs as it will create intermediate directories as well, if needed.

import os

#dir is not keyword
def makemydir(whatever):
  try:
    os.makedirs(whatever)
  except OSError:
    pass
  # let exception propagate if we just can't
  # cd into the specified directory
  os.chdir(whatever)

psql: server closed the connection unexepectedly

In my case, it was because I set up the IP configuration wrongly in pg_hba.conf, that sits inside data folder in Windows.

# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
host    all             all             192.168.1.0/24            md5

I mistakenly entered (copied-pasted :-) ) 192.168.0.0 instead of 192.168.1.0.

Java: how do I initialize an array size if it's unknown?

I agree that a data structure like a List is the best way to go:

List<Integer> values = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
int value;
int numValues = 0;
do {
    value = in.nextInt();
    values.add(value);
} while (value >= 1) && (value <= 100);

Or you can just allocate an array of a max size and load values into it:

int maxValues = 100;
int [] values = new int[maxValues];
Scanner in = new Scanner(System.in);
int value;
int numValues = 0;
do {
    value = in.nextInt();
    values[numValues++] = value;
} while (value >= 1) && (value <= 100) && (numValues < maxValues);

Find elements inside forms and iframe using Java and Selenium WebDriver

Before you try searching for the elements within the iframe you will have to switch Selenium focus to the iframe.

Try this before searching for the elements within the iframe:

driver.switchTo().frame(driver.findElement(By.name("iFrameTitle")));

How can I store the result of a system command in a Perl variable?

Using backtick or qx helps, thanks everybody for the answers. However, I found that if you use backtick or qx, the output contains trailing newline and I need to remove that. So I used chomp.

chomp($host = `hostname`);
chomp($domain = `domainname`);
$fqdn = $host.".".$domain;

More information here: http://irouble.blogspot.in/2011/04/perl-chomp-backticks.html

Generate full SQL script from EF 5 Code First Migrations

For anyone using entity framework core ending up here. This is how you do it.

# Powershell / Package manager console
Script-Migration

# Cli 
dotnet ef migrations script

You can use the -From and -To parameter to generate an update script to update a database to a specific version.

Script-Migration -From 20190101011200_Initial-Migration -To 20190101021200_Migration-2

https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/#generate-sql-scripts

There are several options to this command.

The from migration should be the last migration applied to the database before running the script. If no migrations have been applied, specify 0 (this is the default).

The to migration is the last migration that will be applied to the database after running the script. This defaults to the last migration in your project.

An idempotent script can optionally be generated. This script only applies migrations if they haven't already been applied to the database. This is useful if you don't exactly know what the last migration applied to the database was or if you are deploying to multiple databases that may each be at a different migration.

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

Short answer is:

junk$nm[junk$nm %in% "B"] <- "b"

Take a look at Index vectors in R Introduction (if you don't read it yet).


EDIT. As noticed in comments this solution works for character vectors so fail on your data.

For factor best way is to change level:

levels(junk$nm)[levels(junk$nm)=="B"] <- "b"

Converting string to title case

Works fine even with camel case: 'someText in YourPage'

public static class StringExtensions
{
    /// <summary>
    /// Title case example: 'Some Text In Your Page'.
    /// </summary>
    /// <param name="text">Support camel and title cases combinations: 'someText in YourPage'</param>
    public static string ToTitleCase(this string text)
    {
        if (string.IsNullOrEmpty(text))
        {
            return text;
        }
        var result = string.Empty;
        var splitedBySpace = text.Split(new[]{ ' ' }, StringSplitOptions.RemoveEmptyEntries);
        foreach (var sequence in splitedBySpace)
        {
            // let's check the letters. Sequence can contain even 2 words in camel case
            for (var i = 0; i < sequence.Length; i++)
            {
                var letter = sequence[i].ToString();
                // if the letter is Big or it was spaced so this is a start of another word
                if (letter == letter.ToUpper() || i == 0)
                {
                    // add a space between words
                    result += ' ';
                }
                result += i == 0 ? letter.ToUpper() : letter;
            }
        }            
        return result.Trim();
    }
}

How to Refresh a Component in Angular

Adding this to code to the required component's constructor worked for me.

this.router.routeReuseStrategy.shouldReuseRoute = function () {
  return false;
};

this.mySubscription = this.router.events.subscribe((event) => {
  if (event instanceof NavigationEnd) {
    // Trick the Router into believing it's last link wasn't previously loaded
    this.router.navigated = false;
  }
});

Make sure to unsubscribe from this mySubscription in ngOnDestroy().

ngOnDestroy() {
  if (this.mySubscription) {
    this.mySubscription.unsubscribe();
  }
}

Refer to this thread for more details - https://github.com/angular/angular/issues/13831

Counting lines, words, and characters within a text file using Python

One of the way I like is this one , but may be good for small files

with open(fileName,'r') as content_file:
    content = content_file.read()
    lineCount = len(re.split("\n",content))
    words = re.split("\W+",content.lower())

To count words, there is two way, if you don't care about repetition you can just do

words_count = len(words)

if you want the counts of each word you can just do

import collections
words_count = collections.Counter(words) #Count the occurrence of each word

Get first day of week in SQL Server

For those who need the answer at work and creating function is forbidden by your DBA, the following solution will work:

select *,
cast(DATEADD(day, -1*(DATEPART(WEEKDAY, YouDate)-1), YourDate) as DATE) as WeekStart
From.....

This gives the start of that week. Here I assume that Sundays are the start of weeks. If you think that Monday is the start, you should use:

select *,
cast(DATEADD(day, -1*(DATEPART(WEEKDAY, YouDate)-2), YourDate) as DATE) as WeekStart
From.....

What is the difference between baud rate and bit rate?

The bit rate is a measure of the number of bits that are transmitted per unit of time.

The baud rate, which is also known as symbol rate, measures the number of symbols that are transmitted per unit of time. A symbol typically consists of a fixed number of bits depending on what the symbol is defined as(for example 8bit or 9bit data). The baud rate is measured in symbols per second.

Take an example, where an ascii character 'R' is transmitted over a serial channel every one second.

The binary equivalent is 01010010.

So in this case, the baud rate is 1(one symbol transmitted per second) and the bit rate is 8 (eight bits are transmitted per second).

MySQLi count(*) always returns 1

You have to fetch that one record, it will contain the result of Count()

$result = $db->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];

Updating the list view when the adapter data changes

Change this line:

mMyListView.setAdapter(new ArrayAdapter<String>(this, 
                           android.R.layout.simple_list_item_1, 
                           listItems));

to:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                                   android.R.layout.simple_list_item_1, 
                                   listItems)
mMyListView.setAdapter(adapter);

and after updating the value of a list item, call:

adapter.notifyDataSetChanged();

Null pointer Exception on .setOnClickListener

android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Because Submit button is inside login_modal so you need to use loginDialog view to access button:

Submit = (Button)loginDialog.findViewById(R.id.Submit);

#pragma mark in Swift?

You can use // MARK:


There has also been discussion that liberal use of class extensions might be a better practice anyway. Since extensions can implement protocols, you can e.g. put all of your table view delegate methods in an extension and group your code at a more semantic level than #pragma mark is capable of.

Reload content in modal (twitter bootstrap)

var $table = $('#myTable2');
$table.bootstrapTable('destroy');

Worked for me

Extracting specific selected columns to new DataFrame as a copy

Generic functional form

def select_columns(data_frame, column_names):
    new_frame = data_frame.loc[:, column_names]
    return new_frame

Specific for your problem above

selected_columns = ['A', 'C', 'D']
new = select_columns(old, selected_columns)

Checkout remote branch using git svn

Standard Subversion layout

Create a git clone of that includes your Subversion trunk, tags, and branches with

git svn clone http://svn.example.com/project -T trunk -b branches -t tags

The --stdlayout option is a nice shortcut if your Subversion repository uses the typical structure:

git svn clone http://svn.example.com/project --stdlayout

Make your git repository ignore everything the subversion repo does:

git svn show-ignore >> .git/info/exclude

You should now be able to see all the Subversion branches on the git side:

git branch -r

Say the name of the branch in Subversion is waldo. On the git side, you'd run

git checkout -b waldo-svn remotes/waldo

The -svn suffix is to avoid warnings of the form

warning: refname 'waldo' is ambiguous.

To update the git branch waldo-svn, run

git checkout waldo-svn
git svn rebase

Starting from a trunk-only checkout

To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config to contain

[svn-remote "svn-mybranch"]
        url = http://svn.example.com/project/branches/mybranch
        fetch = :refs/remotes/mybranch

You'll need to develop the habit of running

git svn fetch --fetch-all

to update all of what git svn thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run

git checkout -b mybranch-svn remotes/mybranch

For the branches from which you intend to git svn dcommit, keep their histories linear!


Further information

You may also be interested in reading an answer to a related question.

Programmatic equivalent of default(Type)

This should work: Nullable<T> a = new Nullable<T>().GetValueOrDefault();

How to change the type of a field?

Convert String field to Integer:

db.db-name.find({field-name: {$exists: true}}).forEach(function(obj) { 
    obj.field-name = new NumberInt(obj.field-name);
    db.db-name.save(obj);
});

Convert Integer field to String:

db.db-name.find({field-name: {$exists: true}}).forEach(function(obj) {
    obj.field-name = "" + obj.field-name;
    db.db-name.save(obj);
});

How to add checkboxes to JTABLE swing

1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,

2) AbstractTableModel should be useful, where is in the JTable required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel,

3) consider using DefaultTableModel, (if you are not sure about how to works) instead of AbstractTableModel,

table_with_BooleanType_column

could be generated from simple code:

import javax.swing.*;
import javax.swing.table.*;

public class TableCheckBox extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;

    public TableCheckBox() {
        Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
        Object[][] data = {
            {"Buy", "IBM", new Integer(1000), new Double(80.50), false},
            {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
            {"Sell", "Apple", new Integer(3000), new Double(7.35), true},
            {"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
        };
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            /*@Override
            public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
            }*/
            @Override
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    case 1:
                        return String.class;
                    case 2:
                        return Integer.class;
                    case 3:
                        return Double.class;
                    default:
                        return Boolean.class;
                }
            }
        };
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(scrollPane);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TableCheckBox frame = new TableCheckBox();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocation(150, 150);
                frame.setVisible(true);
            }
        });
    }
}

What's the best three-way merge tool?

Diffuse is an easy to use three-way merge tool. It supports all of the platforms and version control systems you mentioned, and it can compare more than three files at the same time.

enter image description here

How to change identity column values programmatically?

Through the UI in SQL Server 2005 manager, change the column remove the autonumber (identity) property of the column (select the table by right clicking on it and choose "Design").

Then run your query:

UPDATE table SET Id = Id + 1

Then go and add the autonumber property back to the column.

Convert a string to a double - is this possible?

Why is floatval the best option for financial comparison data? bc functions only accurately turn strings into real numbers.

How to change the button text of <input type="file" />?

I think this is what you want:

<button style="display:block;width:120px; height:30px;" onclick="document.getElementById('getFile').click()">Your text here</button>


<input type='file' id="getFile" style="display:none"> 

How to know function return type and argument types?

I attended a coursera course, there was lesson in which, we were taught about design recipe.

Below docstring format I found preety useful.

def area(base, height):
    '''(number, number ) -> number    #**TypeContract**
    Return the area of a tring with dimensions base   #**Description**
    and height

    >>>area(10,5)          #**Example **
    25.0
    >>area(2.5,3)
    3.75
    '''
    return (base * height) /2 

I think if docstrings are written in this way, it might help a lot to developers.

Link to video [Do watch the video] : https://www.youtube.com/watch?v=QAPg6Vb_LgI

AngularJS: How can I pass variables between controllers?

I looked thru the answers above, I recommend pejman's Dec 29 '16 at 13:31 suggestion but he/she has not left a full answer. Here it is, I will put this as --> (you need a service and a listener $watch on one of the scopes from controllers for changes in the service area)

var app = 
angular.module('myApp', ['ngRoute', 'ngSanitize']);

app.service('bridgeService', function () {
    var msg = ""; 
    return msg;
});
app.controller('CTRL_1'
, function ($scope, $http, bridgeService) 
{
    $http.get(_restApi, config)
    .success(
    function (serverdata, status, config) {
        $scope.scope1Box = bridgeService.msg = serverdata;
    });
});
app.controller('CTRL_2'
, function ($scope, $http, bridgeService) 
{
    $scope.$watch( function () {
        return (bridgeService.msg);
    }, function (newVal, oldVal) {
        $scope.scope2Box = newVal;
    }, true
    );
});

How do I assert an Iterable contains elements with a certain property?

AssertJ 3.9.1 supports direct predicate usage in anyMatch method.

assertThat(collection).anyMatch(element -> element.someProperty.satisfiesSomeCondition())

This is generally suitable use case for arbitrarily complex condition.

For simple conditions I prefer using extracting method (see above) because resulting iterable-under-test might support value verification with better readability. Example: it can provide specialized API such as contains method in Frank Neblung's answer. Or you can call anyMatch on it later anyway and use method reference such as "searchedvalue"::equals. Also multiple extractors can be put into extracting method, result subsequently verified using tuple().

how to read a long multiline string line by line in python

by splitting with newlines.

for line in wallop_of_a_string_with_many_lines.split('\n'):
  #do_something..

if you iterate over a string, you are iterating char by char in that string, not by line.

>>>string = 'abc'
>>>for line in string:
    print line

a
b
c

AngularJS sorting by property

I will add my upgraded version of filter which able to supports next syntax:

ng-repeat="(id, item) in $ctrl.modelData | orderObjectBy:'itemProperty.someOrder':'asc'

app.filter('orderObjectBy', function(){

         function byString(o, s) {
            s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
            s = s.replace(/^\./, '');           // strip a leading dot
            var a = s.split('.');
            for (var i = 0, n = a.length; i < n; ++i) {
                var k = a[i];
                if (k in o) {
                    o = o[k];
                } else {
                    return;
                }
            }
            return o;
        }

        return function(input, attribute, direction) {
            if (!angular.isObject(input)) return input;

            var array = [];
            for(var objectKey in input) {
                if (input.hasOwnProperty(objectKey)) {
                    array.push(input[objectKey]);
                }
            }

            array.sort(function(a, b){
                a = parseInt(byString(a, attribute));
                b = parseInt(byString(b, attribute));
                return direction == 'asc' ? a - b : b - a;
            });
            return array;
        }
    })

Thanks to Armin and Jason for their answers in this thread, and Alnitak in this thread.

Combining INSERT INTO and WITH/CTE

Yep:

WITH tab (
  bla bla
)

INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos (  BatchID,                                                        AccountNo,
APartyNo,
SourceRowID)    

SELECT * FROM tab

Note that this is for SQL Server, which supports multiple CTEs:

WITH x AS (), y AS () INSERT INTO z (a, b, c) SELECT a, b, c FROM y

Teradata allows only one CTE and the syntax is as your example.

Sorting dropdown alphabetically in AngularJS

You should be able to use filter: orderBy

orderBy can accept a third option for the reverse flag.

<select ng-option="item.name for item in items | orderBy:'name':true"></select>

Here item is sorted by 'name' property in a reversed order. The 2nd argument can be any order function, so you can sort in any rule.

@see http://docs.angularjs.org/api/ng.filter:orderBy

Store images in a MongoDB database

"You should always use GridFS for storing files larger than 16MB" - When should I use GridFS?

MongoDB BSON documents are capped at 16 MB. So if the total size of your array of files is less than that, you may store them directly in your document using the BinData data type.

Videos, images, PDFs, spreadsheets, etc. - it doesn't matter, they are all treated the same. It's up to your application to return an appropriate content type header to display them.

Check out the GridFS documentation for more details.

Convert categorical data in pandas dataframe

For a certain column, if you don't care about the ordering, use this

df['col1_num'] = df['col1'].apply(lambda x: np.where(df['col1'].unique()==x)[0][0])

If you care about the ordering, specify them as a list and use this

df['col1_num'] = df['col1'].apply(lambda x: ['first', 'second', 'third'].index(x))

Max size of an iOS application

Now Accepting Larger Binaries February 12, 2015

The size limit of an app package submitted through iTunes Connect has increased from 2 GB to 4 GB, so you can include more media in your submission and provide a more complete, rich user experience upon installation. Please keep in mind that this change does not affect the cellular network delivery size limit of 100 MB.

https://developer.apple.com/news/?id=02122015a

Delete a row in DataGridView Control in VB.NET

If dgv(11, dgv.CurrentRow.Index).Selected = True Then
    dgv.Rows.RemoveAt(dgv.CurrentRow.Index)
Else
    Exit Sub
End If

CMake does not find Visual C++ compiler

Because CMake is not able to find your Visual Studio compiler. Start any project which will download the required compilers and CMake must be able to find it then.

How to write lists inside a markdown table?

another solution , you can add <br> tag to your table

    |Method name| Behavior |
    |--|--|
    | OnAwakeLogicController(); | Its called when MainLogicController is loaded into the memory , its also hold the following actions :- <br> 1. Checking Audio Settings <br>2. Initializing Level Controller|

enter image description here

Accessing nested JavaScript objects and arrays by string path

You can use ramda library.

Learning ramda also helps you to work with immutable objects easily.


var obj = {
  a:{
    b: {
      c:[100,101,{
        d: 1000
      }]
    }
  }
};


var lens = R.lensPath('a.b.c.2.d'.split('.'));
var result = R.view(lens, obj);


https://codepen.io/ghominejad/pen/BayJZOQ

How to compare two strings are equal in value, what is the best method?

You can either use the == operator or the Object.equals(Object) method.

The == operator checks whether the two subjects are the same object, whereas the equals method checks for equal contents (length and characters).

if(objectA == objectB) {
   // objects are the same instance. i.e. compare two memory addresses against each other.
}

if(objectA.equals(objectB)) {
   // objects have the same contents. i.e. compare all characters to each other 
}

Which you choose depends on your logic - use == if you can and equals if you do not care about performance, it is quite fast anyhow.

String.intern() If you have two strings, you can internate them, i.e. make the JVM create a String pool and returning to you the instance equal to the pool instance (by calling String.intern()). This means that if you have two Strings, you can call String.intern() on both and then use the == operator. String.intern() is however expensive, and should only be used as an optimalization - it only pays off for multiple comparisons.

All in-code Strings are however already internated, so if you are not creating new Strings, you are free to use the == operator. In general, you are pretty safe (and fast) with

if(objectA == objectB || objectA.equals(objectB)) {

}

if you have a mix of the two scenarios. The inline

if(objectA == null ? objectB == null : objectA.equals(objectB)) {

}

can also be quite useful, it also handles null values since String.equals(..) checks for null.

How to determine device screen size category (small, normal, large, xlarge) using code?

Couldn't you do this using a string resource and enums? You can define a string resource that had the name of the screen size, such as SMALL, MEDIUM, or LARGE. Then you could use the value of the string resource to create an instance of the enum.

  1. Define an Enum in your code for the different screen sizes you care about.

    public Enum ScreenSize {
        SMALL,
        MEDIUM,
        LARGE,;
    }
    
  2. Define a string resource, say screensize, whose value will be either SMALL, MEDIUM, or LARGE.

    <string name="screensize">MEDIUM</string>
    
  3. Put a copy of screensize in a string resource in each dimension you care about.
    For example, <string name="screensize">MEDIUM</string> would go in values-sw600dp/strings.xml and values-medium/strings.xml and <string name="screensize">LARGE</string> would go in sw720dp/strings.xml and values-large/strings.xml.
  4. In code, write
    ScreenSize size = ScreenSize.valueOf(getReources().getString(R.string.screensize);

Convert String to Double - VB

VB.NET Sample Code

Dim A as String = "5.3"
Dim B as Double

B = CDbl(Val(A)) '// Val do hard work

'// Get output 
MsgBox (B) '// Output is 5,3 Without Val result is 53.0

List(of String) or Array or ArrayList

Neither collection will let you add items that way.

You can make an extension to make for examle List(Of String) have an Add method that can do that:

Imports System.Runtime.CompilerServices
Module StringExtensions

  <Extension()>
  Public Sub Add(ByVal list As List(Of String), ParamArray values As String())
    For Each s As String In values
      list.Add(s)
    Next
  End Sub

End Module

Now you can add multiple value in one call:

Dim lstOfStrings as New List(Of String)
lstOfStrings.Add(String1, String2, String3, String4)

Seaborn plots not showing up

My advice is just to give a

plt.figure() and give some sns plot. For example

sns.distplot(data).

Though it will look it doesnt show any plot, When you maximise the figure, you will be able to see the plot.

How to get cumulative sum

There is a much faster CTE implementation available in this excellent post: http://weblogs.sqlteam.com/mladenp/archive/2009/07/28/SQL-Server-2005-Fast-Running-Totals.aspx

The problem in this thread can be expressed like this:

    DECLARE @RT INT
    SELECT @RT = 0

    ;
    WITH  abcd
            AS ( SELECT TOP 100 percent
                        id
                       ,SomeNumt
                       ,MySum
                       order by id
               )
      update abcd
      set @RT = MySum = @RT + SomeNumt
      output inserted.*

Django - how to create a file and save it to a model's FileField?

It's good practice to use a context manager or call close() in case of exceptions during the file saving process. Could happen if your storage backend is down, etc.

Any overwrite behavior should be configured in your storage backend. For example S3Boto3Storage has a setting AWS_S3_FILE_OVERWRITE. If you're using FileSystemStorage you can write a custom mixin.

You might also want to call the model's save method instead of the FileField's save method if you want any custom side-effects to happen, like last-updated timestamps. If that's the case, you can also set the name attribute of the file to the name of the file - which is relative to MEDIA_ROOT. It defaults to the full path of the file which can cause problems if you don't set it - see File.__init__() and File.name.

Here's an example where self is the model instance where my_file is the FileField / ImageFile, calling save() on the whole model instance instead of just FileField:

import os
from django.core.files import File

with open(filepath, 'rb') as fi:
    self.my_file = File(fi, name=os.path.basename(fi.name))
    self.save()

Is it possible to change javascript variable values while debugging in Google Chrome?

Yes! Finally! I just tried it with Chrome, Version 66.0.3359.170 (Official Build) (64-bit) on Mac.

You can change the values in the scopes as in the first picture, or with the console as in the second picture.

Chrome debugger change values

enter image description here

What is the role of the bias in neural networks?

Expanding on @zfy explanation... The equation for one input, one neuron, one output should look:

y = a * x + b * 1    and out = f(y)

where x is the value from the input node and 1 is the value of the bias node; y can be directly your output or be passed into a function, often a sigmoid function. Also note that the bias could be any constant, but to make everything simpler we always pick 1 (and probably that's so common that @zfy did it without showing & explaining it).

Your network is trying to learn coefficients a and b to adapt to your data. So you can see why adding the element b * 1 allows it to fit better to more data: now you can change both slope and intercept.

If you have more than one input your equation will look like:

y = a0 * x0 + a1 * x1 + ... + aN * 1

Note that the equation still describes a one neuron, one output network; if you have more neurons you just add one dimension to the coefficient matrix, to multiplex the inputs to all nodes and sum back each node contribution.

That you can write in vectorized format as

A = [a0, a1, .., aN] , X = [x0, x1, ..., 1]
Y = A . XT

i.e. putting coefficients in one array and (inputs + bias) in another you have your desired solution as the dot product of the two vectors (you need to transpose X for the shape to be correct, I wrote XT a 'X transposed')

So in the end you can also see your bias as is just one more input to represent the part of the output that is actually independent of your input.

Query to convert from datetime to date mysql

I see the many types of uses, but I find this layout more useful as a reference tool:

SELECT DATE_FORMAT('2004-01-20' ,'%Y-%m-01');

enter image description here

Invert match with regexp

It's indeed almost a duplicate. I guess the regex you're looking for is

(?!foo).*

Best way to find the months between two dates

Here is my solution for this:

def calc_age_months(from_date, to_date):
    from_date = time.strptime(from_date, "%Y-%m-%d")
    to_date = time.strptime(to_date, "%Y-%m-%d")

    age_in_months = (to_date.tm_year - from_date.tm_year)*12 + (to_date.tm_mon - from_date.tm_mon)

    if to_date.tm_mday < from_date.tm_mday:
        return age_in_months -1
    else
        return age_in_months

This will handle some edge cases as well where the difference in months between 31st Dec 2018 and 1st Jan 2019 will be zero (since the difference is only a day).

How can I extract audio from video with ffmpeg?

To extract the audio stream without re-encoding:

ffmpeg -i input-video.avi -vn -acodec copy output-audio.aac
  • -vn is no video.
  • -acodec copy says use the same audio stream that's already in there.

Read the output to see what codec it is, to set the right filename extension.

Text File Parsing with Python

There are a few ways to go about this. One option would be to use inputfile.read() instead of inputfile.readlines() - you'd need to write separate code to strip the first four lines, but if you want the final output as a single string anyway, this might make the most sense.

A second, simpler option would be to rejoin the strings after striping the first four lines with my_text = ''.join(my_text). This is a little inefficient, but if speed isn't a major concern, the code will be simplest.

Finally, if you actually want the output as a list of strings instead of a single string, you can just modify your data parser to iterate over the list. That might looks something like this:

def data_parser(lines, dic):
    for i, j in dic.iteritems():
        for (k, line) in enumerate(lines):
            lines[k] = line.replace(i, j)
    return lines

How to parse/format dates with LocalDateTime? (Java 8)

Both answers above explain very well the question regarding string patterns. However, just in case you are working with ISO 8601 there is no need to apply DateTimeFormatter since LocalDateTime is already prepared for it:

Convert LocalDateTime to Time Zone ISO8601 String

LocalDateTime ldt = LocalDateTime.now(); 
ZonedDateTime zdt = ldt.atZone(ZoneOffset.UTC); //you might use a different zone
String iso8601 = zdt.toString();

Convert from ISO8601 String back to a LocalDateTime

String iso8601 = "2016-02-14T18:32:04.150Z";
ZonedDateTime zdt = ZonedDateTime.parse(iso8601);
LocalDateTime ldt = zdt.toLocalDateTime();

What is the regex for "Any positive integer, excluding 0"

Got this one:

^[1-9]|[0-9]{2,}$

Someone beats it? :)

How do I space out the child elements of a StackPanel?

Grid.ColumnSpacing, Grid.RowSpacing, StackPanel.Spacing are now on UWP preview, all will allow to better acomplish what is requested here.

These properties are currently only available with the Windows 10 Fall Creators Update Insider SDK, but should make it to the final bits!

How to load external scripts dynamically in Angular?

You can use following technique to dynamically load JS scripts and libraries on demand in your Angular project.

script.store.ts will contain the path of the script either locally or on a remote server and a name that will be used to load the script dynamically

 interface Scripts {
    name: string;
    src: string;
}  
export const ScriptStore: Scripts[] = [
    {name: 'filepicker', src: 'https://api.filestackapi.com/filestack.js'},
    {name: 'rangeSlider', src: '../../../assets/js/ion.rangeSlider.min.js'}
];

script.service.ts is an injectable service that will handle the loading of script, copy script.service.ts as it is

import {Injectable} from "@angular/core";
import {ScriptStore} from "./script.store";

declare var document: any;

@Injectable()
export class ScriptService {

private scripts: any = {};

constructor() {
    ScriptStore.forEach((script: any) => {
        this.scripts[script.name] = {
            loaded: false,
            src: script.src
        };
    });
}

load(...scripts: string[]) {
    var promises: any[] = [];
    scripts.forEach((script) => promises.push(this.loadScript(script)));
    return Promise.all(promises);
}

loadScript(name: string) {
    return new Promise((resolve, reject) => {
        //resolve if already loaded
        if (this.scripts[name].loaded) {
            resolve({script: name, loaded: true, status: 'Already Loaded'});
        }
        else {
            //load script
            let script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = this.scripts[name].src;
            if (script.readyState) {  //IE
                script.onreadystatechange = () => {
                    if (script.readyState === "loaded" || script.readyState === "complete") {
                        script.onreadystatechange = null;
                        this.scripts[name].loaded = true;
                        resolve({script: name, loaded: true, status: 'Loaded'});
                    }
                };
            } else {  //Others
                script.onload = () => {
                    this.scripts[name].loaded = true;
                    resolve({script: name, loaded: true, status: 'Loaded'});
                };
            }
            script.onerror = (error: any) => resolve({script: name, loaded: false, status: 'Loaded'});
            document.getElementsByTagName('head')[0].appendChild(script);
        }
    });
}

}

Inject this ScriptService wherever you need it and load js libs like this

this.script.load('filepicker', 'rangeSlider').then(data => {
    console.log('script loaded ', data);
}).catch(error => console.log(error));

Grep only the first match and stop

You can use below command if you want to print entire line and file name if the occurrence of particular word in current directory you are searching.

grep -m 1 -r "Not caching" * | head -1

How to rename a table column in Oracle 10g

The syntax of the query is as follows:

Alter table <table name> rename column <column name> to <new column name>;

Example:

Alter table employee rename column eName to empName;

To rename a column name without space to a column name with space:

Alter table employee rename column empName to "Emp Name";

To rename a column with space to a column name without space:

Alter table employee rename column "emp name" to empName;

Secure Web Services: REST over HTTPS vs SOAP + WS-Security. Which is better?

REST Over HTTPS Should be a secure method as long as API provider implements authorization a server end. In a case of web application as well what we do is accessing a web application via HTTPS and some authentication/authorization, traditionally web applications did not have security issues then Restful API would also counter security issues without problem !

'AND' vs '&&' as operator

Let me explain the difference between “and” - “&&” - "&".

"&&" and "and" both are logical AND operations and they do the same thing, but the operator precedence is different.

The precedence (priority) of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator.

Mixing them together in single operation, could give you unexpected results in some cases I recommend always using &&, but that's your choice.


On the other hand "&" is a bitwise AND operation. It's used for the evaluation and manipulation of specific bits within the integer value.

Example if you do (14 & 7) the result would be 6.

7   = 0111
14  = 1110
------------
    = 0110 == 6

Simplest way to do grouped barplot

Not a barplot solution but using lattice and barchart:

library(lattice)
barchart(Species~Reason,data=Reasonstats,groups=Catergory, 
         scales=list(x=list(rot=90,cex=0.8)))

enter image description here

What is the syntax for adding an element to a scala.collection.mutable.Map?

The point is that the first line of your codes is not what you expected.

You should use:

val map = scala.collection.mutable.Map[A,B]()

You then have multiple equivalent alternatives to add items:

scala> val map = scala.collection.mutable.Map[String,String]()
map: scala.collection.mutable.Map[String,String] = Map()


scala> map("k1") = "v1"

scala> map
res1: scala.collection.mutable.Map[String,String] = Map((k1,v1))


scala> map += "k2" -> "v2"
res2: map.type = Map((k1,v1), (k2,v2))


scala> map.put("k3", "v3")
res3: Option[String] = None

scala> map
res4: scala.collection.mutable.Map[String,String] = Map((k3,v3), (k1,v1), (k2,v2))

And starting Scala 2.13:

scala> map.addOne("k4" -> "v4")
res5: map.type = HashMap(k1 -> v1, k2 -> v2, k3 -> v3, k4 -> v4)

Restoring MySQL database from physical files

In my case, simply removing the tc.log in /var/lib/mysql was enough to start mariadb/mysql again.

Session state can only be used when enableSessionState is set to true either in a configuration

I want to let everyone know that sometimes this error just is a result of some weird memory error. Restart your pc and go back into visual studio and it will be gone!! Bizarre! Try that before you start playing around with your web config file etc like I did!!!! ;-)

Python Threading String Arguments

You're trying to create a tuple, but you're just parenthesizing a string :)

Add an extra ',':

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=(dRecieved,))  # <- note extra ','
processThread.start()

Or use brackets to make a list:

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=[dRecieved])  # <- 1 element list
processThread.start()

If you notice, from the stack trace: self.__target(*self.__args, **self.__kwargs)

The *self.__args turns your string into a list of characters, passing them to the processLine function. If you pass it a one element list, it will pass that element as the first argument - in your case, the string.

JavaScript DOM: Find Element Index In Container

If you want to write this compactly all you need is:

var i = 0;
for (;yourElement.parentNode[i]!==yourElement;i++){}
indexOfYourElement = i;

We just cycle through the elements in the parent node, stopping when we find your element.

You can also easily do:

for (;yourElement.parentNode.getElementsByTagName("li")[i]!==yourElement;i++){}

if that's all you want to look through.

Reporting Services Remove Time from DateTime in Expression

=CDate(Now).ToString("dd/MM/yyyy")

Although you are hardcoding the date formart to a locale.

How to access component methods from “outside” in ReactJS?

Another way so easy:

function outside:

function funx(functionEvents, params) {
  console.log("events of funx function: ", functionEvents);
  console.log("this of component: ", this);
  console.log("params: ", params);
  thisFunction.persist();
}

Bind it:

constructor(props) {
   super(props);
    this.state = {};
    this.funxBinded = funx.bind(this);
  }
}

Please see complete tutorial here: How to use "this" of a React Component from outside?

Just disable scroll not hide it?

With jQuery inluded:


disable

$.fn.disableScroll = function() {
    window.oldScrollPos = $(window).scrollTop();

    $(window).on('scroll.scrolldisabler',function ( event ) {
       $(window).scrollTop( window.oldScrollPos );
       event.preventDefault();
    });
};

enable

$.fn.enableScroll = function() {
    $(window).off('scroll.scrolldisabler');
};

usage

//disable
$("#selector").disableScroll();
//enable
$("#selector").enableScroll();

How to correctly use the ASP.NET FileUpload control

ASP.NET controls should rather be placed in aspx markup file. That is the preferred way of working with them. So add FileUpload control to your page. Make sure it has all required attributes including ID and runat:

<asp:FileUpload ID="FileUpload1" runat="server" />

Instance of FileUpload1 will be automatically created in auto-generated/updated *.designer.cs file which is a partial class for your page. You usually do not have to care about what's in it, just assume that any control on an aspx page is automatically instantiated.

Add a button that will do the post back:

<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

Then go to your *.aspx.cs file where you have your code and add button click handler. In C# it looks like this:

protected void Button1_Click(object sender, EventArgs e)
{
  if (this.FileUpload1.HasFile)
  {
    this.FileUpload1.SaveAs("c:\\" + this.FileUpload1.FileName);
  }
}

And that's it. All should work as expected.

Which version of CodeIgniter am I currently using?

Yes, the constant CI_VERSION will give you the current CodeIgniter version number. It's defined in: /system/codeigniter/CodeIgniter.php As of CodeIgniter 2, it's defined in /system/core/CodeIgniter.php

For example,

echo CI_VERSION; // echoes something like 1.7.1

How can I make a ComboBox non-editable in .NET?

To add a Visual Studio GUI reference, you can find the DropDownStyle options under the Properties of the selected ComboBox:

enter image description here

Which will automatically add the line mentioned in the first answer to the Form.Designer.cs InitializeComponent(), like so:

this.comboBoxBatch.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;

Simple Android RecyclerView example

Here's a much newer Kotlin solution for this which is much simpler than many of the answers written here, it uses anonymous class.

val items = mutableListOf<String>()

inner class ItemHolder(view: View): RecyclerView.ViewHolder(view) {
    var textField: TextView = view.findViewById(android.R.id.text1) as TextView
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    rvitems.layoutManager = LinearLayoutManager(context)
    rvitems.adapter = object : RecyclerView.Adapter<ItemHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemHolder {
            return ItemHolder(LayoutInflater.from(parent.context).inflate(android.R.layout.simple_list_item_1, parent, false))
        }

        override fun getItemCount(): Int {
            return items.size
        }

        override fun onBindViewHolder(holder: ItemHolder, position: Int) {
            holder.textField.text = items[position]
            holder.textField.setOnClickListener {
                Toast.makeText(context, "Clicked $position", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

I took the liberty to use android.R.layout.simple_list_item_1 as it's simpler. I wanted to simplify it even further and put ItemHolder as an inner class but couldn't quite figure out how to reference it in a type in the outer class parameter.

Real escape string and PDO

You should use PDO Prepare

From the link:

Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.

Returning binary file from controller in ASP.NET Web API

You could try

httpResponseMessage.Content.Headers.Add("Content-Type", "application/octet-stream");

PostgreSQL: How to make "case-insensitive" query

You can also read up on the ILIKE keyword. It can be quite useful at times, albeit it does not conform to the SQL standard. See here for more information: http://www.postgresql.org/docs/9.2/static/functions-matching.html

jQuery Set Select Index

select 3rd option

$('#selectBox').val($('#selectBox option').eq(2).val());

Example on jsfiddle

How to draw a rounded Rectangle on HTML Canvas?

I started with @jhoff's solution, but rewrote it to use width/height parameters, and using arcTo makes it quite a bit more terse:

CanvasRenderingContext2D.prototype.roundRect = function (x, y, w, h, r) {
  if (w < 2 * r) r = w / 2;
  if (h < 2 * r) r = h / 2;
  this.beginPath();
  this.moveTo(x+r, y);
  this.arcTo(x+w, y,   x+w, y+h, r);
  this.arcTo(x+w, y+h, x,   y+h, r);
  this.arcTo(x,   y+h, x,   y,   r);
  this.arcTo(x,   y,   x+w, y,   r);
  this.closePath();
  return this;
}

Also returning the context so you can chain a little. E.g.:

ctx.roundRect(35, 10, 225, 110, 20).stroke(); //or .fill() for a filled rect

Making macOS Installer Packages which are Developer ID ready

A +1 to accepted answer:

Destination Selection in Installer

If domain (a.k.a destination) selection is desired between user domain and system domain then rather than trying <domains enable_anywhere="true"> use following:

<domains enable_currentUserHome="true" enable_localSystem="true"/>

enable_currentUserHome installs application app under ~/Applications/ and enable_localSystem allows the application to be installed under /Application

I've tried this in El Capitan 10.11.6 (15G1217) and it seems to be working perfectly fine in 1 dev machine and 2 different VMs I tried.

How to hide the keyboard when I press return key in a UITextField?

You can connect "Primary Action Triggered" (right click on UITextField) with an IBAction and you can resign first responder (without delegation). Example (Swift 4):

@IBAction func textFieldPrimaryAction(_ sender: UITextField) {
    sender.resignFirstResponder()
    ...
}

How do I enable FFMPEG logging and where can I find the FFMPEG log file?

appears that if you add this to the command line:

 -loglevel debug

or

 -loglevel verbose

You get more verbose debugging output to the command line.

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

Column/Vertical selection with Keyboard in SublimeText 3

The reason why the sublime documented shortcuts for Mac does not work are they are linked to the shortcuts of other Mac functionalities such as Mission Control, Application Windows, etc. Solution: Go to System Preferences -> Keyboard -> Shortcuts and then un-check the options for Mission Control and Application Windows. Now try "Control + Shift [+ Arrow keys]" for selecting the required text and then move the cursor to the required location without any mouse click, so that the selection can be pasted with the correct indentation at the required location.

How do detect Android Tablets in general. Useragent?

Xoom has the word Xoom in the user-agent: Mozilla/5.0 (Linux; U; Android 3.0.1; en-us; Xoom Build/HRI66) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13

Galaxy Tab has "Mobile" in the user-agent: Mozilla/5.0 (Linux; U; Android 2.2; en-us; SCH-I800 Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1

So, it's easy to detect the Xoom, hard to detect if a specific Android version is mobile or not.

Conditionally Remove Dataframe Rows with R

Use the which function:

A <- c('a','a','b','b','b')
B <- c(1,0,1,1,0)
d <- data.frame(A, B)

r <- with(d, which(B==0, arr.ind=TRUE))
newd <- d[-r, ]

List vs tuple, when to use each?

Must it be mutable? Use a list. Must it not be mutable? Use a tuple.

Otherwise, it's a question of choice.

For collections of heterogeneous objects (like a address broken into name, street, city, state and zip) I prefer to use a tuple. They can always be easily promoted to named tuples.

Likewise, if the collection is going to be iterated over, I prefer a list. If it's just a container to hold multiple objects as one, I prefer a tuple.

"Automatic" vs "Automatic (Delayed start)"

In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.

Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.

Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).

The registry keys of interest (At least in some versions of windows) are:

  • HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart will have the value 1 if delayed, 0 if not.
  • HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay (on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.

how to get file path from sd card in android

Environment.getExternalStorageDirectory() will NOT return path to micro SD card Storage.

how to get file path from sd card in android

By sd card, I am assuming that, you meant removable micro SD card.

In API level 19 i.e. in Android version 4.4 Kitkat, they have added File[] getExternalFilesDirs (String type) in Context Class that allows apps to store data/files in micro SD cards.

Android 4.4 is the first release of the platform that has actually allowed apps to use SD cards for storage. Any access to SD cards before API level 19 was through private, unsupported APIs.

Environment.getExternalStorageDirectory() was there from API level 1

getExternalFilesDirs(String type) returns absolute paths to application-specific directories on all shared/external storage devices. It means, it will return paths to both internal and external memory. Generally, second returned path would be the storage path for microSD card (if any).

But note that,

Shared storage may not always be available, since removable media can be ejected by the user. Media state can be checked using getExternalStorageState(File).

There is no security enforced with these files. For example, any application holding WRITE_EXTERNAL_STORAGE can write to these files.

The Internal and External Storage terminology according to Google/official Android docs is quite different from what we think.

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

As @swanliu pointed out it is due to a bad connection.
However before adjusting the server timing and client timeout , I would first try and use a better connection pooling strategy.

Connection Pooling

Hibernate itself admits that its connection pooling strategy is minimal

Hibernate's own connection pooling algorithm is, however, quite rudimentary. It is intended to help you get started and is not intended for use in a production system, or even for performance testing. You should use a third party pool for best performance and stability. Just replace the hibernate.connection.pool_size property with connection pool specific settings. This will turn off Hibernate's internal pool. For example, you might like to use c3p0.
As stated in Reference : http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html

I personally use C3P0. however there are other alternatives available including DBCP.
Check out

Below is a minimal configuration of C3P0 used in my application:

<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="c3p0.acquire_increment">1</property> 
<property name="c3p0.idle_test_period">100</property> <!-- seconds --> 
<property name="c3p0.max_size">100</property> 
<property name="c3p0.max_statements">0</property> 
<property name="c3p0.min_size">10</property> 
<property name="c3p0.timeout">1800</property> <!-- seconds --> 

By default, pools will never expire Connections. If you wish Connections to be expired over time in order to maintain "freshness", set maxIdleTime and/or maxConnectionAge. maxIdleTime defines how many seconds a Connection should be permitted to go unused before being culled from the pool. maxConnectionAge forces the pool to cull any Connections that were acquired from the database more than the set number of seconds in the past.
As stated in Reference : http://www.mchange.com/projects/c3p0/index.html#managing_pool_size

Edit:
I updated the configuration file (Reference), as I had just copy pasted the one for my project earlier. The timeout should ideally solve the problem, If that doesn't work for you there is an expensive solution which I think you could have a look at:

Create a file “c3p0.properties” which must be in the root of the classpath (i.e. no way to override it for particular parts of the application). (Reference)

# c3p0.properties
c3p0.testConnectionOnCheckout=true

With this configuration each connection is tested before being used. It however might affect the performance of the site.

Check if string begins with something?

A little more reusable function:

beginsWith = function(needle, haystack){
    return (haystack.substr(0, needle.length) == needle);
}

jQuery scroll to element

_x000D_
_x000D_
jQuery(document).ready(function($) {_x000D_
  $('a[href^="#"]').bind('click.smoothscroll',function (e) {_x000D_
    e.preventDefault();_x000D_
    var target = this.hash,_x000D_
        $target = $(target);_x000D_
_x000D_
    $('html, body').stop().animate( {_x000D_
      'scrollTop': $target.offset().top-40_x000D_
    }, 900, 'swing', function () {_x000D_
      window.location.hash = target;_x000D_
    } );_x000D_
  } );_x000D_
} );
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<ul role="tablist">_x000D_
  <li class="active" id="p1"><a href="#pane1" role="tab">Section 1</a></li>_x000D_
  <li id="p2"><a href="#pane2" role="tab">Section 2</a></li>_x000D_
  <li id="p3"><a href="#pane3" role="tab">Section 3</a></li>_x000D_
</ul>_x000D_
_x000D_
<div id="pane1"></div>_x000D_
<div id="pane2"></div>_x000D_
<div id="pane3"></div>
_x000D_
_x000D_
_x000D_

How can I drop a table if there is a foreign key constraint in SQL Server?

The Best Answer to dropping the table containing foreign constraints is :

  • Step 1 : Drop the Primary key of the table.
  • Step 2 : Now it will prompt whether to delete all the foreign references or not.
  • Step 3 : Delete the table.

matplotlib: how to change data points color based on some variable

This is what matplotlib.pyplot.scatter is for.

As a quick example:

import matplotlib.pyplot as plt
import numpy as np

# Generate data...
t = np.linspace(0, 2 * np.pi, 20)
x = np.sin(t)
y = np.cos(t)

plt.scatter(t,x,c=y)
plt.show()

enter image description here

Run a single migration file

Looks like at least in the latest Rails release (5.2 at the time of writing) there is one more way of filtering the migrations being ran. One can pass a filter in a SCOPE environment variable which would be then used to select migration files.

Assuming you have two migration files 1_add_foos.rb and 2_add_foos.run_this_one.rb running

SCOPE=run_this_one rails db:migrate:up

will select and run only 2_add_foos.run_this_one.rb. Keep in mind that all migration files matching the scope will be ran.

How to get Text BOLD in Alert or Confirm box?

Maybe you coul'd use UTF8 bold chars.

For examples: https://yaytext.com/bold-italic/

It works on Chromium 80.0, I don't know on other browsers...

How Do I Make Glyphicons Bigger? (Change Size?)

Fontawesome has a perfect solution to this.

I implemented the same. just on your main .css file add this

.gi-2x{font-size: 2em;}
.gi-3x{font-size: 3em;}
.gi-4x{font-size: 4em;}
.gi-5x{font-size: 5em;}

In your example you just have to do this.

<div class = "jumbotron">
    <span class="glyphicon glyphicon-globe gi-5x"></span>
</div>  

Android Webview - Completely Clear the Cache

Make sure you use below method for the form data not be displayed as autopop when clicked on input fields.

getSettings().setSaveFormData(false);

How to get the size of a varchar[n] field in one SQL statement?

This is a function for calculating max valid length for varchar(Nn):

CREATE FUNCTION [dbo].[GetMaxVarcharColumnLength] (@TableSchema NVARCHAR(MAX), @TableName NVARCHAR(MAX), @ColumnName VARCHAR(MAX))
RETURNS INT
AS
BEGIN
    RETURN (SELECT character_maximum_length FROM information_schema.columns  
            WHERE table_schema = @TableSchema AND table_name = @TableName AND column_name = @ColumnName);
END

Usage:

IF LEN(@Name) > [dbo].[GetMaxVarcharColumnLength]('person', 'FamilyStateName', 'Name') 
            RETURN [dbo].[err_Internal_StringForVarcharTooLong]();

How do I find the length of an array?

You have a bunch of options to be used to get a C array size.

int myArray[] = {0, 1, 2, 3, 4, 5, 7};

1) sizeof(<array>) / sizeof(<type>):

std::cout << "Size:" << sizeof(myArray) / sizeof(int) << std::endl;

2) sizeof(<array>) / sizeof(*<array>):

std::cout << "Size:" << sizeof(myArray) / sizeof(*myArray) << std::endl;

3) sizeof(<array>) / sizeof(<array>[<element>]):

std::cout << "Size:" << sizeof(myArray) / sizeof(myArray[0]) << std::endl;

Stock ticker symbol lookup API

Use YQL: a sql-like language to retrieve stuff from public api's: YQL Console (external link)

It gives you a nice XML file to work with!

How to make an introduction page with Doxygen

As of v1.8.8 there is also the option USE_MDFILE_AS_MAINPAGE. So make sure to add your index file, e.g. README.md, to INPUT and set it as this option's value:

INPUT += README.md
USE_MDFILE_AS_MAINPAGE = README.md

What is “assert” in JavaScript?

If the assertion is false, the message is displayed. Specifically, if the first argument is false, the second argument (the string message) will be be logged in the developer tools console. If the first argument is true, basically nothing happens. A simple example – I’m using Google Developer Tools:

var isTrue = true;
var isFalse = false;
console.assert(isTrue, 'Equals true so will NOT log to the console.');
console.assert(isFalse, 'Equals false so WILL log to the console.');

JavaScript dictionary with names

Try:

var myMappings = {
    "Name":     "10%",
    "Phone":    "10%",
    "Address":  "50%",
    "Zip":      "10%",
    "Comments": "20%"
}

// Access is like this
myMappings["Name"] // Returns "10%"
myMappings.Name // The same thing as above

// To loop through...
for(var title in myMappings) {
    // Do whatever with myMappings[title]
}

Cookie blocked/not saved in IFRAME in Internet Explorer

A better solution would be to make an Ajax call inside the iframe to the page that would get/set cookies...

Useful example of a shutdown hook in Java?

You could do the following:

  • Let the shutdown hook set some AtomicBoolean (or volatile boolean) "keepRunning" to false
  • (Optionally, .interrupt the working threads if they wait for data in some blocking call)
  • Wait for the working threads (executing writeBatch in your case) to finish, by calling the Thread.join() method on the working threads.
  • Terminate the program

Some sketchy code:

  • Add a static volatile boolean keepRunning = true;
  • In run() you change to

    for (int i = 0; i < N && keepRunning; ++i)
        writeBatch(pw, i);
    
  • In main() you add:

    final Thread mainThread = Thread.currentThread();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            keepRunning = false;
            mainThread.join();
        }
    });
    

That's roughly how I do a graceful "reject all clients upon hitting Control-C" in terminal.


From the docs:

When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.

That is, a shutdown hook keeps the JVM running until the hook has terminated (returned from the run()-method.

Change the jquery show()/hide() animation?

You can also use a fadeIn/FadeOut Combo, too....

$('.test').bind('click', function(){
    $('.div1').fadeIn(500); 
    $('.div2').fadeOut(500);
    $('.div3').fadeOut(500);
    return false;
});

How to dynamically change a web page's title?

Using the document.title is how you would accomplish it in JavaScript, but how is this supposed to assist with SEO? Bots don't generally execute javascript code as they traverse through pages.

Set inputType for an EditText Programmatically?

Hide:

edtPassword.setInputType(InputType.TYPE_CLASS_TEXT);
edtPassword.setTransformationMethod(null);

Show:

edtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);                    
edtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());

Converting a column within pandas dataframe from int to string

In [16]: df = DataFrame(np.arange(10).reshape(5,2),columns=list('AB'))

In [17]: df
Out[17]: 
   A  B
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9

In [18]: df.dtypes
Out[18]: 
A    int64
B    int64
dtype: object

Convert a series

In [19]: df['A'].apply(str)
Out[19]: 
0    0
1    2
2    4
3    6
4    8
Name: A, dtype: object

In [20]: df['A'].apply(str)[0]
Out[20]: '0'

Don't forget to assign the result back:

df['A'] = df['A'].apply(str)

Convert the whole frame

In [21]: df.applymap(str)
Out[21]: 
   A  B
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9

In [22]: df.applymap(str).iloc[0,0]
Out[22]: '0'

df = df.applymap(str)

How can I solve ORA-00911: invalid character error?

If a special character other than $, _, and # is used in the name of a column or table, the name must be enclosed in double quotations. Link

How do I enable logging for Spring Security?

You can easily enable debugging support using an option for the @EnableWebSecurity annotation:

@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    …
}

If you need profile-specific control the in your application-{profile}.properties file

org.springframework.security.config.annotation.web.builders.WebSecurity.debugEnabled=false

Get Detailed Post: http://www.bytefold.com/enable-disable-profile-specific-spring-security-debug-flag/

How to force uninstallation of windows service

You can manually delete the registry key for your service, located at HKLM\SYSTEM\CurrentControlSet\Services, after that you won't see the service in service control manager (need to refresh or reopen to see the change), and you can reinstall the service as usual.

Easy way to password-protect php page

This helped me a lot and save me much time, its easy to use, and work well, i've even take the risque of change it and it still works.

Fairly good if you dont want to lost to much time on doing it :)

http://www.zubrag.com/scripts/password-protect.php

iterating and filtering two lists using java 8

`List<String> unavailable = list1.stream()
                .filter(e -> (list2.stream()
                        .filter(d -> d.getStr().equals(e))
                        .count())<1)
                        .collect(Collectors.toList());`
for this if i change to 
`List<String> unavailable = list1.stream()
                .filter(e -> (list2.stream()
                        .filter(d -> d.getStr().equals(e))
                        .count())>0)
                        .collect(Collectors.toList());`
will it give me list1 matched with list2 right? 

HTTP redirect: 301 (permanent) vs. 302 (temporary)

Mostly 301 vs 302 is important for indexing in search engines, as their crawlers take this into account and transfer PageRank when using 301.

See Peter Lee's answer for more details.

Can a local variable's memory be accessed outside its scope?

You actually invoked undefined behaviour.

Returning the address of a temporary works, but as temporaries are destroyed at the end of a function the results of accessing them will be undefined.

So you did not modify a but rather the memory location where a once was. This difference is very similar to the difference between crashing and not crashing.

Move an array element from one array position to another

_x000D_
_x000D_
var ELEMS = ['a', 'b', 'c', 'd', 'e'];_x000D_
/*_x000D_
    Source item will remove and it will be placed just after destination_x000D_
*/_x000D_
function moveItemTo(sourceItem, destItem, elements) {_x000D_
    var sourceIndex = elements.indexOf(sourceItem);_x000D_
    var destIndex = elements.indexOf(destItem);_x000D_
    if (sourceIndex >= -1 && destIndex > -1) {_x000D_
        elements.splice(destIndex, 0, elements.splice(sourceIndex, 1)[0]);_x000D_
    }_x000D_
    return elements;_x000D_
}_x000D_
console.log('Init: ', ELEMS);_x000D_
var result = moveItemTo('a', 'c', ELEMS);_x000D_
console.log('BeforeAfter: ', result);
_x000D_
_x000D_
_x000D_

How to make scipy.interpolate give an extrapolated result beyond the input range?

Here's an alternative method that uses only the numpy package. It takes advantage of numpy's array functions, so may be faster when interpolating/extrapolating large arrays:

import numpy as np

def extrap(x, xp, yp):
    """np.interp function with linear extrapolation"""
    y = np.interp(x, xp, yp)
    y = np.where(x<xp[0], yp[0]+(x-xp[0])*(yp[0]-yp[1])/(xp[0]-xp[1]), y)
    y = np.where(x>xp[-1], yp[-1]+(x-xp[-1])*(yp[-1]-yp[-2])/(xp[-1]-xp[-2]), y)
    return y

x = np.arange(0,10)
y = np.exp(-x/3.0)
xtest = np.array((8.5,9.5))

print np.exp(-xtest/3.0)
print np.interp(xtest, x, y)
print extrap(xtest, x, y)

Edit: Mark Mikofski's suggested modification of the "extrap" function:

def extrap(x, xp, yp):
    """np.interp function with linear extrapolation"""
    y = np.interp(x, xp, yp)
    y[x < xp[0]] = yp[0] + (x[x<xp[0]]-xp[0]) * (yp[0]-yp[1]) / (xp[0]-xp[1])
    y[x > xp[-1]]= yp[-1] + (x[x>xp[-1]]-xp[-1])*(yp[-1]-yp[-2])/(xp[-1]-xp[-2])
    return y

Path of currently executing powershell script

Split-Path $MyInvocation.MyCommand.Path -Parent

What is the correct wget command syntax for HTTPS with username and password?

You could try the same address with HTTP instead of HTTPS. Be aware that this does use HTTP instead of HTTPS and only some sites might support this method.

Example address: https://cdimage.debian.org/debian-cd/current/amd64/iso-cd/debian-10.3.0-amd64-netinst.iso

wget http://cdimage.debian.org/debian-cd/current/amd64/iso-cd/debian-10.3.0-amd64-netinst.iso

*notice the http:// instead of https://.

This is probably not recommended though :)

If you can, try use curl.


EDIT:

FYI an example with username (and prompt for password) would be:

curl --user $USERNAME -O http://cdimage.debian.org/debian-cd/current/amd64/iso-cd/debian-10.3.0-amd64-netinst.iso

Where -O is

 -O, --remote-name
              Write output to a local file named like the remote file we get. (Only the file part of the remote file is used, the path is cut off.)

SQL distinct for 2 fields in a database

You can get result distinct by two columns use below SQL:

SELECT COUNT(*) FROM (SELECT DISTINCT c1, c2 FROM [TableEntity]) TE

Can you remove elements from a std::list while iterating through it?

You need to do the combination of Kristo's answer and MSN's:

// Note: Using the pre-increment operator is preferred for iterators because
//       there can be a performance gain.
//
// Note: As long as you are iterating from beginning to end, without inserting
//       along the way you can safely save end once; otherwise get it at the
//       top of each loop.

std::list< item * >::iterator iter = items.begin();
std::list< item * >::iterator end  = items.end();

while (iter != end)
{
    item * pItem = *iter;

    if (pItem->update() == true)
    {
        other_code_involving(pItem);
        ++iter;
    }
    else
    {
        // BTW, who is deleting pItem, a.k.a. (*iter)?
        iter = items.erase(iter);
    }
}

Of course, the most efficient and SuperCool® STL savy thing would be something like this:

// This implementation of update executes other_code_involving(Item *) if
// this instance needs updating.
//
// This method returns true if this still needs future updates.
//
bool Item::update(void)
{
    if (m_needsUpdates == true)
    {
        m_needsUpdates = other_code_involving(this);
    }

    return (m_needsUpdates);
}

// This call does everything the previous loop did!!! (Including the fact
// that it isn't deleting the items that are erased!)
items.remove_if(std::not1(std::mem_fun(&Item::update)));

PHP header redirect 301 - what are the implications?

Just a tip: using http_response_code is much easier to remember than writing the full header:

http_response_code(301);
header('Location: /option-a'); 
exit;

Running JAR file on Windows

Easiest route is probably upgrading or re-installing the Java Runtime Environment (JRE).

Or this:

  • Open the Windows Explorer, from the Tools select 'Folder Options...'
  • Click the File Types tab, scroll down and select JAR File type.
  • Press the Advanced button.
  • In the Edit File Type dialog box, select open in Actions box and click Edit...
  • Press the Browse button and navigate to the location the Java interpreter javaw.exe.
  • In the Application used to perform action field, needs to display something similar to C:\Program Files\Java\j2re1.4.2_04\bin\javaw.exe" -jar "%1" % (Note: the part starting with 'javaw' must be exactly like that; the other part of the path name can vary depending on which version of Java you're using) then press the OK buttons until all the dialogs are closed.

Which was stolen from here: http://windowstipoftheday.blogspot.com/2005/10/setting-jar-file-association.html

Understanding Linux /proc/id/maps

Each row in /proc/$PID/maps describes a region of contiguous virtual memory in a process or thread. Each row has the following fields:

address           perms offset  dev   inode   pathname
08048000-08056000 r-xp 00000000 03:0c 64593   /usr/sbin/gpm
  • address - This is the starting and ending address of the region in the process's address space
  • permissions - This describes how pages in the region can be accessed. There are four different permissions: read, write, execute, and shared. If read/write/execute are disabled, a - will appear instead of the r/w/x. If a region is not shared, it is private, so a p will appear instead of an s. If the process attempts to access memory in a way that is not permitted, a segmentation fault is generated. Permissions can be changed using the mprotect system call.
  • offset - If the region was mapped from a file (using mmap), this is the offset in the file where the mapping begins. If the memory was not mapped from a file, it's just 0.
  • device - If the region was mapped from a file, this is the major and minor device number (in hex) where the file lives.
  • inode - If the region was mapped from a file, this is the file number.
  • pathname - If the region was mapped from a file, this is the name of the file. This field is blank for anonymous mapped regions. There are also special regions with names like [heap], [stack], or [vdso]. [vdso] stands for virtual dynamic shared object. It's used by system calls to switch to kernel mode. Here's a good article about it: "What is linux-gate.so.1?"

You might notice a lot of anonymous regions. These are usually created by mmap but are not attached to any file. They are used for a lot of miscellaneous things like shared memory or buffers not allocated on the heap. For instance, I think the pthread library uses anonymous mapped regions as stacks for new threads.

how can I debug a jar at runtime?

http://www.eclipsezone.com/eclipse/forums/t53459.html

Basically run it with:

-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=1044

The application, at launch, will wait until you connect from another source.

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

"CSV file does not exist" for a filename with embedded quotes

Adnane's answer helped me.

Here's my full code on mac, hope this helps someone. All my csv files are saved in /Users/lionelyu/Documents/Python/Python Projects/

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')

path = '/Users/lionelyu/Documents/Python/Python Projects/'

aapl = pd.read_csv(path + 'AAPL_CLOSE.csv',index_col='Date',parse_dates=True)
cisco = pd.read_csv(path + 'CISCO_CLOSE.csv',index_col='Date',parse_dates=True)
ibm = pd.read_csv(path + 'IBM_CLOSE.csv',index_col='Date',parse_dates=True)
amzn = pd.read_csv(path + 'AMZN_CLOSE.csv',index_col='Date',parse_dates=True)

Can't operator == be applied to generic types in C#?


bool Compare(T x, T y) where T : class { return x == y; }

The above will work because == is taken care of in case of user-defined reference types.
In case of value types, == can be overridden. In which case, "!=" should also be defined.

I think that could be the reason, it disallows generic comparison using "==".

How can I read a text file from the SD card in Android?

BufferedReader br = null;
try {
        String fpath = Environment.getExternalStorageDirectory() + <your file name>;
        try {
            br = new BufferedReader(new FileReader(fpath));
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        String line = "";
        while ((line = br.readLine()) != null) {
         //Do something here 
        }

Why is an OPTIONS request sent and can I disable it?

What worked for me was to import "github.com/gorilla/handlers" and then use it this way:

router := mux.NewRouter()
router.HandleFunc("/config", getConfig).Methods("GET")
router.HandleFunc("/config/emcServer", createEmcServers).Methods("POST")

headersOk := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})

log.Fatal(http.ListenAndServe(":" + webServicePort, handlers.CORS(originsOk, headersOk, methodsOk)(router)))

As soon as I executed an Ajax POST request and attaching JSON data to it, Chrome would always add the Content-Type header which was not in my previous AllowedHeaders config.

How do I format a string using a dictionary in python-3.x?

Is this good for you?

geopoint = {'latitude':41.123,'longitude':71.091}
print('{latitude} {longitude}'.format(**geopoint))

Why am I getting tree conflicts in Subversion?

I had this same problem, and resolved it by re-doing the merge using these instructions. Basically, it uses SVN's "2-URL merge" to update trunk to the current state of your branch, without bothering so much about history and tree conflicts. Saved me from manually fixing 114 tree conflicts.

I'm not sure if it preserves history as well as one would like, but it was worth it in my case.

How can I run an EXE program from a Windows Service using C#?

This will never work, at least not under Windows Vista or later. The key problem is that you're trying to execute this from within a Windows Service, rather than a standard Windows application. The code you've shown will work perfectly in a Windows Forms, WPF, or Console application, but it won't work at all in a Windows Service.

Windows Services cannot start additional applications because they are not running in the context of any particular user. Unlike regular Windows applications, services are now run in an isolated session and are prohibited from interacting with a user or the desktop. This leaves no place for the application to be run.

More information is available in the answers to these related questions:

The best solution to your problem, as you've probably figured out by now, is to create a standard Windows application instead of a service. These are designed to be run by a particular user and are associated with that user's desktop. This way, you can run additional applications whenever you want, using the code that you've already shown.

Another possible solution, assuming that your Console application does not require an interface or output of any sort, is to instruct the process not to create a window. This will prevent Windows from blocking the creation of your process, because it will no longer request that a Console window be created. You can find the relevant code in this answer to a related question.

Convert HTML5 into standalone Android App

You can use https://appery.io/ It is the same phonegap but in very convinient wrapper

jQuery Set Cursor Position in Text Area

Based on this question, the answer will not work perfectly for ie and opera when there is new line in the textarea. The answer explain how to adjust the selectionStart, selectionEnd before calling setSelectionRange.

I have try the adjustOffset from the other question with the solution proposed by @AVProgrammer and it work.

function adjustOffset(el, offset) {
    /* From https://stackoverflow.com/a/8928945/611741 */
    var val = el.value, newOffset = offset;
    if (val.indexOf("\r\n") > -1) {
        var matches = val.replace(/\r\n/g, "\n").slice(0, offset).match(/\n/g);
        newOffset += matches ? matches.length : 0;
    }
    return newOffset;
}

$.fn.setCursorPosition = function(position){
    /* From https://stackoverflow.com/a/7180862/611741 */
    if(this.lengh == 0) return this;
    return $(this).setSelection(position, position);
}

$.fn.setSelection = function(selectionStart, selectionEnd) {
    /* From https://stackoverflow.com/a/7180862/611741 
       modified to fit https://stackoverflow.com/a/8928945/611741 */
    if(this.lengh == 0) return this;
    input = this[0];

    if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
    } else if (input.setSelectionRange) {
        input.focus();
        selectionStart = adjustOffset(input, selectionStart);
        selectionEnd = adjustOffset(input, selectionEnd);
        input.setSelectionRange(selectionStart, selectionEnd);
    }

    return this;
}

$.fn.focusEnd = function(){
    /* From https://stackoverflow.com/a/7180862/611741 */
    this.setCursorPosition(this.val().length);
}

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

Try to use mousemove event lisentner

var audio = document.createElement("AUDIO")
document.body.appendChild(audio);
audio.src = "./audio/rain.m4a"

document.body.addEventListener("mousemove", function () {
    audio.play()
})

require is not defined? Node.js

This can now also happen in Node.js as of version 14.

It happens when you declare your package type as module in your package.json. If you do this, certain CommonJS variables can't be used, including require.

To fix this, remove "type": "module" from your package.json and make sure you don't have any files ending with .mjs.

How to access html form input from asp.net code behind

It should normally be done with Request.Form["elementName"].

For example, if you have <input type="text" name="email" /> then you can use Request.Form["email"] to access its value.

Counting how many times a certain char appears in a string before any other char appears

You could do this, it doesn't require LINQ, but it's not the best way to do it(since you make split the whole string and put it in an array and just pick the length of it, you could better just do a while loop and check every character), but it works.

int count = test.Split('$').Length - 1;

Defined Edges With CSS3 Filter Blur

You can stop the image from overlapping it's edges by clipping the image and applying a wrapper element which sets the blur effect to 0 pixels. This is how it looks like:

HTML

<div id="wrapper">
  <div id="image"></div>
</div>

CSS

#wrapper {
  width: 1024px;
  height: 768px;

  border: 1px solid black;

  // 'blur(0px)' will prevent the wrapped image
  // from overlapping the border
  -webkit-filter: blur(0px);
  -moz-filter: blur(0px);
  -ms-filter: blur(0px);
  filter: blur(0px);
}

#wrapper #image {
  width: 1024px;
  height: 768px;

  background-image: url("../images/cats.jpg");
  background-size: cover;

  -webkit-filter: blur(10px);
  -moz-filter: blur(10px);
  -ms-filter: blur(10px);
  filter: blur(10px);

  // Position 'absolute' is needed for clipping
  position: absolute;
  clip: rect(0px, 1024px, 768px, 0px);
}

What is the most efficient way to loop through dataframes with pandas?

I checked out iterrows after noticing Nick Crawford's answer, but found that it yields (index, Series) tuples. Not sure which would work best for you, but I ended up using the itertuples method for my problem, which yields (index, row_value1...) tuples.

There's also iterkv, which iterates through (column, series) tuples.

SQL to search objects, including stored procedures, in Oracle

I would use DBA_SOURCE (if you have access to it) because if the object you require is not owned by the schema under which you are logged in you will not see it.

If you need to know the functions and Procs inside the packages try something like this:

select * from all_source
 where type = 'PACKAGE'
   and (upper(text) like '%FUNCTION%' or upper(text) like '%PROCEDURE%')
   and owner != 'SYS';

The last line prevents all the sys stuff (DBMS_ et al) from being returned. This will work in user_source if you just want your own schema stuff.

How to overcome the CORS issue in ReactJS

Temporary solve this issue by a chrome plugin called CORS. Btw backend server have to send proper header to front end requests.

Convert double to string

Try c.ToString("F6");

(For a full explanation of numeric formatting, see MSDN)

What is the difference between DTR/DSR and RTS/CTS flow control?

  • DTR - Data Terminal Ready
  • DSR - Data Set Ready
  • RTS - Request To Send
  • CTS - Clear To Send

There are multiple ways of doing things because there were never any protocols built into the standards. You use whatever ad-hoc "standard" your equipment implements.

Just based on the names, RTS/CTS would seem to be a natural fit. However, it's backwards from the needs that developed over time. These signals were created at a time when a terminal would batch-send a screen full of data, but the receiver might not be ready, thus the need for flow control. Later the problem would be reversed, as the terminal couldn't keep up with data coming from the host, but the RTS/CTS signals go the wrong direction - the interface isn't orthogonal, and there's no corresponding signals going the other way. Equipment makers adapted as best they could, including using the DTR and DSR signals.

EDIT

To add a bit more detail, its a two level hierarchy so "officially" both must happen for communication to take place. The behavior is defined in the original CCITT (now ITU-T) standard V.28.

enter image description here

The DCE is a modem connecting between the terminal and telephone network. In the telephone network was another piece of equipment which split off to the data network, eg. X.25.

The modem has three states: Powered off, Ready (Data Set Ready is true), and connected (Data Carrier Detect)

The terminal can't do anything until the modem is connected.

When the modem wants to send data, it raises RTS and the modem grants the request with CTS. The modem lowers CTS when its internal buffer is full.

So nostalgic!

How do I programmatically click on an element in JavaScript?

I used KooiInc's function listed above but I had to use two different input types one 'button' for IE and one 'submit' for FireFox. I am not exactly sure why but it works.

// HTML

<input type="button" id="btnEmailHidden" style="display:none" />
<input type="submit" id="btnEmailHidden2" style="display:none" />

// in JavaScript

var hiddenBtn = document.getElementById("btnEmailHidden");

if (hiddenBtn.fireEvent) {
    hiddenBtn.fireEvent('onclick');
    hiddenBtn[eType]();
}
else {
    // dispatch for firefox + others
    var evObj = document.createEvent('MouseEvent');
    evObj.initEvent(eType, true, true);
    var hiddenBtn2 = document.getElementById("btnEmailHidden2");
    hiddenBtn2.dispatchEvent(evObj);
}

I have search and tried many suggestions but this is what ended up working. If I had some more time I would have liked to investigate why submit works with FF and button with IE but that would be a luxury right now so on to the next problem.

Is "&#160;" a replacement of "&nbsp;"?

  • &nbsp; is the character entity reference (meant to be easily parseable by humans).
  • &#160; is the numeric entity reference (meant to be easily parseable by machines).

They are the same except for the fact that the latter does not need another lookup table to find its actual value. The lookup table is called a DTD, by the way.

You can read more about character entity references in the offical W3C documents.

Why does sudo change the PATH?

Er, it's not really a test if you don't add something to your path:

bill@bill-desktop:~$ ls -l /opt/pkg/bin
total 12
-rwxr-xr-x 1 root root   28 2009-01-22 18:58 foo
bill@bill-desktop:~$ which foo
/opt/pkg/bin/foo
bill@bill-desktop:~$ sudo su
root@bill-desktop:/home/bill# which foo
root@bill-desktop:/home/bill# 

Python: Remove division decimal

When a number as a decimal it is usually a float in Python.

If you want to remove the decimal and keep it an integer (int). You can call the int() method on it like so...

>>> int(2.0)
2

However, int rounds down so...

>>> int(2.9)
2

If you want to round to the nearest integer you can use round:

>>> round(2.9)
3.0
>>> round(2.4)
2.0

And then call int() on that:

>>> int(round(2.9))
3
>>> int(round(2.4))
2

Perform Button click event when user press Enter key in Textbox

in the html code only, add a panel that contains the page's controls. Inside the panel, add a line DefaultButton = "buttonNameThatClicksAtEnter". See the example below, there should be nothing else required.

<asp:Panel runat="server" DefaultButton="Button1"> //add this!
  //here goes all the page controls and the trigger button
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Send" />
</asp:Panel> //and this too!

how to filter out a null value from spark dataframe

df.where(df.col("friend_id").isNull)

Current time in microseconds in java

Java support microseconds through TimeUnit enum.

Here is the java doc: Enum TimeUnit

You can get microseconds in java by this way:

long microsenconds = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());

You also can convert microseconds back to another time units, for example:

long seconds = TimeUnit.MICROSECONDS.toSeconds(microsenconds);

How to combine two strings together in PHP?

$result = $data1 . $data2;

This is called string concatenation. Your example lacks a space though, so for that specifically, you would need:

$result = $data1 . ' ' . $data2;

Can't access 127.0.0.1

In windows first check under services if world wide web publishing services is running. If not start it.

If you cannot find it switch on IIS features of windows: In 7,8,10 it is under control panel , "turn windows features on or off". Internet Information Services World Wide web services and Internet information Services Hostable Core are required. Not sure if there is another way to get it going on windows, but this worked for me for all browsers. You might need to add localhost or http:/127.0.0.1 to the trusted websites also under IE settings.

MSSQL Error 'The underlying provider failed on Open'

For me it was just a simple mistake:

I used Amazon EC2, and I used my elastic IP address in the connection string, but when I changed IP addresses I forgot to update my connection string.

Trying to get property of non-object - Laravel 5

If you working with or loops (for, foreach, etc.) or relationships (one to many, many to many, etc.), this may mean that one of the queries is returning a null variable or a null relationship member.

For example: In a table, you may want to list users with their roles.

<table>
    <tr>
        <th>Name</th>
        <th>Role</th>
    </tr>
    @foreach ($users as $user)
    <tr>
        <td>{{ $user->name }}</td>
        <td>{{ $user->role->name }}</td>
    </tr>
    @endforeach
</table>

In the above case, you may receive this error if there is even one User who does not have a Role. You should replace {{ $user->role->name }} with {{ !empty($user->role) ? $user->role->name:'' }}, like this:

<table>
    <tr>
        <th>Name</th>
        <th>Role</th>
    </tr>
    @foreach ($users as $user)
    <tr>
        <td>{{ $user->name }}</td>
        <td>{{ !empty($user->role) ? $user->role->name:'' }}</td>
    </tr>
    @endforeach
</table>

Edit: You can use Laravel's the optional method to avoid errors (more information). For example:

<table>
    <tr>
        <th>Name</th>
        <th>Role</th>
    </tr>
    @foreach ($users as $user)
    <tr>
        <td>{{ $user->name }}</td>
        <td>{{ optional($user->role)->name }}</td>
    </tr>
    @endforeach
</table>

If you are using PHP 8, you can use the null safe operator:

<table>
    <tr>
        <th>Name</th>
        <th>Role</th>
    </tr>
    @foreach ($users as $user)
    <tr>
        <td>{{ $user?->name }}</td>
        <td>{{ $user?->role?->name }}</td>
    </tr>
    @endforeach
</table>

How do I make Git use the editor of my choice for commits?

For MAC, BBEdit:

First, open BBEdit, click on the BBEdit logo, and choose Install Command-Line Tools.

Then from the command line,

git config --global core.editor "BBEdit -w"

When to use extern in C++

This is useful when you want to have a global variable. You define the global variables in some source file, and declare them extern in a header file so that any file that includes that header file will then see the same global variable.

Uncaught SyntaxError: Invalid or unexpected token

I also had an issue with multiline strings in this scenario. @Iman's backtick(`) solution worked great in the modern browsers but caused an invalid character error in Internet Explorer. I had to use the following:

'@item.MultiLineString.Replace(Environment.NewLine, "<br />")'

Then I had to put the carriage returns back again in the js function. Had to use RegEx to handle multiple carriage returns.

// This will work for the following:
// "hello\nworld"
// "hello<br>world"
// "hello<br />world"
$("#MyTextArea").val(multiLineString.replace(/\n|<br\s*\/?>/gi, "\r"));

Escape double quote in VB string

Another example:

Dim myPath As String = """" & Path.Combine(part1, part2) & """"

Good luck!

split string only on first instance - java

Yes you can, just pass the integer param to the split method

String stSplit = "apple=fruit table price=5"

stSplit.split("=", 2);

Here is a java doc reference : String#split(java.lang.String, int)

Executing multi-line statements in the one-line command-line?

If your system is Posix.2 compliant it should supply the printf utility:

$ printf "print 'zap'\nfor r in range(3): print 'rob'" | python
zap
rob
rob
rob

The current .NET SDK does not support targeting .NET Standard 2.0 error in Visual Studio 2017 update 15.3

Actually, to me it happened in opposite way to another answers.

I did install the latest .NET Core SDK before the issue appeared (3.0.0-preview2 in my case) having not the latest version of Visual Studio (not sure if that would make any difference).

So, the solution was just to uninstall that latest .NET Core SDK. (This is not perfect if you need it, so you might consider Visual Studio upgrade to the latest one, but at least that solved ongoing issue).

best way to get the key of a key/value javascript object

Object.keys() The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

var arr1 = Object.keys(obj);

Object.values() The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

var arr2 = Object.values(obj);

For more please go here

Javascript/jQuery: Set Values (Selection) in a multiple Select

Pure JavaScript ES5 solution

For some reason you don't use jQuery nor ES6? This might help you:

_x000D_
_x000D_
var values = "Test,Prof,Off";_x000D_
var splitValues = values.split(',');_x000D_
var multi = document.getElementById('strings');_x000D_
_x000D_
multi.value = null; // Reset pre-selected options (just in case)_x000D_
var multiLen = multi.options.length;_x000D_
for (var i = 0; i < multiLen; i++) {_x000D_
  if (splitValues.indexOf(multi.options[i].value) >= 0) {_x000D_
    multi.options[i].selected = true;_x000D_
  }_x000D_
}
_x000D_
<select name='strings' id="strings" multiple style="width:100px;">_x000D_
    <option value="Test">Test</option>_x000D_
    <option value="Prof">Prof</option>_x000D_
    <option value="Live">Live</option>_x000D_
    <option value="Off">Off</option>_x000D_
    <option value="On" selected>On</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to print to stderr in Python?

Python 2:

print >> sys.stderr, "fatal error"

Python 3:

print("fatal error", file=sys.stderr)

Long answer

print >> sys.stderr is gone in Python3. http://docs.python.org/3.0/whatsnew/3.0.html says:

Old: print >> sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

For many of us, it feels somewhat unnatural to relegate the destination to the end of the command. The alternative

sys.stderr.write("fatal error\n")

looks more object oriented, and elegantly goes from the generic to the specific. But note that write is not a 1:1 replacement for print.

Where is debug.keystore in Android Studio

The easiest thing I can think of is to grab the fingerprint from the debug.keystore (paths are mentioned in other answers) and add that to your project. No need to copy keystores or add new apps. Just append to the list of fingerprints for each machine you develop on.

FWIW, I ran into this when I switched from one laptop to another. I bounce around a lot.

https://support.google.com/firebase/answer/7000104?hl=en#sha1

Hope that helps some folks out! :)

Angular 2 Scroll to bottom (Chat style)

After reading other solutions, the best solution I can think of, so you run only what you need is the following: You use ngOnChanges to detect the proper change

ngOnChanges() {
  if (changes.messages) {
      let chng = changes.messages;
      let cur  = chng.currentValue;
      let prev = chng.previousValue;
      if(cur && prev) {
        // lazy load case
        if (cur[0].id != prev[0].id) {
          this.lazyLoadHappened = true;
        }
        // new message
        if (cur[cur.length -1].id != prev[prev.length -1].id) {
          this.newMessageHappened = true;
        }
      }
    }

}

And you use ngAfterViewChecked to actually enforce the change before it renders but after the full height is calculated

ngAfterViewChecked(): void {
    if(this.newMessageHappened) {
      this.scrollToBottom();
      this.newMessageHappened = false;
    }
    else if(this.lazyLoadHappened) {
      // keep the same scroll
      this.lazyLoadHappened = false
    }
  }

If you are wondering how to implement scrollToBottom

@ViewChild('scrollWrapper') private scrollWrapper: ElementRef;
scrollToBottom(){
    try {
      this.scrollWrapper.nativeElement.scrollTop = this.scrollWrapper.nativeElement.scrollHeight;
    } catch(err) { }
  }

How to get substring from string in c#?

var data =" Retrieves a substring from this instance. The substring starts at a specified character position.";

var result = data.Split(new[] {'.'}, 1)[0];

Output:

Retrieves a substring from this instance. The substring starts at a specified character position.

What's the simplest way to print a Java array?

Using org.apache.commons.lang3.StringUtils.join(*) methods can be an option
For example:

String[] strArray = new String[] { "John", "Mary", "Bob" };
String arrayAsCSV = StringUtils.join(strArray, " , ");
System.out.printf("[%s]", arrayAsCSV);
//output: [John , Mary , Bob]

I used the following dependency

<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>

Make a link in the Android browser start up my app?

Here's my recipe:

Create a static HTML that redirects to your requested app URL, put that page on the web.

That way, the links you share are 'real' links as far as Android is concerned ( they will be 'clickable').

You 'share' a regular HTTP link, www.your.server.com/foo/bar.html This URL returns a simple 8 line HTML that redirects to your app's URI (window.location = "blah://kuku") (note that 'blah' doesn't have to be HTTP or HTTPS any more).

Once you get this up and running, you can augment the HTML with all the fancy capabilities as suggested above.

This works with the built-in browser, Opera, and Firefox (haven't tested any other browser). Firefox asks 'This link needs to be opened with an application' (ok, cancel). Other browsers apparently don't worry about security that much, they just open the app, no questions asked.

When do you use POST and when do you use GET?

1.3 Quick Checklist for Choosing HTTP GET or POST

Use GET if:

    The interaction is more like a question (i.e., it is a safe operation such as a query, read operation, or lookup).

Use POST if:

    The interaction is more like an order, or
    The interaction changes the state of the resource in a way that the user would perceive (e.g., a subscription to a service), or
    The user be held accountable for the results of the interaction.

Source.

IOError: [Errno 32] Broken pipe: Python

Closes should be done in reverse order of the opens.

Finding child element of parent pure javascript

You have a parent element, you want to get all child of specific attribute 1. get the parent 2. get the parent nodename by using parent.nodeName.toLowerCase() convert the nodename to lower case e.g DIV will be div 3. for further specific purpose, get an attribute of the parent e.g parent.getAttribute("id"). this will give you id of the parent 4. Then use document.QuerySelectorAll(paret.nodeName.toLowerCase()+"#"_parent.getAttribute("id")+" input " ); if you want input children of the parent node

_x000D_
_x000D_
let parent = document.querySelector("div.classnameofthediv")_x000D_
let parent_node = parent.nodeName.toLowerCase()_x000D_
let parent_clas_arr = parent.getAttribute("class").split(" ");_x000D_
let parent_clas_str = '';_x000D_
  parent_clas_arr.forEach(e=>{_x000D_
     parent_clas_str +=e+'.';_x000D_
  })_x000D_
let parent_class_name = parent_clas_str.substr(0, parent_clas_str.length-1)  //remove the last dot_x000D_
let allchild = document.querySelectorAll(parent_node+"."+parent_class_name+" input")
_x000D_
_x000D_
_x000D_

Emulate/Simulate iOS in Linux

On linux you can check epiphany-browser, resizes the windows you'll get same bugs as in ios. Both browsers uses Webkit.

Ubuntu/Mint:

sudo apt install epiphany-browser

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

If you get an icon error when submitting an application from Xcode9, or if you cannot see app icon on your simulator as well as a device, just update your cocoapods to the latest version in your project. That issue is a bug in Xcode9 with cocoapods.


There's a new guideline for iPhoneX that can be seen here.


Here's a helpful website that creates an icon for iOS, Mac App and Android app.

You just need to drag and drop your 1024 x 1024 icon and the site will create all the icon sizes and send it to your email. Then follow the following method to set icons for iOS app.

After Apple launched iOS 8, iPhone 6 and 6 Plus, the app icon sizes and launch image sizes changed. Please visit my post for new sizes:

Image resolution for new iPhone 6 and 6+, @3x support added?


Yes, you need to add a 120x120 high resolution icon. Now, if you want to target only iOS 7, you just need 76 x 76, 120 x 120 and 152 x 152 icon sizes. If you also want to target iOS 6, you’ll need 57 x 57, 72 x 72, 76 x 76, 114 x 114, 120 x 120, 144 x 144 and 152 x 152 icon sizes. Without counting Spotlight and Settings icon if you don’t want the OS to interpolate them!

Enter image description here

Enter image description here

As per the blog post New Metrics for iOS 7 App Icons.

UPDATE:

As per Apple Guideline App-icon OR Icon and Image Sizes:

Icon dimensions (iOS 7 and later)

Enter image description here

Icon dimensions (iOS 6.1 and earlier)

Enter image description here

Create different sizes of the app icon for different devices. If you’re creating a universal app, you need to supply app icons in all four sizes.

For iPhone and iPod touch, both of these sizes are required:

  • 120 x 120 pixels

  • 60 x 60 pixels (standard resolution)

For iPad, both of these sizes are required:

  • 152 x 152

  • 76 x 76 pixels (standard resolution)


Now set this into Project:

  • Create a new icon with 120 pixels with high-resolution and 60 pixels as regular as above that the Apple documentation mentions and set the name. For example, icon-120.png and icon-152.png.

  • Put this icons into your project Resource folder and add this icon into the project:

Enter image description here

  • After this, click on ProjectName-Info.plist and find the icon files row. If you can't find it, then add it by clicking the (+) sign and select icon files and then set all icon images like below.

Enter image description here

Enter image description here

Now archive and distribute your project as we did for submission of the app binary into the App Store. I hope now you can submit your app without any icon issue.


NOTE:

Be careful to provide all the icons you need. Otherwise your app will not pass Apple validation. If you’ve received this kind of email:

Invalid Image - For iOS applications, icons included in the binary submission must be in the PNG format.

- If your application supports the iPhone device family, you must include square icons of the following dimensions: 57x57 pixels and 120x120 pixels.

- If your application supports the iPad device family, you must include square icons of the following dimensions: 72x72 pixels, 76x76 pixels and 152x152 pixels

Apple is now accepting applications that work on iOS 7 as well, so whatever the Deployment target 6.1 or earlier, but you also need to provide the iOS 7 icon sizes as I mention above (that the store is expecting).

Xcode 5 app icon Manage

If you are using xCode5 The first thing to update is the icons. Xcode 5 introduces Asset Catalogs to simply managing multiple copies of an image (such as for multiple resolutions). We’ll create one to manage both the Game’s icons, along with the Launch Images.

enter image description here

Now, click the Use Asset Catalog button. When confirming the migration, you’re also asked if you wish to migrate the Launch Images (which is iOS talk for the splash screen that appears when starting your app) - you’ll want to ensure this is checked as well.

enter image description here

Please take a Look for more Info Apple doc of Asset Catalogs

How do I do pagination in ASP.NET MVC?

Here's a link that helped me with this.

It uses PagedList.MVC NuGet package. I'll try to summarize the steps

  1. Install the PagedList.MVC NuGet package

  2. Build project

  3. Add using PagedList; to the controller

  4. Modify your action to set page public ActionResult ListMyItems(int? page) { List list = ItemDB.GetListOfItems(); int pageSize = 3; int pageNumber = (page ?? 1); return View(list.ToPagedList(pageNumber, pageSize)); }

  5. Add paging links to the bottom of your view @*Your existing view*@ Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount @Html.PagedListPager(Model, page => Url.Action("Index", new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))

Best way to add Gradle support to IntelliJ Project

Another way, simpler.

Add your

build.gradle

file to the root of your project. Close the project. Manually remove *.iml file. Then choose "Import Project...", navigate to your project directory, select the build.gradle file and click OK.

How to delete an app from iTunesConnect / App Store Connect

You Can Now Delete App.

On October 4, 2018, Apple released a new update of the appstoreconnect (previously iTunesConnect).

It's now easier to manage apps you no longer need in App Store Connect by removing them from your main view in My Apps, even if they haven't been submitted for approval. You must have the Legal or Admin role to remove apps.

From the homepage, click My Apps, then choose the app you want to remove. Scroll to the Additional Information section, then click Remove App. In the dialog that appears, click Remove. You can restore a removed app at any time, as long as the app name is not currently in use by another developer.

From the homepage, click My Apps. In the upper right-hand corner, click the arrow next to All Statuses. From the drop-down menu, choose Removed Apps. Choose the app you want to restore. Scroll to the Additional Information section, then click Restore App.

You can show the removed app by clicking on all Statuses on the top right of the screen and then select Removed Apps. Thank you @Daniel for the tips.

enter image description here

Please note:

you can only remove apps if all versions of that app are in one of the following states: Prepare for Submission, Invalid Binary, Developer Rejected, Rejected, Metadata Rejected, Developer, Removed from Sale.

Calling a parent window function from an iframe

Window.postMessage()

This method safely enables cross-origin communication.

And if you have access to parent page code then any parent method can be called as well as any data can be passed directly from Iframe. Here is a small example:

Parent page:

if (window.addEventListener) {
    window.addEventListener("message", onMessage, false);        
} 
else if (window.attachEvent) {
    window.attachEvent("onmessage", onMessage, false);
}

function onMessage(event) {
    // Check sender origin to be trusted
    if (event.origin !== "http://example.com") return;

    var data = event.data;

    if (typeof(window[data.func]) == "function") {
        window[data.func].call(null, data.message);
    }
}

// Function to be called from iframe
function parentFunc(message) {
    alert(message);
}

Iframe code:

window.parent.postMessage({
    'func': 'parentFunc',
    'message': 'Message text from iframe.'
}, "*");
// Use target origin instead of *

UPDATES:

Security note:

Always provide a specific targetOrigin, NOT *, if you know where the other window's document should be located. Failing to provide a specific target discloses the data you send to any interested malicious site (comment by ZalemCitizen).

References:

When 1 px border is added to div, Div size increases, Don't want to do that

Having used many of these solutions, I find using the trick of setting border-color: transparent to be the most flexible and widely-supported:

.some-element {
    border: solid 1px transparent;
}

.some-element-selected {
    border: solid 1px black;
}

Why it's better:

  • No need to to hard-code the element's width
  • Great cross-browser support (only IE6 missed)
  • Unlike with outline, you can still specify, e.g., top and bottom borders separately
  • Unlike setting border color to be that of the background, you don't need to update this if you change the background, and it's compatible with non-solid colored backgrounds.

How to drop all tables from the database with manage.py CLI in Django?

This answer is for postgresql DB:

Run: echo 'drop owned by some_user' | ./manage.py dbshell

NOTE: some_user is the name of the user you use to access the database, see settings.py file:

default_database = {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'somedbname',
    'USER': 'some_user',
    'PASSWORD': 'somepass',
    'HOST': 'postgresql',
    'PORT': '',
}

How do I import a namespace in Razor View Page?

The first way is that use @using statement in .cshtml files, that imports a namespace to current file only, and the second:

In the "web.config" file in "Views" directory of your project (notice it is not the main web.config in project's root), find this section:

<system.web.webPages.razor>
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
      <add namespace="System.Web.Mvc" />
      <add namespace="System.Web.Mvc.Ajax" />
      .
      .
      <!-- etc -->
    </namespaces>
  </pages>
</system.web.webPages.razor>

you can add your custom namespace like this:

<add namespace="My.Custom" />

that will add the namespace to all of .cshtml (and/or .vbhtml) files; also you can change views inheritance from here, like:

<pages pageBaseType="My.Custom.MyWebViewPage">

Regards.


UPDATE: Thanks to @Nick Silberstein to his reminder about areas! He said:

If you're working within an area, you must add the namespace within the Web.config under /Areas/<AreaName>/Views/ rather than /Views/

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

I had Microsoft Access Database Engine 2010 Redistributable already installed on my machine but was still receiving the Microsoft ACE OLEDB Provider error.

Then I recalled that I had upgraded to Office 2016 recently, so, may be I should try reinstalling Microsoft Access Database Engine 2010 Redistributable. And that fixed the problem on my machine.

So, if you have upgraded to different version of MS Office or even repaired/reinstalled your MS Office then try reinstalling Microsoft Access Database Engine 2010 Redistributable before wasting time with finding other fixes. Good luck!

git status shows fatal: bad object HEAD

In my case the error came out of nowhere, but didn't let me push to the remote branch.

git fetch origin

And that solved it.

I agree this may not solve the issue for everyone, but before trying a more complex approach give it a shot at this one, nothing to loose.

Jenkins: Can comments be added to a Jenkinsfile?

Comments work fine in any of the usual Java/Groovy forms, but you can't currently use groovydoc to process your Jenkinsfile (s).

First, groovydoc chokes on files without extensions with the wonderful error

java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:109)
    at org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:131)
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1967)
    at org.codehaus.groovy.tools.groovydoc.SimpleGroovyClassDocAssembler.<init>(SimpleGroovyClassDocAssembler.java:67)
    at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.parseGroovy(GroovyRootDocBuilder.java:131)
    at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.getClassDocsFromSingleSource(GroovyRootDocBuilder.java:83)
    at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.processFile(GroovyRootDocBuilder.java:213)
    at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.buildTree(GroovyRootDocBuilder.java:168)
    at org.codehaus.groovy.tools.groovydoc.GroovyDocTool.add(GroovyDocTool.java:82)
    at org.codehaus.groovy.tools.groovydoc.GroovyDocTool$add.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
    at org.codehaus.groovy.tools.groovydoc.Main.execute(Main.groovy:214)
    at org.codehaus.groovy.tools.groovydoc.Main.main(Main.groovy:180)
    ... 6 more

... and second, as far as I can tell Javadoc-style commments at the start of a groovy script are ignored. So even if you copy/rename your Jenkinsfile to Jenkinsfile.groovy, you won't get much useful output.

I want to be able to use a

/**
 * Document my Jenkinsfile's overall purpose here
 */

comment at the start of my Jenkinsfile. No such luck (yet).

groovydoc will process classes and methods defined in your Jenkinsfile if you pass -private to the command, though.

Java get last element of a collection

Well one solution could be:

list.get(list.size()-1)

Edit: You have to convert the collection to a list before maybe like this: new ArrayList(coll)

How to upload file using Selenium WebDriver in Java

I have tried to use the above robot there is a need to add a delay :( also you cannot debug or do something else because you lose the focus :(

//open upload window upload.click();

//put path to your image in a clipboard
StringSelection ss = new StringSelection(file.getAbsoluteFile());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);

//imitate mouse events like ENTER, CTRL+C, CTRL+V
Robot robot = new Robot();
robot.delay(250);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(50);
robot.keyRelease(KeyEvent.VK_ENTER);

Youtube - How to force 480p video quality in embed link / <iframe>

You can use the fmt= parameter and fill the value based on the following table :

http://en.wikipedia.org/wiki/YouTube#Quality_and_codecs

Ex : your URL would become :

http://www.youtube.com/embed/FqRgAs0SOpU?fmt=35

PHP: convert spaces in string into %20?

I believe that, if you need to use the %20 variant, you could perhaps use rawurlencode().

Difference between VARCHAR and TEXT in MySQL

There is an important detail that has been omitted in the answer above.

MySQL imposes a limit of 65,535 bytes for the max size of each row. The size of a VARCHAR column is counted towards the maximum row size, while TEXT columns are assumed to be storing their data by reference so they only need 9-12 bytes. That means even if the "theoretical" max size of your VARCHAR field is 65,535 characters you won't be able to achieve that if you have more than one column in your table.

Also note that the actual number of bytes required by a VARCHAR field is dependent on the encoding of the column (and the content). MySQL counts the maximum possible bytes used toward the max row size, so if you use a multibyte encoding like utf8mb4 (which you almost certainly should) it will use up even more of your maximum row size.

Correction: Regardless of how MySQL computes the max row size, whether or not the VARCHAR/TEXT field data is ACTUALLY stored in the row or stored by reference depends on your underlying storage engine. For InnoDB the row format affects this behavior. (Thanks Bill-Karwin)

Reasons to use TEXT:

  • If you want to store a paragraph or more of text
  • If you don't need to index the column
  • If you have reached the row size limit for your table

Reasons to use VARCHAR:

  • If you want to store a few words or a sentence
  • If you want to index the (entire) column
  • If you want to use the column with foreign-key constraints

Given final block not properly padded

I met this issue due to operation system, simple to different platform about JRE implementation.

new SecureRandom(key.getBytes())

will get the same value in Windows, while it's different in Linux. So in Linux need to be changed to

SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes());
kgen.init(128, secureRandom);

"SHA1PRNG" is the algorithm used, you can refer here for more info about algorithms.

Create a simple 10 second countdown

JavaScript has built in to it a function called setInterval, which takes two arguments - a function, callback and an integer, timeout. When called, setInterval will call the function you give it every timeout milliseconds.

For example, if you wanted to make an alert window every 500 milliseconds, you could do something like this.

function makeAlert(){ 
    alert("Popup window!");
};

setInterval(makeAlert, 500);

However, you don't have to name your function or declare it separately. Instead, you could define your function inline, like this.

setInterval(function(){ alert("Popup window!"); }, 500);

Once setInterval is called, it will run until you call clearInterval on the return value. This means that the previous example would just run infinitely. We can put all of this information together to make a progress bar that will update every second and after 10 seconds, stop updating.

_x000D_
_x000D_
var timeleft = 10;_x000D_
var downloadTimer = setInterval(function(){_x000D_
  if(timeleft <= 0){_x000D_
    clearInterval(downloadTimer);_x000D_
  }_x000D_
  document.getElementById("progressBar").value = 10 - timeleft;_x000D_
  timeleft -= 1;_x000D_
}, 1000);
_x000D_
<progress value="0" max="10" id="progressBar"></progress>
_x000D_
_x000D_
_x000D_

Alternatively, this will create a text countdown.

_x000D_
_x000D_
var timeleft = 10;_x000D_
var downloadTimer = setInterval(function(){_x000D_
  if(timeleft <= 0){_x000D_
    clearInterval(downloadTimer);_x000D_
    document.getElementById("countdown").innerHTML = "Finished";_x000D_
  } else {_x000D_
    document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";_x000D_
  }_x000D_
  timeleft -= 1;_x000D_
}, 1000);
_x000D_
<div id="countdown"></div>
_x000D_
_x000D_
_x000D_

Postgresql - unable to drop database because of some auto connections to DB

In terminal try this command:

ps -ef | grep postgres

you will see like:

501 1445 3645 0 12:05AM 0:00.03 postgres: sasha dbname [local] idle

The third number (3645) is PID.

You can delete this

sudo kill -9 3645

And after that start your PostgreSQL connection.

Start manually:

pg_ctl -D /usr/local/var/postgres start