Programs & Examples On #Archetypes

Archetypes is a framework designed to ease the building of applications for Plone and CMF. Its main goal is to provide a standardized way to build content objects based on schema definitions

Maven 3 Archetype for Project With Spring, Spring MVC, Hibernate, JPA

Possible duplicate: Is there a maven 2 archetype for spring 3 MVC applications?

That said, I would encourage you to think about making your own archetype. The reason is, no matter what you end up getting from someone else's, you can do better in not that much time, and a decent sized Java project is going to end up making a lot of jar projects.

How do I add indices to MySQL tables?

ALTER TABLE `table` ADD INDEX `product_id_index` (`product_id`)

Never compare integer to strings in MySQL. If id is int, remove the quotes.

Static class initializer in PHP

Note - the RFC proposing this is still in the draft state.


class Singleton
{
    private static function __static()
    {
        //...
    }
    //...
}

proposed for PHP 7.x (see https://wiki.php.net/rfc/static_class_constructor )

How to set width of a div in percent in JavaScript?

document.getElementById('header').style.width = '50%';

If you are using Firebug or the Chrome/Safari Developer tools, execute the above in the console, and you'll see the Stack Overflow header shrink by 50%.

Android Material: Status bar color won't change

I know this doesn't answer the question, but with Material Design (API 21+) we can change the color of the status bar by adding this line in the theme declaration in styles.xml:

<!-- MAIN THEME -->
<style name="AppTheme" parent="@android:style/Theme.Material.Light">
    <item name="android:actionBarStyle">@style/actionBarCustomization</item>
    <item name="android:spinnerDropDownItemStyle">@style/mySpinnerDropDownItemStyle</item>
    <item name="android:spinnerItemStyle">@style/mySpinnerItemStyle</item>
    <item name="android:colorButtonNormal">@color/myDarkBlue</item>
    <item name="android:statusBarColor">@color/black</item>
</style>

Notice the android:statusBarColor, where we can define the color, otherwise the default is used.

Converting Go struct to JSON

You need to export the User.name field so that the json package can see it. Rename the name field to Name.

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    Name string
}

func main() {
    user := &User{Name: "Frank"}
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}

Output:

{"Name":"Frank"}

Tomcat: LifecycleException when deploying

I got this error when there was no enough space in server. check logs and server spaces

How do I exclude all instances of a transitive dependency when using Gradle?

In addition to what @berguiga-mohamed-amine stated, I just found that a wildcard requires leaving the module argument the empty string:

compile ("com.github.jsonld-java:jsonld-java:$jsonldJavaVersion") {
    exclude group: 'org.apache.httpcomponents', module: ''
    exclude group: 'org.slf4j', module: ''
}

Split string into string array of single characters

Most likely you're looking for the ToCharArray() method. However, you will need to do slightly more work if a string[] is required, as you noted in your post.

    string str = "this is a test.";
    char[] charArray = str.ToCharArray();
    string[] strArray = str.Select(x => x.ToString()).ToArray();

Edit: If you're worried about the conciseness of the conversion, I suggest you make it into an extension method.

public static class StringExtensions
{
    public static string[] ToStringArray(this string s)
    {
        if (string.IsNullOrEmpty(s))
            return null;

        return s.Select(x => x.ToString()).ToArray();
    }
} 

How to display a loading screen while site content loads

Typically sites that do this by loading content via ajax and listening to the readystatechanged event to update the DOM with a loading GIF or the content.

How are you currently loading your content?

The code would be similar to this:

function load(url) {
    // display loading image here...
    document.getElementById('loadingImg').visible = true;
    // request your data...
    var req = new XMLHttpRequest();
    req.open("POST", url, true);

    req.onreadystatechange = function () {
        if (req.readyState == 4 && req.status == 200) {
            // content is loaded...hide the gif and display the content...
            if (req.responseText) {
                document.getElementById('content').innerHTML = req.responseText;
                document.getElementById('loadingImg').visible = false;
            }
        }
    };
    request.send(vars);
}

There are plenty of 3rd party javascript libraries that may make your life easier, but the above is really all you need.

How to force a html5 form validation without submitting it via jQuery

Here is a more general way that is a bit cleaner:

Create your form like this (can be a dummy form that does nothing):

<form class="validateDontSubmit">
...

Bind all forms that you dont really want to submit:

$(document).on('submit','.validateDontSubmit',function (e) {
    //prevent the form from doing a submit
    e.preventDefault();
    return false;
})

Now lets say you have an <a> (within the <form>) that on click you want to validate the form:

$('#myLink').click(function(e){
  //Leverage the HTML5 validation w/ ajax. Have to submit to get em. Wont actually submit cuz form
  //has .validateDontSubmit class
  var $theForm = $(this).closest('form');
  //Some browsers don't implement checkValidity
  if (( typeof($theForm[0].checkValidity) == "function" ) && !$theForm[0].checkValidity()) {
     return;
  }

  //if you've gotten here - play on playa'
});

Few notes here:

  • I have noticed that you don't have to actually submit the form for validation to occur - the call to checkValidity() is enough (at least in chrome). If others could add comments with testing this theory on other browsers I'll update this answer.
  • The thing that triggers the validation does not have to be within the <form>. This was just a clean and flexible way to have a general purpose solution..

how to open .mat file without using MATLAB?

There's a really nice easy way to do this in Macintosh OsX. A fellow has made a quicklook plugin (command-space) that renders .mat formats so you can view the variables inside etc. Quite useful! https://github.com/jaketmp/matlab-quicklook/releases

HTML Table cell background image alignment

This works in IE9 (Compatibility View and Normal Mode), Firefox 17, and Chrome 23:

<table>
    <tr>
        <td style="background-image:url(untitled.png); background-position:right 0px; background-repeat:no-repeat;">
            Hello World
        </td>
    </tr>
</table>

req.body empty on posts

My problem was creating the route first require("./routes/routes")(app); I shifted it to the end of the code before app.listen and it worked!

How to prevent downloading images and video files from my website?

It also doesn't hurt to watermark your images with Photoshop or even in Lightroom 3 now. Make sure the watermark is clear and in a conspicuous place on your image. That way if it's downloaded, at least you get the advertising!

Dependency Injection vs Factory Pattern

With a factory you can group related interfaces, So If the parameters passed can be grouped in a factory then its also a good solution for constructor overinjection look at this code *):

public AddressModelFactory(IAddressAttributeService addressAttributeService,
        IAddressAttributeParser addressAttributeParser,
        ILocalizationService localizationService,
        IStateProvinceService stateProvinceService,
        IAddressAttributeFormatter addressAttributeFormatter)
    {
        this._addressAttributeService = addressAttributeService;
        this._addressAttributeParser = addressAttributeParser;
        this._localizationService = localizationService;
        this._stateProvinceService = stateProvinceService;
        this._addressAttributeFormatter = addressAttributeFormatter;
    }

Look at the constructor, you only have to pass the IAddressModelFactory there, so less parameters *):

 public CustomerController(IAddressModelFactory addressModelFactory,
        ICustomerModelFactory customerModelFactory,
        IAuthenticationService authenticationService,
        DateTimeSettings dateTimeSettings,
        TaxSettings taxSettings,
        ILocalizationService localizationService,
        IWorkContext workContext,
        IStoreContext storeContext,
        ICustomerService customerService,
        ICustomerAttributeParser customerAttributeParser,
        ICustomerAttributeService customerAttributeService,
        IGenericAttributeService genericAttributeService,
        ICustomerRegistrationService customerRegistrationService,
        ITaxService taxService,
        CustomerSettings customerSettings,
        AddressSettings addressSettings,...

You see in CustomerController a lot of parameters passed, Yes you can see this as constructor overinjection but this is how DI works. And no nothing is wrong with the CustomerController.

*) Code is from nopCommerce.

scale Image in an UIButton to AspectFit?

If you really want to scale an image, do it, but you should resize it before using it. Resizing it at run time will just lose CPU cycles.

This is the category I'm using to scale an image :

UIImage+Extra.h

@interface UIImage (Extras)
- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize;
@end;

UIImage+Extra.m

@implementation UIImage (Extras)

- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {

UIImage *sourceImage = self;
UIImage *newImage = nil;

CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;

CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;

CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;

CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

if (!CGSizeEqualToSize(imageSize, targetSize)) {

        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;

        if (widthFactor < heightFactor) 
                scaleFactor = widthFactor;
        else
                scaleFactor = heightFactor;

        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;

        // center the image

        if (widthFactor < heightFactor) {
                thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 
        } else if (widthFactor > heightFactor) {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
}


// this is actually the interesting part:

UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0);

CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width  = scaledWidth;
thumbnailRect.size.height = scaledHeight;

[sourceImage drawInRect:thumbnailRect];

newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

if(newImage == nil) NSLog(@"could not scale image");


return newImage ;
}

@end

You can use it to the size you want. Like :

[self.itemImageButton setImage:[stretchImage imageByScalingProportionallyToSize:CGSizeMake(20,20)]];

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

In order to use a CLR 2.0 mixed mode assembly, you need to modify your App.Config file to include:

<?xml version="1.0"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>

The key is the useLegacyV2RuntimeActivationPolicy flag. This causes the CLR to use the latest version (4.0) to load your mixed mode assembly. Without this, it will not work.

Note that this only matters for mixed mode (C++/CLI) assemblies. You can load all managed CLR 2 assemblies without specifying this in app.config.

Change user-agent for Selenium web-driver

There is no way in Selenium to read the request or response headers. You could do it by instructing your browser to connect through a proxy that records this kind of information.

Setting the User Agent in Firefox

The usual way to change the user agent for Firefox is to set the variable "general.useragent.override" in your Firefox profile. Note that this is independent from Selenium.

You can direct Selenium to use a profile different from the default one, like this:

from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", "whatever you want")
driver = webdriver.Firefox(profile)

Setting the User Agent in Chrome

With Chrome, what you want to do is use the user-agent command line option. Again, this is not a Selenium thing. You can invoke Chrome at the command line with chrome --user-agent=foo to set the agent to the value foo.

With Selenium you set it like this:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
opts = Options()
opts.add_argument("user-agent=whatever you want")

driver = webdriver.Chrome(chrome_options=opts)

Both methods above were tested and found to work. I don't know about other browsers.

Getting the User Agent

Selenium does not have methods to query the user agent from an instance of WebDriver. Even in the case of Firefox, you cannot discover the default user agent by checking what general.useragent.override would be if not set to a custom value. (This setting does not exist before it is set to some value.)

Once the browser is started, however, you can get the user agent by executing:

agent = driver.execute_script("return navigator.userAgent")

The agent variable will contain the user agent.

Submit form using AJAX and jQuery

There is a nice form plugin that allows you to send an HTML form asynchroniously.

$(document).ready(function() { 
    $('#myForm1').ajaxForm(); 
});

or

$("select").change(function(){
    $('#myForm1').ajaxSubmit();
});

to submit the form immediately

Count the number of all words in a string

require(stringr)

Define a very simple function

str_words <- function(sentence) {

  str_count(sentence, " ") + 1

}

Check

str_words(This is a sentence with six words)

how to call url of any other website in php

If you meant .. to REDIRECT from that page to another, the function is really simple

header("Location:www.google.com");

crop text too long inside div

You can use:

overflow:hidden;

to hide the text outside the zone.

Note that it may cut the last letter (so a part of the last letter will still be displayed). A nicer way is to display an ellipsis at the end. You can do it by using text-overflow:

overflow: hidden;
white-space: nowrap; /* Don't forget this one */
text-overflow: ellipsis;

How to select from subquery using Laravel Query Builder?

Laravel v5.6.12 (2018-03-14) added fromSub() and fromRaw() methods to query builder (#23476).

The accepted answer is correct but can be simplified into:

DB::query()->fromSub(function ($query) {
    $query->from('abc')->groupBy('col1');
}, 'a')->count();

The above snippet produces the following SQL:

select count(*) as aggregate from (select * from `abc` group by `col1`) as `a`

Determine the process pid listening on a certain port

on windows, the netstat option to get the pid's is -o and -p selects a protocol filter, ex.: netstat -a -p tcp -o

Limit the length of a string with AngularJS

Here is the simple one line fix without css.

{{ myString | limitTo: 20 }}{{myString.length > 20 ? '...' : ''}}

How to handle onchange event on input type=file in jQuery?

It should work fine, are you wrapping the code in a $(document).ready() call? If not use that or use live i.e.

$('#fileupload1').live('change', function(){ 
    alert("hola");
});

Here is a jsFiddle of this working against jQuery 1.4.4

Can I have a video with transparent background using HTML5 video tag?

Update: Webm with an alpha channel is now supported in Chrome and Firefox.

For other browers, there are workarounds, but they involve re-rendering the video using Canvas and it is kind of a hack. seeThru is one example. It works pretty well on HTML5 desktop browsers (even IE9) but it doesn't seem to work very well on mobile. I couldn't get it to work at all on Chrome for Android. It did work on Firefox for Android but with a pretty lousy framerate. I think you might be out of luck for mobile, although I'd love to be proven wrong.

How can I manually generate a .pyc file from a .py file

You can use compileall in the terminal. The following command will go recursively into sub directories and make pyc files for all the python files it finds. The compileall module is part of the python standard library, so you don't need to install anything extra to use it. This works exactly the same way for python2 and python3.

python -m compileall .

Break string into list of characters in Python

You can do this using list:

new_list = list(fL)

Be aware that any spaces in the line will be included in this list, to the best of my knowledge.

How to highlight text using javascript

Simple TypeScript example

NOTE: While I agree with @Stefan in many things, I only needed a simple match highlighting:

module myApp.Search {
    'use strict';

    export class Utils {
        private static regexFlags = 'gi';
        private static wrapper = 'mark';

        private static wrap(match: string): string {
            return '<' + Utils.wrapper + '>' + match + '</' + Utils.wrapper + '>';
        }

        static highlightSearchTerm(term: string, searchResult: string): string {
            let regex = new RegExp(term, Utils.regexFlags);

            return searchResult.replace(regex, match => Utils.wrap(match));
        }
    }
}

And then constructing the actual result:

module myApp.Search {
    'use strict';

    export class SearchResult {
        id: string;
        title: string;

        constructor(result, term?: string) {
            this.id = result.id;
            this.title = term ? Utils.highlightSearchTerm(term, result.title) : result.title;
        }
    }
}

Trigger standard HTML5 validation (form) without using submit button?

I know it is an old topic, but when there is a very complex (especially asynchronous) validation process, there is a simple workaround:

<form id="form1">
<input type="button" onclick="javascript:submitIfVeryComplexValidationIsOk()" />
<input type="submit" id="form1_submit_hidden" style="display:none" />
</form>
...
<script>
function submitIfVeryComplexValidationIsOk() {
    var form1 = document.forms['form1']
    if (!form1.checkValidity()) {
        $("#form1_submit_hidden").click()
        return
    }

    if (checkForVeryComplexValidation() === 'Ok') {
         form1.submit()
    } else {
         alert('form is invalid')
    }
}
</script>

How to use pagination on HTML tables?

With Reference to Anusree answer above and with respect,I am tweeking the code little bit to make sure it works in most of the cases.

  1. Created a reusable function paginate('#myTableId') which can be called any number times for any table.
  2. Adding code inside ajaxComplete function to make sure paging is called once table using jquery is completely loaded. We use paging mostly for ajax based tables.
  3. Remove Pagination div and rebind on every pagination call
  4. Configuring Number of rows per page

Code:

$(document).ready(function () {
    $(document).ajaxComplete(function () {
        paginate('#myTableId',10);
        function paginate(tableName,RecordsPerPage) {
            $('#nav').remove();
            $(tableName).after('<div id="nav"></div>');
            var rowsShown = RecordsPerPage;
            var rowsTotal = $(tableName + ' tbody tr').length;
            var numPages = rowsTotal / rowsShown;
            for (i = 0; i < numPages; i++) {
                var pageNum = i + 1;
                $('#nav').append('<a href="#" rel="' + i + '">' + pageNum + '</a> ');
            }
            $(tableName + ' tbody tr').hide();
            $(tableName + ' tbody tr').slice(0, rowsShown).show();
            $('#nav a:first').addClass('active');
            $('#nav a').bind('click', function () {

                $('#nav a').removeClass('active');
                $(this).addClass('active');
                var currPage = $(this).attr('rel');
                var startItem = currPage * rowsShown;
                var endItem = startItem + rowsShown;
                $(tableName + ' tbody tr').css('opacity', '0.0').hide().slice(startItem, endItem).
                    css('display', 'table-row').animate({ opacity: 1 }, 300);
            });
        }
    });
});

XAMPP Port 80 in use by "Unable to open process" with PID 4

So I have faced the same problem when trying to start apache service and I would like to share my solutions with you. Here is some notes about services or programs that may use port 80:

  1. Skype: skype uses port 80/443 by default. You can change this from tools->options-> advanced->connections and disable checkbox "use port 80 and 443 for addtional incoming connections".
  2. IIS: IIS uses port 80 be default so you need to shut down it. You can use the following two commands net stop w3svc net stop iisadmin
  3. SQL Server Reporting Service: You need to stop this service because it may take port 80 if IIS is not running. Go to local services and stop it.

These options work great with me and I can start apache service without errors.

The other option is to change apache listen port from httpd.conf and set another port number.

Hope this solution helps anyone who face the same problem again.

Getting user input

Use the following simple way to interactively get user data by a prompt as Arguments on what you want.

Version : Python 3.X

name = input('Enter Your Name: ')
print('Hello ', name)

How to pass a URI to an intent?

you can store the uri as string

intent.putExtra("imageUri", imageUri.toString());

and then just convert the string back to uri like this

Uri myUri = Uri.parse(extras.getString("imageUri"));

TypeScript function overloading

Function overloading in typescript:

According to Wikipedia, (and many programming books) the definition of method/function overloading is the following:

In some programming languages, function overloading or method overloading is the ability to create multiple functions of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context.

In typescript we cannot have different implementations of the same function that are called according to the number and type of arguments. This is because when TS is compiled to JS, the functions in JS have the following characteristics:

  • JavaScript function definitions do not specify data types for their parameters
  • JavaScript functions do not check the number of arguments when called

Therefore, in a strict sense, one could argue that TS function overloading doesn't exists. However, there are things you can do within your TS code that can perfectly mimick function overloading.

Here is an example:

function add(a: number, b: number, c: number): number;
function add(a: number, b: number): any;
function add(a: string, b: string): any;

function add(a: any, b: any, c?: any): any {
  if (c) {
    return a + c;
  }
  if (typeof a === 'string') {
    return `a is ${a}, b is ${b}`;
  } else {
    return a + b;
  }
}

The TS docs call this method overloading, and what we basically did is supplying multiple method signatures (descriptions of possible parameters and types) to the TS compiler. Now TS can figure out if we called our function correctly during compile time and give us an error if we called the function incorrectly.

Get current value when change select option - Angular2

Template:

<select class="randomClass" id="randomId" (change) = 
"filterSelected($event.target.value)">

<option *ngFor = 'let type of filterTypes' [value]='type.value'>{{type.display}} 
</option>

</select>

Component:

public filterTypes = [{
  value : 'New', display : 'Open'
},
{
  value : 'Closed', display : 'Closed'
}]


filterSelected(selectedValue:string){
  console.log('selected value= '+selectedValue)

}

Converting a double to an int in C#

you can round your double and cast ist:

(int)Math.Round(myDouble);

Styling input radio with css

You should use some background image to your radio buttons and flip it with another image on change

.radio {
    background: url(customButton.png) no-repeat;
}

Checking if a number is a prime number in Python

This is the most efficient way to see if a number is prime, if you only have a few query. If you ask a lot of numbers if they are prime try Sieve of Eratosthenes.

import math

def is_prime(n):
    if n == 2:
        return True
    if n % 2 == 0 or n <= 1:
        return False

    sqr = int(math.sqrt(n)) + 1

    for divisor in range(3, sqr, 2):
        if n % divisor == 0:
            return False
    return True

How can I fix the Microsoft Visual Studio error: "package did not load correctly"?

I also experienced this issue after installing Telerik Reporting. I was not able to launch any solution in Visual Studio 2013, nor could I close Visual Studio 2013.

After uninstalling the reporting package and deleting Local / Roaming AppData for Visual Studio 2012, the problem was fixed.

installing vmware tools: location of GCC binary?

Install prerequisites VMware Tools for LinuxOS:

If you have RHEL/CentOS:

yum install perl gcc make kernel-headers kernel-devel -y

If you have Ubuntu/Debian:

sudo apt-get -y install linux-headers-server build-essential
  • build-essential, also install: dpkg-dev, g++, gcc, lib6-dev, libc-dev, make

Extracted from: http://www.sysadmit.com/2016/01/vmware-tools-linux-instalar-requisitos.html

Python error: AttributeError: 'module' object has no attribute

My solution is put those imports in __init__.py of lib:

in file: __init__.py
import mod1

Then,

import lib
lib.mod1

would work fine.

Make a URL-encoded POST request using `http.NewRequest(...)`

URL-encoded payload must be provided on the body parameter of the http.NewRequest(method, urlStr string, body io.Reader) method, as a type that implements io.Reader interface.

Based on the sample code:

package main

import (
    "fmt"
    "net/http"
    "net/url"
    "strconv"
    "strings"
)

func main() {
    apiUrl := "https://api.com"
    resource := "/user/"
    data := url.Values{}
    data.Set("name", "foo")
    data.Set("surname", "bar")

    u, _ := url.ParseRequestURI(apiUrl)
    u.Path = resource
    urlStr := u.String() // "https://api.com/user/"

    client := &http.Client{}
    r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
    r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

    resp, _ := client.Do(r)
    fmt.Println(resp.Status)
}

resp.Status is 200 OK this way.

Invoking JavaScript code in an iframe from the parent page

The IFRAME should be in the frames[] collection. Use something like

frames['iframeid'].method();

Creating a JSON dynamically with each input value using jquery

May be this will help, I'd prefer pure JS wherever possible, it improves the performance drastically as you won't have lots of JQuery function calls.

var obj = [];
var elems = $("input[class=email]");

for (i = 0; i < elems.length; i += 1) {
    var id = this.getAttribute('title');
    var email = this.value;
    tmp = {
        'title': id,
        'email': email
    };

    obj.push(tmp);
}

Insert an item into sorted list in Python

I'm learning Algorithm right now, so i wonder how bisect module writes. Here is the code from bisect module about inserting an item into sorted list, which uses dichotomy:

def insort_right(a, x, lo=0, hi=None):
    """Insert item x in list a, and keep it sorted assuming a is sorted.
    If x is already in a, insert it to the right of the rightmost x.
    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.
    """

    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if x < a[mid]:
            hi = mid
        else:
            lo = mid+1
    a.insert(lo, x)

MySql: Tinyint (2) vs tinyint(1) - what is the difference?

mysql> CREATE TABLE tin3(id int PRIMARY KEY,val TINYINT(10) ZEROFILL);
Query OK, 0 rows affected (0.04 sec)

mysql> INSERT INTO tin3 VALUES(1,12),(2,7),(4,101);
Query OK, 3 rows affected (0.02 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM tin3;
+----+------------+
| id | val        |
+----+------------+
|  1 | 0000000012 |
|  2 | 0000000007 |
|  4 | 0000000101 |
+----+------------+
3 rows in set (0.00 sec)

mysql>

mysql> SELECT LENGTH(val) FROM tin3 WHERE id=2;
+-------------+
| LENGTH(val) |
+-------------+
|          10 |
+-------------+
1 row in set (0.01 sec)


mysql> SELECT val+1 FROM tin3 WHERE id=2;
+-------+
| val+1 |
+-------+
|     8 |
+-------+
1 row in set (0.00 sec)

How to do a LIKE query with linq?

2019 is here:

Requires EF6

using System.Data.Entity;
string searchStr ="bla bla bla";
var result = _dbContext.SomeTable.Where(x=> DbFunctions.Like(x.NameAr, string.Format("%{0}%", searchStr ))).FirstOrDefault();

TypeScript: Interfaces vs Types

the documentation has explained

  • One difference is that interfaces create a new name that is used everywhere. Type aliases don’t create a new name — for instance, error messages won’t use the alias name.in older versions of TypeScript, type aliases couldn’t be extended or implemented from (nor could they extend/implement other types). As of version 2.7, type aliases can be extended by creating a new intersection type
  • On the other hand, if you can’t express some shape with an interface and you need to use a union or tuple type, type aliases are usually the way to go.

Interfaces vs. Type Aliases

Do Java arrays have a maximum size?

There are actually two limits. One, the maximum element indexable for the array and, two, the amount of memory available to your application. Depending on the amount of memory available and the amount used by other data structures, you may hit the memory limit before you reach the maximum addressable array element.

Bash script - variable content as a command to run

line=$((${RANDOM} % $(wc -l < /etc/passwd)))
sed -n "${line}p" /etc/passwd

just with your file instead.

In this example I used the file /etc/password, using the special variable ${RANDOM} (about which I learned here), and the sed expression you had, only difference is that I am using double quotes instead of single to allow the variable expansion.

Can I run multiple versions of Google Chrome on the same machine? (Mac or Windows)

I adopted @RobW's nice answer to get it working on Mac OS X 10.8. Other versions of Mac OS X may probably work too.

The little extra work is actually only needed to keep your original Google Chrome user settings and the old version separated.

  1. Download another version of Google Chrome, like the Dev channel and extract the .app file

  2. (optional) Rename it to Google Chrome X.app – if not already different from Google Chrome.app

(Be sure to replace X for all following steps with the actual version of Chrome you just downloaded)

  1. Move Google Chrome X.app to /Applications without overwritting your current Chrome

  2. Open the Terminal, create a shell script and make your script executable:

    cd /Applications
    touch google-chrome-version-start.sh
    chmod +x google-chrome-version-start.sh
    nano google-chrome-version-start.sh
    
  3. Modify the following code according to the version you downloaded and paste it into the script

    #!/usr/bin/env bash
    /Applications/Google\ Chrome\ X.app/Contents/MacOS/Google\ Chrome\ X --user-data-dir="tmp/Google Chrome/X/" & disown
    

    For example for Dev Channel:

    #!/usr/bin/env bash
    /Applications/Google\ Chrome\ Dev.app/Contents/MacOS/Google\ Chrome\ Dev --user-data-dir="tmp/Google Chrome Dev/" & disown
    

    (This will store Chrome's data at ~/tmp/Google Chrome/VERSION/. For more explanations see the original answer.)

  4. Now execute the script and be happy!

    /Application/google-chrome-version-start.sh
    

Tested it with Google Chrome 88 on a Mac running OS X 10.15 Catalina

var functionName = function() {} vs function functionName() {}

About performance:

New versions of V8 introduced several under-the-hood optimizations and so did SpiderMonkey.

There is almost no difference now between expression and declaration.
Function expression appears to be faster now.

Chrome 62.0.3202 Chrome test

FireFox 55 Firefox test

Chrome Canary 63.0.3225 Chrome Canary test


Anonymous function expressions appear to have better performance against Named function expression.


Firefox Firefox named_anonymous Chrome Canary Chrome canary named_anonymous Chrome Chrome named_anonymous

Cannot load properties file from resources directory

Right click the Resources folder and select Build Path > Add to Build Path

Ruby: kind_of? vs. instance_of? vs. is_a?

It is more Ruby-like to ask objects whether they respond to a method you need or not, using respond_to?. This allows both minimal interface and implementation unaware programming.

It is not always applicable of course, thus there is still a possibility to ask about more conservative understanding of "type", which is class or a base class, using the methods you're asking about.

how to implement login auth in node.js

_x000D_
_x000D_
======authorization====== MIDDLEWARE_x000D_
_x000D_
const jwt = require('../helpers/jwt')_x000D_
const User = require('../models/user')_x000D_
_x000D_
module.exports = {_x000D_
  authentication: function(req, res, next) {_x000D_
    try {_x000D_
      const user = jwt.verifyToken(req.headers.token, process.env.JWT_KEY)_x000D_
      User.findOne({ email: user.email }).then(result => {_x000D_
        if (result) {_x000D_
          req.body.user = result_x000D_
          req.params.user = result_x000D_
          next()_x000D_
        } else {_x000D_
          throw new Error('User not found')_x000D_
        }_x000D_
      })_x000D_
    } catch (error) {_x000D_
      console.log('langsung dia masuk sini')_x000D_
_x000D_
      next(error)_x000D_
    }_x000D_
  },_x000D_
_x000D_
  adminOnly: function(req, res, next) {_x000D_
    let loginUser = req.body.user_x000D_
    if (loginUser && loginUser.role === 'admin') {_x000D_
      next()_x000D_
    } else {_x000D_
      next(new Error('Not Authorized'))_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
====error handler==== MIDDLEWARE_x000D_
const errorHelper = require('../helpers/errorHandling')_x000D_
_x000D_
module.exports = function(err, req, res, next) {_x000D_
  //   console.log(err)_x000D_
  let errorToSend = errorHelper(err)_x000D_
  // console.log(errorToSend)_x000D_
  res.status(errorToSend.statusCode).json(errorToSend)_x000D_
}_x000D_
_x000D_
_x000D_
====error handling==== HELPER_x000D_
var nodeError = ["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"]_x000D_
var mongooseError = ["MongooseError","DisconnectedError","DivergentArrayError","MissingSchemaError","DocumentNotFoundError","MissingSchemaError","ObjectExpectedError","ObjectParameterError","OverwriteModelError","ParallelSaveError","StrictModeError","VersionError"]_x000D_
var mongooseErrorFromClient = ["CastError","ValidatorError","ValidationError"];_x000D_
var jwtError = ["TokenExpiredError","JsonWebTokenError","NotBeforeError"]_x000D_
_x000D_
function nodeErrorMessage(message){_x000D_
    switch(message){_x000D_
        case "Token is undefined":{_x000D_
            return 403;_x000D_
        }_x000D_
        case "User not found":{_x000D_
            return 403;_x000D_
        }_x000D_
        case "Not Authorized":{_x000D_
            return 401;_x000D_
        }_x000D_
        case "Email is Invalid!":{_x000D_
            return 400;_x000D_
        }_x000D_
        case "Password is Invalid!":{_x000D_
            return 400;_x000D_
        }_x000D_
        case "Incorrect password for register as admin":{_x000D_
            return 400;_x000D_
        }_x000D_
        case "Item id not found":{_x000D_
            return 400;_x000D_
        }_x000D_
        case "Email or Password is invalid": {_x000D_
            return 400_x000D_
        }_x000D_
        default :{_x000D_
            return 500;_x000D_
        }_x000D_
    }_x000D_
}_x000D_
_x000D_
module.exports = function(errorObject){_x000D_
    // console.log("===ERROR OBJECT===")_x000D_
    // console.log(errorObject)_x000D_
    // console.log("===ERROR STACK===")_x000D_
    // console.log(errorObject.stack);_x000D_
_x000D_
    let statusCode = 500;  _x000D_
    let returnObj = {_x000D_
        error : errorObject_x000D_
    }_x000D_
    if(jwtError.includes(errorObject.name)){_x000D_
        statusCode = 403;_x000D_
        returnObj.message = "Token is Invalid"_x000D_
        returnObj.source = "jwt"_x000D_
    }_x000D_
    else if(nodeError.includes(errorObject.name)){_x000D_
        returnObj.error = JSON.parse(JSON.stringify(errorObject, ["message", "arguments", "type", "name"]))_x000D_
        returnObj.source = "node";_x000D_
        statusCode = nodeErrorMessage(errorObject.message);_x000D_
        returnObj.message = errorObject.message;_x000D_
    }else if(mongooseError.includes(errorObject.name)){_x000D_
        returnObj.source = "database"_x000D_
        returnObj.message = "Error from server"_x000D_
    }else if(mongooseErrorFromClient.includes(errorObject.name)){_x000D_
        returnObj.source = "database";_x000D_
        errorObject.message ? returnObj.message = errorObject.message : returnObj.message = "Bad Request"_x000D_
        statusCode = 400;_x000D_
    }else{_x000D_
        returnObj.source = "unknown error";_x000D_
        returnObj.message = "Something error";_x000D_
    }_x000D_
    returnObj.statusCode = statusCode;_x000D_
    _x000D_
    return returnObj;_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
===jwt====_x000D_
const jwt = require('jsonwebtoken')_x000D_
_x000D_
function generateToken(payload) {_x000D_
    let token = jwt.sign(payload, process.env.JWT_KEY)_x000D_
    return token_x000D_
}_x000D_
_x000D_
function verifyToken(token) {_x000D_
    let payload = jwt.verify(token, process.env.JWT_KEY)_x000D_
    return payload_x000D_
}_x000D_
_x000D_
module.exports = {_x000D_
    generateToken, verifyToken_x000D_
}_x000D_
_x000D_
===router index===_x000D_
const express = require('express')_x000D_
const router = express.Router()_x000D_
_x000D_
// router.get('/', )_x000D_
router.use('/users', require('./users'))_x000D_
router.use('/products', require('./product'))_x000D_
router.use('/transactions', require('./transaction'))_x000D_
_x000D_
module.exports = router_x000D_
_x000D_
====router user ====_x000D_
const express = require('express')_x000D_
const router = express.Router()_x000D_
const User = require('../controllers/userController')_x000D_
const auth = require('../middlewares/auth')_x000D_
_x000D_
/* GET users listing. */_x000D_
router.post('/register', User.register)_x000D_
router.post('/login', User.login)_x000D_
router.get('/', auth.authentication, User.getUser)_x000D_
router.post('/logout', auth.authentication, User.logout)_x000D_
module.exports = router_x000D_
_x000D_
_x000D_
====app====_x000D_
require('dotenv').config()_x000D_
const express = require('express')_x000D_
const cookieParser = require('cookie-parser')_x000D_
const logger = require('morgan')_x000D_
const cors = require('cors')_x000D_
const indexRouter = require('./routes/index')_x000D_
const errorHandler = require('./middlewares/errorHandler')_x000D_
const mongoose = require('mongoose')_x000D_
const app = express()_x000D_
_x000D_
mongoose.connect(process.env.DB_URI, {_x000D_
  useNewUrlParser: true,_x000D_
  useUnifiedTopology: true,_x000D_
  useCreateIndex: true,_x000D_
  useFindAndModify: false_x000D_
})_x000D_
_x000D_
app.use(cors())_x000D_
app.use(logger('dev'))_x000D_
app.use(express.json())_x000D_
app.use(express.urlencoded({ extended: false }))_x000D_
app.use(cookieParser())_x000D_
_x000D_
app.use('/', indexRouter)_x000D_
app.use(errorHandler)_x000D_
_x000D_
module.exports = app
_x000D_
_x000D_
_x000D_

Is there a way to specify how many characters of a string to print out using printf()?

In addition to specify a fixed amount of characters, you can also use * which means that printf takes the number of characters from an argument:

#include <stdio.h>

int main(int argc, char *argv[])
{
        const char hello[] = "Hello world";
        printf("message: '%.3s'\n", hello);
        printf("message: '%.*s'\n", 3, hello);
        printf("message: '%.*s'\n", 5, hello);
        return 0;
}

Prints:

message: 'Hel'
message: 'Hel'
message: 'Hello'

Can comments be used in JSON?

It depends on your JSON library. Json.NET supports JavaScript-style comments, /* commment */.

See another Stack Overflow question.

Create a hidden field in JavaScript

You can use jquery for create element on the fly

$('#form').append('<input type="hidden" name="fieldname" value="fieldvalue" />');

or other way

$('<input>').attr({
    type: 'hidden',
    id: 'fieldId',
    name: 'fieldname'
}).appendTo('form')

Java: splitting a comma-separated string but ignoring commas in quotes

Try:

public class Main { 
    public static void main(String[] args) {
        String line = "foo,bar,c;qual=\"baz,blurb\",d;junk=\"quux,syzygy\"";
        String[] tokens = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
        for(String t : tokens) {
            System.out.println("> "+t);
        }
    }
}

Output:

> foo
> bar
> c;qual="baz,blurb"
> d;junk="quux,syzygy"

In other words: split on the comma only if that comma has zero, or an even number of quotes ahead of it.

Or, a bit friendlier for the eyes:

public class Main { 
    public static void main(String[] args) {
        String line = "foo,bar,c;qual=\"baz,blurb\",d;junk=\"quux,syzygy\"";

        String otherThanQuote = " [^\"] ";
        String quotedString = String.format(" \" %s* \" ", otherThanQuote);
        String regex = String.format("(?x) "+ // enable comments, ignore white spaces
                ",                         "+ // match a comma
                "(?=                       "+ // start positive look ahead
                "  (?:                     "+ //   start non-capturing group 1
                "    %s*                   "+ //     match 'otherThanQuote' zero or more times
                "    %s                    "+ //     match 'quotedString'
                "  )*                      "+ //   end group 1 and repeat it zero or more times
                "  %s*                     "+ //   match 'otherThanQuote'
                "  $                       "+ // match the end of the string
                ")                         ", // stop positive look ahead
                otherThanQuote, quotedString, otherThanQuote);

        String[] tokens = line.split(regex, -1);
        for(String t : tokens) {
            System.out.println("> "+t);
        }
    }
}

which produces the same as the first example.

EDIT

As mentioned by @MikeFHay in the comments:

I prefer using Guava's Splitter, as it has saner defaults (see discussion above about empty matches being trimmed by String#split(), so I did:

Splitter.on(Pattern.compile(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"))

ReactJs: What should the PropTypes be for this.props.children?

If you want to match exactly a component type, check this

MenuPrimary.propTypes = {
  children: PropTypes.oneOfType([
    PropTypes.arrayOf(MenuPrimaryItem),
    PropTypes.objectOf(MenuPrimaryItem)
  ])
}

If you want to match exactly some component types, check this

const HeaderTypes = [
  PropTypes.objectOf(MenuPrimary),
  PropTypes.objectOf(UserInfo)
]

Header.propTypes = {
  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.oneOfType([...HeaderTypes])),
    ...HeaderTypes
  ])
}

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

How to expand textarea width to 100% of parent (or how to expand any HTML element to 100% of parent width)?

You need to define width of the div containing the textarea and when you declare textarea, you can then set .main > textarea to have width: inherit.

Note: .main > textarea means a <textarea> inside of an element with class="main".

Here is the working solution

The HTML:

<div class="wrapper">
  <div class="left">left</div>
  <div class="main">
    <textarea name="" cols="" rows=""></textarea>
  </div>
</div>

The CSS:

.wrapper {
  display: table;
  width: 100%;
}

.left {
  width: 20%;
  background: #cccccc;
  display: table-cell;
}

.main {
  width: 80%;
  background: gray;
  display: inline;
}

.main > textarea {
  width: inherit;
}

How to stop console from closing on exit?

Yes, in VS2010 they changed this behavior somewhy.
Open your project and navigate to the following menu: Project -> YourProjectName Properties -> Configuration Properties -> Linker -> System. There in the field SubSystem use the drop-down to select Console (/SUBSYSTEM:CONSOLE) and apply the change.
"Start without debugging" should do the right thing now.

Or, if you write in C++ or in C, put

system("pause");

at the end of your program, then you'll get "Press any key to continue..." even when running in debug mode.

What is the result of % in Python?

Be aware that

(3 +2 + 1 - 5) + (4 % 2) - (1/4) + 6

even with the brackets results in 6.75 instead of 7 if calculated in Python 3.4.


And the '/' operator is not that easy to understand, too (python2.7): try...

- 1/4

1 - 1/4

This is a bit off-topic here, but should be considered when evaluating the above expression :)

Bash: infinite sleep (infinite blocking)

sleep infinity looks most elegant, but sometimes it doesn't work for some reason. In that case, you can try other blocking commands such as cat, read, tail -f /dev/null, grep a etc.

PowerMockito mock single static method and return object

What you want to do is a combination of part of 1 and all of 2.

You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.

But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.

From the javadoc:

Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.

The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.

Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:

import static org.mockito.Mockito.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

class ClassWithStatics {
  public static String getString() {
    return "String";
  }

  public static int getInt() {
    return 1;
  }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
  @Test
  public void test() {
    PowerMockito.mockStatic(ClassWithStatics.class);

    when(ClassWithStatics.getString()).thenReturn("Hello!");

    System.out.println("String: " + ClassWithStatics.getString());
    System.out.println("Int: " + ClassWithStatics.getInt());
  }
}

The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.

CLEAR SCREEN - Oracle SQL Developer shortcut?

Use the following command to clear screen in sqlplus.

SQL > clear scr 

How do I import a namespace in Razor View Page?

For namespace and Library

@using NameSpace_Name

For Model

@model Application_Name.Models.Model_Name 

For Iterate the list on Razor Page (You Have to use foreach loop for access the list items)

@model List<Application_Name.Models.Model_Name>

@foreach (var item in Model)
   {  
          <tr>
                <td>@item.srno</td>
                <td>@item.name</td>
         </tr>  
   }

How to identify a strong vs weak relationship on ERD?

In entity relationship modeling, solid lines represent strong relationships and dashed lines represent weak relationships.

The type 'string' must be a non-nullable type in order to use it as parameter T in the generic type or method 'System.Nullable<T>'

Use string instead of string? in all places in your code.

The Nullable<T> type requires that T is a non-nullable value type, for example int or DateTime. Reference types like string can already be null. There would be no point in allowing things like Nullable<string> so it is disallowed.

Also if you are using C# 3.0 or later you can simplify your code by using auto-implemented properties:

public class WordAndMeaning
{
    public string Word { get; set; }
    public string Meaning { get; set; }
}

Tomcat request timeout

With Tomcat 7, you can add the StuckThreadDetectionValve which will enable you to identify threads that are "stuck". You can set-up the valve in the Context element of the applications where you want to do detecting:

<Context ...>
  ...
  <Valve 
    className="org.apache.catalina.valves.StuckThreadDetectionValve"
    threshold="60" />
  ...
</Context>

This would write a WARN entry into the tomcat log for any thread that takes longer than 60 seconds, which would enable you to identify the applications and ban them because they are faulty.

Based on the source code you may be able to write your own valve that attempts to stop the thread, however this would have knock on effects on the thread pool and there is no reliable way of stopping a thread in Java without the cooperation of that thread...

Compare every item to every other item in ArrayList

In some cases this is the best way because your code may have change something and j=i+1 won't check that.

for (int i = 0; i < list.size(); i++){  
    for (int j = 0; j < list.size(); j++) {
                if(i == j) {
               //to do code here
                    continue;
                }

}

}

Professional jQuery based Combobox control?

I had the same problem, so I ended up making my own.

It has a template system built in, so you can make the results look like anything you want. Works on all major browsers and accepts arrays & json objects. http://code.google.com/p/custom-combobox/

Android Completely transparent Status Bar?

This is only for API Level >= 21. It works for me. Here is my code (Kotlin)

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        findViewById<View>(android.R.id.content).systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
}

Reading from file using read() function

Read Byte by Byte and check that each byte against '\n' if it is not, then store it into buffer
if it is '\n' add '\0' to buffer and then use atoi()

You can read a single byte like this

char c;
read(fd,&c,1);

See read()

Create MSI or setup project with Visual Studio 2012

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

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

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

Split a String into an array in Swift?

The whitespace issue

Generally, people reinvent this problem and bad solutions over and over. Is this a space? " " and what about "\n", "\t" or some unicode whitespace character that you've never seen, in no small part because it is invisible. While you can get away with

A weak solution

import Foundation
let pieces = "Mary had little lamb".componentsSeparatedByString(" ")

If you ever need to shake your grip on reality watch a WWDC video on strings or dates. In short, it is almost always better to allow Apple to solve this kind of mundane task.

Robust Solution: Use NSCharacterSet

The way to do this correctly, IMHO, is to use NSCharacterSet since as stated earlier your whitespace might not be what you expect and Apple has provided a whitespace character set. To explore the various provided character sets check out Apple's NSCharacterSet developer documentation and then, only then, augment or construct a new character set if it doesn't fit your needs.

NSCharacterSet whitespaces

Returns a character set containing the characters in Unicode General Category Zs and CHARACTER TABULATION (U+0009).

let longerString: String = "This is a test of the character set splitting system"
let components = longerString.components(separatedBy: .whitespaces)
print(components)

Vertically aligning text next to a radio button

_x000D_
_x000D_
input.radio {vertical-align:middle; margin-top:8px; margin-bottom:12px;}
_x000D_
_x000D_
_x000D_

SIMPLY Adjust top and bottom as needed for PERFECT ALIGNMENT of radio button or checkbox

_x000D_
_x000D_
<input type="radio" class="radio">
_x000D_
_x000D_
_x000D_

Omitting the first line from any Linux command output

Pipe it to awk:

awk '{if(NR>1)print}'

or sed

sed -n '1!p'

How to lose margin/padding in UITextView?

you can use textContainerInset property of UITextView:

textView.textContainerInset = UIEdgeInsetsMake(10, 10, 10, 10);

(top, left, bottom, right)

Select multiple columns in data.table by their numeric indices

@Tom, thank you very much for pointing out this solution. It works great for me.

I was looking for a way to just exclude one column from printing and from the example above. To exclude the second column you can do something like this

library(data.table)
dt <- data.table(a=1:2, b=2:3, c=3:4)
dt[,.SD,.SDcols=-2]
dt[,.SD,.SDcols=c(1,3)]

How do I create a SQL table under a different schema?

The default schema for the user could be changed with the following query and avoids changing the property every time a table is to be created.

USE [DBName] 
GO 
ALTER USER [YourUserName] WITH DEFAULT_SCHEMA = [YourSchema] 
GO

Converting a Java Keystore into PEM Format

Direct conversion from jks to pem file using the keytool

keytool -exportcert -alias selfsigned -keypass password -keystore test-user.jks -rfc -file test-user.pem

What are Maven goals and phases and what is their difference?

The chosen answer is great, but still I would like to add something small to the topic. An illustration.

It clearly demonstrates how the different phases binded to different plugins and the goals that those plugins expose.

So, let's examine a case of running something like mvn compile:

  • It's a phase which execute the compiler plugin with compile goal
  • Compiler plugin got different goals. For mvn compile it's mapped to a specific goal, the compile goal.
  • It's the same as running mvn compiler:compile

Therefore, phase is made up of plugin goals.

enter image description here

Link to the reference

Android: How to set password property in an edit text?

Password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

This one works for me.
But you have to look at Octavian Damiean's comment, he's right.

how to attach url link to an image?

"How to attach url link to an image?"

You do it like this:

<a href="http://www.google.com"><img src="http://www.google.com/intl/en_ALL/images/logo.gif"/></a>

See it in action.

Renaming part of a filename

Something like this will do it. The for loop may need to be modified depending on which filenames you wish to capture.

for fspec1 in DET01-ABC-5_50-*.dat ; do
    fspec2=$(echo ${fspec1} | sed 's/-ABC-/-XYZ-/')
    mv ${fspec1} ${fspec2}
done

You should always test these scripts on copies of your data, by the way, and in totally different directories.

Extension methods must be defined in a non-generic static class

Extension method should be inside a static class. So please add your extension method inside a static class.

so for example it should be like this

public static class myclass
    {
        public static Byte[] ToByteArray(this Stream stream)
        {
            Int32 length = stream.Length > Int32.MaxValue ? Int32.MaxValue : Convert.ToInt32(stream.Length);
            Byte[] buffer = new Byte[length];
            stream.Read(buffer, 0, length);
            return buffer;
        }

    }

In plain English, what does "git reset" do?

When you commit something to git you first have to stage (add to the index) your changes. This means you have to git add all the files you want to have included in this commit before git considers them part of the commit. Let's first have a look over the image of a git repo: enter image description here

so, its simple now. We have to work in working directory, creating files, directories and all. These changes are untracked changes. To make them tracked, we need to add them to git index by using git add command. Once they are added to git index. We can now commit these changes, if we want to push it to git repository.

But suddenly we came to know while commiting that we have one extra file which we added in index is not required to push in git repository. It means we don't want that file in index. Now the question is how to remove that file from git index, Since we used git add to put them in the index it would be logical to use git rm? Wrong! git rm will simply delete the file and add the deletion to the index. So what to do now:

Use:-

git reset

It Clears your index, leaves your working directory untouched. (simply unstaging everything).

It can be used with number of options with it. There are three main options to use with git reset: --hard, --soft and --mixed. These affect what get’s reset in addition to the HEAD pointer when you reset.

First, --hard resets everything. Your current directory would be exactly as it would if you had been following that branch all along. The working directory and the index are changed to that commit. This is the version that I use most often. git reset --hard is something like svn revert .

Next, the complete opposite, —soft, does not reset the working tree nor the index. It only moves the HEAD pointer. This leaves your current state with any changes different than the commit you are switching to in place in your directory, and “staged” for committing. If you make a commit locally but haven’t pushed the commit to the git server, you can reset to the previous commit, and recommit with a good commit message.

Finally, --mixed resets the index, but not the working tree. So the changes are all still there, but are “unstaged” and would need to be git add’ed or git commit -a. we use this sometimes if we committed more than we meant to with git commit -a, we can back out the commit with git reset --mixed, add the things that we want to commit and just commit those.

Difference between git revert and git reset :-


In simple words, git reset is a command to "fix-uncommited mistakes" and git revert is a command to "fix-commited mistake".

It means if we have made some error in some change and commited and pushed the same to git repo, then git revert is the solution. And if in case we have identified the same error before pushing/commiting, we can use git reset to fix the issue.

I hope it will help you to get rid of your confusion.

Get attribute name value of <input>

While there is no denying that jQuery is a powerful tool, it is a really bad idea to use it for such a trivial operation as "get an element's attribute value".

Judging by the current accepted answer, I am going to assume that you were able to add an ID attribute to your element and use that to select it.

With that in mind, here are two pieces of code. First, the code given to you in the Accepted Answer:

$("#ID").attr("name");

And second, the Vanilla JS version of it:

document.getElementById('ID').getAttribute("name");

My results:

  • jQuery: 300k operations / second
  • JavaScript: 11,000k operations / second

You can test for yourself here. The "plain JavaScript" vesion is over 35 times faster than the jQuery version.

Now, that's just for one operation, over time you will have more and more stuff going on in your code. Perhaps for something particularly advanced, the optimal "pure JavaScript" solution would take one second to run. The jQuery version might take 30 seconds to a whole minute! That's huge! People aren't going to sit around for that. Even the browser will get bored and offer you the option to kill the webpage for taking too long!

As I said, jQuery is a powerful tool, but it should not be considered the answer to everything.

How to find elements with 'value=x'?

The following worked for me:

$("[id=attached_docs][value=123]")

Netbeans installation doesn't find JDK

This is only due to javahome path missing.

Use the command line below:--

For Windows OS- Open your command prompt

netbeans-6.5.1-windows.exe --javahome "C:\\Program Files\Java\jdk1.5.0"

For Linux OS- Open your Terminal

netbeans-6.5.1-windows.sh --javahome /usr/jdk/jdk1.6.0_04

The problem solved.

Search for exact match of string in excel row using VBA Macro

Never mind, I found the answer.

This will do the trick.

Dim colIndex As Long    
colIndex = Application.Match(colName, Range(Cells(rowIndex, 1), Cells(rowIndex, 100)), 0)

How to make Bitmap compress without change the bitmap size?

Are you sure it is smaller?

Bitmap original = BitmapFactory.decodeStream(getAssets().open("1024x768.jpg"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
original.compress(Bitmap.CompressFormat.PNG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

Log.e("Original   dimensions", original.getWidth()+" "+original.getHeight());
Log.e("Compressed dimensions", decoded.getWidth()+" "+decoded.getHeight());

Gives

12-07 17:43:36.333: E/Original   dimensions(278): 1024 768
12-07 17:43:36.333: E/Compressed dimensions(278): 1024 768

Maybe you get your bitmap from a resource, in which case the bitmap dimension will depend on the phone screen density

Bitmap bitmap=((BitmapDrawable)getResources().getDrawable(R.drawable.img_1024x768)).getBitmap();
Log.e("Dimensions", bitmap.getWidth()+" "+bitmap.getHeight());

12-07 17:43:38.733: E/Dimensions(278): 768 576

Why "Data at the root level is invalid. Line 1, position 1." for XML Document?

Main culprit for this error is logic which determines encoding when converting Stream or byte[] array to .NET string.

Using StreamReader created with 2nd constructor parameter detectEncodingFromByteOrderMarks set to true, will determine proper encoding and create string which does not break XmlDocument.LoadXml method.

public string GetXmlString(string url)
{
    using var stream = GetResponseStream(url);
    using var reader = new StreamReader(stream, true);
    return reader.ReadToEnd(); // no exception on `LoadXml`
}

Common mistake would be to just blindly use UTF8 encoding on the stream or byte[]. Code bellow would produce string that looks valid when inspected in Visual Studio debugger, or copy-pasted somewhere, but it will produce the exception when used with Load or LoadXml if file is encoded differently then UTF8 without BOM.

public string GetXmlString(string url)
{
    byte[] bytes = GetResponseByteArray(url);
    return System.Text.Encoding.UTF8.GetString(bytes); // potentially exception on `LoadXml`
}

So, in the case of your third party library, they probably use 2nd approach to decode XML stream to string, thus the exception.

CURLOPT_RETURNTRANSFER set to true doesnt work on hosting server

If you set CURLOPT_RETURNTRANSFER to true or 1 then the return value from curl_exec will be the actual result from the successful operation. In other words it will not return TRUE on success. Although it will return FALSE on failure.

As described in the Return Values section of curl-exec PHP manual page: http://php.net/manual/function.curl-exec.php

You should enable the CURLOPT_FOLLOWLOCATION option for redirects but this would be a problem if your server is in safe_mode and/or open_basedir is in effect which can cause issues with curl as well.

#1062 - Duplicate entry for key 'PRIMARY'

The DB I was importing had a conflict during the import due to the presence of a column both autoincrement and primary key.

The problem was that in the .sql file the table was chopped into multiple "INSERT INTO" and during the import these queries were executed all together.

MY SOLUTION was to deselect the "Run multiple queries in each execution" on Navicat and it worked perfectly

What is a "thread" (really)?

I am going to use a lot of text from the book Operating Systems Concepts by ABRAHAM SILBERSCHATZ, PETER BAER GALVIN and GREG GAGNE along with my own understanding of things.

Process

Any application resides in the computer in the form of text (or code).

We emphasize that a program by itself is not a process. A program is a passive entity, such as a file containing a list of instructions stored on disk (often called an executable file).

When we start an application, we create an instance of execution. This instance of execution is called a process. EDIT:(As per my interpretation, analogous to a class and an instance of a class, the instance of a class being a process. )

An example of processes is that of Google Chrome. When we start Google Chrome, 3 processes are spawned:

• The browser process is responsible for managing the user interface as well as disk and network I/O. A new browser process is created when Chrome is started. Only one browser process is created.

Renderer processes contain logic for rendering web pages. Thus, they contain the logic for handling HTML, Javascript, images, and so forth. As a general rule, a new renderer process is created for each website opened in a new tab, and so several renderer processes may be active at the same time.

• A plug-in process is created for each type of plug-in (such as Flash or QuickTime) in use. Plug-in processes contain the code for the plug-in as well as additional code that enables the plug-in to communicate with associated renderer processes and the browser process.

Thread

To answer this I think you should first know what a processor is. A Processor is the piece of hardware that actually performs the computations. EDIT: (Computations like adding two numbers, sorting an array, basically executing the code that has been written)

Now moving on to the definition of a thread.

A thread is a basic unit of CPU utilization; it comprises a thread ID, a program counter, a register set, and a stack.

EDIT: Definition of a thread from intel's website:

A Thread, or thread of execution, is a software term for the basic ordered sequence of instructions that can be passed through or processed by a single CPU core.

So, if the Renderer process from the Chrome application sorts an array of numbers, the sorting will take place on a thread/thread of execution. (The grammar regarding threads seems confusing to me)

My Interpretation of Things

A process is an execution instance. Threads are the actual workers that perform the computations via CPU access. When there are multiple threads running for a process, the process provides common memory.

EDIT: Other Information that I found useful to give more context

All modern day computer have more than one threads. The number of threads in a computer depends on the number of cores in a computer.

Concurrent Computing:

From Wikipedia:

Concurrent computing is a form of computing in which several computations are executed during overlapping time periods—concurrently—instead of sequentially (one completing before the next starts). This is a property of a system—this may be an individual program, a computer, or a network—and there is a separate execution point or "thread of control" for each computation ("process").

So, I could write a program which calculates the sum of 4 numbers:

(1 + 3) + (4 + 5)

In the program to compute this sum (which will be one process running on a thread of execution) I can fork another process which can run on a different thread to compute (4 + 5) and return the result to the original process, while the original process calculates the sum of (1 + 3).

Get a resource using getResource()

TestGameTable.class.getResource("/unibo/lsb/res/dice.jpg");
  • leading slash to denote the root of the classpath
  • slashes instead of dots in the path
  • you can call getResource() directly on the class.

How do I copy items from list to list without foreach?

Here another method but it is little worse compare to other.

List<int> i=original.Take(original.count).ToList();

bootstrap 3 wrap text content within div for horizontal alignment

1) Maybe oveflow: hidden; will do the trick?

2) You need to set the size of each div with the text and button so that each of these divs have the same height. Then for your button:

button {
  position: absolute;
  bottom: 0;
}

How to make a <svg> element expand or contract to its parent container?

For your iphone You could use in your head balise :

"width=device-width"

Javascript to stop HTML5 video playback on modal window close

I managed to stop the video using "get(0)" (Retrieve the DOM elements matched by the jQuery object):

$("#closeSimple").click(function() {
    $("div#simpleModal").removeClass("show");
    $("#videoContainer").get(0).pause();
    return false;
});

How to remove element from array in forEach loop?

You could also use indexOf instead to do this

var i = review.indexOf('\u2022 \u2022 \u2022');
if (i !== -1) review.splice(i,1);

How do I get AWS_ACCESS_KEY_ID for Amazon?

To find the AWS_SECRET_ACCESS_KEY Its better to create new create "IAM" user Here is the steps https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html 1. Sign in to the AWS Management Console and open the IAM console at https://console.aws.amazon.com/iam/.

  1. In the navigation pane, choose Users and then choose Add user.

How to access a value defined in the application.properties file in Spring Boot

Tried Class PropertiesLoaderUtils ?

This approach uses no annotation of Spring boot. A traditional Class way.

example:

Resource resource = new ClassPathResource("/application.properties");
    Properties props = PropertiesLoaderUtils.loadProperties(resource);
    String url_server=props.getProperty("server_url");

Use getProperty() method to pass the key and access the value in the properties file.

Eslint: How to disable "unexpected console statement" in Node.js?

My 2 cents contribution:

Besides removing the console warning (as shown above), it's best to remove yours logs from PROD environments (for security reasons). The best way I found to do so, is by adding this to nuxt.config.js

  build: {
   terser: {
      terserOptions: {
        compress: {
          //this removes console.log from production environment
          drop_console: true
        }
      }
    }
  }

How it works: Nuxt already uses terser as minifier. This config will force terser to ignore/remove all console logs commands during compression.

Simple timeout in java

The example 1 will not compile. This version of it compiles and runs. It uses lambda features to abbreviate it.

/*
 * [RollYourOwnTimeouts.java]
 *
 * Summary: How to roll your own timeouts.
 *
 * Copyright: (c) 2016 Roedy Green, Canadian Mind Products, http://mindprod.com
 *
 * Licence: This software may be copied and used freely for any purpose but military.
 *          http://mindprod.com/contact/nonmil.html
 *
 * Requires: JDK 1.8+
 *
 * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/
 *
 * Version History:
 *  1.0 2016-06-28 initial version
 */
package com.mindprod.example;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import static java.lang.System.*;

/**
 * How to roll your own timeouts.
 * Based on code at http://stackoverflow.com/questions/19456313/simple-timeout-in-java
 *
 * @author Roedy Green, Canadian Mind Products
 * @version 1.0 2016-06-28 initial version
 * @since 2016-06-28
 */

public class RollYourOwnTimeout
    {

    private static final long MILLIS_TO_WAIT = 10 * 1000L;

    public static void main( final String[] args )
        {
        final ExecutorService executor = Executors.newSingleThreadExecutor();

        // schedule the work
        final Future<String> future = executor.submit( RollYourOwnTimeout::requestDataFromWebsite );

        try
            {
            // where we wait for task to complete
            final String result = future.get( MILLIS_TO_WAIT, TimeUnit.MILLISECONDS );
            out.println( "result: " + result );
            }

        catch ( TimeoutException e )
            {
            err.println( "task timed out" );
            future.cancel( true /* mayInterruptIfRunning */ );
            }

        catch ( InterruptedException e )
            {
            err.println( "task interrupted" );
            }

        catch ( ExecutionException e )
            {
            err.println( "task aborted" );
            }

        executor.shutdownNow();

        }
/**
 * dummy method to read some data from a website
 */
private static String requestDataFromWebsite()
    {
    try
        {
        // force timeout to expire
        Thread.sleep( 14_000L );
        }
    catch ( InterruptedException e )
        {
        }
    return "dummy";
    }

}

How to change the href for a hyperlink using jQuery

The simple way to do so is :

Attr function (since jQuery version 1.0)

$("a").attr("href", "https://stackoverflow.com/") 

or

Prop function (since jQuery version 1.6)

$("a").prop("href", "https://stackoverflow.com/")

Also, the advantage of above way is that if selector selects a single anchor, it will update that anchor only and if selector returns a group of anchor, it will update the specific group through one statement only.

Now, there are lot of ways to identify exact anchor or group of anchors:

Quite Simple Ones:

  1. Select anchor through tag name : $("a")
  2. Select anchor through index: $("a:eq(0)")
  3. Select anchor for specific classes (as in this class only anchors with class active) : $("a.active")
  4. Selecting anchors with specific ID (here in example profileLink ID) : $("a#proileLink")
  5. Selecting first anchor href: $("a:first")

More useful ones:

  1. Selecting all elements with href attribute : $("[href]")
  2. Selecting all anchors with specific href: $("a[href='www.stackoverflow.com']")
  3. Selecting all anchors not having specific href: $("a[href!='www.stackoverflow.com']")
  4. Selecting all anchors with href containing specific URL: $("a[href*='www.stackoverflow.com']")
  5. Selecting all anchors with href starting with specific URL: $("a[href^='www.stackoverflow.com']")
  6. Selecting all anchors with href ending with specific URL: $("a[href$='www.stackoverflow.com']")

Now, if you want to amend specific URLs, you can do that as:

For instance if you want to add proxy website for all the URLs going to google.com, you can implement it as follows:

$("a[href^='http://www.google.com']")
   .each(function()
   { 
      this.href = this.href.replace(/http:\/\/www.google.com\//gi, function (x) {
        return "http://proxywebsite.com/?query="+encodeURIComponent(x);
    });
   });

git stash -> merge stashed change with current changes

Running git stash pop or git stash apply is essentially a merge. You shouldn't have needed to commit your current changes unless the files changed in the stash are also changed in the working copy, in which case you would've seen this error message:

error: Your local changes to the following files would be overwritten by merge:
       file.txt
Please, commit your changes or stash them before you can merge.
Aborting

In that case, you can't apply the stash to your current changes in one step. You can commit the changes, apply the stash, commit again, and squash those two commits using git rebase if you really don't want two commits, but that may be more trouble that it's worth.

Adb Devices can't find my phone

Try doing this:

  • Unplug the device
  • Execute adb kill-server && adb start-server(that restarts adb)
  • Re-plug the device

Also you can try to edit an adb config file .android/adb_usb.ini and add a line 04e8 after the header. Restart adb required for changes to take effect.

Android textview outline text

You can do this programmatically with the below snippet. That provides white letters with black background:

textView.setTextColor(Color.WHITE);            
textView.setShadowLayer(1.6f,1.5f,1.3f,Color.BLACK);

The parameters of the method are radius,dx,dy,color. You can change them for you specific needs.

I hope I will help someone that creates TextView programmatically and not having it inside xml.

Cheers to the stackOverflow community!

Can Android do peer-to-peer ad-hoc networking?

Here's a bug report on the feature you're requesting.

It's status is "reviewed" but I don't believe it's been implemented yet.

http://code.google.com/p/android/issues/detail?id=82

How to call a function in shell Scripting?

#!/bin/bash

process_install()
{
    commands... 
    commands... 
}

process_exit()
{
    commands... 
    commands... 
}


if [ "$choice" = "true" ] then
    process_install
else
    process_exit
fi

How does one output bold text in Bash?

In theory like so:

# BOLD
$ echo -e "\033[1mThis is a BOLD line\033[0m"
This is a BOLD line

# Using tput
tput bold 
echo "This" #BOLD
tput sgr0 #Reset text attributes to normal without clear.
echo "This" #NORMAL

# UNDERLINE
$ echo -e "\033[4mThis is a underlined line.\033[0m"
This is a underlined line. 

But in practice it may be interpreted as "high intensity" color instead.

(source: http://unstableme.blogspot.com/2008/01/ansi-escape-sequences-for-writing-text.html)

How to add a margin to a table row <tr>

You might try to use CSS transforms for indenting a whole tr:

tr.indent {
   -webkit-transform: translate(20px,0);
   -moz-transform: translate(20px,0);
}

I think this is a valid solution. Seems to work fine in Firefox 16, Chrome 23 and Safari 6 on my OSX.

Calling Member Functions within Main C++

On an informal note, you can also call non-static member functions on temporaries:

MyClass().printInformation();

(on another informal note, the end of the lifetime of the temporary variable (variable is important, because you can also call non-const member functions) comes at the end of the full expression (";"))

Splitting String and put it on int array

Java 8 offers a streams-based alternative to manual iteration:

int[] intArray = Arrays.stream(input.split(","))
    .mapToInt(Integer::parseInt)
    .toArray();

Be prepared to catch NumberFormatException if it's possible for the input to contain character sequences that cannot be converted to an integer.

refresh div with jquery

I tried the first solution and it works but the end user can easily identify that the div's are refreshing as it is fadeIn(), without fade in i tried .toggle().toggle() and it works perfect. you can try like this

_x000D_
_x000D_
$("#panel").toggle().toggle();
_x000D_
_x000D_
_x000D_

it works perfectly for me as i'm developing a messenger and need to minimize and maximize the chat box's and this does it best rather than the above code.

Bootstrap: How do I identify the Bootstrap version?

Shoud be stated on the top of the page.

Something like.

/* =========================================================
 * bootstrap-modal.js v1.4.0
 * http://twitter.github.com/bootstrap/javascript.html#modal
 * =========================================================
 * Copyright 2011 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================= */

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I think you've missed the point of access control.

A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.

Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.

In your specific case, it seems that paste.ee doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).

How do I prevent a form from being resized by the user?

Set the min and max size of form to same numbers. Do not show min and max buttons.

What are unit tests, integration tests, smoke tests, and regression tests?

  • Integration testing: Integration testing is the integrate another element
  • Smoke testing: Smoke testing is also known as build version testing. Smoke testing is the initial testing process exercised to check whether the software under test is ready/stable for further testing.
  • Regression testing: Regression testing is repeated testing. Whether new software is effected in another module or not.
  • Unit testing: It is a white box testing. Only developers involve in it

Does file_get_contents() have a timeout setting?

For prototyping, using curl from the shell with the -m parameter allow to pass milliseconds, and will work in both cases, either the connection didn't initiate, error 404, 500, bad url, or the whole data wasn't retrieved in full in the allowed time range, the timeout is always effective. Php won't ever hang out.

Simply don't pass unsanitized user data in the shell call.

system("curl -m 50 -X GET 'https://api.kraken.com/0/public/OHLC?pair=LTCUSDT&interval=60' -H  'accept: application/json' > data.json");
// This data had been refreshed in less than 50ms
var_dump(json_decode(file_get_contents("data.json"),true));

Set type for function parameters?

It can easilly be done with ArgueJS:

function myFunction ()
{
  arguments = __({myDate: Date, myString: String});
  // do stuff
};

INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE

Although I am very late to this but after seeing some legitimate questions for those who wanted to use INSERT-SELECT query with GROUP BY clause, I came up with the work around for this.

Taking further the answer of Marcus Adams and accounting GROUP BY in it, this is how I would solve the problem by using Subqueries in the FROM Clause

INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct, 
                inact, inadur, inadist, 
                smlct, smldur, smldist, 
                larct, lardur, lardist, 
                emptyct, emptydur)
SELECT sb.id, uid, sb.location, sb.animal, sb.starttime, sb.endtime, sb.entct, 
       sb.inact, sb.inadur, sb.inadist, 
       sb.smlct, sb.smldur, sb.smldist, 
       sb.larct, sb.lardur, sb.lardist, 
       sb.emptyct, sb.emptydur
FROM
(SELECT id, uid, location, animal, starttime, endtime, entct, 
       inact, inadur, inadist, 
       smlct, smldur, smldist, 
       larct, lardur, lardist, 
       emptyct, emptydur 
FROM tmp WHERE uid=x
GROUP BY location) as sb
ON DUPLICATE KEY UPDATE entct=sb.entct, inact=sb.inact, ...

Get Insert Statement for existing row in MySQL

With PDO you can do it this way.

$stmt = DB::getDB()->query("SELECT * FROM sometable", array());

$array = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $fields = array_keys($array[0]);

    $statement = "INSERT INTO user_profiles_copy (".implode(",",$fields).") VALUES ";
    $statement_values = null;

    foreach ($array as $key => $post) {
        if(isset($statement_values)) {
            $statement_values .= ", \n";
        }

        $values = array_values($post);
        foreach($values as $index => $value) {
            $quoted = str_replace("'","\'",str_replace('"','\"', $value));
            $values[$index] = (!isset($value) ? 'NULL' : "'" . $quoted."'") ;
        }

        $statement_values .= "(".implode(',',$values).")";


    }
    $statement .= $statement_values . ";";

    echo $statement;

How can I represent an 'Enum' in Python?

The new standard in Python is PEP 435, so an Enum class will be available in future versions of Python:

>>> from enum import Enum

However to begin using it now you can install the original library that motivated the PEP:

$ pip install flufl.enum

Then you can use it as per its online guide:

>>> from flufl.enum import Enum
>>> class Colors(Enum):
...     red = 1
...     green = 2
...     blue = 3
>>> for color in Colors: print color
Colors.red
Colors.green
Colors.blue

Better way to find control in ASP.NET

Late as usual. If anyone is still interested in this there are a number of related SO questions and answers. My version of recursive extension method for resolving this:

public static IEnumerable<T> FindControlsOfType<T>(this Control parent)
                                                        where T : Control
{
    foreach (Control child in parent.Controls)
    {
        if (child is T)
        {
            yield return (T)child;
        }
        else if (child.Controls.Count > 0)
        {
            foreach (T grandChild in child.FindControlsOfType<T>())
            {
                yield return grandChild;
            }
        }
    }
}

Get Client Machine Name in PHP

What's this "other information"? An IP address?

In PHP, you use $_SERVER['REMOTE_ADDR'] to get the IP address of the remote client, then you can use gethostbyaddr() to try and conver that IP into a hostname - but not all IPs have a reverse mapping configured.

UEFA/FIFA scores API

UEFA internally provides their own LIVEX Api for their Broadcasting Partners. That one is perfect enough to develop the Applications by their partners for themselves.

What does the ??!??! operator do in C?

Well, why this exists in general is probably different than why it exists in your example.

It all started half a century ago with repurposing hardcopy communication terminals as computer user interfaces. In the initial Unix and C era that was the ASR-33 Teletype.

This device was slow (10 cps) and noisy and ugly and its view of the ASCII character set ended at 0x5f, so it had (look closely at the pic) none of the keys:

{ | } ~ 

The trigraphs were defined to fix a specific problem. The idea was that C programs could use the ASCII subset found on the ASR-33 and in other environments missing the high ASCII values.

Your example is actually two of ??!, each meaning |, so the result is ||.

However, people writing C code almost by definition had modern equipment,1 so my guess is: someone showing off or amusing themself, leaving a kind of Easter egg in the code for you to find.

It sure worked, it led to a wildly popular SO question.

ASR-33 Teletype

                                            ASR-33 Teletype


1. For that matter, the trigraphs were invented by the ANSI committee, which first met after C become a runaway success, so none of the original C code or coders would have used them.

Setting values of input fields with Angular 6

As an alternate you can use reactive forms. Here is an example: https://stackblitz.com/edit/angular-pqb2xx

Template

<form [formGroup]="mainForm" ng-submit="submitForm()">
  Global Price: <input type="number" formControlName="globalPrice">
  <button type="button" [disabled]="mainForm.get('globalPrice').value === null" (click)="applyPriceToAll()">Apply to all</button>
  <table border formArrayName="orderLines">
  <ng-container *ngFor="let orderLine of orderLines let i=index" [formGroupName]="i">
    <tr>
       <td>{{orderLine.time | date}}</td>
       <td>{{orderLine.quantity}}</td>
       <td><input formControlName="price" type="number"></td>
    </tr>
</ng-container>
  </table>
</form>

Component

import { Component } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';
  mainForm: FormGroup;
  orderLines = [
    {price: 10, time: new Date(), quantity: 2},
    {price: 20, time: new Date(), quantity: 3},
    {price: 30, time: new Date(), quantity: 3},
    {price: 40, time: new Date(), quantity: 5}
    ]
  constructor() {
    this.mainForm = this.getForm();
  }

  getForm(): FormGroup {
    return new FormGroup({
      globalPrice: new FormControl(),
      orderLines: new FormArray(this.orderLines.map(this.getFormGroupForLine))
    })
  }

  getFormGroupForLine(orderLine: any): FormGroup {
    return new FormGroup({
      price: new FormControl(orderLine.price)
    })
  }

  applyPriceToAll() {
    const formLines = this.mainForm.get('orderLines') as FormArray;
    const globalPrice = this.mainForm.get('globalPrice').value;
    formLines.controls.forEach(control => control.get('price').setValue(globalPrice));
    // optionally recheck value and validity without emit event.
  }

  submitForm() {

  }
}

Load and execute external js file in node.js with access to local variables?

Sorry for resurrection. You could use child_process module to execute external js files in node.js

var child_process = require('child_process');

//EXECUTE yourExternalJsFile.js
child_process.exec('node yourExternalJsFile.js', (error, stdout, stderr) => {
    console.log(`${stdout}`);
    console.log(`${stderr}`);
    if (error !== null) {
        console.log(`exec error: ${error}`);
    }
});

How should I resolve java.lang.IllegalArgumentException: protocol = https host = null Exception?

Might help some else - I came here because I missed putting two // after http:. This is what I had:

http:/abc.my.domain.com:55555/update

Bootstrap 4, how to make a col have a height of 100%?

Although it is not a good solution but may solve your problem. You need to use position absolute in #yellow element!

_x000D_
_x000D_
#yellow {height: 100%; background: yellow; position: absolute; top: 0px; left: 0px;}_x000D_
.container-fluid {position: static !important;}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<div class="container-fluid">_x000D_
  <div class="row justify-content-center">_x000D_
_x000D_
    <div class="col-4" id="yellow">_x000D_
      XXXX_x000D_
    </div>_x000D_
_x000D_
    <div class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8">_x000D_
      Form Goes Here_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
_x000D_
_x000D_
_x000D_

Android: remove notification from notification bar

simply set setAutoCancel(True) like the following code:

Intent resultIntent = new Intent(GameLevelsActivity.this, NotificationReceiverActivityAdv.class);

PendingIntent resultPendingIntent =
        PendingIntent.getActivity(
                GameLevelsActivity.this,
                0,
                resultIntent,
                PendingIntent.FLAG_UPDATE_CURRENT
                );

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
        getApplicationContext()).setSmallIcon(R.drawable.icon)
        .setContentTitle(adv_title)
        .setContentText(adv_desc)
        .setContentIntent(resultPendingIntent)
         //HERE IS WHAT YOY NEED:
        .setAutoCancel(true);

NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(547, mBuilder.build());`

Short rot13 function - Python

I couldn't leave this question here with out a single statement using the modulo operator.

def rot13(s):
    return ''.join([chr(x.islower() and ((ord(x) - 84) % 26) + 97
                        or x.isupper() and ((ord(x) - 52) % 26) + 65
                        or ord(x))
                    for x in s])

This is not pythonic nor good practice, but it works!

>> rot13("Hello World!")
Uryyb Jbeyq!

How to list files using dos commands?

Try dir /b, for bare format.

dir /? will show you documentation of what you can do with the dir command. Here is the output from my Windows 7 machine:

C:\>dir /?
Displays a list of files and subdirectories in a directory.

DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
  [/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]

  [drive:][path][filename]
              Specifies drive, directory, and/or files to list.

  /A          Displays files with specified attributes.
  attributes   D  Directories                R  Read-only files
               H  Hidden files               A  Files ready for archiving
               S  System files               I  Not content indexed files
               L  Reparse Points             -  Prefix meaning not
  /B          Uses bare format (no heading information or summary).
  /C          Display the thousand separator in file sizes.  This is the
              default.  Use /-C to disable display of separator.
  /D          Same as wide but files are list sorted by column.
  /L          Uses lowercase.
  /N          New long list format where filenames are on the far right.
  /O          List by files in sorted order.
  sortorder    N  By name (alphabetic)       S  By size (smallest first)
               E  By extension (alphabetic)  D  By date/time (oldest first)
               G  Group directories first    -  Prefix to reverse order
  /P          Pauses after each screenful of information.
  /Q          Display the owner of the file.
  /R          Display alternate data streams of the file.
  /S          Displays files in specified directory and all subdirectories.
  /T          Controls which time field displayed or used for sorting
  timefield   C  Creation
              A  Last Access
              W  Last Written
  /W          Uses wide list format.
  /X          This displays the short names generated for non-8dot3 file
              names.  The format is that of /N with the short name inserted
              before the long name. If no short name is present, blanks are
              displayed in its place.
  /4          Displays four-digit years

Switches may be preset in the DIRCMD environment variable.  Override
preset switches by prefixing any switch with - (hyphen)--for example, /-W.

RichTextBox (WPF) does not have string property "Text"

There is no Text property in the WPF RichTextBox control. Here is one way to get all of the text out:

TextRange range = new TextRange(myRTB.Document.ContentStart, myRTB.Document.ContentEnd);

string allText = range.Text;

How to update single value inside specific array item in redux

This is how I did it for one of my projects:

const markdownSaveActionCreator = (newMarkdownLocation, newMarkdownToSave) => ({
  type: MARKDOWN_SAVE,
  saveLocation: newMarkdownLocation,
  savedMarkdownInLocation: newMarkdownToSave  
});

const markdownSaveReducer = (state = MARKDOWN_SAVED_ARRAY_DEFAULT, action) => {
  let objTemp = {
    saveLocation: action.saveLocation, 
    savedMarkdownInLocation: action.savedMarkdownInLocation
  };

  switch(action.type) {
    case MARKDOWN_SAVE:
      return( 
        state.map(i => {
          if (i.saveLocation === objTemp.saveLocation) {
            return Object.assign({}, i, objTemp);
          }
          return i;
        })
      );
    default:
      return state;
  }
};

What is %0|%0 and how does it work?

This is the Windows version of a fork bomb.

%0 is the name of the currently executing batch file. A batch file that contains just this line:

%0|%0

Is going to recursively execute itself forever, quickly creating many processes and slowing the system down.

This is not a bug in windows, it is just a very stupid thing to do in a batch file.

How to make android listview scrollable?

You shouldn't put a ListView inside a ScrollView because the ListView class implements its own scrolling and it just doesn't receive gestures because they all are handled by the parent ScrollView

Where does Chrome store extensions?

For Chrome on Mac, if you have multiple profiles, you can find it under your profile folder, either Default or Profile #. i.e either

~/Library/Application Support/Google/Chrome/Default/Extensions/ or ~/Library/Application Support/Google/Chrome/<Profile 1>/Extensions/

net::ERR_INSECURE_RESPONSE in Chrome

I was getting this error on amazon.ca, meetup.com, and the Symantec homepage.

I went to the update page in the Chrome browser (it was at 53.*) and checked for an upgrade, and it showed there was no updates available. After asking around my office, it turns out the latest version was 55 but I was stuck on 53 for some reason.

After upgrading (had to manually download from the Chrome website) the issues were gone!

Make 2 functions run at the same time

The thread module does work simultaneously unlike multiprocess, but the timing is a bit off. The code below prints a "1" and a "2". These are called by different functions respectively. I did notice that when printed to the console, they would have slightly different timings.

from threading import Thread

def one():
    while(1 == num):
        print("1")
        time.sleep(2)
    
def two():
    while(1 == num):
        print("2")
        time.sleep(2)


p1 = Thread(target = one)
p2 = Thread(target = two)

p1.start()
p2.start()

Output: (Note the space is for the wait in between printing)

1
2

2
1

12
   
21

12
   
1
2

Not sure if there is a way to correct this, or if it matters at all. Just something I noticed.

How to connect to local instance of SQL Server 2008 Express

var.connectionstring = "server=localhost; database=dbname; integrated security=yes"

or

var.connectionstring = "server=localhost; database=dbname; login=yourlogin; pwd=yourpass"

response.sendRedirect() from Servlet to JSP does not seem to work

You can use this:

response.sendRedirect(String.format("%s%s", request.getContextPath(), "/views/equipment/createEquipment.jsp"));

The last part is your path in your web-app

Should image size be defined in the img tag height/width attributes or in CSS?

Option a. Simple straight fwd. What you see is what you get easy to make calculations.

Option b. Too messy to do this inline unless you want to have a site that can stretch. IE if you used the with:86em however modern browsers seem to handle this functionally adequately for my purposes.. . Personally the only time that i would use something like this is if i were to create a thumbnails catalogue.

/*css*/
ul.myThumbs{}
ul.myThumbs li {float:left; width:50px;}
ul.myThumbs li img{width:50px; height:50px;border:0;}

<!--html-->
<ul><li>
<img src="~/img/products/thumbs/productid.jpg" alt="" />
</li></ul>

Option c. Too messy to maintain.

Can PHP cURL retrieve response headers AND body in a single request?

If you specifically want the Content-Type, there's a special cURL option to retrieve it:

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
$content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);

PHP preg_match - only allow alphanumeric strings and - _ characters

Here is one equivalent of the accepted answer for the UTF-8 world.

if (!preg_match('/^[\p{L}\p{N}_-]+$/u', $string)){
  //Disallowed Character In $string
}

Explanation:

  • [] => character class definition
  • p{L} => matches any kind of letter character from any language
  • p{N} => matches any kind of numeric character
  • _- => matches underscore and hyphen
  • + => Quantifier — Matches between one to unlimited times (greedy)
  • /u => Unicode modifier. Pattern strings are treated as UTF-16. Also causes escape sequences to match unicode characters

Note, that if the hyphen is the last character in the class definition it does not need to be escaped. If the dash appears elsewhere in the class definition it needs to be escaped, as it will be seen as a range character rather then a hyphen.

How to connect SQLite with Java?

Hey i have posted a video tutorial on youtube about this, you can check that and you can find here the sample code :

http://myfundatimemachine.blogspot.in/2012/06/database-connection-to-java-application.html

Any way to Invoke a private method?

Use getDeclaredMethod() to get a private Method object and then use method.setAccessible() to allow to actually call it.

JavaScript: remove event listener

If someone uses jquery, he can do it like this :

var click_count = 0;
$( "canvas" ).bind( "click", function( event ) {
    //do whatever you want
    click_count++;
    if ( click_count == 50 ) {
        //remove the event
        $( this ).unbind( event );
    }
});

Hope that it can help someone. Note that the answer given by @user113716 work nicely :)

DynamoDB vs MongoDB NoSQL

With 500k documents, there is no reason to scale whatsoever. A typical laptop with an SSD and 8GB of ram can easily do 10s of millions of records, so if you are trying to pick because of scaling your choice doesn't really matter. I would suggest you pick what you like the most, and perhaps where you can find the most online support with.

Python Image Library fails with message "decoder JPEG not available" - PIL

On Fedora 17 I had to install libjpeg-devel and afterwards reinstall PIL:

sudo yum install --assumeyes libjpeg-devel
sudo pip-python install --upgrade PIL

what is the difference between OLE DB and ODBC data sources?

Here's my understanding (non-authoritative):

ODBC is a technology-agnostic open standard supported by most software vendors. OLEDB is a technology-specific Microsoft's API from the COM-era (COM was a component and interoperability technology before .NET)

At some point various datasouce vendors (e.g. Oracle etc.), willing to be compatible with Microsoft data consumers, developed OLEDB providers for their products, but for the most part OLEDB remains a Microsoft-only standard. Now, most Microsoft data sources allow both ODBC and OLEDB access, mainly for compatibility with legacy ODBC data consumers. Also, there exists OLEDB provider (wrapper) for ODBC which allows one to use OLEDB to access ODBC data sources if one so wishes.

In terms of the features OLEDB is substantially richer than ODBC but suffers from one-ring-to-rule-them-all syndrome (overly generic, overcomplicated, non-opinionated).

In non-Microsoft world ODBC-based data providers and clients are widely used and not going anywhere.

Inside Microsoft bubble OLEDB is being phased out in favor of native .NET APIs build on top of whatever the native transport layer for that data source is (e.g. TDS for MS SQL Server).

Get the date (a day before current time) in Bash

Not very sexy but might do the job:

perl -e 'my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time - 86400);$year += 1900; $mon+= 1; printf ("YESTERDAY: %04d%02d%02d \n", $year, $mon, $mday)'

Formated from "martin clayton" answer.

Display only 10 characters of a long string?

Although this won't limit the string to exactly 10 characters, why not let the browser do the work for you with CSS:

.no-overflow {
    white-space: no-wrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

and then for the table cell that contains the string add the above class and set the maximum permitted width. The result should end up looking better than anything done based on measuring the string length.

Best practice: PHP Magic Methods __set and __get

I am now returning to setters and getters but I am also putting the getters and setters in the magic methos __get and __set. This way I have a default behavior when I do this

$class->var;

This will just call the getter I have set in the __get. Normally I will just use the getter directly but there are still some instances where this is just simpler.

Hashing a dictionary?

I do it like this:

hash(str(my_dict))

How to install PHP mbstring on CentOS 6.2

*Make sure you update your linux box first

yum update

In case someone still has this problem, this is a valid solution:

centos-release : rpm -q centos-release

Centos 6.*

wget http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
rpm -ivh epel-release-6-8.noarch.rpm
wget http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
rpm -Uvh remi-release-6*.rpm

Centos 5.*

wget http://ftp.jaist.ac.jp/pub/Linux/Fedora/epel/5/x86_64/epel-release-5-4.noarch.rpm
rpm -ivh epel-release-5-4.noarch.rpm
wget http://rpms.famillecollet.com/enterprise/remi-release-5.rpm
rpm -Uvh remi-release-5*.rpm

Then just do this to update:

yum --enablerepo=remi upgrade php-mbstring

Or this to install:

yum --enablerepo=remi install php-mbstring

How do I detect "shift+enter" and generate a new line in Textarea?

I found this thread looking for a way to control Shift + any key. I pasted together other solutions to make this combined function to accomplish what I needed. I hope it helps someone else.

function () {
    return this.each(function () {
    $(this).keydown(function (e) {
        var key = e.charCode || e.keyCode || 0;
        // Shift + anything is not desired
        if (e.shiftKey) {
            return false;
        }
        // allow backspace, tab, delete, enter, arrows, numbers 
        //and keypad numbers ONLY
        // home, end, period, and numpad decimal
        return (
            key == 8 ||
            key == 9 ||
            key == 13 ||
            key == 46 ||
            key == 110 ||
            key == 190 ||
            (key >= 35 && key <= 40) ||
            (key >= 48 && key <= 57) ||
            (key >= 96 && key <= 105));
    });
});

Get original URL referer with PHP?

Store it either in a cookie (if it's acceptable for your situation), or in a session variable.

session_start();

if ( !isset( $_SESSION["origURL"] ) )
    $_SESSION["origURL"] = $_SERVER["HTTP_REFERER"];

How do I change the root directory of an Apache server?

In Apache version 2.4.18 (Ubuntu).

  1. Open the file /etc/apache2/apache2.conf and search for <Directory /var/www/> and replace to your directory.

  2. Open file /etc/apache2/sites-available/000-default.conf, search for DocumentRoot /var/www/html and replace it with your DocumentRoot.

How can I URL encode a string in Excel VBA?

If you also want it to work on MacOs create a seperate function

Function macUriEncode(value As String) As String

    Dim script As String
    script = "do shell script " & """/usr/bin/python -c 'import sys, urllib; print urllib.quote(sys.argv[1])' """ & Chr(38) & " quoted form of """ & value & """"

    macUriEncode = MacScript(script)

End Function

How to ping a server only once from within a batch file?

I know why, you are using the file name "ping" and you are using the code "ping", it just keeps trying to run itself because its selected directory in where that file is, if you want it to actually ping, put this before the ping command: "cd C:\Windows\system32", the actual file that pings the server is in there!

Error inflating when extending a class

Another possible cause of the "Error inflating class" message could be misspelling the full package name where it's specified in XML:

<com.alpenglow.androcap.GhostSurfaceCameraView android:id="@+id/ghostview_cameraview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>

Opening your layout XML file in the Eclipse XML editor should highlight this problem.

Android - save/restore fragment state

Android fragment has some advantages and some disadvantages. The most disadvantage of the fragment is that when you want to use a fragment you create it ones. When you use it, onCreateView of the fragment is called for each time. If you want to keep state of the components in the fragment you must save fragment state and yout must load its state in the next shown. This make fragment view a bit slow and weird.

I have found a solution and I have used this solution: "Everything is great. Every body can try".

When first time onCreateView is being run, create view as a global variable. When second time you call this fragment onCreateView is called again you can return this global view. The fragment component state will be kept.

View view;

@Override
public View onCreateView(LayoutInflater inflater,
        @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    setActionBar(null);
    if (view != null) {
        if ((ViewGroup)view.getParent() != null)
            ((ViewGroup)view.getParent()).removeView(view);
        return view; 
    }
    view = inflater.inflate(R.layout.mylayout, container, false);
}

Get last 3 characters of string

The easiest way would be using Substring

string str = "AM0122200204";
string substr = str.Substring(str.Length - 3);

Using the overload with one int as I put would get the substring of a string, starting from the index int. In your case being str.Length - 3, since you want to get the last three chars.

How to format a floating number to fixed width in Python

See Python 3.x format string syntax:

IDLE 3.5.1   
numbers = ['23.23', '.1233', '1', '4.223', '9887.2']

for x in numbers:  
    print('{0: >#016.4f}'. format(float(x)))  

     23.2300
      0.1233
      1.0000
      4.2230
   9887.2000

ServletContext.getRequestDispatcher() vs ServletRequest.getRequestDispatcher()

I think you will understand it through these examples below.

Source code structure:

/src/main/webapp/subdir/sample.jsp
/src/main/webapp/sample.jsp

Context is: TestApp
So the entry point: http://yourhostname-and-port/TestApp


Forward to RELATIVE path:

Using servletRequest.getRequestDispatcher("sample.jsp"):

http://yourhostname-and-port/TestApp/subdir/fwdServlet  ==> \subdir\sample.jsp
http://yourhostname-and-port/TestApp/fwdServlet ==> /sample.jsp

Using servletContext.getRequestDispatcher("sample.jsp"):

http://yourhostname-and-port/TestApp/subdir/fwdServlet ==> java.lang.IllegalArgumentException: Path sample.jsp does not start with a "/" character
http://yourhostname-and-port/TestApp/fwdServlet ==> java.lang.IllegalArgumentException: Path sample.jsp does not start with a "/" character


Forward to ABSOLUTE path:

Using servletRequest.getRequestDispatcher("/sample.jsp"):

http://yourhostname-and-port/TestApp/subdir/fwdServlet  ==> /sample.jsp
http://yourhostname-and-port/TestApp/fwdServlet ==> /sample.jsp

Using servletContext.getRequestDispatcher("/sample.jsp"):

http://yourhostname-and-port/TestApp/subdir/fwdServlet ==> /sample.jsp
http://yourhostname-and-port/TestApp/fwdServlet ==> /sample.jsp

How to create a link to a directory

Symbolic or soft link (files or directories, more flexible and self documenting)

#     Source                             Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx

Hard link (files only, less flexible and not self documenting)

#   Source                             Link
ln /home/jake/doc/test/2000/something /home/jake/xxx

More information: man ln


/home/jake/xxx is like a new directory. To avoid "is not a directory: No such file or directory" error, as @trlkly comment, use relative path in the target, that is, using the example:

  1. cd /home/jake/
  2. ln -s /home/jake/doc/test/2000/something xxx

Trying to get property of non-object - CodeIgniter

To access the elements in the array, use array notation: $product['prodname']

$product->prodname is object notation, which can only be used to access object attributes and methods.

How do I automatically update a timestamp in PostgreSQL

Updating timestamp, only if the values changed

Based on E.J's link and add a if statement from this link (https://stackoverflow.com/a/3084254/1526023)

CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
   IF row(NEW.*) IS DISTINCT FROM row(OLD.*) THEN
      NEW.modified = now(); 
      RETURN NEW;
   ELSE
      RETURN OLD;
   END IF;
END;
$$ language 'plpgsql';

Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src'

I had the same issue and it turns out there was an error in the directory of the file I was trying to serve instead of:

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

I had :

_x000D_
_x000D_
app.use(express.static('./dist'));
_x000D_
_x000D_
_x000D_

How to create a release signed apk file using Gradle?

To complement the other answers, you can also place your gradle.properties file in your own module folder, together with build.gradle, just in case your keystore is specific to one project.

Render partial from different folder (not shared)

you should try this

~/Views/Shared/parts/UMFview.ascx

place the ~/Views/ before your code

Positioning background image, adding padding

this is actually pretty easily done. You're almost there, doing what you've done with background-position: right center;. What is actually needed in this case is something very much like that. Let's convert these to percentages. We know that center=50%, so that's easy enough. Now, in order to get the padding you wanted, you need to position the background like so: background-position: 99% 50%.

The second, and more effective way of going about this, is to use the same background-position idea, and just use background-position: 400px (width of parent) 50%;. Of course, this method requires a static width, but will give you the same thing every time.

Method 1 (99% 50%)
Method 2 (400px 50%)

JPA: difference between @JoinColumn and @PrimaryKeyJoinColumn?

I normally differentiate these two via this diagram:

Use PrimaryKeyJoinColumn

enter image description here

Use JoinColumn

enter image description here

How to get memory available or used in C#

You can use:

Process proc = Process.GetCurrentProcess();

To get the current process and use:

proc.PrivateMemorySize64;

To get the private memory usage. For more information look at this link.

Sound effects in JavaScript / HTML5

I know this is a total hack but thought I should add this sample open source audio library I put on github awhile ago...

https://github.com/run-time/jThump

After clicking the link below, type on the home row keys to play a blues riff (also type multiple keys at the same time etc.)

Sample using jThump library >> http://davealger.com/apps/jthump/

It basically works by making invisible <iframe> elements that load a page that plays a sound onReady().

This is certainly not ideal but you could +1 this solution based on creativity alone (and the fact that it is open source and works in any browser that I've tried it on) I hope this gives someone else searching some ideas at least.

:)

Python Decimals format

Here's a function that will do the trick:

def myformat(x):
    return ('%.2f' % x).rstrip('0').rstrip('.')

And here are your examples:

>>> myformat(1.00)
'1'
>>> myformat(1.20)
'1.2'
>>> myformat(1.23)
'1.23'
>>> myformat(1.234)
'1.23'
>>> myformat(1.2345)
'1.23'

Edit:

From looking at other people's answers and experimenting, I found that g does all of the stripping stuff for you. So,

'%.3g' % x

works splendidly too and is slightly different from what other people are suggesting (using '{0:.3}'.format() stuff). I guess take your pick.

How to put comments in Django templates

Comment tags are documented at https://docs.djangoproject.com/en/stable/ref/templates/builtins/#std:templatetag-comment

{% comment %} this is a comment {% endcomment %}

Single line comments are documented at https://docs.djangoproject.com/en/stable/topics/templates/#comments

{# this won't be rendered #}

Format number to 2 decimal places

Show as decimal Select ifnull(format(100.00, 1, 'en_US'), 0) 100.0

Show as Percentage Select concat(ifnull(format(100.00, 0, 'en_US'), 0), '%') 100%

Excel VBA Run-time Error '32809' - Trying to Understand it

I did the following and worked like a charm:

  1. Install Office 2013 (I haven't tried with 2010 but I think it would work too).
  2. Install Office 2013 SP1.
  3. Run Windows Updates and install all Office and Windows updates.
  4. Reboot computer.
  5. Done.

This worked for me in two different computers. I hope this will work in yours too!

html div onclick event

Try out this example, the onclick is still called from your HTML, and event bubbling is stopped.

<div class="expandable-panel-heading">
<h2>
  <a id="ancherComplaint" href="#addComplaint" onclick="markActiveLink(this);event.stopPropagation();">ABC</a>
</h2>
</div>

http://jsfiddle.net/NXML7/1/

What is setup.py?

setup.py is Python's answer to a multi-platform installer and make file.

If you’re familiar with command line installations, then make && make install translates to python setup.py build && python setup.py install.

Some packages are pure Python, and are only byte compiled. Others may contain native code, which will require a native compiler (like gcc or cl) and a Python interfacing module (like swig or pyrex).

Convert normal date to unix timestamp

_x000D_
_x000D_
var d = '2016-01-01T00:00:00.000Z';_x000D_
console.log(new Date(d).valueOf()); // returns the number of milliseconds since the epoch
_x000D_
_x000D_
_x000D_

Iterating over arrays in Python 3

When you loop in an array like you did, your for variable(in this example i) is current element of your array.

For example if your ar is [1,5,10], the i value in each iteration is 1, 5, and 10. And because your array length is 3, the maximum index you can use is 2. so when i = 5 you get IndexError. You should change your code into something like this:

for i in ar:
    theSum = theSum + i

Or if you want to use indexes, you should create a range from 0 ro array length - 1.

for i in range(len(ar)):
    theSum = theSum + ar[i]

In mocha testing while calling asynchronous function how to avoid the timeout Error: timeout of 2000ms exceeded

If you are using arrow functions:

it('should do something', async () => {
  // do your testing
}).timeout(15000)

what is an illegal reflective access

If you want to go with the add-open option, here's a command to find which module provides which package ->

java --list-modules | tr @ " " | awk '{ print $1 }' | xargs -n1 java -d

the name of the module will be shown with the @ while the name of the packages without it

NOTE: tested with JDK 11

IMPORTANT: obviously is better than the provider of the package does not do the illegal access

How can I directly view blobs in MySQL Workbench

In short:

  1. Go to Edit > Preferences
  2. Choose SQL Editor
  3. Under SQL Execution, check Treat BINARY/VARBINARY as nonbinary character string
  4. Restart MySQL Workbench (you will not be prompted or informed of this requirement).

In MySQL Workbench 6.0+

  1. Go to Edit > Preferences
  2. Choose SQL Queries
  3. Under Query Results, check Treat BINARY/VARBINARY as nonbinary character string
  4. It's not mandatory to restart MySQL Workbench (you will not be prompted or informed of this requirement).*

With this setting you will be able to concatenate fields without getting blobs.

I think this applies to versions 5.2.22 and later and is the result of this MySQL bug.

Disclaimer: I don't know what the downside of this setting is - maybe when you are selecting BINARY/VARBINARY values you will see it as plain text which may be misleading and/or maybe it will hinder performance if they are large enough?

'adb' is not recognized as an internal or external command, operable program or batch file

If you want to use it every time add the path of adb to your system variables: enter to cmd (command prompt) and write the following:

echo %PATH%

this command will show you what it was before you will add adb path

setx PATH "%PATH%;C:\Program Files\android-sdk-windows\platform-tools"

be careful the path that you want to add if it contains double quote

after you restart your cmd rewrite:

echo %PATH%

you will find that the path is added

PS: if you just want to add the path to cmd just to this session you can use:

set PATH=%PATH%;C:\Program Files\android-sdk-windows\platform-tools

How do I delete all the duplicate records in a MySQL table without temp tables

If you are not using any primary key, then execute following queries at one single stroke. By replacing values:

# table_name - Your Table Name
# column_name_of_duplicates - Name of column where duplicate entries are found

create table table_name_temp like table_name;
insert into table_name_temp select distinct(column_name_of_duplicates),value,type from table_name group by column_name_of_duplicates;
delete from table_name;
insert into table_name select * from table_name_temp;
drop table table_name_temp
  1. create temporary table and store distinct(non duplicate) values
  2. make empty original table
  3. insert values to original table from temp table
  4. delete temp table

It is always advisable to take backup of database before you play with it.

Pandas: how to change all the values of a column?

Or if one want to use lambda function in the apply function:

data['Revenue']=data['Revenue'].apply(lambda x:float(x.replace("$","").replace(",", "").replace(" ", "")))