Programs & Examples On #Jabaco

Jabaco empowers the VB6 programmer to write for the Java platform.

In Angular, I need to search objects in an array

Saw this thread but I wanted to search for IDs that did not match my search. Code to do that:

found = $filter('filter')($scope.fish, {id: '!fish_id'}, false);

How to add image in Flutter

their is no need to create asset directory and under it images directory and then you put image. Better is to just create Images directory inside your project where pubspec.yaml exist and put images inside it and access that images just like as shown in tutorial/documention

assets: - images/lake.jpg // inside pubspec.yaml

Adding and removing style attribute from div with jquery

The easy way to handle this (and best HTML solution to boot) is to set up classes that have the styles you want to use. Then it's a simple matter of using addClass() and removeClass(), or even toggleClass().

$('#voltaic_holder').addClass('shiny').removeClass('dull');

or even

$('#voltaic_holder').toggleClass('shiny dull');

How to vertically center a "div" element for all browsers using CSS?

Declare this Mixin:

@mixin vertical-align($position: relative) {
  position: $position;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}

Then include it in your element:

.element{
    @include vertical-align();
}

What are the "standard unambiguous date" formats for string-to-date conversion in R?

As a complement to @JoshuaUlrich answer, here is the definition of function as.Date.character:

as.Date.character
function (x, format = "", ...) 
{
    charToDate <- function(x) {
        xx <- x[1L]
        if (is.na(xx)) {
            j <- 1L
            while (is.na(xx) && (j <- j + 1L) <= length(x)) xx <- x[j]
            if (is.na(xx)) 
                f <- "%Y-%m-%d"
        }
        if (is.na(xx) || !is.na(strptime(xx, f <- "%Y-%m-%d", 
            tz = "GMT")) || !is.na(strptime(xx, f <- "%Y/%m/%d", 
            tz = "GMT"))) 
            return(strptime(x, f))
        stop("character string is not in a standard unambiguous format")
    }
    res <- if (missing(format)) 
        charToDate(x)
    else strptime(x, format, tz = "GMT")
    as.Date(res)
}
<bytecode: 0x265b0ec>
<environment: namespace:base>

So basically if both strptime(x, format="%Y-%m-%d") and strptime(x, format="%Y/%m/%d") throws an NA it is considered ambiguous and if not unambiguous.

How to add new contacts in android

These examples are fine, I wanted to point out that you can achieve the same result using an Intent. The intent opens the Contacts app with the fields you provide already filled in.

It's up to the user to save the newly created contact.

You can read about it here: https://developer.android.com/training/contacts-provider/modify-data.html

Intent contactIntent = new Intent(ContactsContract.Intents.Insert.ACTION);
contactIntent.setType(ContactsContract.RawContacts.CONTENT_TYPE);

contactIntent
        .putExtra(ContactsContract.Intents.Insert.NAME, "Contact Name")
        .putExtra(ContactsContract.Intents.Insert.PHONE, "5555555555");

startActivityForResult(contactIntent, 1);

startActivityForResult() gives you the opportunity to see the result.

I've noticed the resultCode works on >5.0 devices,

but I have an older Samsung (<5) that always returns RESULT_CANCELLED (0).

Which I understand is the default return if an activity doesn't expect to return anything.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (requestCode == 1)
    {
        if (resultCode == Activity.RESULT_OK) {
            Toast.makeText(this, "Added Contact", Toast.LENGTH_SHORT).show();
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            Toast.makeText(this, "Cancelled Added Contact", Toast.LENGTH_SHORT).show();
        }
    }
}

Access Form - Syntax error (missing operator) in query expression

I had this same problem. As Dedren says, the problem is not the query, but the form object's control source. Put [] around each objects Control Source. eg: Contol Source: [Product number], Control Source: Salesperson.[Salesperson number], etc.

Makita recomends going to the original table that you are referencing in your query and rename the field so that there are no spaces eg: SalesPersonNumber, ProductNumber, etc. This will solve many future problems as well. Best of Luck!

How to show all of columns name on pandas dataframe?

To obtain all the column names of a DataFrame, df_data in this example, you just need to use the command df_data.columns.values. This will show you a list with all the Column names of your Dataframe

Code:

df_data=pd.read_csv('../input/data.csv')
print(df_data.columns.values)

Output:

['PassengerId' 'Survived' 'Pclass' 'Name' 'Sex' 'Age' 'SibSp' 'Parch' 'Ticket' 'Fare' 'Cabin' 'Embarked']

Entity Framework 6 Code first Default value

Set the default value for the column in table in MSSQL Server, and in class code add attribute, like this:

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]

for the same property.

MySQL Multiple Joins in one query?

Just add another join:

SELECT dashboard_data.headline,
       dashboard_data.message,
       dashboard_messages.image_id,
       images.filename 
FROM dashboard_data 
    INNER JOIN dashboard_messages
            ON dashboard_message_id = dashboard_messages.id 
    INNER JOIN images
            ON dashboard_messages.image_id = images.image_id

How to check if another instance of my shell script is running

pidof wasn't working for me so I searched some more and came across pgrep

for pid in $(pgrep -f my_script.sh); do
    if [ $pid != $$ ]; then
        echo "[$(date)] : my_script.sh : Process is already running with PID $pid"
        exit 1
    else
      echo "Running with PID $pid"
    fi  
done

Taken in part from answers above and https://askubuntu.com/a/803106/802276

Transposing a 2D-array in JavaScript

I didn't find an answer that satisfied me, so I wrote one myself, I think it is easy to understand and implement and suitable for all situations.

    transposeArray: function (mat) {
        let newMat = [];
        for (let j = 0; j < mat[0].length; j++) {  // j are columns
            let temp = [];
            for (let i = 0; i < mat.length; i++) {  // i are rows
                temp.push(mat[i][j]);  // so temp will be the j(th) column in mat
            }
            newMat.push(temp);  // then just push every column in newMat
        }
        return newMat;
    }

Django development IDE

I've also had good results with Eclipse and Pydev. Although I still require a shell opened to the project directory to run manage.py commands. I've also been using it with the Bazaar plugin for revision control and syncing code with the server.

Absolute Positioning & Text Alignment

The div doesn't take up all the available horizontal space when absolutely positioned. Explicitly setting the width to 100% will solve the problem:

HTML

<div id="my-div">I want to be centered</div>?

CSS

#my-div {
   position: absolute;
   bottom: 15px;
   text-align: center;
   width: 100%;
}

?

Initializing entire 2D array with one value

int array[ROW][COLUMN]={1};

This initialises only the first element to 1. Everything else gets a 0.

In the first instance, you're doing the same - initialising the first element to 0, and the rest defaults to 0.

The reason is straightforward: for an array, the compiler will initialise every value you don't specify with 0.

With a char array you could use memset to set every byte, but this will not generally work with an int array (though it's fine for 0).

A general for loop will do this quickly:

for (int i = 0; i < ROW; i++)
  for (int j = 0; j < COLUMN; j++)
    array[i][j] = 1;

Or possibly quicker (depending on the compiler)

for (int i = 0; i < ROW*COLUMN; i++)
  *((int*)a + i) = 1;

How to provide password to a command that prompts for one in bash?

Secure commands will not allow this, and rightly so, I'm afraid - it's a security hole you could drive a truck through.

If your command does not allow it using input redirection, or a command-line parameter, or a configuration file, then you're going to have to resort to serious trickery.

Some applications will actually open up /dev/tty to ensure you will have a hard time defeating security. You can get around them by temporarily taking over /dev/tty (creating your own as a pipe, for example) but this requires serious privileges and even it can be defeated.

Difference between Static methods and Instance methods

Methods and variables that are not declared as static are known as instance methods and instance variables. To refer to instance methods and variables, you must instantiate the class first means you should create an object of that class first.For static you don't need to instantiate the class u can access the methods and variables with the class name using period sign which is in (.)

for example:

Person.staticMethod();           //accessing static method.

for non-static method you must instantiate the class.

Person person1 = new Person();   //instantiating
person1.nonStaticMethod();       //accessing non-static method.

MySQL Workbench not displaying query results

The result set wasn't showing for me either. I was able to make it appear by hiding the output area and running a simple select statement. Then I "show"ed the output area again and had what I was looking for -- both the result set and the output area

warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777

I had the same error here MacOSX 10.11 - it seems ruby checks to see if any directory (including the parents) in the path are world writable. In my case there wasn't a /usr/local/bin present as nothing had created it.

Run this command in your terminal.Try this sudo chmod 775 /usr/local After this if you have any password on your mac , then you have to enter the password . Now this issue will be fix.

Strip spaces/tabs/newlines - python

How about a one-liner using a list comprehension within join?

>>> foobar = "aaa bbb\t\t\tccc\nddd"
>>> print(foobar)
aaa bbb                 ccc
ddd

>>> print(''.join([c for c in foobar if c not in [' ', '\t', '\n']]))
aaabbbcccddd

Change value of input placeholder via model?

You can bind with a variable in the controller:

<input type="text" ng-model="inputText" placeholder="{{somePlaceholder}}" />

In the controller:

$scope.somePlaceholder = 'abc';

How to add leading zeros for for-loop in shell?

Use printf command to have 0 padding:

printf "%02d\n" $num

Your for loop will be like this:

for (( num=1; num<=5; num++ )); do printf "%02d\n" $num; done
01
02
03
04
05

How can you remove all documents from a collection with Mongoose?

MongoDB shell version v4.2.6
Node v14.2.0

Assuming you have a Tour Model: tourModel.js

const mongoose = require('mongoose');

const tourSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'A tour must have a name'],
    unique: true,
    trim: true,
  },
  createdAt: {
    type: Date,
    default: Date.now(),
  },
});
const Tour = mongoose.model('Tour', tourSchema);

module.exports = Tour;

Now you want to delete all tours at once from your MongoDB, I also providing connection code to connect with the remote cluster. I used deleteMany(), if you do not pass any args to deleteMany(), then it will delete all the documents in Tour collection.

const mongoose = require('mongoose');
const Tour = require('./../../models/tourModel');
const conStr = 'mongodb+srv://lord:<PASSWORD>@cluster0-eeev8.mongodb.net/tour-guide?retryWrites=true&w=majority';
const DB = conStr.replace('<PASSWORD>','ADUSsaZEKESKZX');
mongoose.connect(DB, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
    useUnifiedTopology: true,
  })
  .then((con) => {
    console.log(`DB connection successful ${con.path}`);
  });

const deleteAllData = async () => {
  try {
    await Tour.deleteMany();
    console.log('All Data successfully deleted');
  } catch (err) {
    console.log(err);
  }
};

Remove all special characters except space from a string using JavaScript

Whose special characters you want to remove from a string, prepare a list of them and then user javascript replace function to remove all special characters.

var str = 'abc'de#;:sfjkewr47239847duifyh';
alert(str.replace("'","").replace("#","").replace(";","").replace(":",""));

or you can run loop for a whole string and compare single single character with the ASCII code and regenerate a new string.

How do you force a CIFS connection to unmount

Try umount -f /mnt/share. Works OK with NFS, never tried with cifs.

Also, take a look at autofs, it will mount the share only when accessed, and will unmount it afterworlds.

There is a good tutorial at www.howtoforge.net

Is log(n!) = T(n·log(n))?

http://en.wikipedia.org/wiki/Stirling%27s_approximation Stirling approximation might help you. It is really helpful in dealing with problems on factorials related to huge numbers of the order of 10^10 and above.

enter image description here

What is the main difference between PATCH and PUT request?

Put and Patch method are similar . But in rails it has different metod If we want to update/replace whole record then we have to use Put method. If we want to update particular record use Patch method.

How to start an application using android ADB tools?

adb shell am start -n '<appPackageName>/.<appActitivityName>

Ex:

adb shell am start -n 'com.android.settings/.wifi.WifiStatusTest'

You can use APK-INFO application to know the list of App Activities with respect to each App Package

Changing width property of a :before css selector using JQuery

I don't think there's a jQuery-way to directly access the pseudoclass' rules, but you could always append a new style element to the document's head like:

$('head').append('<style>.column:before{width:800px !important;}</style>');

See a live demo here

I also remember having seen a plugin that tackles this issue once but I couldn't find it on first googling unfortunately.

Oracle get previous day records

You can remove the time part of a date by using TRUNC.

select field,datetime_field 
  from database
 where datetime_field >= trunc(sysdate-1,'DD');

That query will give you all rows with dates starting from yesterday. Note the second argument to trunc(). You can use this to truncate any part of the date.

If your datetime_fied contains '2011-05-04 08:23:54', the following date will be returned

trunc(datetime_field, 'HH24') => 2011-05-04 08:00:00
trunc(datetime_field, 'DD')   => 2011-05-04 00:00:00
trunc(datetime_field, 'MM')   => 2011-05-01 00:00:00
trunc(datetime_field, 'YYYY') => 2011-00-01 00:00:00

Using Java 8's Optional with Stream::flatMap

What about that?

private static List<String> extractString(List<Optional<String>> list) {
    List<String> result = new ArrayList<>();
    list.forEach(element -> element.ifPresent(result::add));
    return result;
}

https://stackoverflow.com/a/58281000/3477539

Difference between Git and GitHub

What is Git:

"Git is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency"

Git is a distributed peer-peer version control system. Each node in the network is a peer, storing entire repositories which can also act as a multi-node distributed back-ups. There is no specific concept of a central server although nodes can be head-less or 'bare', taking on a role similar to the central server in centralised version control systems.

What is GitHub:

"GitHub is a web-based Git repository hosting service, which offers all of the distributed revision control and source code management (SCM) functionality of Git as well as adding its own features."

Github provides access control and several collaboration features such as wikis, task management, and bug tracking and feature requests for every project.

You do not need GitHub to use Git.

GitHub (and any other local, remote or hosted system) can all be peers in the same distributed versioned repositories within a single project.

Github allows you to:

  • Share your repositories with others.
  • Access other user's repositories.
  • Store remote copies of your repositories (github servers) as backup of your local copies.

Hidden features of Python

dict's constructor accepts keyword arguments:

>>> dict(foo=1, bar=2)
{'foo': 1, 'bar': 2}

Date constructor returns NaN in IE, but works in Firefox and Chrome

The Date constructor accepts any value. If the primitive [[value]] of the argument is number, then the Date that is created has that value. If primitive [[value]] is String, then the specification only guarantees that the Date constructor and the parse method are capable of parsing the result of Date.prototype.toString and Date.prototype.toUTCString()

A reliable way to set a Date is to construct one and use the setFullYear and setTime methods.

An example of that appears here: http://jibbering.com/faq/#parseDate

ECMA-262 r3 does not define any date formats. Passing string values to the Date constructor or Date.parse has implementation-dependent outcome. It is best avoided.


Edit: The entry from comp.lang.javascript FAQ is: An Extended ISO 8601 local date format YYYY-MM-DD can be parsed to a Date with the following:-

/**Parses string formatted as YYYY-MM-DD to a Date object.
 * If the supplied string does not match the format, an 
 * invalid Date (value NaN) is returned.
 * @param {string} dateStringInRange format YYYY-MM-DD, with year in
 * range of 0000-9999, inclusive.
 * @return {Date} Date object representing the string.
 */

  function parseISO8601(dateStringInRange) {
    var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
        date = new Date(NaN), month,
        parts = isoExp.exec(dateStringInRange);

    if(parts) {
      month = +parts[2];
      date.setFullYear(parts[1], month - 1, parts[3]);
      if(month != date.getMonth() + 1) {
        date.setTime(NaN);
      }
    }
    return date;
  }

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6

In my case, jvmTarget was already set in build.gradle file as below.

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

But my issue was still there. Finally, it gets resolved after Changing Target JVM version from 1.6 to 1.8 in Preferences > Other Settings > Kotlin Compiler > Target JVM version. see attached picture,

enter image description here

What is VanillaJS?

VanillaJS === JavaScript i.e.VanillaJS is native JavaScript

Why, Vanilla says it all!!!

Computer software, and sometimes also other computing-related systems like computer hardware or algorithms, are called vanilla when not customized from their original form, meaning that they are used without any customization or updates applied to them (Refer this article). So Vanilla often refers to pure or plain.

In the English language Vanilla has a similar meaning, In information technology, vanilla (pronounced vah-NIHL-uh ) is an adjective meaning plain or basic. Or having no special or extra features, ordinary or standard.

So why name it VanillaJS? As the accepted answer says some bosses want to work with a framework (because it's more organized and flexible and do all the things we want??) but simply JavaScript will do the job. Yet you need to add a framework somewhere. Use VanillaJS...

Is it a Joke? YES

Want some fun? Where can you find it, http://vanilla-js.com/ Download and see for yourself!!! It's 0 bytes uncompressed, 25 bytes gzipped :D

Found this pun on internet regarding JS frameworks (Not to condemn the existing JS frameworks though, they'll make life really easy :)), enter image description here

Also refer,

How to detect if a string contains at least a number?

Use this:

SELECT * FROM Table WHERE Column LIKE '%[0-9]%'

MSDN - LIKE (Transact-SQL)

What is "not assignable to parameter of type never" error in typescript?

Remove "strictNullChecks": true from "compilerOptions" or set it to false in the tsconfig.json file of your Ng app. These errors will go away like anything and your app would compile successfully.

Disclaimer: This is just a workaround. This error appears only when the null checks are not handled properly which in any case is not a good way to get things done.

jquery $(this).id return Undefined

Another option (just so you've seen it):

$(function () {
    $(".inputs").click(function (e) {
         alert(e.target.id);
    });
});

HTH.

How to add trendline in python matplotlib dot (scatter) graphs?

as explained here

With help from numpy one can calculate for example a linear fitting.

# plot the data itself
pylab.plot(x,y,'o')

# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])

How can I dynamically add a directive in AngularJS?

The accepted answer by Josh David Miller works great if you are trying to dynamically add a directive that uses an inline template. However if your directive takes advantage of templateUrl his answer will not work. Here is what worked for me:

.directive('helperModal', [, "$compile", "$timeout", function ($compile, $timeout) {
    return {
        restrict: 'E',
        replace: true,
        scope: {}, 
        templateUrl: "app/views/modal.html",
        link: function (scope, element, attrs) {
            scope.modalTitle = attrs.modaltitle;
            scope.modalContentDirective = attrs.modalcontentdirective;
        },
        controller: function ($scope, $element, $attrs) {
            if ($attrs.modalcontentdirective != undefined && $attrs.modalcontentdirective != '') {
                var el = $compile($attrs.modalcontentdirective)($scope);
                $timeout(function () {
                    $scope.$digest();
                    $element.find('.modal-body').append(el);
                }, 0);
            }
        }
    }
}]);

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

I've found this to work very well. It uses the .range property of the .autofilter object, which seems to be a rather obscure, but very handy, feature:

Sub copyfiltered()
    ' Copies the visible columns
    ' and the selected rows in an autofilter
    '
    ' Assumes that the filter was previously applied
    '
    Dim wsIn As Worksheet
    Dim wsOut As Worksheet

    Set wsIn = Worksheets("Sheet1")
    Set wsOut = Worksheets("Sheet2")

    ' Hide the columns you don't want to copy
    wsIn.Range("B:B,D:D").EntireColumn.Hidden = True

    'Copy the filtered rows from wsIn and and paste in wsOut
    wsIn.AutoFilter.Range.Copy Destination:=wsOut.Range("A1")
End Sub

gcloud command not found - while installing Google Cloud SDK

$ sudo su
$ /opt/google-appengine-sdk/bin/gcloud components update
$ su <yourusername>

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

I know replaceAll method is much easier but I wanted to post this as well.

public static String removeExtraSpace(String input) {
    input= input.trim();
    ArrayList <String> x= new ArrayList<>(Arrays.asList(input.split("")));
    for(int i=0; i<x.size()-1;i++) {
        if(x.get(i).equals(" ") && x.get(i+1).equals(" ")) { 
            x.remove(i); 
            i--; 
        }
    }
    String word="";
    for(String each: x) 
        word+=each;
    return word;
}

launch sms application with an intent

Intent eventIntentMessage =getPackageManager()
 .getLaunchIntentForPackage(Telephony.Sms.getDefaultSmsPackage(getApplicationContext));
startActivity(eventIntentMessage);

Getting GET "?" variable in laravel

I haven't tested on other Laravel versions but on 5.3-5.8 you reference the query parameter as if it were a member of the Request class.

1. Url

http://example.com/path?page=2

2. In a route callback or controller action using magic method Request::__get()

Route::get('/path', function(Request $request){
 dd($request->page);
}); 

//or in your controller
public function foo(Request $request){
 dd($request->page);
}

//NOTE: If you are wondering where the request instance is coming from, Laravel automatically injects the request instance from the IOC container
//output
"2"

3. Default values

We can also pass in a default value which is returned if a parameter doesn't exist. It's much cleaner than a ternary expression that you'd normally use with the request globals

   //wrong way to do it in Laravel
   $page = isset($_POST['page']) ? $_POST['page'] : 1; 

   //do this instead
   $request->get('page', 1);

   //returns page 1 if there is no page
   //NOTE: This behaves like $_REQUEST array. It looks in both the
   //request body and the query string
   $request->input('page', 1);

4. Using request function

$page = request('page', 1);
//returns page 1 if there is no page parameter in the query  string
//it is the equivalent of
$page = 1; 
if(!empty($_GET['page'])
   $page = $_GET['page'];

The default parameter is optional therefore one can omit it

5. Using Request::query()

While the input method retrieves values from entire request payload (including the query string), the query method will only retrieve values from the query string

//this is the equivalent of retrieving the parameter
//from the $_GET global array
$page = $request->query('page');

//with a default
$page = $request->query('page', 1);

6. Using the Request facade

$page = Request::get('page');

//with a default value
$page = Request::get('page', 1);

You can read more in the official documentation https://laravel.com/docs/5.8/requests

What is the difference between float and double?

Huge difference.

As the name implies, a double has 2x the precision of float[1]. In general a double has 15 decimal digits of precision, while float has 7.

Here's how the number of digits are calculated:

double has 52 mantissa bits + 1 hidden bit: log(253)÷log(10) = 15.95 digits

float has 23 mantissa bits + 1 hidden bit: log(224)÷log(10) = 7.22 digits

This precision loss could lead to greater truncation errors being accumulated when repeated calculations are done, e.g.

float a = 1.f / 81;
float b = 0;
for (int i = 0; i < 729; ++ i)
    b += a;
printf("%.7g\n", b); // prints 9.000023

while

double a = 1.0 / 81;
double b = 0;
for (int i = 0; i < 729; ++ i)
    b += a;
printf("%.15g\n", b); // prints 8.99999999999996

Also, the maximum value of float is about 3e38, but double is about 1.7e308, so using float can hit "infinity" (i.e. a special floating-point number) much more easily than double for something simple, e.g. computing the factorial of 60.

During testing, maybe a few test cases contain these huge numbers, which may cause your programs to fail if you use floats.


Of course, sometimes, even double isn't accurate enough, hence we sometimes have long double[1] (the above example gives 9.000000000000000066 on Mac), but all floating point types suffer from round-off errors, so if precision is very important (e.g. money processing) you should use int or a fraction class.


Furthermore, don't use += to sum lots of floating point numbers, as the errors accumulate quickly. If you're using Python, use fsum. Otherwise, try to implement the Kahan summation algorithm.


[1]: The C and C++ standards do not specify the representation of float, double and long double. It is possible that all three are implemented as IEEE double-precision. Nevertheless, for most architectures (gcc, MSVC; x86, x64, ARM) float is indeed a IEEE single-precision floating point number (binary32), and double is a IEEE double-precision floating point number (binary64).

How to get domain root url in Laravel 4?

use directly where you want controller or web.php

Request::getHost();

HTML input time in 24 format

In my case, it is taking time in AM and PM but sending data in 00-24 hours format to the server on form submit. and when use that DB data in its value then it will automatically select the appropriate AM or PM to edit form value.

Get name of current script in Python

import sys
print(sys.argv[0])

This will print foo.py for python foo.py, dir/foo.py for python dir/foo.py, etc. It's the first argument to python. (Note that after py2exe it would be foo.exe.)

Batch file to copy directories recursively

You may write a recursive algorithm in Batch that gives you exact control of what you do in every nested subdirectory:

@echo off
call :treeProcess
goto :eof

:treeProcess
rem Do whatever you want here over the files of this subdir, for example:
copy *.* C:\dest\dir
for /D %%d in (*) do (
    cd %%d
    call :treeProcess
    cd ..
)
exit /b

Windows Batch File Looping Through Directories to Process Files?

How to hide elements without having them take space on the page?

To use display:none is a good option just to removing an element BUT it will be also removed for screenreaders. There are also discussions if it effects SEO. There's a good, short article on that topic on A List Apart

If you really just want hide and not remove an element, better use:

div {
  position: absolute; 
  left: -999em;
}

Like this it can be also read by screen readers.

The only disadvantage of this method is, that this DIV is actually rendered and it might effect the performance, especially on mobile phones.

Installing a specific version of angular with angular cli

Edit #2 ( 7/2/2017)

If you install the angular cli right now, you'd probably have the new name of angular cli which is @angular/cli, so you need to uninstall it using

npm uninstall -g @angular/cli

and follow the code above. I'm still getting upvotes for this so I updated my answer for those who want to use the older version for some reasons.


Edit #1

If you really want to create a new project with previous version of Angular using the cli, try to downgrade the angular-cli before the final release. Something like:

npm uninstall -g angular-cli
npm cache clean
npm install -g [email protected]

Initial

You can change the version of the angular in the package.json . I'm guessing you want to use older version of angular but I suggest you use the latest version. Using:

ng new app-name

will always use the latest version of angular.

How to test if list element exists?

Here is a performance comparison of the proposed methods in other answers.

> foo <- sapply(letters, function(x){runif(5)}, simplify = FALSE)
> microbenchmark::microbenchmark('k' %in% names(foo), 
                                 is.null(foo[['k']]), 
                                 exists('k', where = foo))
Unit: nanoseconds
                     expr  min   lq    mean median   uq   max neval cld
      "k" %in% names(foo)  467  933 1064.31    934  934 10730   100  a 
      is.null(foo[["k"]])    0    0  168.50      1  467  3266   100  a 
 exists("k", where = foo) 6532 6998 7940.78   7232 7465 56917   100   b

If you are planing to use the list as a fast dictionary accessed many times, then the is.null approach might be the only viable option. I assume it is O(1), while the %in% approach is O(n)?

Assert that a method was called in a Python unit test

You can mock out aw.Clear, either manually or using a testing framework like pymox. Manually, you'd do it using something like this:

class MyTest(TestCase):
  def testClear():
    old_clear = aw.Clear
    clear_calls = 0
    aw.Clear = lambda: clear_calls += 1
    aps.Request('nv2', aw)
    assert clear_calls == 1
    aw.Clear = old_clear

Using pymox, you'd do it like this:

class MyTest(mox.MoxTestBase):
  def testClear():
    aw = self.m.CreateMock(aps.Request)
    aw.Clear()
    self.mox.ReplayAll()
    aps.Request('nv2', aw)

Programmatically extract contents of InstallShield setup.exe

There's no supported way to do this, but won't you have to examine the files related to each installer to figure out how to actually install them after extracting them? Assuming you can spend the time to figure out which command-line applies, here are some candidate parameters that normally allow you to extract an installation.

MSI Based (may not result in a usable image for an InstallScript MSI installation):

  • setup.exe /a /s /v"/qn TARGETDIR=\"choose-a-location\""

    or, to also extract prerequisites (for versions where it works),

  • setup.exe /a"choose-another-location" /s /v"/qn TARGETDIR=\"choose-a-location\""

InstallScript based:

  • setup.exe /s /extract_all

Suite based (may not be obvious how to install the resulting files):

  • setup.exe /silent /stage_only ISRootStagePath="choose-a-location"

c++ integer->std::string conversion. Simple function?

Not really, in the standard. Some implementations have a nonstandard itoa() function, and you could look up Boost's lexical_cast, but if you stick to the standard it's pretty much a choice between stringstream and sprintf() (snprintf() if you've got it).

S3 - Access-Control-Allow-Origin Header

The accepted answer works, but it seems that if you go to the resource directly, then there are no cross-origin headers. If you are using cloudfront, this will cause cloudfront to cache the version without headers.When you then go to a different url that loads this resource, you will get this cross-origin issue.

How to access the contents of a vector from a pointer to the vector in C++?

vector<int> v;
v.push_back(906);
vector<int> * p = &v;
cout << (*p)[0] << endl;

How to fix homebrew permissions?

To resolve errors for Brew permissions on folder run

brew prune

This will resolve the issues & we don't have to chown any directories.

Are PHP Variables passed by value or by reference?

Objects are passed by reference in PHP 5 and by value in PHP 4. Variables are passed by value by default!

Read here: http://www.webeks.net/programming/php/ampersand-operator-used-for-assigning-reference.html

Excel VBA Run Time Error '424' object required

Private Sub CommandButton1_Click()

    Workbooks("Textfile_Receiving").Sheets("menu").Range("g1").Value = PROV.Text
    Workbooks("Textfile_Receiving").Sheets("menu").Range("g2").Value = MUN.Text
    Workbooks("Textfile_Receiving").Sheets("menu").Range("g3").Value = CAT.Text
    Workbooks("Textfile_Receiving").Sheets("menu").Range("g4").Value = Label5.Caption

    Me.Hide

    Run "filename"

End Sub

Private Sub MUN_Change()
    Dim r As Integer
    r = 2

    While Range("m" & CStr(r)).Value <> ""
        If Range("m" & CStr(r)).Value = MUN.Text Then
        Label5.Caption = Range("n" & CStr(r)).Value
        End If
        r = r + 1
    Wend

End Sub

Private Sub PROV_Change()
    If PROV.Text = "LAGUNA" Then
        MUN.Text = ""
        MUN.RowSource = "Menu!M26:M56"
    ElseIf PROV.Text = "CAVITE" Then
        MUN.Text = ""
        MUN.RowSource = "Menu!M2:M25"
    ElseIf PROV.Text = "QUEZON" Then
        MUN.Text = ""
        MUN.RowSource = "Menu!M57:M97"
    End If
End Sub

How to add one day to a date?

As mentioned in the Top answer, since java 8 it is possible to do:

Date dt = new Date();
LocalDateTime.from(dt.toInstant()).plusDays(1);

but this can sometimes lead to an DateTimeException like this:

java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: 2014-11-29T03:20:10.800Z of type java.time.Instant

It is possible to avoid this Exception by simply passing the time zone:

LocalDateTime.from(dt.toInstant().atZone(ZoneId.of("UTC"))).plusDays(1);

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

SQL not a single-group group function

If you want downloads number for each customer, use:

select ssn
     , sum(time)
  from downloads
 group by ssn

If you want just one record -- for a customer with highest number of downloads -- use:

select *
  from (
        select ssn
             , sum(time)
          from downloads
         group by ssn
         order by sum(time) desc
       )
 where rownum = 1

However if you want to see all customers with the same number of downloads, which share the highest position, use:

select *
  from (
        select ssn
             , sum(time)
             , dense_rank() over (order by sum(time) desc) r
          from downloads
         group by ssn
       )
 where r = 1

How to check if there exists a process with a given pid in Python?

mluebke code is not 100% correct; kill() can also raise EPERM (access denied) in which case that obviously means a process exists. This is supposed to work:

(edited as per Jason R. Coombs comments)

import errno
import os

def pid_exists(pid):
    """Check whether pid exists in the current process table.
    UNIX only.
    """
    if pid < 0:
        return False
    if pid == 0:
        # According to "man 2 kill" PID 0 refers to every process
        # in the process group of the calling process.
        # On certain systems 0 is a valid PID but we have no way
        # to know that in a portable fashion.
        raise ValueError('invalid PID 0')
    try:
        os.kill(pid, 0)
    except OSError as err:
        if err.errno == errno.ESRCH:
            # ESRCH == No such process
            return False
        elif err.errno == errno.EPERM:
            # EPERM clearly means there's a process to deny access to
            return True
        else:
            # According to "man 2 kill" possible error values are
            # (EINVAL, EPERM, ESRCH)
            raise
    else:
        return True

You can't do this on Windows unless you use pywin32, ctypes or a C extension module. If you're OK with depending from an external lib you can use psutil:

>>> import psutil
>>> psutil.pid_exists(2353)
True

Can VS Code run on Android?

The accepted answer is correct as asked, below answers the opposite question of developing Android on VS Code.

Extensions

Ultimately you can automate building and running your app on a device emulator by adding the function below to your $PATH and running runDebugApp <module> <start activity> from the integrated terminal:

# run android app
# usage runDebugApp [module] [fully qualified start activity com.package/com.package.MainActivity]
function runDebugApp(){
  ./gradlew -offline :"$1":installDebug && adb shell am start "$2" && adb logcat -d > logcat.log
}

How to style the parent element when hovering a child element?

This is extremely easy to do in Sass! Don't delve into JavaScript for this. The & selector in sass does exactly this.

http://thesassway.com/intermediate/referencing-parent-selectors-using-ampersand

base 64 encode and decode a string in angular (2+)

Use btoa() for encode and atob() for decode

text_val:any="your encoding text";

Encoded Text: console.log(btoa(this.text_val)); //eW91ciBlbmNvZGluZyB0ZXh0

Decoded Text: console.log(atob("eW91ciBlbmNvZGluZyB0ZXh0")); //your encoding text

Modifying the "Path to executable" of a windows service

There is also this approach seen on SuperUser which uses the sc command line instead of modifying the registry:

sc config <service name> binPath= <binary path>

Note: the space after binPath= is important. You can also query the current configuration using:

sc qc <service name>

This displays output similar to:

[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: ServiceName

    TYPE               : 10  WIN32_OWN_PROCESS
    START_TYPE         : 2   AUTO_START
    ERROR_CONTROL      : 1   NORMAL
    BINARY_PATH_NAME   : C:\Services\ServiceName
    LOAD_ORDER_GROUP   :
    TAG                : 0
    DISPLAY_NAME       : <Display name>
    DEPENDENCIES       :
    SERVICE_START_NAME : user-name@domain-name

how to insert value into DataGridView Cell?

You can access any DGV cell as follows :

dataGridView1.Rows[rowIndex].Cells[columnIndex].Value = value;

But usually it's better to use databinding : you bind the DGV to a data source (DataTable, collection...) through the DataSource property, and only work on the data source itself. The DataGridView will automatically reflect the changes, and changes made on the DataGridView will be reflected on the data source

Iterate through 2 dimensional array

 //This is The easiest I can Imagine . 
 // You need to just change the order of Columns and rows , Yours is printing columns X rows and the solution is printing them rows X columns 
for(int rows=0;rows<array.length;rows++){
    for(int columns=0;columns <array[rows].length;columns++){
        System.out.print(array[rows][columns] + "\t" );}
    System.out.println();}

How do I write a custom init for a UIView subclass in Swift?

Here is how I do it on iOS 9 in Swift -

import UIKit

class CustomView : UIView {

    init() {
        super.init(frame: UIScreen.mainScreen().bounds);

        //for debug validation
        self.backgroundColor = UIColor.blueColor();
        print("My Custom Init");

        return;
    }

    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"); }
}

Here is a full project with example:

CSS content generation before or after 'input' elements

This is not due to input tags not having any content per-se, but that their content is outside the scope of CSS.

input elements are a special type called replaced elements, these do not support :pseudo selectors like :before and :after.

In CSS, a replaced element is an element whose representation is outside the scope of CSS. These are kind of external objects whose representation is independent of the CSS. Typical replaced elements are <img>, <object>, <video> or form elements like <textarea> and <input>. Some elements, like <audio> or <canvas> are replaced elements only in specific cases. Objects inserted using the CSS content properties are anonymous replaced elements.

Note that this is even referred to in the spec:

This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML).

And more explicitly:

Replaced elements do not have ::before and ::after pseudo-elements

parsing JSONP $http.jsonp() response in angular.js

This should work just fine for you, so long as the function jsonp_callback is visible in the global scope:

function jsonp_callback(data) {
    // returning from async callbacks is (generally) meaningless
    console.log(data.found);
}

var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=jsonp_callback";

$http.jsonp(url);

Full demo: http://jsfiddle.net/mattball/a4Rc2/ (disclaimer: I've never written any AngularJS code before)

Git: How do I list only local branches?

If the leading asterisk is a problem, I pipe the git branch as follows

git branch | awk -F ' +' '! /\(no branch\)/ {print $2}'

This also eliminates the '(no branch)' line that shows up when you have detached head.

How to get screen width and height

Display display = getActivity().getWindowManager().getDefaultDisplay(); 
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
Log.d("Tag", "Getting Width >> " + screenWidth);
Log.d("Tag", "Getting Height >> " + screenHeight);

This worked properly in my application

How to change screen resolution of Raspberry Pi

If you are like me using a TFT that is connected via SPI (e. g. PiTFT 2.8" 320x240) driven by FBTFT in combination with fbcp to utilise hardware accelerated video decoding (using omxplayer) like it is descriped here. You should add the following into the /boot/config.txt to force the output to HDMI and set the resolution to 320x240:

hdmi_force_hotplug=1
hdmi_cvt=320 240 60 1 0 0 0
hdmi_group=2
hdmi_mode=87

CSS strikethrough different color from text?

Single Property solution is:

.className {
    text-decoration: line-through red;
};

Define your color after line through property.

How to combine class and ID in CSS selector?

There's nothing wrong with combining an id and a class on one element, but you shouldn't need to identify it by both for one rule. If you really want to you can do:

#content.sectionA{some rules}

You don't need the div in front of the ID as others have suggested.

In general, CSS rules specific to that element should be set with the ID, and those are going to carry a greater weight than those of just the class. Rules specified by the class would be properties that apply to multiple items that you don't want to change in multiple places anytime you need to adjust.

That boils down to this:

 .sectionA{some general rules here}
 #content{specific rules, and overrides for things in .sectionA}

Make sense?

In which case do you use the JPA @JoinTable annotation?

It lets you handle Many to Many relationship. Example:

Table 1: post

post has following columns
____________________
|  ID     |  DATE   |
|_________|_________|
|         |         |
|_________|_________|

Table 2: user

user has the following columns:

____________________
|     ID  |NAME     |
|_________|_________|
|         |         |
|_________|_________|

Join Table lets you create a mapping using:

@JoinTable(
  name="USER_POST",
  joinColumns=@JoinColumn(name="USER_ID", referencedColumnName="ID"),
  inverseJoinColumns=@JoinColumn(name="POST_ID", referencedColumnName="ID"))

will create a table:

____________________
|  USER_ID| POST_ID |
|_________|_________|
|         |         |
|_________|_________|

About "*.d.ts" in TypeScript

d stands for Declaration Files:

When a TypeScript script gets compiled there is an option to generate a declaration file (with the extension .d.ts) that functions as an interface to the components in the compiled JavaScript. In the process the compiler strips away all function and method bodies and preserves only the signatures of the types that are exported. The resulting declaration file can then be used to describe the exported virtual TypeScript types of a JavaScript library or module when a third-party developer consumes it from TypeScript.

The concept of declaration files is analogous to the concept of header file found in C/C++.

declare module arithmetics {
    add(left: number, right: number): number;
    subtract(left: number, right: number): number;
    multiply(left: number, right: number): number;
    divide(left: number, right: number): number;
}

Type declaration files can be written by hand for existing JavaScript libraries, as has been done for jQuery and Node.js.

Large collections of declaration files for popular JavaScript libraries are hosted on GitHub in DefinitelyTyped and the Typings Registry. A command-line utility called typings is provided to help search and install declaration files from the repositories.

Order by in Inner Join

I found this to be an issue when joining but you might find this blog useful in understanding how Joins work in the back. How Joins Work..

[Edited] @Shree Thank you for pointing that out. On the paragraph of Merge Join. It mentions on how joins work...

Like hash join, merge join consists of two steps. First, both tables of the join are sorted on the join attribute. This can be done with just two passes through each table via an external merge sort. Finally, the result tuples are generated as the next ordered element is pulled from each table and the join attributes are compared

.

How do I remove a comma off the end of a string?

Precede that with:

if(substr($string, -1)==",")

Getting new Twitter API consumer and secret keys

Simply go here: https://dev.twitter.com/apps/new Make sure you have logged in with your Twitter account - then create - even if your just entering random (Test) Content - create your app - afterwards you will receive all the data you require :)

Adding options to a <select> using jQuery?

You can append and set the Value attribute with text:

$("#id").append($('<option></option>').attr("value", '').text(''));
$("#id").append($('<option></option>').attr("value", '4').text('Financial Institutions'));

How to switch activity without animation in Android?

create your own style overriding android:Theme

<style name="noAnimationStyle" parent="android:Theme">
    <item name="android:windowAnimationStyle">@null</item>
</style>

Then use it in manifest like this:

<activity android:name=".MainActivity"
    android:theme="@style/noAnimationStyle">
</activity>

How to get a vCard (.vcf file) into Android contacts from website

Just to let you know: I just tried it using a vCard 2.1 file created according to the vCard 2.1 spec. I found that vCard 2.1, despite being an old version, already covered everything I needed, including a base64-encoded photo and international character sets.

It worked perfectly on my unmodified Android 4.1.1 device (Galaxy S3). It also worked on an old iPhone 3GS (iOS 5, via the Evernote app) and a coworker's unmodified old Android 2.1 device. You only need to set the Content-disposition to attachment as suggested above.

A minor problem was that I triggered the VCF download using a QR code, which I scanned with the Microsoft Tag app. That app told me Android couldn't handle the text/x-vcard media type (or just text/vcard, no matter). Once I opened the link in a Web browser (I tried Chrome and the Android default browser), it worked fine.

How to get local server host and port in Spring Boot?

You can get hostname from spring cloud property in spring-cloud-commons-2.1.0.RC2.jar

environment.getProperty("spring.cloud.client.ip-address");
environment.getProperty("spring.cloud.client.hostname");

spring.factories of spring-cloud-commons-2.1.0.RC2.jar

org.springframework.boot.env.EnvironmentPostProcessor=\
org.springframework.cloud.client.HostInfoEnvironmentPostProcessor

JSON.Net Self referencing loop detected

for asp.net core 3.1.3 this worked for me

services.AddControllers().AddNewtonsoftJson(opt=>{
            opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        });

Where is the Global.asax.cs file?

It don't create normally; you need to add it by yourself.

After adding Global.asax by

  • Right clicking your website -> Add New Item -> Global Application Class -> Add

You need to add a class

  • Right clicking App_Code -> Add New Item -> Class -> name it Global.cs -> Add

Inherit the newly generated by System.Web.HttpApplication and copy all the method created Global.asax to Global.cs and also add an inherit attribute to the Global.asax file.

Your Global.asax will look like this: -

<%@ Application Language="C#" Inherits="Global" %>

Your Global.cs in App_Code will look like this: -

public class Global : System.Web.HttpApplication
{
    public Global()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }
    /// Many other events like begin request...e.t.c, e.t.c
}

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 &

e.g.

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

What is the difference between #include <filename> and #include "filename"?

For #include "" a compiler normally searches the folder of the file which contains that include and then the other folders. For #include <> the compiler does not search the current file's folder.

How to downgrade Xcode to previous version?

When you log in to your developer account, you can find a link at the bottom of the download section for Xcode that says "Looking for an older version of Xcode?". In there you can find download links to older versions of Xcode and other developer tools

List View Filter Android

Add an EditText on top of your listview in its .xml layout file. And in your activity/fragment..

lv = (ListView) findViewById(R.id.list_view);
    inputSearch = (EditText) findViewById(R.id.inputSearch);

// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name,    products);
lv.setAdapter(adapter);       
inputSearch.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        // When user changed the Text
        MainActivity.this.adapter.getFilter().filter(cs);
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }

    @Override
    public void afterTextChanged(Editable arg0) {}
});

The basic here is to add an OnTextChangeListener to your edit text and inside its callback method apply filter to your listview's adapter.

EDIT

To get filter to your custom BaseAdapter you"ll need to implement Filterable interface.

class CustomAdapter extends BaseAdapter implements Filterable {

    public View getView(){
    ...
    }
    public Integer getCount()
    {
    ...
    }

    @Override
    public Filter getFilter() {

        Filter filter = new Filter() {

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {

                arrayListNames = (List<String>) results.values;
                notifyDataSetChanged();
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

                FilterResults results = new FilterResults();
                ArrayList<String> FilteredArrayNames = new ArrayList<String>();

                // perform your search here using the searchConstraint String.

                constraint = constraint.toString().toLowerCase();
                for (int i = 0; i < mDatabaseOfNames.size(); i++) {
                    String dataNames = mDatabaseOfNames.get(i);
                    if (dataNames.toLowerCase().startsWith(constraint.toString()))  {
                        FilteredArrayNames.add(dataNames);
                    }
                }

                results.count = FilteredArrayNames.size();
                results.values = FilteredArrayNames;
                Log.e("VALUES", results.values.toString());

                return results;
            }
        };

        return filter;
    }
}

Inside performFiltering() you need to do actual comparison of the search query to values in your database. It will pass its result to publishResults() method.

String comparison in bash. [[: not found

I had this problem when installing Heroku Toolbelt

This is how I solved the problem

$ ls -l /bin/sh
lrwxrwxrwx 1 root root 4 ago 15  2012 /bin/sh -> dash

As you can see, /bin/sh is a link to "dash" (not bash), and [[ is bash syntactic sugarness. So I just replaced the link to /bin/bash. Careful using rm like this in your system!

$ sudo rm /bin/sh
$ sudo ln -s /bin/bash /bin/sh

How can you find the height of text on an HTML canvas?

Just to add to Daniel's answer (which is great! and absolutely right!), version without JQuery:

function objOff(obj)
{
    var currleft = currtop = 0;
    if( obj.offsetParent )
    { do { currleft += obj.offsetLeft; currtop += obj.offsetTop; }
      while( obj = obj.offsetParent ); }
    else { currleft += obj.offsetLeft; currtop += obj.offsetTop; }
    return [currleft,currtop];
}
function FontMetric(fontName,fontSize) 
{
    var text = document.createElement("span");
    text.style.fontFamily = fontName;
    text.style.fontSize = fontSize + "px";
    text.innerHTML = "ABCjgq|"; 
    // if you will use some weird fonts, like handwriting or symbols, then you need to edit this test string for chars that will have most extreme accend/descend values

    var block = document.createElement("div");
    block.style.display = "inline-block";
    block.style.width = "1px";
    block.style.height = "0px";

    var div = document.createElement("div");
    div.appendChild(text);
    div.appendChild(block);

    // this test div must be visible otherwise offsetLeft/offsetTop will return 0
    // but still let's try to avoid any potential glitches in various browsers
    // by making it's height 0px, and overflow hidden
    div.style.height = "0px";
    div.style.overflow = "hidden";

    // I tried without adding it to body - won't work. So we gotta do this one.
    document.body.appendChild(div);

    block.style.verticalAlign = "baseline";
    var bp = objOff(block);
    var tp = objOff(text);
    var taccent = bp[1] - tp[1];
    block.style.verticalAlign = "bottom";
    bp = objOff(block);
    tp = objOff(text);
    var theight = bp[1] - tp[1];
    var tdescent = theight - taccent;

    // now take it off :-)
    document.body.removeChild(div);

    // return text accent, descent and total height
    return [taccent,theight,tdescent];
}

I've just tested the code above and works great on latest Chrome, FF and Safari on Mac.

EDIT: I have added font size as well and tested with webfont instead of system font - works awesome.

What is "string[] args" in Main class for?

Further to everyone else's answer, you should note that the parameters are optional in C# if your application does not use command line arguments.

This code is perfectly valid:

internal static Program
{
    private static void Main()
    {
        // Get on with it, without any arguments...
    }
}

Problems with entering Git commit message with Vim

Have you tried just going: git commit -m "Message here"

So in your case:

git commit -m "Form validation added"

After you've added your files of course.

Are types like uint32, int32, uint64, int64 defined in any stdlib header?

The C99 stdint.h defines these:

  • int8_t
  • int16_t
  • int32_t
  • uint8_t
  • uint16_t
  • uint32_t

And, if the architecture supports them:

  • int64_t
  • uint64_t

There are various other integer typedefs in stdint.h as well.

If you're stuck without a C99 environment then you should probably supply your own typedefs and use the C99 ones anyway.

The uint32 and uint64 (i.e. without the _t suffix) are probably application specific.

How to initialize a private static const map in C++?

You could try this:

MyClass.h

class MyClass {
private:
    static const std::map<key, value> m_myMap; 
    static const std::map<key, value> createMyStaticConstantMap();
public:
    static std::map<key, value> getMyConstantStaticMap( return m_myMap );
}; //MyClass

MyClass.cpp

#include "MyClass.h"

const std::map<key, value> MyClass::m_myMap = MyClass::createMyStaticConstantMap();

const std::map<key, value> MyClass::createMyStaticConstantMap() {
    std::map<key, value> mMap;
    mMap.insert( std::make_pair( key1, value1 ) );
    mMap.insert( std::make_pair( key2, value2 ) );
    // ....
    mMap.insert( std::make_pair( lastKey, lastValue ) ); 
    return mMap;
} // createMyStaticConstantMap

With this implementation your classes constant static map is a private member and can be accessible to other classes using a public get method. Otherwise since it is constant and can not change, you can remove the public get method and move the map variable into the classes public section. I would however leave the createMap method private or protected if inheritance and or polymorphism is required. Here are some samples of use.

 std::map<key,value> m1 = MyClass::getMyMap();
 // then do work on m1 or
 unsigned index = some predetermined value
 MyClass::getMyMap().at( index ); // As long as index is valid this will 
 // retun map.second or map->second value so if in this case key is an
 // unsigned and value is a std::string then you could do
 std::cout << std::string( MyClass::getMyMap().at( some index that exists in map ) ); 
// and it will print out to the console the string locted in the map at this index. 
//You can do this before any class object is instantiated or declared. 

 //If you are using a pointer to your class such as:
 std::shared_ptr<MyClass> || std::unique_ptr<MyClass>
 // Then it would look like this:
 pMyClass->getMyMap().at( index ); // And Will do the same as above
 // Even if you have not yet called the std pointer's reset method on
 // this class object. 

 // This will only work on static methods only, and all data in static methods must be available first.

I had edited my original post, there was nothing wrong with the original code in which I posted for it compiled, built and ran correctly, it was just that my first version I presented as an answer the map was declared as public and the map was const but wasn't static.

Remove padding or margins from Google Charts

There is this possibility like Aman Virk mentioned:

var options = {
    chartArea:{left:10,top:20,width:"100%",height:"100%"}
};

But keep in mind that the padding and margin aren't there to bother you. If you have the possibility to switch between different types of charts like a ColumnChart and the one with vertical columns then you need some margin for displaying the labels of those lines.

If you take away that margin then you will end up showing only a part of the labels or no labels at all.

So if you just have one chart type then you can change the margin and padding like Arman said. But if it's possible to switch don't change them.

How do I create a GUI for a windows application using C++?

I strongly prefer simply using Microsoft Visual Studio and writing a native Win32 app.

For a GUI as simple as the one that you describe, you could simply create a Dialog Box and use it as your main application window. The default application created by the Win32 Project wizard in Visual Studio actually pops a window, so you can replace that window with your Dialog Box and replace the WndProc with a similar (but simpler) DialogProc.

The question, then, is one of tools and cost. The Express Edition of Visual C++ does everything you want except actually create the Dialog Template resource. For this, you could either code it in the RC file by hand or in memory by hand. Related SO question: Windows API Dialogs without using resource files.

Or you could try one of the free resource editors that others have recommended.

Finally, the Visual Studio 2008 Standard Edition is a costlier option but gives you an integrated resource editor.

Call a Javascript function every 5 seconds continuously

For repeating an action in the future, there is the built in setInterval function that you can use instead of setTimeout.
It has a similar signature, so the transition from one to another is simple:

setInterval(function() {
    // do stuff
}, duration);

How do I set up HttpContent for my HttpClient PostAsync second parameter?

    public async Task<ActionResult> Index()
    {
        apiTable table = new apiTable();
        table.Name = "Asma Nadeem";
        table.Roll = "6655";

        string str = "";
        string str2 = "";

        HttpClient client = new HttpClient();

        string json = JsonConvert.SerializeObject(table);

        StringContent httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

        var response = await client.PostAsync("http://YourSite.com/api/apiTables", httpContent);

        str = "" + response.Content + " : " + response.StatusCode;

        if (response.IsSuccessStatusCode)
        {       
            str2 = "Data Posted";
        }

        return View();
    }

Freezing Row 1 and Column A at the same time

Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.

For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".

Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html

Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx

How to get the date and time values in a C program?

One liner to get local time information: struct tm *tinfo = localtime(&(time_t){time(NULL)});

Python: Convert timedelta to int in a dataframe

Timedelta objects have read-only instance attributes .days, .seconds, and .microseconds.

Firebase cloud messaging notification not received by device

I had a similar problem, but in my case I was missing the google-services plugin from my Gradle build (I was adding Firebase to an existing project).

I added the following to my root build.gradle:

classpath 'com.google.gms:google-services:3.1.0'

and the following to the end of my app-level build.gradle:

apply plugin: 'com.google.gms.google-services'

I then had to download the google-services.json file from the Firebase Console (having originally imported an existing Google Cloud project) and copy it to my app directory`.

SQL Error: ORA-00922: missing or invalid option

there's nothing wrong with using CHAR like that.. I think your problem is that you have a space in your tablename. It should be: charteredflight or chartered_flight..

To add server using sp_addlinkedserver

FOR SQL SERVER

EXEC sp_addlinkedserver @server='servername' 

No need to specify other parameters. You can go through this article.

How to convert Django Model object to dict with its fields and values?

Best solution you have ever see.

Convert django.db.models.Model instance and all related ForeignKey, ManyToManyField and @Property function fields into dict.

"""
Convert django.db.models.Model instance and all related ForeignKey, ManyToManyField and @property function fields into dict.
Usage:
    class MyDjangoModel(... PrintableModel):
        to_dict_fields = (...)
        to_dict_exclude = (...)
        ...
    a_dict = [inst.to_dict(fields=..., exclude=...) for inst in MyDjangoModel.objects.all()]
"""
import typing

import django.core.exceptions
import django.db.models
import django.forms.models


def get_decorators_dir(cls, exclude: typing.Optional[set]=None) -> set:
    """
    Ref: https://stackoverflow.com/questions/4930414/how-can-i-introspect-properties-and-model-fields-in-django
    :param exclude: set or None
    :param cls:
    :return: a set of decorators
    """
    default_exclude = {"pk", "objects"}
    if not exclude:
        exclude = default_exclude
    else:
        exclude = exclude.union(default_exclude)

    return set([name for name in dir(cls) if name not in exclude and isinstance(getattr(cls, name), property)])


class PrintableModel(django.db.models.Model):

    class Meta:
        abstract = True

    def __repr__(self):
        return str(self.to_dict())

    def to_dict(self, fields: typing.Optional[typing.Iterable]=None, exclude: typing.Optional[typing.Iterable]=None):
        opts = self._meta
        data = {}

        # support fields filters and excludes
        if not fields:
            fields = set()
        else:
            fields = set(fields)
        default_fields = getattr(self, "to_dict_fields", set())
        fields = fields.union(default_fields)

        if not exclude:
            exclude = set()
        else:
            exclude = set(exclude)
        default_exclude = getattr(self, "to_dict_exclude", set())
        exclude = exclude.union(default_exclude)

        # support syntax "field__childField__..."
        self_fields = set()
        child_fields = dict()
        if fields:
            for i in fields:
                splits = i.split("__")
                if len(splits) == 1:
                    self_fields.add(splits[0])
                else:
                    self_fields.add(splits[0])

                    field_name = splits[0]
                    child_fields.setdefault(field_name, set())
                    child_fields[field_name].add("__".join(splits[1:]))

        self_exclude = set()
        child_exclude = dict()
        if exclude:
            for i in exclude:
                splits = i.split("__")
                if len(splits) == 1:
                    self_exclude.add(splits[0])
                else:
                    field_name = splits[0]
                    if field_name not in child_exclude:
                        child_exclude[field_name] = set()
                    child_exclude[field_name].add("__".join(splits[1:]))

        for f in opts.concrete_fields + opts.many_to_many:
            if self_fields and f.name not in self_fields:
                continue
            if self_exclude and f.name in self_exclude:
                continue

            if isinstance(f, django.db.models.ManyToManyField):
                if self.pk is None:
                    data[f.name] = []
                else:
                    result = []
                    m2m_inst = f.value_from_object(self)
                    for obj in m2m_inst:
                        if isinstance(PrintableModel, obj) and hasattr(obj, "to_dict"):
                            d = obj.to_dict(
                                fields=child_fields.get(f.name),
                                exclude=child_exclude.get(f.name),
                            )
                        else:
                            d = django.forms.models.model_to_dict(
                                obj,
                                fields=child_fields.get(f.name),
                                exclude=child_exclude.get(f.name)
                            )
                        result.append(d)
                    data[f.name] = result
            elif isinstance(f, django.db.models.ForeignKey):
                if self.pk is None:
                    data[f.name] = []
                else:
                    data[f.name] = None
                    try:
                        foreign_inst = getattr(self, f.name)
                    except django.core.exceptions.ObjectDoesNotExist:
                        pass
                    else:
                        if isinstance(foreign_inst, PrintableModel) and hasattr(foreign_inst, "to_dict"):
                            data[f.name] = foreign_inst.to_dict(
                                fields=child_fields.get(f.name),
                                exclude=child_exclude.get(f.name)
                            )
                        elif foreign_inst is not None:
                            data[f.name] = django.forms.models.model_to_dict(
                                foreign_inst,
                                fields=child_fields.get(f.name),
                                exclude=child_exclude.get(f.name),
                            )

            elif isinstance(f, (django.db.models.DateTimeField, django.db.models.DateField)):
                v = f.value_from_object(self)
                if v is not None:
                    data[f.name] = v.isoformat()
                else:
                    data[f.name] = None
            else:
                data[f.name] = f.value_from_object(self)

        # support @property decorator functions
        decorator_names = get_decorators_dir(self.__class__)
        for name in decorator_names:
            if self_fields and name not in self_fields:
                continue
            if self_exclude and name in self_exclude:
                continue

            value = getattr(self, name)
            if isinstance(value, PrintableModel) and hasattr(value, "to_dict"):
                data[name] = value.to_dict(
                    fields=child_fields.get(name),
                    exclude=child_exclude.get(name)
                )
            elif hasattr(value, "_meta"):
                # make sure it is a instance of django.db.models.fields.Field
                data[name] = django.forms.models.model_to_dict(
                    value,
                    fields=child_fields.get(name),
                    exclude=child_exclude.get(name),
                )
            elif isinstance(value, (set, )):
                data[name] = list(value)
            else:
                data[name] = value

        return data

https://gist.github.com/shuge/f543dc2094a3183f69488df2bfb51a52

How to dynamically allocate memory space for a string and get that string from user?

You could have an array that starts out with 10 elements. Read input character by character. If it goes over, realloc another 5 more. Not the best, but then you can free the other space later.

Get the difference between two dates both In Months and days in sql

Here I'm just doing the difference between today, and a CREATED_DATE DATE field in a table, which obviously is a date in the past:

SELECT  
((FLOOR(ABS(MONTHS_BETWEEN(CREATED_DATE, SYSDATE))) / 12) * 12) || ' months, '  AS MONTHS,
-- we take total days - years(as days) - months(as days) to get remaining days
FLOOR((SYSDATE - CREATED_DATE) -      -- total days
(FLOOR((SYSDATE - CREATED_DATE)/365)*12)*(365/12) -      -- years, as days
-- this is total months - years (as months), to get number of months, 
-- then multiplied by 30.416667 to get months as days (and remove it from total days)
FLOOR(((SYSDATE - CREATED_DATE)/365)*12 - (FLOOR((SYSDATE - CREATED_DATE)/365)*12)) * (365/12))
|| ' days ' AS DAYS 
FROM MyTable

I use (365/12), or 30.416667, as my conversion factor because I'm using total days and removing years and months (as days) to get the remainder number of days. It was good enough for my purposes, anyway.

How do I pass a string into subprocess.Popen (using the stdin argument)?

I am using python3 and found out that you need to encode your string before you can pass it into stdin:

p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
out, err = p.communicate(input='one\ntwo\nthree\nfour\nfive\nsix\n'.encode())
print(out)

Stopword removal with NLTK

I suggest you create your own list of operator words that you take out of the stopword list. Sets can be conveniently subtracted, so:

operators = set(('and', 'or', 'not'))
stop = set(stopwords...) - operators

Then you can simply test if a word is in or not in the set without relying on whether your operators are part of the stopword list. You can then later switch to another stopword list or add an operator.

if word.lower() not in stop:
    # use word

HTML Table different number of columns in different rows

Colspan:

<table>
   <tr>
      <td> Row 1 Col 1</td>
      <td> Row 1 Col 2</td>
</tr>
<tr>
      <td colspan=2> Row 2 Long Col</td>
</tr>
</table>

How do I make calls to a REST API using C#?

Since you are using Visual Studio 11 Beta, you will want to use the latest and greatest. The new Web API contains classes for this.

See HttpClient: http://wcf.codeplex.com/wikipage?title=WCF%20HTTP

How can I do a case insensitive string comparison?

You should use static String.Compare function like following

x => String.Compare (x.Username, (string)drUser["Username"],
                     StringComparison.OrdinalIgnoreCase) == 0

How to display default text "--Select Team --" in combo box on pageload in WPF?

Not tried it with combo boxes but this has worked for me with other controls...

ageektrapped blogpost

He uses the adorner layer here to display a watermark.

How to download a file using a Java REST service and a data stream

See example here: Input and Output binary streams using JERSEY?

Pseudo code would be something like this (there are a few other similar options in above mentioned post):

@Path("file/")
@GET
@Produces({"application/pdf"})
public StreamingOutput getFileContent() throws Exception {
     public void write(OutputStream output) throws IOException, WebApplicationException {
        try {
          //
          // 1. Get Stream to file from first server
          //
          while(<read stream from first server>) {
              output.write(<bytes read from first server>)
          }
        } catch (Exception e) {
            throw new WebApplicationException(e);
        } finally {
              // close input stream
        }
    }
}

How to suppress scientific notation when printing float values?

This is using Captain Cucumber's answer, but with 2 additions.

1) allowing the function to get non scientific notation numbers and just return them as is (so you can throw a lot of input that some of the numbers are 0.00003123 vs 3.123e-05 and still have function work.

2) added support for negative numbers. (in original function, a negative number would end up like 0.0000-108904 from -1.08904e-05)

def getExpandedScientificNotation(flt):
    was_neg = False
    if not ("e" in flt):
        return flt
    if flt.startswith('-'):
        flt = flt[1:]
        was_neg = True 
    str_vals = str(flt).split('e')
    coef = float(str_vals[0])
    exp = int(str_vals[1])
    return_val = ''
    if int(exp) > 0:
        return_val += str(coef).replace('.', '')
        return_val += ''.join(['0' for _ in range(0, abs(exp - len(str(coef).split('.')[1])))])
    elif int(exp) < 0:
        return_val += '0.'
        return_val += ''.join(['0' for _ in range(0, abs(exp) - 1)])
        return_val += str(coef).replace('.', '')
    if was_neg:
        return_val='-'+return_val
    return return_val

Remove all special characters from a string

Update

The solution below has a "SEO friendlier" version:

function hyphenize($string) {
    $dict = array(
        "I'm"      => "I am",
        "thier"    => "their",
        // Add your own replacements here
    );
    return strtolower(
        preg_replace(
          array( '#[\\s-]+#', '#[^A-Za-z0-9. -]+#' ),
          array( '-', '' ),
          // the full cleanString() can be downloaded from http://www.unexpectedit.com/php/php-clean-string-of-utf8-chars-convert-to-similar-ascii-char
          cleanString(
              str_replace( // preg_replace can be used to support more complicated replacements
                  array_keys($dict),
                  array_values($dict),
                  urldecode($string)
              )
          )
        )
    );
}

function cleanString($text) {
    $utf8 = array(
        '/[áàâãªä]/u'   =>   'a',
        '/[ÁÀÂÃÄ]/u'    =>   'A',
        '/[ÍÌÎÏ]/u'     =>   'I',
        '/[íìîï]/u'     =>   'i',
        '/[éèêë]/u'     =>   'e',
        '/[ÉÈÊË]/u'     =>   'E',
        '/[óòôõºö]/u'   =>   'o',
        '/[ÓÒÔÕÖ]/u'    =>   'O',
        '/[úùûü]/u'     =>   'u',
        '/[ÚÙÛÜ]/u'     =>   'U',
        '/ç/'           =>   'c',
        '/Ç/'           =>   'C',
        '/ñ/'           =>   'n',
        '/Ñ/'           =>   'N',
        '/–/'           =>   '-', // UTF-8 hyphen to "normal" hyphen
        '/[’‘‹›‚]/u'    =>   ' ', // Literally a single quote
        '/[“”«»„]/u'    =>   ' ', // Double quote
        '/ /'           =>   ' ', // nonbreaking space (equiv. to 0x160)
    );
    return preg_replace(array_keys($utf8), array_values($utf8), $text);
}

The rationale for the above functions (which I find way inefficient - the one below is better) is that a service that shall not be named apparently ran spelling checks and keyword recognition on the URLs.

After losing a long time on a customer's paranoias, I found out they were not imagining things after all -- their SEO experts [I am definitely not one] reported that, say, converting "Viaggi Economy Perù" to viaggi-economy-peru "behaved better" than viaggi-economy-per (the previous "cleaning" removed UTF8 characters; Bogotà became bogot, Medellìn became medelln and so on).

There were also some common misspellings that seemed to influence the results, and the only explanation that made sense to me is that our URL were being unpacked, the words singled out, and used to drive God knows what ranking algorithms. And those algorithms apparently had been fed with UTF8-cleaned strings, so that "Perù" became "Peru" instead of "Per". "Per" did not match and sort of took it in the neck.

In order to both keep UTF8 characters and replace some misspellings, the faster function below became the more accurate (?) function above. $dict needs to be hand tailored, of course.

Previous answer

A simple approach:

// Remove all characters except A-Z, a-z, 0-9, dots, hyphens and spaces
// Note that the hyphen must go last not to be confused with a range (A-Z)
// and the dot, NOT being special (I know. My life was a lie), is NOT escaped

$str = preg_replace('/[^A-Za-z0-9. -]/', '', $str);

// Replace sequences of spaces with hyphen
$str = preg_replace('/  */', '-', $str);

// The above means "a space, followed by a space repeated zero or more times"
// (should be equivalent to / +/)

// You may also want to try this alternative:
$str = preg_replace('/\\s+/', '-', $str);

// where \s+ means "zero or more whitespaces" (a space is not necessarily the
// same as a whitespace) just to be sure and include everything

Note that you might have to first urldecode() the URL, since %20 and + both are actually spaces - I mean, if you have "Never%20gonna%20give%20you%20up" you want it to become Never-gonna-give-you-up, not Never20gonna20give20you20up . You might not need it, but I thought I'd mention the possibility.

So the finished function along with test cases:

function hyphenize($string) {
    return 
    ## strtolower(
          preg_replace(
            array('#[\\s-]+#', '#[^A-Za-z0-9. -]+#'),
            array('-', ''),
        ##     cleanString(
              urldecode($string)
        ##     )
        )
    ## )
    ;
}

print implode("\n", array_map(
    function($s) {
            return $s . ' becomes ' . hyphenize($s);
    },
    array(
    'Never%20gonna%20give%20you%20up',
    "I'm not the man I was",
    "'Légeresse', dit sa majesté",
    )));


Never%20gonna%20give%20you%20up    becomes  never-gonna-give-you-up
I'm not the man I was              becomes  im-not-the-man-I-was
'Légeresse', dit sa majesté        becomes  legeresse-dit-sa-majeste

To handle UTF-8 I used a cleanString implementation found online (link broken since, but a stripped down copy with all the not-too-esoteric UTF8 characters is at the beginning of the answer; it's also easy to add more characters to it if you need) that converts UTF8 characters to normal characters, thus preserving the word "look" as much as possible. It could be simplified and wrapped inside the function here for performance.

The function above also implements converting to lowercase - but that's a taste. The code to do so has been commented out.

When should the xlsm or xlsb formats be used?

One could think that xlsb has only advantages over xlsm. The fact that xlsm is XML-based and xlsb is binary is that when workbook corruption occurs, you have better chances to repair a xlsm than a xlsb.

How to get maximum value from the Collection (for example ArrayList)?

package in.co.largestinarraylist;

import java.util.ArrayList;
import java.util.Scanner;

public class LargestInArrayList {

    public static void main(String[] args) {

        int n;
        ArrayList<Integer> L = new ArrayList<Integer>();
        int max;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter Size of Array List");
        n = in.nextInt();
        System.out.println("Enter elements in Array List");

        for (int i = 0; i < n; i++) {
            L.add(in.nextInt());
        }

        max = L.get(0);

        for (int i = 0; i < L.size(); i++) {
            if (L.get(i) > max) {
                max = L.get(i);
            }
        }

        System.out.println("Max Element: " + max);
        in.close();
    }
}

Git merge without auto commit

When there is one commit only in the branch, I usually do

git merge branch_name --ff

react-native: command not found

I ran into this issue by being a bit silly. I use nvm to manage my different versions of node, and installed react-native into a version of node that was not my default. Upon opening a new shell, I lost my command. :) Switching back of course fixed things.

How do I make a div full screen?

You can use HTML5 Fullscreen API for this (which is the most suitable way i think).

The fullscreen has to be triggered via a user event (click, keypress) otherwise it won't work.

Here is a button which makes the div fullscreen on click. And in fullscreen mode, the button click will exit fullscreen mode.

_x000D_
_x000D_
$('#toggle_fullscreen').on('click', function(){_x000D_
  // if already full screen; exit_x000D_
  // else go fullscreen_x000D_
  if (_x000D_
    document.fullscreenElement ||_x000D_
    document.webkitFullscreenElement ||_x000D_
    document.mozFullScreenElement ||_x000D_
    document.msFullscreenElement_x000D_
  ) {_x000D_
    if (document.exitFullscreen) {_x000D_
      document.exitFullscreen();_x000D_
    } else if (document.mozCancelFullScreen) {_x000D_
      document.mozCancelFullScreen();_x000D_
    } else if (document.webkitExitFullscreen) {_x000D_
      document.webkitExitFullscreen();_x000D_
    } else if (document.msExitFullscreen) {_x000D_
      document.msExitFullscreen();_x000D_
    }_x000D_
  } else {_x000D_
    element = $('#container').get(0);_x000D_
    if (element.requestFullscreen) {_x000D_
      element.requestFullscreen();_x000D_
    } else if (element.mozRequestFullScreen) {_x000D_
      element.mozRequestFullScreen();_x000D_
    } else if (element.webkitRequestFullscreen) {_x000D_
      element.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);_x000D_
    } else if (element.msRequestFullscreen) {_x000D_
      element.msRequestFullscreen();_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
#container{_x000D_
  border:1px solid red;_x000D_
  border-radius: .5em;_x000D_
  padding:10px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="container">_x000D_
  <p>_x000D_
    <a href="#" id="toggle_fullscreen">Toggle Fullscreen</a>_x000D_
  </p>_x000D_
  I will be fullscreen, yay!_x000D_
</div>
_x000D_
_x000D_
_x000D_

Please also note that Fullscreen API for Chrome does not work in non-secure pages. See https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins for more details.

Another thing to note is the :fullscreen CSS selector. You can append this to any css selector so the that the rules will be applied when that element is fullscreen:

#container:-webkit-full-screen,
#container:-moz-full-screen,
#container:-ms-fullscreen,
#container:fullscreen {
    width: 100vw;
    height: 100vh;
    }

Connecting to local SQL Server database using C#

I like to use the handy process outlined here to build connection strings using a .udl file. This allows you to test them from within the udl file to ensure that you can connect before you run any code.

Hope that helps.

java.lang.OutOfMemoryError: GC overhead limit exceeded

For the record, we had the same problem today. We fixed it by using this option:

-XX:-UseConcMarkSweepGC

Apparently, this modified the strategy used for garbage collection, which made the issue disappear.

Print a list in reverse order with range()?

Very often asked question is whether range(9, -1, -1) better than reversed(range(10)) in Python 3? People who have worked in other languages with iterators immediately tend to think that reversed() must cache all values and then return in reverse order. Thing is that Python's reversed() operator doesn't work if the object is just an iterator. The object must have one of below two for reversed() to work:

  1. Either support len() and integer indexes via []
  2. Or have __reversed__() method implemented.

If you try to use reversed() on object that has none of above then you will get:

>>> [reversed((x for x in range(10)))]
TypeError: 'generator' object is not reversible

So in short, Python's reversed() is only meant on array like objects and so it should have same performance as forward iteration.

But what about range()? Isn't that a generator? In Python 3 it is generator but wrapped in a class that implements both of above. So range(100000) doesn't take up lot of memory but it still supports efficient indexing and reversing.

So in summary, you can use reversed(range(10)) without any hit on performance.

How to set data attributes in HTML elements

Vanilla Javascript solution

HTML

<div id="mydiv" data-myval="10"></div>

JavaScript:

  • Using DOM's getAttribute() property

     var brand = mydiv.getAttribute("data-myval")//returns "10"
     mydiv.setAttribute("data-myval", "20")      //changes "data-myval" to "20"
     mydiv.removeAttribute("data-myval")         //removes "data-myval" attribute entirely
    
  • Using JavaScript's dataset property

    var myval = mydiv.dataset.myval     //returns "10"
    mydiv.dataset.myval = '20'          //changes "data-myval" to "20"
    mydiv.dataset.myval = null          //removes "data-myval" attribute
    

How to remove package using Angular CLI?

I think best approach until Angular team add this feature to cli is first create angular (ng new something) in other place and then add what you want to delete. Using git to check witch files are changed or added by angular cli. then you can revert that changes. Be careful of untracked files from .gitignore.

Build .so file from .c file using gcc command line

To generate a shared library you need first to compile your C code with the -fPIC (position independent code) flag.

gcc -c -fPIC hello.c -o hello.o

This will generate an object file (.o), now you take it and create the .so file:

gcc hello.o -shared -o libhello.so

EDIT: Suggestions from the comments:

You can use

gcc -shared -o libhello.so -fPIC hello.c

to do it in one step. – Jonathan Leffler

I also suggest to add -Wall to get all warnings, and -g to get debugging information, to your gcc commands. – Basile Starynkevitch

How to do a num_rows() on COUNT query in codeigniter?

This will only return 1 row, because you're just selecting a COUNT(). you will use mysql_num_rows() on the $query in this case.

If you want to get a count of each of the ID's, add GROUP BY id to the end of the string.

Performance-wise, don't ever ever ever use * in your queries. If there is 100 unique fields in a table and you want to get them all, you write out all 100, not *. This is because * has to recalculate how many fields it has to go, every single time it grabs a field, which takes a lot more time to call.

What is the boundary in multipart/form-data?

Is the ??? free to be defined by the user?

Yes.

or is it supplied by the HTML?

No. HTML has nothing to do with that. Read below.

Is it possible for me to define the ??? as abcdefg?

Yes.

If you want to send the following data to the web server:

name = John
age = 12

using application/x-www-form-urlencoded would be like this:

name=John&age=12

As you can see, the server knows that parameters are separated by an ampersand &. If & is required for a parameter value then it must be encoded.

So how does the server know where a parameter value starts and ends when it receives an HTTP request using multipart/form-data?

Using the boundary, similar to &.

For example:

--XXX
Content-Disposition: form-data; name="name"

John
--XXX
Content-Disposition: form-data; name="age"

12
--XXX--

In that case, the boundary value is XXX. You specify it in the Content-Type header so that the server knows how to split the data it receives.

So you need to:

  • Use a value that won't appear in the HTTP data sent to the server.

  • Be consistent and use the same value everywhere in the request message.

How to retry image pull in a kubernetes Pods?

First try to see what's wrong with the pod:

kubectl logs -p <your_pod>

In my case it was a problem with the YAML file.

So, I needed to correct the configuration file and replace it:

kubectl replace --force -f <yml_file_describing_pod>

Overlapping Views in Android

Also, take a look at FrameLayout, that's how the Camera's Gallery application implements the Zoom buttons overlay.

How to use document.getElementByName and getElementByTag?

It's getElementsByName() and getElementsByTagName() - note the "s" in "Elements", indicating that both functions return a list of elements, i.e., a NodeList, which you will access like an array. Note that the second function ends with "TagName" not "Tag".

Even if the function only returns one element it will still be in a NodeList of length one. So:

var els = document.getElementsByName('frmMain');
// els.length will be the number of elements returned
// els[0] will be the first element returned
// els[1] the second, etc.

Assuming your form is the first (or only) form on the page you can do this:

document.getElementsByName('frmMain')[0].elements
document.getElementsByTagName('table')[0].elements

Increasing heap space in Eclipse: (java.lang.OutOfMemoryError)

Please make sure your code is fine. I too got stuck in this problem once and tried the solution accepted here but in vain. So I wrote my code again. Apparently I was using a custom array list and adding the values from an array. I tried changing the ArrayList to accept the primitive values only and it worked.

Is there any way to specify a suggested filename when using data: URI?

No.

The entire purpose is that it's a datastream, not a file. The data source should not have any knowledge of the user agent handling it as a file... and it doesn't.

How can I fill a div with an image while keeping it proportional?

You can achieve this using css flex properties. Please see the code below

_x000D_
_x000D_
.img-container {_x000D_
  border: 2px solid red;_x000D_
  justify-content: center;_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  overflow: hidden;_x000D_
  _x000D_
}_x000D_
.img-container .img-to-fit {_x000D_
  flex: 1;_x000D_
  height: 100%;_x000D_
}
_x000D_
<div class="img-container">_x000D_
  <img class="img-to-fit" src="https://images.pexels.com/photos/8633/nature-tree-green-pine.jpg" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I get all the request headers in Django?

According to the documentation request.META is a "standard Python dictionary containing all available HTTP headers". If you want to get all the headers you can simply iterate through the dictionary.

Which part of your code to do this depends on your exact requirement. Anyplace that has access to request should do.

Update

I need to access it in a Middleware class but when i iterate over it, I get a lot of values apart from HTTP headers.

From the documentation:

With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name.

(Emphasis added)

To get the HTTP headers alone, just filter by keys prefixed with HTTP_.

Update 2

could you show me how I could build a dictionary of headers by filtering out all the keys from the request.META variable which begin with a HTTP_ and strip out the leading HTTP_ part.

Sure. Here is one way to do it.

import re
regex = re.compile('^HTTP_')
dict((regex.sub('', header), value) for (header, value) 
       in request.META.items() if header.startswith('HTTP_'))

Multiple aggregate functions in HAVING clause

GROUP BY meetingID
HAVING COUNT(caseID) < 4 AND COUNT(caseID) > 2

Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3

I had same problem.

The cause was that I declared same global variable in 2 files. So it was showing same error saying 2 duplicate symbols.

The solution was to remove those variables.

Python Requests package: Handling xml response

requests does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.

Python comes with built-in XML parsers. I recommend you use the ElementTree API:

import requests
from xml.etree import ElementTree

response = requests.get(url)

tree = ElementTree.fromstring(response.content)

or, if the response is particularly large, use an incremental approach:

    response = requests.get(url, stream=True)
    # if the server sent a Gzip or Deflate compressed response, decompress
    # as we read the raw stream:
    response.raw.decode_content = True

    events = ElementTree.iterparse(response.raw)
    for event, elem in events:
        # do something with `elem`

The external lxml project builds on the same API to give you more features and power still.

How can I add raw data body to an axios request?

Here is my solution:

axios({
  method: "POST",
  url: "https://URL.com/api/services/fetchQuizList",
  headers: {
    "x-access-key": data,
    "x-access-token": token,
  },
  data: {
    quiz_name: quizname,
  },
})
.then(res => {
  console.log("res", res.data.message);
})
.catch(err => {
  console.log("error in request", err);
});

This should help

Html/PHP - Form - Input as array

HTML: Use names as

<input name="levels[level][]">
<input name="levels[build_time][]">

PHP:

$array = filter_input_array(INPUT_POST);
$newArray = array();
foreach (array_keys($array) as $fieldKey) {
    foreach ($array[$fieldKey] as $key=>$value) {
        $newArray[$key][$fieldKey] = $value;
    }
}  

$newArray will hold data as you want

Array ( 
  [0] => Array ( [level] => 1 [build_time] => 123 ) 
  [1] => Array ( [level] => 2 [build_time] => 456 )
)

Stop form from submitting , Using Jquery

Again, AJAX is async. So the showMsg function will be called only after success response from the server.. and the form submit event will not wait until AJAX success.

Move the e.preventDefault(); as first line in the click handler.

$("form").submit(function (e) {
      e.preventDefault(); // this will prevent from submitting the form.
      ...

See below code,

I want it to be allowed HasJobInProgress == False

$(document).ready(function () {
    $("form").submit(function (e) {
        e.preventDefault(); //prevent default form submit
        $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function (data) {
                showMsg(data);
            },
            cache: false
        });
    });
});
$("#cancelButton").click(function () {
    window.location = '@Url.Action("list", "default", new { clientId = Model.ClientId })';
});
$("[type=text]").focus(function () {
    $(this).select();
});
function showMsg(hasCurrentJob) {
    if (hasCurrentJob == "True") {
        alert("The current clients has a job in progress. No changes can be saved until current job completes");
        return false;
    } else {
       $("form").unbind('submit').submit();
    }
}

ReactJS - .JS vs .JSX

JSX tags (<Component/>) are clearly not standard javascript and have no special meaning if you put them inside a naked <script> tag for example. Hence all React files that contain them are JSX and not JS.

By convention, the entry point of a React application is usually .js instead of .jsx even though it contains React components. It could as well be .jsx. Any other JSX files usually have the .jsx extension.

In any case, the reason there is ambiguity is because ultimately the extension does not matter much since the transpiler happily munches any kinds of files as long as they are actually JSX.

My advice would be: don't worry about it.

Automatically size JPanel inside JFrame

As other posters have said, you need to change the LayoutManager being used. I always preferred using a GridLayout so your code would become:

MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new GridLayout());
mainFrame.pack();
mainFrame.setVisible(true);

GridLayout seems more conceptually correct to me when you want your panel to take up the entire screen.

ASP.NET MVC: What is the purpose of @section?

A good example is Javascript. You want this to be at the bottom of the page that is rendered in the browser because this is best practice.

How would you do this from a View based on a Layout/Masterpage where you can only access the middle of the page?

You do this by declaring a Scripts section at the bottom of the Layout page. Then you can add content, in this case Javascript includes (I hope!), from your View page to the bottom of your layout page.

Fatal error: Call to undefined function mcrypt_encrypt()

Check and install php5-mcrypt:

sudo apt-get install php5-mcrypt

Scrollview can host only one direct child

Wrap all the children inside of another LinearLayout with wrap_content for both the width and the height as well as the vertical orientation.

How do I make Git ignore file mode (chmod) changes?

Simple solution:

Hit this Simple command in project Folder(it won't remove your original changes) ...it will only remove changes that had been done while you changed project folder permission

command is below:

git config core.fileMode false

Why this all unnecessary file get modified: because you have changed the project folder permissions with commend sudo chmod -R 777 ./yourProjectFolder

when will you check changes what not you did? you found like below while using git diff filename

old mode 100644
new mode 100755

What is a "cache-friendly" code?

Optimizing cache usage largely comes down to two factors.

Locality of Reference

The first factor (to which others have already alluded) is locality of reference. Locality of reference really has two dimensions though: space and time.

  • Spatial

The spatial dimension also comes down to two things: first, we want to pack our information densely, so more information will fit in that limited memory. This means (for example) that you need a major improvement in computational complexity to justify data structures based on small nodes joined by pointers.

Second, we want information that will be processed together also located together. A typical cache works in "lines", which means when you access some information, other information at nearby addresses will be loaded into the cache with the part we touched. For example, when I touch one byte, the cache might load 128 or 256 bytes near that one. To take advantage of that, you generally want the data arranged to maximize the likelihood that you'll also use that other data that was loaded at the same time.

For just a really trivial example, this can mean that a linear search can be much more competitive with a binary search than you'd expect. Once you've loaded one item from a cache line, using the rest of the data in that cache line is almost free. A binary search becomes noticeably faster only when the data is large enough that the binary search reduces the number of cache lines you access.

  • Time

The time dimension means that when you do some operations on some data, you want (as much as possible) to do all the operations on that data at once.

Since you've tagged this as C++, I'll point to a classic example of a relatively cache-unfriendly design: std::valarray. valarray overloads most arithmetic operators, so I can (for example) say a = b + c + d; (where a, b, c and d are all valarrays) to do element-wise addition of those arrays.

The problem with this is that it walks through one pair of inputs, puts results in a temporary, walks through another pair of inputs, and so on. With a lot of data, the result from one computation may disappear from the cache before it's used in the next computation, so we end up reading (and writing) the data repeatedly before we get our final result. If each element of the final result will be something like (a[n] + b[n]) * (c[n] + d[n]);, we'd generally prefer to read each a[n], b[n], c[n] and d[n] once, do the computation, write the result, increment n and repeat 'til we're done.2

Line Sharing

The second major factor is avoiding line sharing. To understand this, we probably need to back up and look a little at how caches are organized. The simplest form of cache is direct mapped. This means one address in main memory can only be stored in one specific spot in the cache. If we're using two data items that map to the same spot in the cache, it works badly -- each time we use one data item, the other has to be flushed from the cache to make room for the other. The rest of the cache might be empty, but those items won't use other parts of the cache.

To prevent this, most caches are what are called "set associative". For example, in a 4-way set-associative cache, any item from main memory can be stored at any of 4 different places in the cache. So, when the cache is going to load an item, it looks for the least recently used3 item among those four, flushes it to main memory, and loads the new item in its place.

The problem is probably fairly obvious: for a direct-mapped cache, two operands that happen to map to the same cache location can lead to bad behavior. An N-way set-associative cache increases the number from 2 to N+1. Organizing a cache into more "ways" takes extra circuitry and generally runs slower, so (for example) an 8192-way set associative cache is rarely a good solution either.

Ultimately, this factor is more difficult to control in portable code though. Your control over where your data is placed is usually fairly limited. Worse, the exact mapping from address to cache varies between otherwise similar processors. In some cases, however, it can be worth doing things like allocating a large buffer, and then using only parts of what you allocated to ensure against data sharing the same cache lines (even though you'll probably need to detect the exact processor and act accordingly to do this).

  • False Sharing

There's another, related item called "false sharing". This arises in a multiprocessor or multicore system, where two (or more) processors/cores have data that's separate, but falls in the same cache line. This forces the two processors/cores to coordinate their access to the data, even though each has its own, separate data item. Especially if the two modify the data in alternation, this can lead to a massive slowdown as the data has to be constantly shuttled between the processors. This can't easily be cured by organizing the cache into more "ways" or anything like that either. The primary way to prevent it is to ensure that two threads rarely (preferably never) modify data that could possibly be in the same cache line (with the same caveats about difficulty of controlling the addresses at which data is allocated).


  1. Those who know C++ well might wonder if this is open to optimization via something like expression templates. I'm pretty sure the answer is that yes, it could be done and if it was, it would probably be a pretty substantial win. I'm not aware of anybody having done so, however, and given how little valarray gets used, I'd be at least a little surprised to see anybody do so either.

  2. In case anybody wonders how valarray (designed specifically for performance) could be this badly wrong, it comes down to one thing: it was really designed for machines like the older Crays, that used fast main memory and no cache. For them, this really was a nearly ideal design.

  3. Yes, I'm simplifying: most caches don't really measure the least recently used item precisely, but they use some heuristic that's intended to be close to that without having to keep a full time-stamp for each access.

What processes are using which ports on unix?

Given (almost) everything on unix is a file, and lsof lists open files...

Linux : netstat -putan or lsof | grep TCP

OSX : lsof | grep TCP

Other Unixen : lsof way...

Edit a text file on the console using Powershell

Kinesics Text Editor.

It's super fast and handles large text files, though minimal in features. There's a GUI version and console version (k.exe) included. Should work the same on linux.

Example: In my test it took 7 seconds to open a 500mb disk image.

screenshot

How to create unique keys for React elements?

There are many ways in which you can create unique keys, the simplest method is to use the index when iterating arrays.

Example

    var lists = this.state.lists.map(function(list, index) {
        return(
            <div key={index}>
                <div key={list.name} id={list.name}>
                    <h2 key={"header"+list.name}>{list.name}</h2>
                    <ListForm update={lst.updateSaved} name={list.name}/>
                </div>
            </div>
        )
    });

Wherever you're lopping over data, here this.state.lists.map, you can pass second parameter function(list, index) to the callback as well and that will be its index value and it will be unique for all the items in the array.

And then you can use it like

<div key={index}>

You can do the same here as well

    var savedLists = this.state.savedLists.map(function(list, index) {
        var list_data = list.data;
        list_data.map(function(data, index) {
            return (
                <li key={index}>{data}</li>
            )
        });
        return(
            <div key={index}>
                <h2>{list.name}</h2>
                <ul>
                    {list_data}
                </ul>
            </div>
        )
    });

Edit

However, As pointed by the user Martin Dawson in the comment below, This is not always ideal.

So whats the solution then?

Many

  • You can create a function to generate unique keys/ids/numbers/strings and use that
  • You can make use of existing npm packages like uuid, uniqid, etc
  • You can also generate random number like new Date().getTime(); and prefix it with something from the item you're iterating to guarantee its uniqueness
  • Lastly, I recommend using the unique ID you get from the database, If you get it.

Example:

const generateKey = (pre) => {
    return `${ pre }_${ new Date().getTime() }`;
}

const savedLists = this.state.savedLists.map( list => {
    const list_data = list.data.map( data => <li key={ generateKey(data) }>{ data }</li> );
    return(
        <div key={ generateKey(list.name) }>
            <h2>{ list.name }</h2>
            <ul>
                { list_data }
            </ul>
        </div>
    )
});

Could not load file or assembly 'xxx' or one of its dependencies. An attempt was made to load a program with an incorrect format

If you get this error while running the site in IIS 7+ on 64bit servers, you may have assemblies that are 32bit and your application pool will have the option "Enable 32-Bit Applications" set to False; Set this to true and restart the site to get it working.

Handling a Menu Item Click Event - Android

in addition to the options shown in your question, there is the possibility of implementing the action directly in your xml file from the menu, for example:

<item
   android:id="@+id/OK_MENU_ITEM"
   android:onClick="showMsgDirectMenuXml" />

And for your Java (Activity) file, you need to implement a public method with a single parameter of type MenuItem, for example:

 private void showMsgDirectMenuXml(MenuItem item) {
    Toast toast = Toast.makeText(this, "OK", Toast.LENGTH_LONG);
    toast.show();
  }

NOTE: This method will have behavior similar to the onOptionsItemSelected (MenuItem item)

How to connect HTML Divs with Lines?

Check my fiddle from this thread: Draw a line connecting two clicked div columns

The layout is different, but basically the idea is to create invisible divs between the boxes and add corresponding borders with jQuery (the answer is only HTML and CSS)

Causes of getting a java.lang.VerifyError

Check for multiple versions of the same jar file on your classpath.

For example, I had opennlp-tools-1.3.0.jar and opennlp-tools-1.5.3.jar on my classpath and got this error. The solution was to delete opennlp-tools-1.3.0.jar.

How do I check which version of NumPy I'm using?

For Python 3.X print syntax:

python -c "import numpy; print (numpy.version.version)"

Or

python -c "import numpy; print(numpy.__version__)"

What is parsing in terms that a new programmer would understand?

Parsing is about READING data in one format, so that you can use it to your needs.

I think you need to teach them to think like this. So, this is the simplest way I can think of to explain parsing for someone new to this concept.

Generally, we try to parse data one line at a time because generally it is easier for humans to think this way, dividing and conquering, and also easier to code.

We call field to every minimum undivisible data. Name is field, Age is another field, and Surname is another field. For example.

In a line, we can have various fields. In order to distinguish them, we can delimit fields by separators or by the maximum length assign to each field.

For example: By separating fields by comma

Paul,20,Jones

Or by space (Name can have 20 letters max, age up to 3 digits, Jones up to 20 letters)

Paul                020Jones               

Any of the before set of fields is called a record.

To separate between a delimited field record we need to delimit record. A dot will be enough (though you know you can apply CR/LF).

A list could be:

Michael,39,Jordan.Shaquille,40,O'neal.Lebron,24,James.

or with CR/LF

Michael,39,Jordan
Shaquille,40,O'neal
Lebron,24,James

You can say them to list 10 nba (or nlf) players they like. Then, they should type them according to a format. Then make a program to parse it and display each record. One group, can make list in a comma-separated format and a program to parse a list in a fixed size format, and viceversa.

How to simulate POST request?

This should help if you need a publicly exposed website but you're on a dev pc. Also to answer (I can't comment yet): "How do I post to an internal only running development server with this? – stryba "

NGROK creates a secure public URL to a local webserver on your development machine (Permanent URLs available for a fee, temporary for free).
1) Run ngrok.exe to open command line (on desktop)
2) Type ngrok.exe http 80 to start a tunnel,
3) test by browsing to the displayed web address which will forward and display the local default 80 page on your dev pc

Then use some of the tools recommended above to POST to your ngrok site ('https://xxxxxx.ngrok.io') to test your local code.

https://ngrok.com/

How to fix committing to the wrong Git branch?

So if your scenario is that you've committed to master but meant to commit to another-branch (which may or not may not already exist) but you haven't pushed yet, this is pretty easy to fix.

// if your branch doesn't exist, then add the -b argument 
git checkout -b another-branch
git branch --force master origin/master

Now all your commits to master will be on another-branch.

Sourced with love from: http://haacked.com/archive/2015/06/29/git-migrate/

How to undo a git pull?

Reset the master branch:

git reset --hard origin/master

How to make the python interpreter correctly handle non-ASCII characters in string operations?

I know it's an old thread, but I felt compelled to mention the translate method, which is always a good way to replace all character codes above 128 (or other if necessary).

Usage : str.translate(table[, deletechars])

>>> trans_table = ''.join( [chr(i) for i in range(128)] + [' '] * 128 )

>>> 'Résultat'.translate(trans_table)
'R sultat'
>>> '6Â 918Â 417Â 712'.translate(trans_table)
'6  918  417  712'

Starting with Python 2.6, you can also set the table to None, and use deletechars to delete the characters you don't want as in the examples shown in the standard docs at http://docs.python.org/library/stdtypes.html.

With unicode strings, the translation table is not a 256-character string but a dict with the ord() of relevant characters as keys. But anyway getting a proper ascii string from a unicode string is simple enough, using the method mentioned by truppo above, namely : unicode_string.encode("ascii", "ignore")

As a summary, if for some reason you absolutely need to get an ascii string (for instance, when you raise a standard exception with raise Exception, ascii_message ), you can use the following function:

trans_table = ''.join( [chr(i) for i in range(128)] + ['?'] * 128 )
def ascii(s):
    if isinstance(s, unicode):
        return s.encode('ascii', 'replace')
    else:
        return s.translate(trans_table)

The good thing with translate is that you can actually convert accented characters to relevant non-accented ascii characters instead of simply deleting them or replacing them by '?'. This is often useful, for instance for indexing purposes.

How to set opacity in parent div and not affect in child div?

I know this is old, but just in case it will help someone else.

<div style="background-color: rgba(255, 0, 0, 0.5)">child</div> 

Where rgba is: red, green, blue, and a is for transparency.

How do I purge a linux mail box with huge number of emails?

Just use:

mail
d 1-15
quit

Which will delete all messages between number 1 and 15. to delete all, use the d *.

I just used this myself on ubuntu 12.04.4, and it worked like a charm.

For example:

eric@dev ~ $ mail
Heirloom Mail version 12.4 7/29/08.  Type ? for help.
"/var/spool/mail/eric": 2 messages 2 new
>N  1 Cron Daemon           Tue Jul 29 17:43  23/1016  "Cron <eric@ip-10-0-1-51> /usr/bin/php /var/www/sandbox/eric/c"
 N  2 Cron Daemon           Tue Jul 29 17:44  23/1016  "Cron <eric@ip-10-0-1-51> /usr/bin/php /var/www/sandbox/eric/c"
& d *
& quit

Then check your mail again:

eric@dev ~ $ mail
No mail for eric
eric@dev ~ $

What is tripping you up is you are using x or exit to quit which rolls back the changes during that session.

Qt jpg image display

If the only thing you want to do is drop in an image onto a widget withouth the complexity of the graphics API, you can also just create a new QWidget and set the background with StyleSheets. Something like this:

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    ...
    QWidget *pic = new QWidget(this);
    pic->setStyleSheet("background-image: url(test.png)");
    pic->setGeometry(QRect(50,50,128,128));
    ...
}

json_encode sparse PHP array as JSON array, not JSON object

You are observing this behaviour because your array is not sequential - it has keys 0 and 2, but doesn't have 1 as a key.

Just having numeric indexes isn't enough. json_encode will only encode your PHP array as a JSON array if your PHP array is sequential - that is, if its keys are 0, 1, 2, 3, ...

You can reindex your array sequentially using the array_values function to get the behaviour you want. For example, the code below works successfully in your use case:

echo json_encode(array_values($input)).

IIS w3svc error

I have had this problem after a windows update. Windows Process Activation Service is dependent service for W3SVC. First, make sure that Windows Process Activation Service is running. In my case, it was not running and when I tried to run it manually, I got below error.

Windows Process Activation Service Error 2: The system cannot find the file specified

The issue seems to be, that windows adds an incorrect parameter to the WAS service startup parameters. I fixed the issue using the following steps:

  • Start regedit (just type it into start) Navigate to

  • HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\WAS\Parameters

  • Delete the NanoSetup variable. This variable is preventing WAS from starting

  • Start the WAS service using task manager

  • Now start the W3SVC service

  • You can now start your website in IIS again

I found above WPA service solution in this stack overflow thread.

HTTP 401 - what's an appropriate WWW-Authenticate header value?

No, you'll have to specify the authentication method to use (typically "Basic") and the authentication realm. See http://en.wikipedia.org/wiki/Basic_access_authentication for an example request and response.

You might also want to read RFC 2617 - HTTP Authentication: Basic and Digest Access Authentication.

Python read JSON file and modify

There is really quite a number of ways to do this and all of the above are in one way or another valid approaches... Let me add a straightforward proposition. So assuming your current existing json file looks is this....

{
     "name":"myname"
}

And you want to bring in this new json content (adding key "id")

{
     "id": "134",
     "name": "myname"
 }

My approach has always been to keep the code extremely readable with easily traceable logic. So first, we read the entire existing json file into memory, assuming you are very well aware of your json's existing key(s).

import json 

# first, get the absolute path to json file
PATH_TO_JSON = 'data.json' #  assuming same directory (but you can work your magic here with os.)

# read existing json to memory. you do this to preserve whatever existing data. 
with open(PATH_TO_JSON,'r') as jsonfile:
    json_content = json.load(jsonfile) # this is now in memory! you can use it outside 'open'

Next, we use the 'with open()' syntax again, with the 'w' option. 'w' is a write mode which lets us edit and write new information to the file. Here s the catch that works for us ::: any existing json with the same target write name will be erased automatically.

So what we can do now, is simply write to the same filename with the new data

# add the id key-value pair (rmbr that it already has the "name" key value)
json_content["id"] = "134"

with open(PATH_TO_JSON,'w') as jsonfile:
    json.dump(json_content, jsonfile, indent=4) # you decide the indentation level

And there you go! data.json should be good to go for an good old POST request

Linux shell sort file according to the second column?

If this is UNIX:

sort -k 2 file.txt

You can use multiple -k flags to sort on more than one column. For example, to sort by family name then first name as a tie breaker:

sort -k 2,2 -k 1,1 file.txt

Relevant options from "man sort":

-k, --key=POS1[,POS2]

start a key at POS1, end it at POS2 (origin 1)

POS is F[.C][OPTS], where F is the field number and C the character position in the field. OPTS is one or more single-letter ordering options, which override global ordering options for that key. If no key is given, use the entire line as the key.

-t, --field-separator=SEP

use SEP instead of non-blank to blank transition

Batch file FOR /f tokens

for /f "tokens=* delims= " %%f in (myfile) do

This reads a file line-by-line, removing leading spaces (thanks, jeb).

set line=%%f

sets then the line variable to the line just read and

call :procesToken

calls a subroutine that does something with the line

:processToken

is the start of the subroutine mentioned above.

for /f "tokens=1* delims=/" %%a in ("%line%") do

will then split the line at /, but stopping tokenization after the first token.

echo Got one token: %%a

will output that first token and

set line=%%b

will set the line variable to the rest of the line.

if not "%line%" == "" goto :processToken

And if line isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.

Hash string in c#

I think what you're looking for is not hashing but encryption. With hashing, you will not be able to retrieve the original filename from the "hash" variable. With encryption you can, and it is secure.

See AES in ASP.NET with VB.NET for more information about encryption in .NET.

How to set adaptive learning rate for GradientDescentOptimizer?

Tensorflow provides an op to automatically apply an exponential decay to a learning rate tensor: tf.train.exponential_decay. For an example of it in use, see this line in the MNIST convolutional model example. Then use @mrry's suggestion above to supply this variable as the learning_rate parameter to your optimizer of choice.

The key excerpt to look at is:

# Optimizer: set up a variable that's incremented once per batch and
# controls the learning rate decay.
batch = tf.Variable(0)

learning_rate = tf.train.exponential_decay(
  0.01,                # Base learning rate.
  batch * BATCH_SIZE,  # Current index into the dataset.
  train_size,          # Decay step.
  0.95,                # Decay rate.
  staircase=True)
# Use simple momentum for the optimization.
optimizer = tf.train.MomentumOptimizer(learning_rate,
                                     0.9).minimize(loss,
                                                   global_step=batch)

Note the global_step=batch parameter to minimize. That tells the optimizer to helpfully increment the 'batch' parameter for you every time it trains.

How to remove symbols from a string with Python?

I often just open the console and look for the solution in the objects methods. Quite often it's already there:

>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello   s'

Short answer: Use string.replace().

using "if" and "else" Stored Procedures MySQL

I think that this construct: if exists (select... is specific for MS SQL. In MySQL EXISTS predicate tells you whether the subquery finds any rows and it's used like this: SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);

You can rewrite the above lines of code like this:

DELIMITER $$

CREATE PROCEDURE `checando`(in nombrecillo varchar(30), in contrilla varchar(30), out resultado int)

BEGIN
    DECLARE count_prim INT;
    DECLARE count_sec INT;

    SELECT COUNT(*) INTO count_prim FROM compas WHERE nombre = nombrecillo AND contrasenia = contrilla;
    SELECT COUNT(*) INTO count_sec FROM FROM compas WHERE nombre = nombrecillo;

    if (count_prim > 0) then
        set resultado = 0;
    elseif (count_sec > 0) then
        set resultado = -1;
    else 
        set resultado = -2;
    end if;
    SELECT resultado;
END

Change value of input and submit form in JavaScript

You're trying to access an element based on the name attribute which works for postbacks to the server, but JavaScript responds to the id attribute. Add an id with the same value as name and all should work fine.

<form name="myform" id="myform" action="action.php">
  <input type="hidden" name="myinput" id="myinput" value="0" />
  <input type="text" name="message" id="message" value="" />
  <input type="submit" name="submit" id="submit" onclick="DoSubmit()" />
</form>

function DoSubmit(){
  document.getElementById("myinput").value = '1';
  return true;
}

How to completely uninstall python 2.7.13 on Ubuntu 16.04

caution : It is not recommended to remove the default Python from Ubuntu, it may cause GDM(Graphical Display Manager, that provide graphical login capabilities) failed.

To completely uninstall Python2.x.x and everything depends on it. use this command:

sudo apt purge python2.x-minimal

As there are still a lot of packages that depend on Python2.x.x. So you should have a close look at the packages that apt wants to remove before you let it proceed.

Thanks, I hope it will be helpful for you.

HTTP Status 500 - Error instantiating servlet class pkg.coreServlet

I had an issue with Servlet instantiation. I cleaned the project and it worked for me. In eclipse menu, Go to Project->Clean. It should work.

Tomcat is not running even though JAVA_HOME path is correct

Remove the 'bin' from JAVA_HOME. That solves the issue.

SQL: Return "true" if list of records exists?

You can use a SELECT CASE statement like so:

select case when EXISTS (
 select 1 
 from <table>
 where <condition>
 ) then TRUE else FALSE end

It returns TRUE when your query in the parents exists.

Rounding to two decimal places in Python 2.7?

print "financial return of outcome 1 = $%.2f" % (out1)

Android sqlite how to check if a record exists

Here's a simple solution based on a combination of what dipali and Piyush Gupta posted:

  public boolean dbHasData(String searchTable, String searchColumn, String searchKey) {
    String query = "Select * from " + searchTable + " where " + searchColumn + " = ?";
    return getReadableDatabase().rawQuery(query, new String[]{searchKey}).moveToFirst();
  }

Declaring variables in Excel Cells

You can use (hidden) cells as variables. E.g., you could hide Column C, set C1 to

=20

and use it as

=c1*20

Alternatively you can write VBA Macros which set and read a global variable.

Edit: AKX renders my Answer partially incorrect. I had no idea you could name cells in Excel.

javascript compare strings without being case sensitive

You can make both arguments lower case, and that way you will always end up with a case insensitive search.

var string1 = "aBc";
var string2 = "AbC";

if (string1.toLowerCase() === string2.toLowerCase())
{
    #stuff
}

Automatic confirmation of deletion in powershell

The default is: no prompt.

You can enable it with -Confirm or disable it with -Confirm:$false

However, it will still prompt, when the target:

  • is a directory
  • and it is not empty
  • and the -Recurse parameter is not specified.

-Force is required to also remove hidden and read-only items etc.

To sum it up:

Remove-Item -Recurse -Force -Confirm:$false

...should cover all scenarios.

Create a Path from String in Java7

If possible I would suggest creating the Path directly from the path elements:

Path path = Paths.get("C:", "dir1", "dir2", "dir3");
// if needed
String textPath = path.toString(); // "C:\\dir1\\dir2\\dir3"

Use Excel pivot table as data source for another Pivot Table

I guess your end goal is to show Distinct (unique) values inside your original Pivot table.

For example you could have data set with OrderNumber, OrderDate, OrderItem, orderQty

First pivot table will show you OrderDate and sum of OrderQty and you probably want to see Count of unique orders in the same Pivot. You woudln't be able to do so within standard pivot table

If you want to do it, you would need Office 2016 (or perhaps pover Pivot might work). In office 2016 select your data > Insert > Pivot Table > choose tick "Add this data to the Data Model"

After that, you would be able to select grouping method as Distinct (Count)

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Use Encoding.Convert to adjust the byte array before attempting to decode it into your destination encoding.

Encoding iso = Encoding.GetEncoding("ISO-8859-1");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(Message);
byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);
string msg = iso.GetString(isoBytes);

Compiler error: "class, interface, or enum expected"

the main method should be declared in the your class like this :

public class derivativeQuiz_source{
    // bunch of methods .....

    public static void main(String args[])
    {
        // code 
    }
}