Programs & Examples On #Django template filters

django-template-filters refers to django template filters that are used to filter the contents of a variable in django templates

How to bind Events on Ajax loaded Content?

If the content is appended after .on() is called, you'll need to create a delegated event on a parent element of the loaded content. This is because event handlers are bound when .on() is called (i.e. usually on page load). If the element doesn't exist when .on() is called, the event will not be bound to it!

Because events propagate up through the DOM, we can solve this by creating a delegated event on a parent element (.parent-element in the example below) that we know exists when the page loads. Here's how:

$('.parent-element').on('click', '.mylink', function(){
  alert ("new link clicked!");
})

Some more reading on the subject:

www-data permissions?

As stated in an article by Slicehost:

User setup

So let's start by adding the main user to the Apache user group:

sudo usermod -a -G www-data demo

That adds the user 'demo' to the 'www-data' group. Do ensure you use both the -a and the -G options with the usermod command shown above.

You will need to log out and log back in again to enable the group change.

Check the groups now:

groups
...
# demo www-data

So now I am a member of two groups: My own (demo) and the Apache group (www-data).

Folder setup

Now we need to ensure the public_html folder is owned by the main user (demo) and is part of the Apache group (www-data).

Let's set that up:

sudo chgrp -R www-data /home/demo/public_html

As we are talking about permissions I'll add a quick note regarding the sudo command: It's a good habit to use absolute paths (/home/demo/public_html) as shown above rather than relative paths (~/public_html). It ensures sudo is being used in the correct location.

If you have a public_html folder with symlinks in place then be careful with that command as it will follow the symlinks. In those cases of a working public_html folder, change each folder by hand.

Setgid

Good so far, but remember the command we just gave only affects existing folders. What about anything new?

We can set the ownership so anything new is also in the 'www-data' group.

The first command will change the permissions for the public_html directory to include the "setgid" bit:

sudo chmod 2750 /home/demo/public_html

That will ensure that any new files are given the group 'www-data'. If you have subdirectories, you'll want to run that command for each subdirectory (this type of permission doesn't work with '-R'). Fortunately new subdirectories will be created with the 'setgid' bit set automatically.

If we need to allow write access to Apache, to an uploads directory for example, then set the permissions for that directory like so:

sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads

The permissions only need to be set once as new files will automatically be assigned the correct ownership.

Parsing date string in Go

Use the exact layout numbers described here and a nice blogpost here.

so:

layout := "2006-01-02T15:04:05.000Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout, str)

if err != nil {
    fmt.Println(err)
}
fmt.Println(t)

gives:

>> 2014-11-12 11:45:26.371 +0000 UTC

I know. Mind boggling. Also caught me first time. Go just doesn't use an abstract syntax for datetime components (YYYY-MM-DD), but these exact numbers (I think the time of the first commit of go Nope, according to this. Does anyone know?).

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

https://cdn.rawgit.com is shutting down. Thus, one of the alternate options can be used. JSDeliver is a free cdn that can be used.

// load any GitHub release, commit, or branch

// note: we recommend using npm for projects that support it

https://cdn.jsdelivr.net/gh/user/repo@version/file

// load jQuery v3.2.1

https://cdn.jsdelivr.net/gh/jquery/[email protected]/dist/jquery.min.js

// use a version range instead of a specific version

https://cdn.jsdelivr.net/gh/jquery/[email protected]/dist/jquery.min.js

https://cdn.jsdelivr.net/gh/jquery/jquery@3/dist/jquery.min.js

// omit the version completely to get the latest one

// you should NOT use this in production

https://cdn.jsdelivr.net/gh/jquery/jquery/dist/jquery.min.js

// add ".min" to any JS/CSS file to get a minified version

// if one doesn't exist, we'll generate it for you

https://cdn.jsdelivr.net/gh/jquery/[email protected]/src/core.min.js

// add / at the end to get a directory listing

https://cdn.jsdelivr.net/gh/jquery/jquery/

ref - https://www.jsdelivr.com/?docs=gh

Set cursor position on contentEditable <div>

This solution works in all major browsers:

saveSelection() is attached to the onmouseup and onkeyup events of the div and saves the selection to the variable savedRange.

restoreSelection() is attached to the onfocus event of the div and reselects the selection saved in savedRange.

This works perfectly unless you want the selection to be restored when the user clicks the div aswell (which is a bit unintuitative as normally you expect the cursor to go where you click but code included for completeness)

To achieve this the onclick and onmousedown events are canceled by the function cancelEvent() which is a cross browser function to cancel the event. The cancelEvent() function also runs the restoreSelection() function because as the click event is cancelled the div doesn't receive focus and therefore nothing is selected at all unless this functions is run.

The variable isInFocus stores whether it is in focus and is changed to "false" onblur and "true" onfocus. This allows click events to be cancelled only if the div is not in focus (otherwise you would not be able to change the selection at all).

If you wish to the selection to be change when the div is focused by a click, and not restore the selection onclick (and only when focus is given to the element programtically using document.getElementById("area").focus(); or similar then simply remove the onclick and onmousedown events. The onblur event and the onDivBlur() and cancelEvent() functions can also safely be removed in these circumstances.

This code should work if dropped directly into the body of an html page if you want to test it quickly:

<div id="area" style="width:300px;height:300px;" onblur="onDivBlur();" onmousedown="return cancelEvent(event);" onclick="return cancelEvent(event);" contentEditable="true" onmouseup="saveSelection();" onkeyup="saveSelection();" onfocus="restoreSelection();"></div>
<script type="text/javascript">
var savedRange,isInFocus;
function saveSelection()
{
    if(window.getSelection)//non IE Browsers
    {
        savedRange = window.getSelection().getRangeAt(0);
    }
    else if(document.selection)//IE
    { 
        savedRange = document.selection.createRange();  
    } 
}

function restoreSelection()
{
    isInFocus = true;
    document.getElementById("area").focus();
    if (savedRange != null) {
        if (window.getSelection)//non IE and there is already a selection
        {
            var s = window.getSelection();
            if (s.rangeCount > 0) 
                s.removeAllRanges();
            s.addRange(savedRange);
        }
        else if (document.createRange)//non IE and no selection
        {
            window.getSelection().addRange(savedRange);
        }
        else if (document.selection)//IE
        {
            savedRange.select();
        }
    }
}
//this part onwards is only needed if you want to restore selection onclick
var isInFocus = false;
function onDivBlur()
{
    isInFocus = false;
}

function cancelEvent(e)
{
    if (isInFocus == false && savedRange != null) {
        if (e && e.preventDefault) {
            //alert("FF");
            e.stopPropagation(); // DOM style (return false doesn't always work in FF)
            e.preventDefault();
        }
        else {
            window.event.cancelBubble = true;//IE stopPropagation
        }
        restoreSelection();
        return false; // false = IE style
    }
}
</script>

Global variable Python classes

What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut or via an instance e.g. shape.lolwut but be careful while setting it as it will set an instance level attribute not class attribute

class Shape(object):
    lolwut = 1

shape = Shape()

print Shape.lolwut,  # 1
print shape.lolwut,  # 1

# setting shape.lolwut would not change class attribute lolwut 
# but will create it in the instance
shape.lolwut = 2

print Shape.lolwut,  # 1
print shape.lolwut,  # 2

# to change class attribute access it via class
Shape.lolwut = 3

print Shape.lolwut,  # 3
print shape.lolwut   # 2 

output:

1 1 1 2 3 2

Somebody may expect output to be 1 1 2 2 3 3 but it would be incorrect

How to check if a registry value exists using C#?

        internal static Func<string, string, bool> regKey = delegate (string KeyLocation, string Value)
        {
            // get registry key with Microsoft.Win32.Registrys
            RegistryKey rk = (RegistryKey)Registry.GetValue(KeyLocation, Value, null); // KeyLocation and Value variables from method, null object because no default value is present. Must be casted to RegistryKey because method returns object.
            if ((rk) == null) // if the RegistryKey is null which means it does not exist
            {
                // the key does not exist
                return false; // return false because it does not exist
            }
            // the registry key does exist
            return true; // return true because it does exist
        };

usage:

        // usage:
        /* Create Key - while (loading)
        {
            RegistryKey k;
            k = Registry.CurrentUser.CreateSubKey("stuff");
            k.SetValue("value", "value");
            Thread.Sleep(int.MaxValue);
        }; // no need to k.close because exiting control */


        if (regKey(@"HKEY_CURRENT_USER\stuff  ...  ", "value"))
        {
             // key exists
             return;
        }
        // key does not exist

UITableViewCell Selected Background Color on Multiple Selection

UITableViewCell has an attribute multipleSelectionBackgroundView. https://developer.apple.com/documentation/uikit/uitableviewcell/1623226-selectedbackgroundview

Just create an UIView define the .backgroundColor of your choice and assign it to your cells .multipleSelectionBackgroundView attribute.

cURL equivalent in Node.js?

See the documentation for the HTTP module for a full example:

https://nodejs.org/api/http.html#http_http_request_options_callback

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

I think this will work even though this was forever ago.

SELECT employee_number, Row_Number()  
   OVER (PARTITION BY course_code ORDER BY course_completion_date DESC ) as rownum
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
   AND rownum = 1

If you want to get the last Id if the date is the same then you can use this assuming your primary key is Id.

SELECT employee_number, Row_Number()  
   OVER (PARTITION BY course_code ORDER BY course_completion_date DESC, Id Desc) as rownum    FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
   AND rownum = 1

Delete a dictionary item if the key exists

You can use dict.pop:

 mydict.pop("key", None)

Note that if the second argument, i.e. None is not given, KeyError is raised if the key is not in the dictionary. Providing the second argument prevents the conditional exception.

Laravel back button

The following is a complete Blade (the templating engine Laravel uses) solution:

{!! link_to(URL::previous(), 'Cancel', ['class' => 'btn btn-default']) !!}

The options array with the class is optional, in this case it specifies the styling for a Bootstrap 3 button.

DTO pattern: Best way to copy properties between two objects

I had an application that I needed to convert from a JPA entity to DTO, and I thought about it and finally came up using org.springframework.beans.BeanUtils.copyProperties for copying simple properties and also extending and using org.springframework.binding.convert.service.DefaultConversionService for converting complex properties.

In detail my service was something like this:

@Service("seedingConverterService")
public class SeedingConverterService extends DefaultConversionService implements ISeedingConverterService  {
    @PostConstruct
    public void init(){
        Converter<Feature,FeatureDTO> featureConverter = new Converter<Feature, FeatureDTO>() {

            @Override
            public FeatureDTO convert(Feature f) {
                FeatureDTO dto = new FeatureDTO();
                //BeanUtils.copyProperties(f, dto,"configurationModel");
                BeanUtils.copyProperties(f, dto);
                dto.setConfigurationModelId(f.getConfigurationModel()==null?null:f.getConfigurationModel().getId());
                return dto;
            }
        };

        Converter<ConfigurationModel,ConfigurationModelDTO> configurationModelConverter = new Converter<ConfigurationModel,ConfigurationModelDTO>() {
            @Override
            public ConfigurationModelDTO convert(ConfigurationModel c) {
                ConfigurationModelDTO dto = new ConfigurationModelDTO();
                //BeanUtils.copyProperties(c, dto, "features");
                BeanUtils.copyProperties(c, dto);
                dto.setAlgorithmId(c.getAlgorithm()==null?null:c.getAlgorithm().getId());
                List<FeatureDTO> l = c.getFeatures().stream().map(f->featureConverter.convert(f)).collect(Collectors.toList());
                dto.setFeatures(l);
                return dto;
            }
        };
        addConverter(featureConverter);
        addConverter(configurationModelConverter);
    }
}

Android: how to get the current day of the week (Monday, etc...) in the user's language?

tl;dr

String output = 
    LocalDate.now( ZoneId.of( "America/Montreal" ) )
             .getDayOfWeek()
             .getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;

java.time

The java.time classes built into Java 8 and later and back-ported to Java 6 & 7 and to Android include the handy DayOfWeek enum.

The days are numbered according to the standard ISO 8601 definition, 1-7 for Monday-Sunday.

DayOfWeek dow = DayOfWeek.of( 1 );

This enum includes the getDisplayName method to generate a String of the localized translated name of the day.

The Locale object specifies a human language to be used in translation, and specifies cultural norms to decide issues such as capitalization and punctuation.

String output = DayOfWeek.MONDAY.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;

To get today’s date, use the LocalDate class. Note that a time zone is crucial as for any given moment the date varies around the globe.

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
DayOfWeek dow = today.getDayOfWeek();
String output = dow.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;

Keep in mind that the locale has nothing to do with the time zone.two separate distinct orthogonal issues. You might want a French presentation of a date-time zoned in India (Asia/Kolkata).

Joda-Time

UPDATE: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

The Joda-Time library provides Locale-driven localization of date-time values.

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zone );

Locale locale = Locale.CANADA_FRENCH;
DateTimeFormatter formatterUnJourQuébécois = DateTimeFormat.forPattern( "EEEE" ).withLocale( locale );

String output = formatterUnJourQuébécois.print( now );

System.out.println("output: " + output );

output: samedi


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

matplotlib get ylim values

Leveraging from the good answers above and assuming you were only using plt as in

import matplotlib.pyplot as plt

then you can get all four plot limits using plt.axis() as in the following example.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5, 6, 7, 8]  # fake data
y = [1, 2, 3, 4, 3, 2, 5, 6]

plt.plot(x, y, 'k')

xmin, xmax, ymin, ymax = plt.axis()

s = 'xmin = ' + str(round(xmin, 2)) + ', ' + \
    'xmax = ' + str(xmax) + '\n' + \
    'ymin = ' + str(ymin) + ', ' + \
    'ymax = ' + str(ymax) + ' '

plt.annotate(s, (1, 5))

plt.show()

The above code should produce the following output plot. enter image description here

Reset all changes after last commit in git

How can I undo every change made to my directory after the last commit, including deleting added files, resetting modified files, and adding back deleted files?

  1. You can undo changes to tracked files with:

    git reset HEAD --hard
    
  2. You can remove untracked files with:

    git clean -f
    
  3. You can remove untracked files and directories with:

    git clean -fd
    

    but you can't undo change to untracked files.

  4. You can remove ignored and untracked files and directories

    git clean -fdx
    

    but you can't undo change to ignored files.

You can also set clean.requireForce to false:

git config --global --add clean.requireForce false

to avoid using -f (--force) when you use git clean.

Virtualbox shared folder permissions

After adding the user to the vboxsf group, you might need to completely log out of the gnome/xfce/??? session, because someone long ago decided that group affiliation should be cached at first login to the window system.

Or go old school:

% newgrp vboxsf

in any shell you want to use to access the folder. Luckily, newgrp looks up the group list for itself and doesn't used the cached values. You'll still need to log out and back in to access the folder from something other than a shell.

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

You can also use this stored procedure if you only want to truncate all tables in a specific schema:

-- =============================================
-- Author:      Ben de Ridder
-- Create date: 20160513
-- Description: Truncate all tables in schema
-- =============================================
CREATE PROCEDURE TruncateAllTablesInSchema
    @schema nvarchar(50)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    DECLARE @table nVARCHAR(255)

    DECLARE db_cursor CURSOR FOR 
        select t.name
          from sys.tables t inner join
               sys.schemas s on 
                    t.schema_id=s.schema_id
         where s.name=@schema
         order by 1

    OPEN db_cursor   

    FETCH NEXT FROM db_cursor INTO @table   

    WHILE @@FETCH_STATUS = 0   
    BEGIN   
           declare @sql nvarchar(1000)

           set @sql = 'truncate table [' + @schema + '].[' + @table + ']'

           exec sp_sqlexec @sql

           FETCH NEXT FROM db_cursor INTO @table   
    END   

    CLOSE db_cursor   
    DEALLOCATE db_cursor 

END
GO

How to move a file?

After Python 3.4, you can also use pathlib's class Path to move file.

from pathlib import Path

Path("path/to/current/file.foo").rename("path/to/new/destination/for/file.foo")

https://docs.python.org/3.4/library/pathlib.html#pathlib.Path.rename

How to list all available Kafka brokers in a cluster?

If you are using new version of Kafka e.g. 5.3.3, you can use

kafka-broker-api-versions  --bootstrap-server BROKER | grep 9092

You just need to pass one of the brokers

How to set the range of y-axis for a seaborn boxplot?

It is standard matplotlib.pyplot:

...
import matplotlib.pyplot as plt
plt.ylim(10, 40)

Or simpler, as mwaskom comments below:

ax.set(ylim=(10, 40))

enter image description here

CURL alternative in Python

import requests

url = 'https://example.tld/'
auth = ('username', 'password')

r = requests.get(url, auth=auth)
print r.content

This is the simplest I've been able to get it.

Plotting multiple curves same graph and same scale

points or lines comes handy if

  • y2 is generated later, or
  • the new data does not have the same x but still should go into the same coordinate system.

As your ys share the same x, you can also use matplot:

matplot (x, cbind (y1, y2), pch = 19)

matplot (x, cbind (y1, y2), pch = 19)

(without the pch matplopt will plot the column numbers of the y matrix instead of dots).

Get Application Directory

I got this

String appPath = App.getApp().getApplicationContext().getFilesDir().getAbsolutePath();

from here:

Creating default object from empty value in PHP?

This message has been E_STRICT for PHP <= 5.3. Since PHP 5.4, it was unluckilly changed to E_WARNING. Since E_WARNING messages are useful, you don't want to disable them completely.

To get rid of this warning, you must use this code:

if (!isset($res)) 
    $res = new stdClass();

$res->success = false;

This is fully equivalent replacement. It assures exactly the same thing which PHP is silently doing - unfortunatelly with warning now - implicit object creation. You should always check if the object already exists, unless you are absolutely sure that it doesn't. The code provided by Michael is no good in general, because in some contexts the object might sometimes be already defined at the same place in code, depending on circumstances.

How to convert Javascript datetime to C# datetime?

If you want to send dates to C# from JS that is actually quite simple - if sending UTC dates is acceptable.

var date = new Date("Tue Jul 12 2011 16:00:00 GMT-0700");
var dateStrToSendToServer = date.toISOString();

... send to C# side ...

var success = DateTimeOffset.TryParse(jsISOStr, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var result);

C# DateTime already understands ISO date formats and will parse it just fine.

To format from C# to JS just use DateTime.UtcNow.ToString("o").

Personally, I'm never comfortable relying on math and logic between different environments to get the milliseconds/ticks to show the EXACT same date and time a user may see on the client (especially where it matters). I would do the same when transferring currency as well (use strings instead to be safe, or separate dollars and cents between two different integers). Sending the date/time as separate values would be just a good (see accepted answer).

Execution failed for task ':app:compileDebugAidl': aidl is missing

The problem was actually in the version Android Studio 1.3 updated from the canary channel. I updated my studio to 1.3 and got the same error but reverting back to studio 1.2.1 made my project run fine.

Date validation with ASP.NET validator

A CustomValidator would also work here:

<asp:CustomValidator runat="server"
    ID="valDateRange" 
    ControlToValidate="txtDatecompleted"
    onservervalidate="valDateRange_ServerValidate" 
    ErrorMessage="enter valid date" />

Code-behind:

protected void valDateRange_ServerValidate(object source, ServerValidateEventArgs args)
{
    DateTime minDate = DateTime.Parse("1000/12/28");
    DateTime maxDate = DateTime.Parse("9999/12/28");
    DateTime dt;

    args.IsValid = (DateTime.TryParse(args.Value, out dt) 
                    && dt <= maxDate 
                    && dt >= minDate);
}

What is the attribute property="og:title" inside meta tag?

og:title is one of the open graph meta tags. og:... properties define objects in a social graph. They are used for example by Facebook.

og:title stands for the title of your object as it should appear within the graph (see here for more http://ogp.me/ )

How to get the next auto-increment id in mysql

Simple query would do SHOW TABLE STATUS LIKE 'table_name'

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"

For me the issue was: Using Hibernate, I saw that it already used slf4j, and it was in my classpath already, so I decided to use it. The next step - adding imlementor for slf4j, so I added to maven:

<dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-jdk14</artifactId>
        <version>1.7.25</version>
</dependency>

But it failed with error! SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”

The solution was: Hibernate's dependency of slf4j was version 1.7.26, and I added minor version dependency 1.7.25. So when I fixed this - all became OK

Remove scroll bar track from ScrollView in Android

By using below, solved the problem

android:scrollbarThumbVertical="@null"

Using str_replace so that it only acts on the first match?

To expand on zombat's answer (which I believe to be the best answer), I created a recursive version of his function that takes in a $limit parameter to specify how many occurrences you want to replace.

function str_replace_limit($haystack, $needle, $replace, $limit, $start_pos = 0) {
    if ($limit <= 0) {
        return $haystack;
    } else {
        $pos = strpos($haystack,$needle,$start_pos);
        if ($pos !== false) {
            $newstring = substr_replace($haystack, $replace, $pos, strlen($needle));
            return str_replace_limit($newstring, $needle, $replace, $limit-1, $pos+strlen($replace));
        } else {
            return $haystack;
        }
    }
}

How do I access store state in React Redux?

You want to do more than just getState. You want to react to changes in the store.

If you aren't using react-redux, you can do this:

function rerender() {
    const state = store.getState();
    render(
        <div>
            { state.items.map((item) => <p> {item.title} </p> )}
        </div>,
        document.getElementById('app')
    );
}

// subscribe to store
store.subscribe(rerender);

// do initial render
rerender();

// dispatch more actions and view will update

But better is to use react-redux. In this case you use the Provider like you mentioned, but then use connect to connect your component to the store.

How to return the current timestamp with Moment.js?

moment().unix() you will get a unix timestamp

moment().valueOf() you will get a full timestamp

Adding a simple UIAlertView

UIAlertView *alert = [[UIAlertView alloc]
 initWithTitle:@"Title" 
 message:@"Message" 
 delegate:nil //or self
 cancelButtonTitle:@"OK"
 otherButtonTitles:nil];

 [alert show];
 [alert autorelease];

How to get PHP $_GET array?

You could make id a series of comma-seperated values, like this:

index.php?id=1,2,3&name=john

Then, within your PHP code, explode it into an array:

$values = explode(",", $_GET["id"]);
print count($values) . " values passed.";

This will maintain brevity. The other (more commonly used with $_POST) method is to use array-style square-brackets:

index.php?id[]=1&id[]=2&id[]=3&name=john

But that clearly would be much more verbose.

How to add new DataRow into DataTable?

If need to copy from another table then need to copy structure first:

DataTable copyDt = existentDt.Clone();
copyDt.ImportRow(existentDt.Rows[0]);

HTTP 404 when accessing .svc file in IIS

In my case, the error was caused by incorrect mapping settings in the file applicationhost.config (\System32\inetsrv\config). For some reason, Visual Studio 2013 corrupted it while creating a virtual directory in IIS. The fix was to manually edit the sites section in the file.

Style input element to fill remaining width of its container

Please use flexbox for this. You have a container that is going to flex its children into a row. The first child takes its space as needed. The second one flexes to take all the remaining space:

_x000D_
_x000D_
<div style="display:flex;flex-direction:row">_x000D_
    <label for="MyInput">label&nbsp;text</label>_x000D_
    <input type="text" id="MyInput" style="flex:1" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to map to multiple elements with Java 8 streams?

It's an interesting question, because it shows that there are a lot of different approaches to achieve the same result. Below I show three different implementations.


Default methods in Collection Framework: Java 8 added some methods to the collections classes, that are not directly related to the Stream API. Using these methods, you can significantly simplify the implementation of the non-stream implementation:

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    Map<String, DataSet> result = new HashMap<>();
    multiDataPoints.forEach(pt ->
        pt.keyToData.forEach((key, value) ->
            result.computeIfAbsent(
                key, k -> new DataSet(k, new ArrayList<>()))
            .dataPoints.add(new DataPoint(pt.timestamp, value))));
    return result.values();
}

Stream API with flatten and intermediate data structure: The following implementation is almost identical to the solution provided by Stuart Marks. In contrast to his solution, the following implementation uses an anonymous inner class as intermediate data structure.

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .flatMap(mdp -> mdp.keyToData.entrySet().stream().map(e ->
            new Object() {
                String key = e.getKey();
                DataPoint dataPoint = new DataPoint(mdp.timestamp, e.getValue());
            }))
        .collect(
            collectingAndThen(
                groupingBy(t -> t.key, mapping(t -> t.dataPoint, toList())),
                m -> m.entrySet().stream().map(e -> new DataSet(e.getKey(), e.getValue())).collect(toList())));
}

Stream API with map merging: Instead of flattening the original data structures, you can also create a Map for each MultiDataPoint, and then merge all maps into a single map with a reduce operation. The code is a bit simpler than the above solution:

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .map(mdp -> mdp.keyToData.entrySet().stream()
            .collect(toMap(e -> e.getKey(), e -> asList(new DataPoint(mdp.timestamp, e.getValue())))))
        .reduce(new HashMap<>(), mapMerger())
        .entrySet().stream()
        .map(e -> new DataSet(e.getKey(), e.getValue()))
        .collect(toList());
}

You can find an implementation of the map merger within the Collectors class. Unfortunately, it is a bit tricky to access it from the outside. Following is an alternative implementation of the map merger:

<K, V> BinaryOperator<Map<K, List<V>>> mapMerger() {
    return (lhs, rhs) -> {
        Map<K, List<V>> result = new HashMap<>();
        lhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
        rhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
        return result;
    };
}

What's an object file in C?

  1. An Object file is the compiled file itself. There is no difference between the two.

  2. An executable file is formed by linking the Object files.

  3. Object file contains low level instructions which can be understood by the CPU. That is why it is also called machine code.

  4. This low level machine code is the binary representation of the instructions which you can also write directly using assembly language and then process the assembly language code (represented in English) into machine language (represented in Hex) using an assembler.

Here's a typical high level flow for this process for code in High Level Language such as C

--> goes through pre-processor

--> to give optimized code, still in C

--> goes through compiler

--> to give assembly code

--> goes through an assembler

--> to give code in machine language which is stored in OBJECT FILES

--> goes through Linker

--> to get an executable file.

This flow can have some variations for example most compilers can directly generate the machine language code, without going through an assembler. Similarly, they can do the pre-processing for you. Still, it is nice to break up the constituents for a better understanding.

400 vs 422 response to POST of data

400 Bad Request is proper HTTP status code for your use case. The code is defined by HTTP/0.9-1.1 RFC.

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

http://tools.ietf.org/html/rfc2616#section-10.4.1

422 Unprocessable Entity is defined by RFC 4918 - WebDav. Note that there is slight difference in comparison to 400, see quoted text below.

This error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

To keep uniform interface you should use 422 only in a case of XML responses and you should also support all status codes defined by Webdav extension, not just 422.

http://tools.ietf.org/html/rfc4918#page-78

See also Mark Nottingham's post on status codes:

it’s a mistake to try to map each part of your application “deeply” into HTTP status codes; in most cases the level of granularity you want to be aiming for is much coarser. When in doubt, it’s OK to use the generic status codes 200 OK, 400 Bad Request and 500 Internal Service Error when there isn’t a better fit.

How to Think About HTTP Status Codes

What is the iBeacon Bluetooth Profile

If the reason you ask this question is because you want to use Core Bluetooth to advertise as an iBeacon rather than using the standard API, you can easily do so by advertising an NSDictionary such as:

{
    kCBAdvDataAppleBeaconKey = <a7c4c5fa a8dd4ba1 b9a8a240 584f02d3 00040fa0 c5>;
}

See this answer for more information.

Can I catch multiple Java exceptions in the same catch clause?

Not exactly before Java 7 but, I would do something like this:

Java 6 and before

try {
  //.....
} catch (Exception exc) {
  if (exc instanceof IllegalArgumentException || exc instanceof SecurityException || 
     exc instanceof IllegalAccessException || exc instanceof NoSuchFieldException ) {

     someCode();

  } else if (exc instanceof RuntimeException) {
     throw (RuntimeException) exc;     

  } else {
    throw new RuntimeException(exc);
  }

}



Java 7

try {
  //.....
} catch ( IllegalArgumentException | SecurityException |
         IllegalAccessException |NoSuchFieldException exc) {
  someCode();
}

How to generate a HTML page dynamically using PHP?

It looks funny but it works.

<?php 
$file = 'newpage.html';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "<!doctype html><html>
<head><meta charset='utf-8'>
<title>new file</title>
</head><body><h3>New HTML file</h3>
</body></html>
";
// Write the contents back to the file
file_put_contents($file, $current);
?>

Setting an image for a UIButton in code

-(void)buttonTouched:(id)sender
{
    UIButton *btn = (UIButton *)sender;

    if( [[btn imageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:@"icon-Locked.png"]])
    {
        [btn setImage:[UIImage imageNamed:@"icon-Unlocked.png"] forState:UIControlStateNormal];
        // other statements....
    }
    else
    {
        [btn setImage:[UIImage imageNamed:@"icon-Locked.png"] forState:UIControlStateNormal];
        // other statements....
    }
}

How to "scan" a website (or page) for info, and bring it into my program?

You'd probably want to look at the HTML to see if you can find strings that are unique and near your text, then you can use line/char-offsets to get to the data.

Could be awkward in Java, if there aren't any XML classes similar to the ones found in System.XML.Linq in C#.

How to find length of dictionary values

Lets do some experimentation, to see how we could get/interpret the length of different dict/array values in a dict.

create our test dict, see list and dict comprehensions:

>>> my_dict = {x:[i for i in range(x)] for x in range(4)}
>>> my_dict
{0: [], 1: [0], 2: [0, 1], 3: [0, 1, 2]}

Get the length of the value of a specific key:

>>> my_dict[3]
[0, 1, 2]
>>> len(my_dict[3])
3

Get a dict of the lengths of the values of each key:

>>> key_to_value_lengths = {k:len(v) for k, v in my_dict.items()}
{0: 0, 1: 1, 2: 2, 3: 3}
>>> key_to_value_lengths[2]
2

Get the sum of the lengths of all values in the dict:

>>> [len(x) for x in my_dict.values()]
[0, 1, 2, 3]
>>> sum([len(x) for x in my_dict.values()])
6

How to get full width in body element

You should set body and html to position:fixed;, and then set right:, left:, top:, and bottom: to 0;. That way, even if content overflows it will not extend past the limits of the viewport.

For example:

<html>
<body>
    <div id="wrapper"></div>
</body>
</html>

CSS:

html, body, {
    position:fixed;
    top:0;
    bottom:0;
    left:0;
    right:0;
}

JS Fiddle Example

Caveat: Using this method, if the user makes their window smaller, content will be cut off.

How can I remove the "No file chosen" tooltip from a file input in Chrome?

You will need to customise the control quite a lot to achieve this.

Please follow the guide at: http://www.quirksmode.org/dom/inputfile.html

Why does Math.Round(2.5) return 2 instead of 3?

This post has the answer you are looking for:

http://weblogs.asp.net/sfurman/archive/2003/03/07/3537.aspx

Basically this is what it says:

Return Value

The number nearest value with precision equal to digits. If value is halfway between two numbers, one of which is even and the other odd, then the even number is returned. If the precision of value is less than digits, then value is returned unchanged.

The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding to nearest, or banker's rounding. If digits is zero, this kind of rounding is sometimes called rounding toward zero.

Batch script loop

Template for a simple but counted loop:

set loopcount=[Number of times]
:loop
[Commands you want to repeat]
set /a loopcount=loopcount-1
if %loopcount%==0 goto exitloop
goto loop
:exitloop

Example: Say "Hello World!" 5 times:

@echo off
set loopcount=5
:loop
echo Hello World!
set /a loopcount=loopcount-1
if %loopcount%==0 goto exitloop
goto loop
:exitloop
pause

This example will output:

Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Press any key to continue . . .

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

DATE: It is used for values with a date part but no time part. MySQL retrieves and displays DATE values in YYYY-MM-DD format. The supported range is 1000-01-01 to 9999-12-31.

DATETIME: It is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in YYYY-MM-DD HH:MM:SS format. The supported range is 1000-01-01 00:00:00 to 9999-12-31 23:59:59.

TIMESTAMP: It is also used for values that contain both date and time parts, and includes the time zone. TIMESTAMP has a range of 1970-01-01 00:00:01 UTC to 2038-01-19 03:14:07 UTC.

TIME: Its values are in HH:MM:SS format (or HHH:MM:SS format for large hours values). TIME values may range from -838:59:59 to 838:59:59. The hours part may be so large because the TIME type can be used not only to represent a time of day (which must be less than 24 hours), but also elapsed time or a time interval between two events (which may be much greater than 24 hours, or even negative).

HTML5: Slider with two inputs possible?

I've been looking for a lightweight, dependency free dual slider for some time (it seemed crazy to import jQuery just for this) and there don't seem to be many out there. I ended up modifying @Wildhoney's code a bit and really like it.

_x000D_
_x000D_
function getVals(){_x000D_
  // Get slider values_x000D_
  var parent = this.parentNode;_x000D_
  var slides = parent.getElementsByTagName("input");_x000D_
    var slide1 = parseFloat( slides[0].value );_x000D_
    var slide2 = parseFloat( slides[1].value );_x000D_
  // Neither slider will clip the other, so make sure we determine which is larger_x000D_
  if( slide1 > slide2 ){ var tmp = slide2; slide2 = slide1; slide1 = tmp; }_x000D_
  _x000D_
  var displayElement = parent.getElementsByClassName("rangeValues")[0];_x000D_
      displayElement.innerHTML = slide1 + " - " + slide2;_x000D_
}_x000D_
_x000D_
window.onload = function(){_x000D_
  // Initialize Sliders_x000D_
  var sliderSections = document.getElementsByClassName("range-slider");_x000D_
      for( var x = 0; x < sliderSections.length; x++ ){_x000D_
        var sliders = sliderSections[x].getElementsByTagName("input");_x000D_
        for( var y = 0; y < sliders.length; y++ ){_x000D_
          if( sliders[y].type ==="range" ){_x000D_
            sliders[y].oninput = getVals;_x000D_
            // Manually trigger event first time to display values_x000D_
            sliders[y].oninput();_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
}
_x000D_
  section.range-slider {_x000D_
    position: relative;_x000D_
    width: 200px;_x000D_
    height: 35px;_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
section.range-slider input {_x000D_
    pointer-events: none;_x000D_
    position: absolute;_x000D_
    overflow: hidden;_x000D_
    left: 0;_x000D_
    top: 15px;_x000D_
    width: 200px;_x000D_
    outline: none;_x000D_
    height: 18px;_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
}_x000D_
_x000D_
section.range-slider input::-webkit-slider-thumb {_x000D_
    pointer-events: all;_x000D_
    position: relative;_x000D_
    z-index: 1;_x000D_
    outline: 0;_x000D_
}_x000D_
_x000D_
section.range-slider input::-moz-range-thumb {_x000D_
    pointer-events: all;_x000D_
    position: relative;_x000D_
    z-index: 10;_x000D_
    -moz-appearance: none;_x000D_
    width: 9px;_x000D_
}_x000D_
_x000D_
section.range-slider input::-moz-range-track {_x000D_
    position: relative;_x000D_
    z-index: -1;_x000D_
    background-color: rgba(0, 0, 0, 1);_x000D_
    border: 0;_x000D_
}_x000D_
section.range-slider input:last-of-type::-moz-range-track {_x000D_
    -moz-appearance: none;_x000D_
    background: none transparent;_x000D_
    border: 0;_x000D_
}_x000D_
  section.range-slider input[type=range]::-moz-focus-outer {_x000D_
  border: 0;_x000D_
}
_x000D_
<!-- This block can be reused as many times as needed -->_x000D_
<section class="range-slider">_x000D_
  <span class="rangeValues"></span>_x000D_
  <input value="5" min="0" max="15" step="0.5" type="range">_x000D_
  <input value="10" min="0" max="15" step="0.5" type="range">_x000D_
</section>
_x000D_
_x000D_
_x000D_

Get first key in a (possibly) associative array?

If efficiency is not that important for you, you can use array_keys($yourArray)[0] in PHP 5.4 (and higher).

Examples:

# 1
$arr = ["my" => "test", "is" => "best"];    
echo array_keys($arr)[0] . "\r\n"; // prints "my"


# 2
$arr = ["test", "best"];
echo array_keys($arr)[0] . "\r\n"; // prints "0"

# 3
$arr = [1 => "test", 2 => "best"];
echo array_keys($arr)[0] . "\r\n"; // prints "1"

The advantage over solution:

list($firstKey) = array_keys($yourArray);

is that you can pass array_keys($arr)[0] as a function parameter (i.e. doSomething(array_keys($arr)[0], $otherParameter)).

HTH

In VBA get rid of the case sensitivity when comparing words?

You can convert both the values to lower case and compare.

Here is an example:

If LCase(Range("J6").Value) = LCase("Tawi") Then
   Range("J6").Value = "Tawi-Tawi"
End If

Understanding passport serialize deserialize

For anyone using Koa and koa-passport:

Know that the key for the user set in the serializeUser method (often a unique id for that user) will be stored in:

this.session.passport.user

When you set in done(null, user) in deserializeUser where 'user' is some user object from your database:

this.req.user OR this.passport.user

for some reason this.user Koa context never gets set when you call done(null, user) in your deserializeUser method.

So you can write your own middleware after the call to app.use(passport.session()) to put it in this.user like so:

app.use(function * setUserInContext (next) {
  this.user = this.req.user
  yield next
})

If you're unclear on how serializeUser and deserializeUser work, just hit me up on twitter. @yvanscher

Excel Formula to SUMIF date falls in particular month

Try this instead:

  =SUM(IF(MONTH($A$2:$A$6)=1,$B$2:$B$6,0))

It's an array formula, so you will need to enter it with the Control-Shift-Enter key combination.

Here's how the formula works.

  1. MONTH($A$2:$A$6) creates an array of numeric values of the month for the dates in A2:A6, that is,
    {1, 1, 1, 2, 2}.
  2. Then the comparison {1, 1, 1, 2, 2}= 1 produces the array {TRUE, TRUE, TRUE, FALSE, FALSE}, which comprises the condition for the IF statement.
  3. The IF statement then returns an array of values, with {430, 96, 400.. for the values of the sum ranges where the month value equals 1 and ..0,0} where the month value does not equal 1.
  4. That array {430, 96, 400, 0, 0} is then summed to get the answer you are looking for.

This is essentially equivalent to what the SUMIF and SUMIFs functions do. However, neither of those functions support the kind of calculation you tried to include in the conditional.

It's also possible to drop the IF completely. Since TRUE and FALSE can also be treated as 1 and 0, this formula--=SUM((MONTH($A$2:$A$6)=1)*$B$2:$B$6)--also works.

Heads up: This does not work in Google Spreadsheets

How to close off a Git Branch?

Yes, just delete the branch by running git push origin :branchname. To fix a new issue later, branch off from master again.

How do I save a stream to a file in C#?

Why not use a FileStream object?

public void SaveStreamToFile(string fileFullPath, Stream stream)
{
    if (stream.Length == 0) return;

    // Create a FileStream object to write a stream to a file
    using (FileStream fileStream = System.IO.File.Create(fileFullPath, (int)stream.Length))
    {
        // Fill the bytes[] array with the stream data
        byte[] bytesInStream = new byte[stream.Length];
        stream.Read(bytesInStream, 0, (int)bytesInStream.Length);

        // Use FileStream object to write to the specified file
        fileStream.Write(bytesInStream, 0, bytesInStream.Length);
     }
}

Apache - MySQL Service detected with wrong path. / Ports already in use

This is how I solved similar problem:

  1. Launch XAMPP Control Panel.
  2. Uninstall the MySQL service: click 'green check' button beside MySQL, under Service column. The 'green check' button will change into 'red cross' button.
  3. Exit XAMPP, and relaunch it again.
  4. Click Start.

I hope it can help solve your problem too.

Convert or extract TTC font to TTF - how to?

You can use onlinefontconverter.com site. It works fine and have plenty of output formats (afm bin cff dfont eot pfa pfb pfm ps pt3 suit svg t42 tfm ttc ttf woff). One of the advantages I saw, is that it export all the fonts contained inside the ttc at once (which is very convenient).

When is it appropriate to use UDP instead of TCP?

UDP has lower overhead, as stated already is good for streaming things like video and audio where it is better to just lose a packet then try to resend and catch up.

There are no guarantees on TCP delivery, you are simply supposed to be told if the socket disconnected or basically if the data is not going to arrive. Otherwise it gets there when it gets there.

A big thing that people forget is that udp is packet based, and tcp is bytestream based, there is no guarantee that the "tcp packet" you sent is the packet that shows up on the other end, it can be dissected into as many packets as the routers and stacks desire. So your software has the additional overhead of parsing bytes back into usable chunks of data, that can take a fair amount of overhead. UDP can be out of order so you have to number your packets or use some other mechanism to re-order them if you care to do so. But if you get that udp packet it arrives with all the same bytes in the same order as it left, no changes. So the term udp packet makes sense but tcp packet doesnt necessarily. TCP has its own re-try and ordering mechanism that is hidden from your application, you can re-invent that with UDP to tailor it to your needs.

UDP is far easier to write code for on both ends, basically because you do not have to make and maintain the point to point connections. My question is typically where are the situations where you would want the TCP overhead? And if you take shortcuts like assuming a tcp "packet" received is the complete packet that was sent, are you better off? (you are likely to throw away two packets if you bother to check the length/content)

Replace invalid values with None in Pandas DataFrame

where is probably what you're looking for. So

data=data.where(data=='-', None) 

From the panda docs:

where [returns] an object of same shape as self and whose corresponding entries are from self where cond is True and otherwise are from other).

How do I get a TextBox to only accept numeric input in WPF?

The following code creates a control which you will be able to use like a normal TextBox however it will only take a positive double as an input:

In the XAML you'll be able to use this control like so:

<local:UnsignedDoubleBox/>

In the C# code add the following inside the current namespace:

public class UnsignedDoubleBox : TextBox
    {
        public UnsignedDoubleBox()
        {
            this.PreviewTextInput += defaultPreviewTextInput;
            DataObject.AddPastingHandler(this, defaultTextBoxPasting);
        }

        private bool IsTextAllowed(TextBox textBox, String text)
        {
            //source: https://stackoverflow.com/questions/23397195/in-wpf-does-previewtextinput-always-give-a-single-character-only#comment89374810_23406386
            String newText = textBox.Text.Insert(textBox.CaretIndex, text);
            double res;
            return double.TryParse(newText, out res) && res >= 0;
        }
        //source: https://stackoverflow.com/a/1268648/13093413
        private void defaultTextBoxPasting(object sender, DataObjectPastingEventArgs e)
        {
            if (e.DataObject.GetDataPresent(typeof(String)))
            {
                String text = (String)e.DataObject.GetData(typeof(String));

                if (!IsTextAllowed((TextBox)sender, text))
                {
                    e.CancelCommand();
                }
            }
            else
            {
                e.CancelCommand();
            }
        }

        private void defaultPreviewTextInput(object sender, TextCompositionEventArgs e)
        {

            if (IsTextAllowed((TextBox)sender, e.Text))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

    }

Header set Access-Control-Allow-Origin in .htaccess doesn't work

Just for the record, I was running into the exact same problem and none of the answers worked.

I used a headers checker tool: http://www.webconfs.com/http-header-check.php

I was testing with my IP (http://192.0.2.1/upload) and what came back was the following:

HTTP/1.1 301 Moved Permanently => 
Date => Sat, 10 Jan 2015 04:03:35 GMT
Server => Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/1.0.0e PHP/5.3.8 mod_perl/2.0.4 Perl/v5.10.1
Location => http://192.0.2.1/upload/
Content-Length => 380
Connection => close
Content-Type => text/html; charset=iso-8859-1

There was a redirection happening and the AJAX request does not honor/follow redirects.

It turned out to be the missing slash at the end of the domain (http://192.0.2.1/upload/)

I tested again with slash at the end and I got this below. Added a slash in the script too, and it was now working.

HTTP/1.1 200 OK => 
Date => Sat, 10 Jan 2015 04:03:53 GMT
Server => Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/1.0.0e PHP/5.3.8 mod_perl/2.0.4 Perl/v5.10.1
X-Powered-By => PHP/5.3.8
Access-Control-Allow-Origin => *
Access-Control-Allow-Methods => PUT, GET, POST, DELETE, OPTIONS
Access-Control-Allow-Headers => *
Content-Length => 1435
Connection => close
Content-Type => text/html

Use this tool to test if your headers are good and to troubleshoot what is happening.

Proper way of checking if row exists in table in PL/SQL block

select max( 1 )
  into my_if_has_data
  from MY_TABLE    X
 where X.my_field   = my_condition
   and rownum       = 1;

Not iterating through all records.

If MY_TABLE has no data, then my_if_has_data sets to null.

X close button only using css

Try This Cross In CSS

_x000D_
_x000D_
.close {_x000D_
  position: absolute;_x000D_
  right: 32px;_x000D_
  top: 32px;_x000D_
  width: 32px;_x000D_
  height: 32px;_x000D_
  opacity: 0.3;_x000D_
}_x000D_
.close:hover {_x000D_
  opacity: 1;_x000D_
}_x000D_
.close:before, .close:after {_x000D_
  position: absolute;_x000D_
  left: 15px;_x000D_
  content: ' ';_x000D_
  height: 33px;_x000D_
  width: 2px;_x000D_
  background-color: #333;_x000D_
}_x000D_
.close:before {_x000D_
  transform: rotate(45deg);_x000D_
}_x000D_
.close:after {_x000D_
  transform: rotate(-45deg);_x000D_
}
_x000D_
<a href="#" class="close">
_x000D_
_x000D_
_x000D_

"Submit is not a function" error in JavaScript

This topic has a lot of answers already, but the one that worked best (and simplest - one line!) for me was a modification of the comment made by Neil E. Pearson from Apr 21 2013:

If you're stuck with your submit button being #submit, you can get around it by stealing another form instance's submit() method.

My modification to his method, and what worked for me:

document.createElement('form').submit.call(document.getElementById(frmProduct));

Understanding the Gemfile.lock file

Bundler is a Gem manager which provides a consistent environment for Ruby projects by tracking and installing the exact gems and versions that are needed.

Gemfile and Gemfile.lock are primary products given by Bundler gem (Bundler itself is a gem).

Gemfile contains your project dependency on gem(s), that you manually mention with version(s) specified, but those gem(s) inturn depends on other gem(s) which is resolved by bundler automatically.

Gemfile.lock contain complete snapshot of all the gem(s) in Gemfile along with there associated dependency.

When you first call bundle install, it will create this Gemfile.lock and uses this file in all subsequent calls to bundle install, which ensures that you have all the dependencies installed and will skip dependency installation.

Same happens when you share your code with different machines

You share your Gemfile.lock along with Gemfile, when you run bundle install on other machine it will refer to your Gemfile.lock and skip dependency resolution step, instead it will install all of the same dependent gem(s) that you used on the original machine, which maintains consistency across multiple machines

Why do we need to maintain consistency along multiple machines ?

  • Running different versions on different machines could lead to broken code

  • Suppose, your app used the version 1.5.3 and it works 14 months ago
    without any problems, and you try to install on different machine
    without Gemfile.lock now you get the version 1.5.8. Maybe it's broken with the latest version of some gem(s) and your application will
    fail. Maintaining consistency is of utmost importance (preferred
    practice).

It is also possible to update gem(s) in Gemfile.lock by using bundle update.

This is based on the concept of conservative updating

Are static class variables possible in Python?

Variables declared inside the class definition, but not inside a method are class or static variables:

>>> class MyClass:
...     i = 3
...
>>> MyClass.i
3 

As @millerdev points out, this creates a class-level i variable, but this is distinct from any instance-level i variable, so you could have

>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)

This is different from C++ and Java, but not so different from C#, where a static member can't be accessed using a reference to an instance.

See what the Python tutorial has to say on the subject of classes and class objects.

@Steve Johnson has already answered regarding static methods, also documented under "Built-in Functions" in the Python Library Reference.

class C:
    @staticmethod
    def f(arg1, arg2, ...): ...

@beidy recommends classmethods over staticmethod, as the method then receives the class type as the first argument, but I'm still a little fuzzy on the advantages of this approach over staticmethod. If you are too, then it probably doesn't matter.

List of All Locales and Their Short Codes?

While accepted answer is pretty complete (I used myself in similar question that arised to me), I think it is worth to put the whole supported language codes and variations, as well as encodings, and point user to a file which is present in almost any linux distributions, in case he simply wants a quicker answer and no internet for example.

This is the file /usr/share/i18n/SUPPORTED and its contents:

aa_DJ.UTF-8 UTF-8
aa_DJ ISO-8859-1
aa_ER UTF-8
aa_ER@saaho UTF-8
aa_ET UTF-8
af_ZA.UTF-8 UTF-8
af_ZA ISO-8859-1
am_ET UTF-8
an_ES.UTF-8 UTF-8
an_ES ISO-8859-15
ar_AE.UTF-8 UTF-8
ar_AE ISO-8859-6
ar_BH.UTF-8 UTF-8
ar_BH ISO-8859-6
ar_DZ.UTF-8 UTF-8
ar_DZ ISO-8859-6
ar_EG.UTF-8 UTF-8
ar_EG ISO-8859-6
ar_IN UTF-8
ar_IQ.UTF-8 UTF-8
ar_IQ ISO-8859-6
ar_JO.UTF-8 UTF-8
ar_JO ISO-8859-6
ar_KW.UTF-8 UTF-8
ar_KW ISO-8859-6
ar_LB.UTF-8 UTF-8
ar_LB ISO-8859-6
ar_LY.UTF-8 UTF-8
ar_LY ISO-8859-6
ar_MA.UTF-8 UTF-8
ar_MA ISO-8859-6
ar_OM.UTF-8 UTF-8
ar_OM ISO-8859-6
ar_QA.UTF-8 UTF-8
ar_QA ISO-8859-6
ar_SA.UTF-8 UTF-8
ar_SA ISO-8859-6
ar_SD.UTF-8 UTF-8
ar_SD ISO-8859-6
ar_SY.UTF-8 UTF-8
ar_SY ISO-8859-6
ar_TN.UTF-8 UTF-8
ar_TN ISO-8859-6
ar_YE.UTF-8 UTF-8
ar_YE ISO-8859-6
az_AZ UTF-8
as_IN UTF-8
ast_ES.UTF-8 UTF-8
ast_ES ISO-8859-15
be_BY.UTF-8 UTF-8
be_BY CP1251
be_BY@latin UTF-8
bem_ZM UTF-8
ber_DZ UTF-8
ber_MA UTF-8
bg_BG.UTF-8 UTF-8
bg_BG CP1251
bho_IN UTF-8
bn_BD UTF-8
bn_IN UTF-8
bo_CN UTF-8
bo_IN UTF-8
br_FR.UTF-8 UTF-8
br_FR ISO-8859-1
br_FR@euro ISO-8859-15
brx_IN UTF-8
bs_BA.UTF-8 UTF-8
bs_BA ISO-8859-2
byn_ER UTF-8
ca_AD.UTF-8 UTF-8
ca_AD ISO-8859-15
ca_ES.UTF-8 UTF-8
ca_ES ISO-8859-1
ca_ES@euro ISO-8859-15
ca_FR.UTF-8 UTF-8
ca_FR ISO-8859-15
ca_IT.UTF-8 UTF-8
ca_IT ISO-8859-15
crh_UA UTF-8
cs_CZ.UTF-8 UTF-8
cs_CZ ISO-8859-2
csb_PL UTF-8
cv_RU UTF-8
cy_GB.UTF-8 UTF-8
cy_GB ISO-8859-14
da_DK.UTF-8 UTF-8
da_DK ISO-8859-1
de_AT.UTF-8 UTF-8
de_AT ISO-8859-1
de_AT@euro ISO-8859-15
de_BE.UTF-8 UTF-8
de_BE ISO-8859-1
de_BE@euro ISO-8859-15
de_CH.UTF-8 UTF-8
de_CH ISO-8859-1
de_DE.UTF-8 UTF-8
de_DE ISO-8859-1
de_DE@euro ISO-8859-15
de_LU.UTF-8 UTF-8
de_LU ISO-8859-1
de_LU@euro ISO-8859-15
dv_MV UTF-8
dz_BT UTF-8
el_GR.UTF-8 UTF-8
el_GR ISO-8859-7
el_CY.UTF-8 UTF-8
el_CY ISO-8859-7
en_AG UTF-8
en_AU.UTF-8 UTF-8
en_AU ISO-8859-1
en_BW.UTF-8 UTF-8
en_BW ISO-8859-1
en_CA.UTF-8 UTF-8
en_CA ISO-8859-1
en_DK.UTF-8 UTF-8
en_DK ISO-8859-1
en_GB.UTF-8 UTF-8
en_GB ISO-8859-1
en_HK.UTF-8 UTF-8
en_HK ISO-8859-1
en_IE.UTF-8 UTF-8
en_IE ISO-8859-1
en_IE@euro ISO-8859-15
en_IN UTF-8
en_NG UTF-8
en_NZ.UTF-8 UTF-8
en_NZ ISO-8859-1
en_PH.UTF-8 UTF-8
en_PH ISO-8859-1
en_SG.UTF-8 UTF-8
en_SG ISO-8859-1
en_US.UTF-8 UTF-8
en_US ISO-8859-1
en_ZA.UTF-8 UTF-8
en_ZA ISO-8859-1
en_ZM UTF-8
en_ZW.UTF-8 UTF-8
en_ZW ISO-8859-1
es_AR.UTF-8 UTF-8
es_AR ISO-8859-1
es_BO.UTF-8 UTF-8
es_BO ISO-8859-1
es_CL.UTF-8 UTF-8
es_CL ISO-8859-1
es_CO.UTF-8 UTF-8
es_CO ISO-8859-1
es_CR.UTF-8 UTF-8
es_CR ISO-8859-1
es_CU UTF-8
es_DO.UTF-8 UTF-8
es_DO ISO-8859-1
es_EC.UTF-8 UTF-8
es_EC ISO-8859-1
es_ES.UTF-8 UTF-8
es_ES ISO-8859-1
es_ES@euro ISO-8859-15
es_GT.UTF-8 UTF-8
es_GT ISO-8859-1
es_HN.UTF-8 UTF-8
es_HN ISO-8859-1
es_MX.UTF-8 UTF-8
es_MX ISO-8859-1
es_NI.UTF-8 UTF-8
es_NI ISO-8859-1
es_PA.UTF-8 UTF-8
es_PA ISO-8859-1
es_PE.UTF-8 UTF-8
es_PE ISO-8859-1
es_PR.UTF-8 UTF-8
es_PR ISO-8859-1
es_PY.UTF-8 UTF-8
es_PY ISO-8859-1
es_SV.UTF-8 UTF-8
es_SV ISO-8859-1
es_US.UTF-8 UTF-8
es_US ISO-8859-1
es_UY.UTF-8 UTF-8
es_UY ISO-8859-1
es_VE.UTF-8 UTF-8
es_VE ISO-8859-1
et_EE.UTF-8 UTF-8
et_EE ISO-8859-1
et_EE.ISO-8859-15 ISO-8859-15
eu_ES.UTF-8 UTF-8
eu_ES ISO-8859-1
eu_ES@euro ISO-8859-15
fa_IR UTF-8
ff_SN UTF-8
fi_FI.UTF-8 UTF-8
fi_FI ISO-8859-1
fi_FI@euro ISO-8859-15
fil_PH UTF-8
fo_FO.UTF-8 UTF-8
fo_FO ISO-8859-1
fr_BE.UTF-8 UTF-8
fr_BE ISO-8859-1
fr_BE@euro ISO-8859-15
fr_CA.UTF-8 UTF-8
fr_CA ISO-8859-1
fr_CH.UTF-8 UTF-8
fr_CH ISO-8859-1
fr_FR.UTF-8 UTF-8
fr_FR ISO-8859-1
fr_FR@euro ISO-8859-15
fr_LU.UTF-8 UTF-8
fr_LU ISO-8859-1
fr_LU@euro ISO-8859-15
fur_IT UTF-8
fy_NL UTF-8
fy_DE UTF-8
ga_IE.UTF-8 UTF-8
ga_IE ISO-8859-1
ga_IE@euro ISO-8859-15
gd_GB.UTF-8 UTF-8
gd_GB ISO-8859-15
gez_ER UTF-8
gez_ER@abegede UTF-8
gez_ET UTF-8
gez_ET@abegede UTF-8
gl_ES.UTF-8 UTF-8
gl_ES ISO-8859-1
gl_ES@euro ISO-8859-15
gu_IN UTF-8
gv_GB.UTF-8 UTF-8
gv_GB ISO-8859-1
ha_NG UTF-8
he_IL.UTF-8 UTF-8
he_IL ISO-8859-8
hi_IN UTF-8
hne_IN UTF-8
hr_HR.UTF-8 UTF-8
hr_HR ISO-8859-2
hsb_DE ISO-8859-2
hsb_DE.UTF-8 UTF-8
ht_HT UTF-8
hu_HU.UTF-8 UTF-8
hu_HU ISO-8859-2
hy_AM UTF-8
hy_AM.ARMSCII-8 ARMSCII-8
id_ID.UTF-8 UTF-8
id_ID ISO-8859-1
ig_NG UTF-8
ik_CA UTF-8
is_IS.UTF-8 UTF-8
is_IS ISO-8859-1
it_CH.UTF-8 UTF-8
it_CH ISO-8859-1
it_IT.UTF-8 UTF-8
it_IT ISO-8859-1
it_IT@euro ISO-8859-15
iu_CA UTF-8
iw_IL.UTF-8 UTF-8
iw_IL ISO-8859-8
ja_JP.EUC-JP EUC-JP
ja_JP.UTF-8 UTF-8
ka_GE.UTF-8 UTF-8
ka_GE GEORGIAN-PS
kk_KZ.UTF-8 UTF-8
kk_KZ PT154
kl_GL.UTF-8 UTF-8
kl_GL ISO-8859-1
km_KH UTF-8
kn_IN UTF-8
ko_KR.EUC-KR EUC-KR
ko_KR.UTF-8 UTF-8
kok_IN UTF-8
ks_IN UTF-8
ks_IN@devanagari UTF-8
ku_TR.UTF-8 UTF-8
ku_TR ISO-8859-9
kw_GB.UTF-8 UTF-8
kw_GB ISO-8859-1
ky_KG UTF-8
lb_LU UTF-8
lg_UG.UTF-8 UTF-8
lg_UG ISO-8859-10
li_BE UTF-8
li_NL UTF-8
lij_IT UTF-8
lo_LA UTF-8
lt_LT.UTF-8 UTF-8
lt_LT ISO-8859-13
lv_LV.UTF-8 UTF-8
lv_LV ISO-8859-13
mag_IN UTF-8
mai_IN UTF-8
mg_MG.UTF-8 UTF-8
mg_MG ISO-8859-15
mhr_RU UTF-8
mi_NZ.UTF-8 UTF-8
mi_NZ ISO-8859-13
mk_MK.UTF-8 UTF-8
mk_MK ISO-8859-5
ml_IN UTF-8
mn_MN UTF-8
mr_IN UTF-8
ms_MY.UTF-8 UTF-8
ms_MY ISO-8859-1
mt_MT.UTF-8 UTF-8
mt_MT ISO-8859-3
my_MM UTF-8
nan_TW@latin UTF-8
nb_NO.UTF-8 UTF-8
nb_NO ISO-8859-1
nds_DE UTF-8
nds_NL UTF-8
ne_NP UTF-8
nl_AW UTF-8
nl_BE.UTF-8 UTF-8
nl_BE ISO-8859-1
nl_BE@euro ISO-8859-15
nl_NL.UTF-8 UTF-8
nl_NL ISO-8859-1
nl_NL@euro ISO-8859-15
nn_NO.UTF-8 UTF-8
nn_NO ISO-8859-1
nr_ZA UTF-8
nso_ZA UTF-8
oc_FR.UTF-8 UTF-8
oc_FR ISO-8859-1
om_ET UTF-8
om_KE.UTF-8 UTF-8
om_KE ISO-8859-1
or_IN UTF-8
os_RU UTF-8
pa_IN UTF-8
pa_PK UTF-8
pap_AN UTF-8
pl_PL.UTF-8 UTF-8
pl_PL ISO-8859-2
ps_AF UTF-8
pt_BR.UTF-8 UTF-8
pt_BR ISO-8859-1
pt_PT.UTF-8 UTF-8
pt_PT ISO-8859-1
pt_PT@euro ISO-8859-15
ro_RO.UTF-8 UTF-8
ro_RO ISO-8859-2
ru_RU.KOI8-R KOI8-R
ru_RU.UTF-8 UTF-8
ru_RU ISO-8859-5
ru_UA.UTF-8 UTF-8
ru_UA KOI8-U
rw_RW UTF-8
sa_IN UTF-8
sc_IT UTF-8
sd_IN UTF-8
sd_IN@devanagari UTF-8
se_NO UTF-8
shs_CA UTF-8
si_LK UTF-8
sid_ET UTF-8
sk_SK.UTF-8 UTF-8
sk_SK ISO-8859-2
sl_SI.UTF-8 UTF-8
sl_SI ISO-8859-2
so_DJ.UTF-8 UTF-8
so_DJ ISO-8859-1
so_ET UTF-8
so_KE.UTF-8 UTF-8
so_KE ISO-8859-1
so_SO.UTF-8 UTF-8
so_SO ISO-8859-1
sq_AL.UTF-8 UTF-8
sq_AL ISO-8859-1
sq_MK UTF-8
sr_ME UTF-8
sr_RS UTF-8
sr_RS@latin UTF-8
ss_ZA UTF-8
st_ZA.UTF-8 UTF-8
st_ZA ISO-8859-1
sv_FI.UTF-8 UTF-8
sv_FI ISO-8859-1
sv_FI@euro ISO-8859-15
sv_SE.UTF-8 UTF-8
sv_SE ISO-8859-1
sw_KE UTF-8
sw_TZ UTF-8
ta_IN UTF-8
ta_LK UTF-8
te_IN UTF-8
tg_TJ.UTF-8 UTF-8
tg_TJ KOI8-T
th_TH.UTF-8 UTF-8
th_TH TIS-620
ti_ER UTF-8
ti_ET UTF-8
tig_ER UTF-8
tk_TM UTF-8
tl_PH.UTF-8 UTF-8
tl_PH ISO-8859-1
tn_ZA UTF-8
tr_CY.UTF-8 UTF-8
tr_CY ISO-8859-9
tr_TR.UTF-8 UTF-8
tr_TR ISO-8859-9
ts_ZA UTF-8
tt_RU UTF-8
tt_RU@iqtelif UTF-8
ug_CN UTF-8
uk_UA.UTF-8 UTF-8
uk_UA KOI8-U
unm_US UTF-8
ur_IN UTF-8
ur_PK UTF-8
uz_UZ ISO-8859-1
uz_UZ@cyrillic UTF-8
ve_ZA UTF-8
vi_VN UTF-8
wa_BE ISO-8859-1
wa_BE@euro ISO-8859-15
wa_BE.UTF-8 UTF-8
wae_CH UTF-8
wal_ET UTF-8
wo_SN UTF-8
xh_ZA.UTF-8 UTF-8
xh_ZA ISO-8859-1
yi_US.UTF-8 UTF-8
yi_US CP1255
yo_NG UTF-8
yue_HK UTF-8
zh_CN.GB18030 GB18030
zh_CN.GBK GBK
zh_CN.UTF-8 UTF-8
zh_CN GB2312
zh_HK.UTF-8 UTF-8
zh_HK BIG5-HKSCS
zh_SG.UTF-8 UTF-8
zh_SG.GBK GBK
zh_SG GB2312
zh_TW.EUC-TW EUC-TW
zh_TW.UTF-8 UTF-8
zh_TW BIG5
zu_ZA.UTF-8 UTF-8
zu_ZA ISO-8859-1

How can I combine multiple rows into a comma-delimited list in Oracle?

Here is a simple way without stragg or creating a function.

create table countries ( country_name varchar2 (100));

insert into countries values ('Albania');

insert into countries values ('Andorra');

insert into countries values ('Antigua');


SELECT SUBSTR (SYS_CONNECT_BY_PATH (country_name , ','), 2) csv
      FROM (SELECT country_name , ROW_NUMBER () OVER (ORDER BY country_name ) rn,
                   COUNT (*) OVER () cnt
              FROM countries)
     WHERE rn = cnt
START WITH rn = 1
CONNECT BY rn = PRIOR rn + 1;

CSV                                                                             
--------------------------
Albania,Andorra,Antigua                                                         

1 row selected.

As others have mentioned, if you are on 11g R2 or greater, you can now use listagg which is much simpler.

select listagg(country_name,', ') within group(order by country_name) csv
  from countries;

CSV                                                                             
--------------------------
Albania, Andorra, Antigua

1 row selected.

Turn off axes in subplots

import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 2)


To turn off axes for all subplots, do either:

[axi.set_axis_off() for axi in ax.ravel()]

or

map(lambda axi: axi.set_axis_off(), ax.ravel())

Copying from one text file to another using Python

Just a slightly cleaned up way of doing this. This is no more or less performant than ATOzTOA's answer, but there's no reason to do two separate with statements.

with open(path_1, 'a') as file_1, open(path_2, 'r') as file_2:
    for line in file_2:
        if 'tests/file/myword' in line:
            file_1.write(line)

Calling a JavaScript function named in a variable

If it´s in the global scope it´s better to use:

function foo()
{
    alert('foo');
}

var a = 'foo';
window[a]();

than eval(). Because eval() is evaaaaaal.

Exactly like Nosredna said 40 seconds before me that is >.<

How to call Android contacts list?

Be careful while working with android contact list.

Reading contact list in above methods work on most android devices except HTC One and Sony Xperia. It wasted my six weeks trying to figure out what is wrong!

Most tutorials available online are almost similar - first read "ALL" contacts, then show in Listview with ArrayAdapter. This is not memory efficient solution. Instead of looking for solutions on other websites first, have a look at developer.android.com. If any solution is not available on developer.android.com you should look somewhere else.

The solution is to use CursorAdapter instead of ArrayAdapter for retrieving contact list. Using ArrayAdapter would work on most devices, but it's not efficient. The CursorAdapter retrieves only a portion of contact list at run time while the ListView is being scrolled.

public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ...
    // Gets the ListView from the View list of the parent activity
    mContactsList =
        (ListView) getActivity().findViewById(R.layout.contact_list_view);
    // Gets a CursorAdapter
    mCursorAdapter = new SimpleCursorAdapter(
            getActivity(),
            R.layout.contact_list_item,
            null,
            FROM_COLUMNS, TO_IDS,
            0);
    // Sets the adapter for the ListView
    mContactsList.setAdapter(mCursorAdapter);
}

Retrieving a List of Contacts: Retrieving a List of Contacts

Static Final Variable in Java

Just having final will have the intended effect.

final int x = 5;

...
x = 10; // this will cause a compilation error because x is final

Declaring static is making it a class variable, making it accessible using the class name <ClassName>.x

How to write to a file, using the logging Python module?

here's a simpler way to go about it. this solution doesn't use a config dictionary and uses a rotation file handler, like so:

import logging
from logging.handlers import RotatingFileHandler

logging.basicConfig(handlers=[RotatingFileHandler(filename=logpath+filename,
                     mode='w', maxBytes=512000, backupCount=4)], level=debug_level,
                     format='%(levelname)s %(asctime)s %(message)s', 
                    datefmt='%m/%d/%Y%I:%M:%S %p')

logger = logging.getLogger('my_logger')

or like so:

import logging
from logging.handlers import RotatingFileHandler

handlers = [
            RotatingFileHandler(filename=logpath+filename, mode='w', maxBytes=512000, 
                                backupCount=4)
           ]
logging.basicConfig(handlers=handlers, level=debug_level, 
                    format='%(levelname)s %(asctime)s %(message)s', 
                    datefmt='%m/%d/%Y%I:%M:%S %p')

logger = logging.getLogger('my_logger')

the handlers variable needs to be an iterable. logpath+filename and debug_level are just variables holding the respective info. of course, the values for the function params are up to you.

the first time i was using the logging module i made the mistake of writing the following, which generates an OS file lock error (the above is the solution to that):

import logging
from logging.handlers import RotatingFileHandler

logging.basicConfig(filename=logpath+filename, level=debug_level, format='%(levelname)s %(asctime)s %(message)s', datefmt='%m/%d/%Y
 %I:%M:%S %p')

logger = logging.getLogger('my_logger')
logger.addHandler(RotatingFileHandler(filename=logpath+filename, mode='w', 
                  maxBytes=512000, backupCount=4))

and Bob's your uncle!

How can I tell jaxb / Maven to generate multiple schema packages?

This is fixed in version 1.6 of the plugin.

            <groupId>org.codehaus.mojo</groupId>
            <artifactId>jaxb2-maven-plugin</artifactId>
            <version>1.6</version>

Quick note though, I noticed that the first iteration output was being deleted. I fixed it by adding the following to each of the executions.

                        <removeOldOutput>false</removeOldOutput>
                        <clearOutputDir>false</clearOutputDir>

Here is my full working example with each iteration outputting correctly. BTW I had to do this due to a duplicate namespace problem with the xsd's I was given. This seems to resolve my problem.

        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>jaxb2-maven-plugin</artifactId>
            <version>1.6</version>
            <executions>
                <execution>
                    <id>submitOrderRequest</id>
                    <goals>
                        <goal>xjc</goal>
                    </goals>
                    <configuration>
                        <extension>true</extension>
                        <schemaDirectory>src/main/resources/xsd/</schemaDirectory>
                        <!-- <schemaFiles>getOrderStatusResponse.xsd,quoteShippingRequest.xsd,quoteShippingResponse.xsd,submitOrderRequest.xsd,submitOrderResponse.xsd</schemaFiles> -->
                        <schemaFiles>submitOrderRequest.xsd</schemaFiles>
                        <bindingDirectory>${project.basedir}/src/main/resources/xjb</bindingDirectory>
                        <bindingFiles>submitOrderRequest.xjb</bindingFiles>
                        <removeOldOutput>false</removeOldOutput>
                        <clearOutputDir>false</clearOutputDir>
                    </configuration>
                </execution>
                <execution>
                    <id>submitOrderResponse</id>
                    <goals>
                        <goal>xjc</goal>
                    </goals>
                    <configuration>
                        <extension>true</extension>
                        <schemaDirectory>src/main/resources/xsd/</schemaDirectory>
                        <!-- <schemaFiles>getOrderStatusResponse.xsd,quoteShippingRequest.xsd,quoteShippingResponse.xsd,submitOrderRequest.xsd,submitOrderResponse.xsd</schemaFiles> -->
                        <schemaFiles>submitOrderResponse.xsd</schemaFiles>
                        <bindingDirectory>${project.basedir}/src/main/resources/xjb</bindingDirectory>
                        <bindingFiles>submitOrderResponse.xjb</bindingFiles>
                        <removeOldOutput>false</removeOldOutput>
                        <clearOutputDir>false</clearOutputDir>
                    </configuration>
                </execution>
            </executions>

        </plugin>

What does set -e mean in a bash script?

I found this post while trying to figure out what the exit status was for a script that was aborted due to a set -e. The answer didn't appear obvious to me; hence this answer. Basically, set -e aborts the execution of a command (e.g. a shell script) and returns the exit status code of the command that failed (i.e. the inner script, not the outer script).

For example, suppose I have the shell script outer-test.sh:

#!/bin/sh
set -e
./inner-test.sh
exit 62;

The code for inner-test.sh is:

#!/bin/sh
exit 26;

When I run outer-script.sh from the command line, my outer script terminates with the exit code of the inner script:

$ ./outer-test.sh
$ echo $?
26

Is there a way to make a DIV unselectable?

WebKit browsers (ie Google Chrome and Safari) have a CSS solution similar to Mozilla's -moz-user-select:none

.no-select{    
    -webkit-user-select: none;
    cursor:not-allowed; /*makes it even more obvious*/
}

How to check if an object is a list or tuple (but not string)?

simplest way... using any and isinstance

>>> console_routers = 'x'
>>> any([isinstance(console_routers, list), isinstance(console_routers, tuple)])
False
>>>
>>> console_routers = ('x',)
>>> any([isinstance(console_routers, list), isinstance(console_routers, tuple)])
True
>>> console_routers = list('x',)
>>> any([isinstance(console_routers, list), isinstance(console_routers, tuple)])
True

How do I get NuGet to install/update all the packages in the packages.config?

Update-Package -ProjectName 'YourProjectNameGoesHere' -Reinstall

This is best and easiest example I found. It will reinstall all nugets that are listed in packages.config and it will preserve current versions. Replace YourProjectNameGoesHere with the project name.

What's the right way to create a date in Java?

You can use SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse("21/12/2012");

But I don't know whether it should be considered more right than to use Calendar ...

how to use math.pi in java

Here is usage of Math.PI to find circumference of circle and Area First we take Radius as a string in Message Box and convert it into integer

public class circle {

    public static void main(String[] args) {
        // TODO code application logic here

        String rad;

        float radius,area,circum;

       rad = JOptionPane.showInputDialog("Enter the Radius of circle:");

        radius = Integer.parseInt(rad);
        area = (float) (Math.PI*radius*radius);
        circum = (float) (2*Math.PI*radius);

        JOptionPane.showMessageDialog(null, "Area: " + area,"AREA",JOptionPane.INFORMATION_MESSAGE);
        JOptionPane.showMessageDialog(null, "circumference: " + circum, "Circumfernce",JOptionPane.INFORMATION_MESSAGE);
    }

}

Set the intervals of x-axis using r

You can use axis:

> axis(side=1, at=c(0:23))

That is, something like this:

plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()

How to convert dd/mm/yyyy string into JavaScript Date object?

You can use toLocaleString(). This is a javascript method.

_x000D_
_x000D_
var event = new Date("01/02/1993");_x000D_
_x000D_
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };_x000D_
_x000D_
console.log(event.toLocaleString('en', options));_x000D_
_x000D_
// expected output: "Saturday, January 2, 1993"
_x000D_
_x000D_
_x000D_

Almost all formats supported. Have look on this link for more details.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

Select distinct using linq

Using morelinq you can use DistinctBy:

myList.DistinctBy(x => x.id);

Otherwise, you can use a group:

myList.GroupBy(x => x.id)
      .Select(g => g.First());

Count(*) vs Count(1) - SQL Server

COUNT(1) is not substantially different from COUNT(*), if at all. As to the question of COUNTing NULLable COLUMNs, this can be straightforward to demo the differences between COUNT(*) and COUNT(<some col>)--

USE tempdb;
GO

IF OBJECT_ID( N'dbo.Blitzen', N'U') IS NOT NULL DROP TABLE dbo.Blitzen;
GO

CREATE TABLE dbo.Blitzen (ID INT NULL, Somelala CHAR(1) NULL);

INSERT dbo.Blitzen SELECT 1, 'A';
INSERT dbo.Blitzen SELECT NULL, NULL;
INSERT dbo.Blitzen SELECT NULL, 'A';
INSERT dbo.Blitzen SELECT 1, NULL;

SELECT COUNT(*), COUNT(1), COUNT(ID), COUNT(Somelala) FROM dbo.Blitzen;
GO

DROP TABLE dbo.Blitzen;
GO

Floating point vs integer calculations on modern hardware

Two points to consider -

Modern hardware can overlap instructions, execute them in parallel and reorder them to make best use of the hardware. And also, any significant floating point program is likely to have significant integer work too even if it's only calculating indices into arrays, loop counter etc. so even if you have a slow floating point instruction it may well be running on a separate bit of hardware overlapped with some of the integer work. My point being that even if the floating point instructions are slow that integer ones, your overall program may run faster because it can make use of more of the hardware.

As always, the only way to be sure is to profile your actual program.

Second point is that most CPUs these days have SIMD instructions for floating point that can operate on multiple floating point values all at the same time. For example you can load 4 floats into a single SSE register and the perform 4 multiplications on them all in parallel. If you can rewrite parts of your code to use SSE instructions then it seems likely it will be faster than an integer version. Visual c++ provides compiler intrinsic functions to do this, see http://msdn.microsoft.com/en-us/library/x5c07e2a(v=VS.80).aspx for some information.

Deleting rows with MySQL LEFT JOIN

Try this:

DELETE `deadline`
FROM `deadline`
INNER JOIN `job` ON `deadline`.`job_id` = `job`.`id`
WHERE `job`.`id` = 123

Simplest way to merge ES6 Maps/Sets?

To merge the sets in the array Sets, you can do

var Sets = [set1, set2, set3];

var merged = new Set([].concat(...Sets.map(set => Array.from(set))));

It is slightly mysterious to me why the following, which should be equivalent, fails at least in Babel:

var merged = new Set([].concat(...Sets.map(Array.from)));

MVC Redirect to View from jQuery with parameters

i used to do like this

inside view

<script type="text/javascript">

//will replace the '_transactionIds_' and '_payeeId_' 
var _addInvoiceUrl = '@(Html.Raw( Url.Action("PayableInvoiceMainEditor", "Payables", new { warehouseTransactionIds ="_transactionIds_",payeeId = "_payeeId_", payeeType="Vendor" })))';

on javascript file

var url = _addInvoiceUrl.replace('_transactionIds_', warehouseTransactionIds).replace('_payeeId_', payeeId);
        window.location.href = url;

in this way i can able to pass the parameter values on demand..

by using @Html.Raw, url will not get amp; for parameters

Add Twitter Bootstrap icon to Input box

For bootstrap 4

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">

            <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
            <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
        <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
        <form class="form-inline my-2 my-lg-0">
                        <div class="input-group">
                            <input class="form-control" type="search" placeholder="Search">
                            <div class="input-group-append">
                                <div class="input-group-text"><i class="fa fa-search"></i></div>
                            </div>
                        </div>
                    </form>

Demo

What is {this.props.children} and when you should use it?

props.children represents the content between the opening and the closing tags when invoking/rendering a component:

const Foo = props => (
  <div>
    <p>I'm {Foo.name}</p>
    <p>abc is: {props.abc}</p>

    <p>I have {props.children.length} children.</p>
    <p>They are: {props.children}.</p>
    <p>{Array.isArray(props.children) ? 'My kids are an array.' : ''}</p>
  </div>
);

const Baz = () => <span>{Baz.name} and</span>;
const Bar = () => <span> {Bar.name}</span>;

invoke/call/render Foo:

<Foo abc={123}>
  <Baz />
  <Bar />
</Foo>

props and props.children

How to sort a Ruby Hash by number value?

That's not the behavior I'm seeing:

irb(main):001:0> metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" =>
 10 }
=> {"siteb.com"=>9, "sitec.com"=>10, "sitea.com"=>745}
irb(main):002:0> metrics.sort {|a1,a2| a2[1]<=>a1[1]}
=> [["sitea.com", 745], ["sitec.com", 10], ["siteb.com", 9]]

Is it possible that somewhere along the line your numbers are being converted to strings? Is there more code you're not posting?

Using Predicate in Swift

Use The Below code:

 func filterContentForSearchText(searchText:NSString, scopes scope:NSString)
{
    //var searchText = ""

    var resultPredicate : NSPredicate = NSPredicate(format: "name contains[c]\(searchText)", nil)

    //var recipes : NSArray = NSArray()

    var searchResults = recipes.filteredArrayUsingPredicate(resultPredicate)
}

Git says remote ref does not exist when I delete remote branch

There's a shortcut to delete the branch in the origin:

git push origin :<branch_name>

Which is the same as doing git push origin --delete <branch_name>

Java: Difference between the setPreferredSize() and setSize() methods in components

setSize will resize the component to the specified size.

setPreferredSize sets the preferred size. The component may not actually be this size depending on the size of the container it's in, or if the user re-sized the component manually.

download a file from Spring boot rest service

using Apache IO could be another option for copy the Stream

@RequestMapping(path = "/file/{fileId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> downloadFile(@PathVariable(value="fileId") String fileId,HttpServletResponse response) throws Exception {

    InputStream yourInputStream = ...
    IOUtils.copy(yourInputStream, response.getOutputStream());
    response.flushBuffer();
    return ResponseEntity.ok().build();
}

maven dependency

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-io</artifactId>
        <version>1.3.2</version>
    </dependency>

Is iterating ConcurrentHashMap values thread safe?

It means that you should not share an iterator object among multiple threads. Creating multiple iterators and using them concurrently in separate threads is fine.

How to check for null in Twig?

How to set default values in twig: http://twig.sensiolabs.org/doc/filters/default.html

{{ my_var | default("my_var doesn't exist") }}

Or if you don't want it to display when null:

{{ my_var | default("") }}

How can I convert an RGB image into grayscale in Python?

You can always read the image file as grayscale right from the beginning using imread from OpenCV:

img = cv2.imread('messi5.jpg', 0)

Furthermore, in case you want to read the image as RGB, do some processing and then convert to Gray Scale you could use cvtcolor from OpenCV:

gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

Excel doesn't update value unless I hit Enter

This doesn't sound intuitive but select the column you're having the issue with and use "text to column" and just press finish. This is the suggested answer from Excel help as well. For some reason in converts text to numbers.

SVN change username

I’ve had the exact same problem and found the solution in Where does SVN client store user authentication data?:

  1. cd to ~/.subversion/auth/.
  2. Do fgrep -l <yourworkmatesusernameORtheserverurl> */*.
  3. Delete the file found.
  4. The next operation on the repository will ask you again for username/password information.

(For Windows, the steps are analogous; the auth directory is in %APPDATA%\Subversion\).

Note that this will only work for SVN access schemes where the user name is part of the server login so it’s no use for repositories accessed using file://.

How to create Python egg file

You are reading the wrong documentation. You want this: https://setuptools.readthedocs.io/en/latest/setuptools.html#develop-deploy-the-project-source-in-development-mode

  1. Creating setup.py is covered in the distutils documentation in Python's standard library documentation here. The main difference (for python eggs) is you import setup from setuptools, not distutils.

  2. Yep. That should be right.

  3. I don't think so. pyc files can be version and platform dependent. You might be able to open the egg (they should just be zip files) and delete .py files leaving .pyc files, but it wouldn't be recommended.

  4. I'm not sure. That might be “Development Mode”. Or are you looking for some “py2exe” or “py2app” mode?

Trim specific character from a string

This can trim several characters at a time:

function trimChars (str, c) {
  var re = new RegExp("^[" + c + "]+|[" + c + "]+$", "g");
  return str.replace(re,"");
}

var x = "|f|oo||"; 
x =  trimChars(x, '|'); // f|oo

var y = "..++|f|oo||++..";
y = trimChars(y, '|.+'); // f|oo

var z = "\\f|oo\\"; // \f|oo\

// For backslash, remember to double-escape:
z = trimChars(z, "\\\\"); // f|oo

For use in your own script and if you don't mind changing the prototype, this can be a convenient "hack":

String.prototype.trimChars = function (c) {
  var re = new RegExp("^[" + c + "]+|[" + c + "]+$", "g");
  return this.replace(re,"");
}

var x = "|f|oo||"; 
x =  x.trimChars('|'); // f|oo

Since I use the trimChars function extensively in one of my scripts, I prefer this solution. But there are potential issues with modifying an object's prototype.

Why is pydot unable to find GraphViz's executables in Windows 8?

you can use pydotplus instead of pydot.then follow the belows:

First, find C:\Users\zhangqianyuan\AppData\Local\Programs\Python\Python36\Lib\site-packages\pydotplus

Second, open graphviz.py

Third, find line 1925 - line 1972, find the function def create(self, prog=None, format='ps'):

Final, in the function:

  1. find:

    if prog not in self.progs:
        raise InvocationException(
            'GraphViz\'s executable "%s" not found' % prog)
    

    `

    if not os.path.exists(self.progs[prog]) or \
            not os.path.isfile(self.progs[prog]):
        raise InvocationException(
            'GraphViz\'s executable "{}" is not'
            ' a file or doesn\'t exist'.format(self.progs[prog])
        )
    
  2. between the two blocks add this(Your Graphviz's executable path):

    self.progs[prog] = "C:/Program Files (x86)/Graphviz2.38/bin/gvedit.exe"

  3. after adding the result is:

    if prog not in self.progs:
        raise InvocationException(
            'GraphViz\'s executable "%s" not found' % prog)
    
    self.progs[prog] = "C:/Program Files (x86)/Graphviz2.38/bin/gvedit.exe"
    
    if not os.path.exists(self.progs[prog]) or \
            not os.path.isfile(self.progs[prog]):
        raise InvocationException(
            'GraphViz\'s executable "{}" is not'
            ' a file or doesn\'t exist'.format(self.progs[prog])
        )
    
  4. save the changed file then you can run it successfully.

  5. you'd better save it as bmp file because png file will not work. picture is here

Obtaining only the filename when using OpenFileDialog property "FileName"

Use: Path.GetFileName Method

var onlyFileName = System.IO.Path.GetFileName(ofd.FileName);

Detect when browser receives file download

A very simple (and lame) one line solution is to use the window.onblur() event to close the loading dialog. Of course, if it takes too long and the user decides to do something else (like reading emails) the loading dialog will close.

Android, How to limit width of TextView (and add three dots at the end of text)?

you can write this line in xml where you take the textview :

android:singleLine="true"

Responsive Bootstrap Jumbotron Background Image

The below code works for all the screens :

.jumbotron {
   background: url('backgroundimage.jpg') no-repeat center center fixed;
   -webkit-background-size: cover;
   -moz-background-size: cover;
   background-size: cover;
   -o-background-size: cover;
}

The cover property will resize the background image to cover the entire container, even if it has to stretch the image or cut a little bit off one of the edges.

configuring project ':app' failed to find Build Tools revision

It happens because Build Tools revision 24.4.1 doesn't exist.

The latest version is 23.0.2.
These tools is included in the SDK package and installed in the <sdk>/build-tools/ directory.

Don't confuse the Android SDK Tools with SDK Build Tools.

Change in your build.gradle

android {
   buildToolsVersion "23.0.2"
   // ...

}

Circle drawing with SVG's arc path

Adobe Illustrator uses bezier curves like SVG, and for circles it creates four points. You can create a circle with two elliptical arc commands...but then for a circle in SVG I would use a <circle /> :)

favicon not working in IE

Right you've not been that helpful (providing source would be have been really useful!) but here you go... Some things to check:

Is the code like this:

<link rel="icon" href="http://www.example.com/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="http://www.example.com/favicon.ico" type="image/x-icon" />

Is it in the <head>?

Is the image a real ico file? (renaming a bitmap is not a real .ico! Mildly different format)

Does it work when you add the page as a bookmark?

Android: how to parse URL String with spaces to URI object?

You should in fact URI-encode the "invalid" characters. Since the string actually contains the complete URL, it's hard to properly URI-encode it. You don't know which slashes / should be taken into account and which not. You cannot predict that on a raw String beforehand. The problem really needs to be solved at a higher level. Where does that String come from? Is it hardcoded? Then just change it yourself accordingly. Does it come in as user input? Validate it and show error, let the user solve itself.

At any way, if you can ensure that it are only the spaces in URLs which makes it invalid, then you can also just do a string-by-string replace with %20:

URI uri = new URI(string.replace(" ", "%20"));

Or if you can ensure that it's only the part after the last slash which needs to be URI-encoded, then you can also just do so with help of android.net.Uri utility class:

int pos = string.lastIndexOf('/') + 1;
URI uri = new URI(string.substring(0, pos) + Uri.encode(string.substring(pos)));

Do note that URLEncoder is insuitable for the task as it's designed to encode query string parameter names/values as per application/x-www-form-urlencoded rules (as used in HTML forms). See also Java URL encoding of query string parameters.

Why does my favicon not show up?

Try adding the profile attribute to your head tag and use "image/x-icon" for the type attribute:

<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="img/favicon.ico">

If the above code doesn't work, try using the full icon path for the href attribute:

<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="http://example.com/img/favicon.ico">

Convert all data frame character columns to factors

The easiest way would be to use the code given below. It would automate the whole process of converting all the variables as factors in a dataframe in R. it worked perfectly fine for me. food_cat here is the dataset which I am using. Change it to the one which you are working on.

    for(i in 1:ncol(food_cat)){

food_cat[,i] <- as.factor(food_cat[,i])

}

how to get domain name from URL

I once had to write such a regex for a company I worked for. The solution was this:

  • Get a list of every ccTLD and gTLD available. Your first stop should be IANA. The list from Mozilla looks great at first sight, but lacks ac.uk for example so for this it is not really usable.
  • Join the list like the example below. A warning: Ordering is important! If org.uk would appear after uk then example.org.uk would match org instead of example.

Example regex:

.*([^\.]+)(com|net|org|info|coop|int|co\.uk|org\.uk|ac\.uk|uk|__and so on__)$

This worked really well and also matched weird, unofficial top-levels like de.com and friends.

The upside:

  • Very fast if regex is optimally ordered

The downside of this solution is of course:

  • Handwritten regex which has to be updated manually if ccTLDs change or get added. Tedious job!
  • Very large regex so not very readable.

Where does one get the "sys/socket.h" header/source file?

Try to reinstall cygwin with selected package:gcc-g++ : gnu compiler collection c++ (from devel category), openssh server and client program (net), make: the gnu version (devel), ncurses terminal (utils), enhanced vim editors (editors), an ANSI common lisp implementation (math) and libncurses-devel (lib).

This library files should be under cygwin\usr\include

Regards.

Convert datetime to Unix timestamp and convert it back in python

Rather than this expression to create a POSIX timestamp from dt,

(dt - datetime(1970,1,1)).total_seconds()

Use this:

int(dt.strftime("%s"))

I get the right answer in your example using the second method.

EDIT: Some followup... After some comments (see below), I was curious about the lack of support or documentation for %s in strftime. Here's what I found:

In the Python source for datetime and time, the string STRFTIME_FORMAT_CODES tells us:

"Other codes may be available on your platform.
 See documentation for the C library strftime function."

So now if we man strftime (on BSD systems such as Mac OS X), you'll find support for %s:

"%s is replaced by the number of seconds since the Epoch, UTC (see mktime(3))."

Anyways, that's why %s works on the systems it does. But there are better solutions to OP's problem (that take timezones into account). See @abarnert's accepted answer here.

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

HTTP post XML data in C#

AlliterativeAlice's example helped me tremendously. In my case, though, the server I was talking to didn't like having single quotes around utf-8 in the content type. It failed with a generic "Server Error" and it took hours to figure out what it didn't like:

request.ContentType = "text/xml; encoding=utf-8";

Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

In my case this error occurred because a make command was expecting to fetch shared libraries (*.so files) from a remote directory indicated by a LDFLAGS environment variable. In a mistake, only static libraries were available there (*.la or *.a files).

Hence, my problem did not reside with the program I was compiling but with the remote libraries it was trying to fetch. So, I did not need to add any flag (say, -fPIC) to the compilation interrupted by the relocation error. Rather, I recompiled the remote library so that the shared objects were available.

Basically, it's been a file-not-found error in disguise.

In my case I had to remove a misplaced --disable-shared switch in the configure invocation for the requisite program, since shared and static libraries were both built as default.


I noticed that most programs build both types of libraries at the same time, so mine is probably a corner case. In general, it may be the case that you rather have to enable shared libraries, depending on defaults.

To inspect your particular situation with compile switches and defaults, I would read out the summary that shows up with ./configure --help | less, typically in the section Optional Features. I often found that this reading is more reliable than installation guides that are not updated while dependency programs evolve.

Calculate difference between two datetimes in MySQL

USE TIMESTAMPDIFF MySQL function. For example, you can use:

SELECT TIMESTAMPDIFF(SECOND, '2012-06-06 13:13:55', '2012-06-06 15:20:18')

In your case, the third parameter of TIMSTAMPDIFF function would be the current login time (NOW()). Second parameter would be the last login time, which is already in the database.

How do I find the difference between two values without knowing which is larger?

You can try: a=[0,1,2,3,4,5,6,7,8,9];

[abs(x[1]-x[0]) for x in zip(a[1:],a[:-1])]

How can I convert string to double in C++?

One of the most elegant solution to this problem is to use boost::lexical_cast as @Evgeny Lazin mentioned.

How to specify multiple return types using type-hints

Python 3.10 (use |): Example for a function which takes a single argument that is either an int or str and returns either an int or str:

def func(arg: int | str) -> int | str:
              ^^^^^^^^^     ^^^^^^^^^ 
             type of arg   return type

Python 3.5 - 3.9 (use typing.Union):

from typing import Union
def func(arg: Union[int, str]) -> Union[int, str]:
              ^^^^^^^^^^^^^^^     ^^^^^^^^^^^^^^^ 
                type of arg         return type

For the special case of X | None you can use Optional[X].

What is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!

How about Processing for JavaScript? I don't know Processing, but the code always seems rather small for what it can do, it's very visual, and you can run it in a browser.
http://processingjs.org/exhibition

set height of imageview as matchparent programmatically

For Kotlin Users

val params = mImageView?.layoutParams as FrameLayout.LayoutParams
params.width = FrameLayout.LayoutParams.MATCH_PARENT
params.height = FrameLayout.LayoutParams.MATCH_PARENT
mImageView?.layoutParams = params

Here I used FrameLayout.LayoutParams since my views( ImageView) parent is FrameLayout

How to set a radio button in Android

For radioButton use

radio1.setChecked(true);

It does not make sense to have just one RadioButton. If you have more of them you need to uncheck others through

radio2.setChecked(false); ...

If your setting is just on/off use CheckBox.

How to check if a variable is an integer in JavaScript?

This will output if it is a number

if (data >= 0 || data <=0){
            console.log('its a number');
          }

Is there a Mutex in Java?

Each object's lock is little different from Mutex/Semaphore design. For example there is no way to correctly implement traversing linked nodes with releasing previous node's lock and capturing next one. But with mutex it is easy to implement:

Node p = getHead();
if (p == null || x == null) return false;
p.lock.acquire();  // Prime loop by acquiring first lock.
// If above acquire fails due to interrupt, the method will
//   throw InterruptedException now, so there is no need for
//   further cleanup.
for (;;) {
Node nextp = null;
boolean found;
try { 
 found = x.equals(p.item); 
 if (!found) { 
   nextp = p.next; 
   if (nextp != null) { 
     try {      // Acquire next lock 
                //   while still holding current 
       nextp.lock.acquire(); 
     } 
     catch (InterruptedException ie) { 
      throw ie;    // Note that finally clause will 
                   //   execute before the throw 
     } 
   } 
 } 
}finally {     // release old lock regardless of outcome 
   p.lock.release();
} 

Currently, there is no such class in java.util.concurrent, but you can find Mutext implementation here Mutex.java. As for standard libraries, Semaphore provides all this functionality and much more.

SQL Server 2008: how do I grant privileges to a username?

Like the following. It will make the user database owner.

EXEC sp_addrolemember N'db_owner', N'USerNAme'

Call one constructor from another

Constructor chaining i.e you can use "Base" for Is a relationship and "This" you can use for same class, when you want call multiple Constructor in single call.

  class BaseClass
{
    public BaseClass():this(10)
    {
    }
    public BaseClass(int val)
    {
    }
}
    class Program
    {
        static void Main(string[] args)
        {
            new BaseClass();
            ReadLine();
        }
    }

List of All Folders and Sub-folders

find . -type d > list.txt

Will list all directories and subdirectories under the current path. If you want to list all of the directories under a path other than the current one, change the . to that other path.

If you want to exclude certain directories, you can filter them out with a negative condition:

find . -type d ! -name "~snapshot" > list.txt

Spring Data JPA - "No Property Found for Type" Exception

If you are using a composite key in your bean, your parameter will be an object. You need to adjust your findBy method according to the new combination.

@Embeddable
public class CombinationId implements Serializable {

  private String xId;
  private String yId;
}

public class RealObject implements Serializable, Persistable<CombinationId> {

  @EmbeddedId private CombinationId id;
}

In that case, your repository findBy method should be as this

@Repository
public interface PaymentProfileRepository extends JpaRepository<RealObject, String> {

  List<RealObject> findById_XId(String someString);
}

Difference between HashMap and Map in Java..?

HashMap is an implementation of Map. Map is just an interface for any type of map.

builtins.TypeError: must be str, not bytes

The outfile should be in binary mode.

outFile = open('output.xml', 'wb')

Python: Get HTTP headers from urllib2.urlopen call?

Actually, it appears that urllib2 can do an HTTP HEAD request.

The question that @reto linked to, above, shows how to get urllib2 to do a HEAD request.

Here's my take on it:

import urllib2

# Derive from Request class and override get_method to allow a HEAD request.
class HeadRequest(urllib2.Request):
    def get_method(self):
        return "HEAD"

myurl = 'http://bit.ly/doFeT'
request = HeadRequest(myurl)

try:
    response = urllib2.urlopen(request)
    response_headers = response.info()

    # This will just display all the dictionary key-value pairs.  Replace this
    # line with something useful.
    response_headers.dict

except urllib2.HTTPError, e:
    # Prints the HTTP Status code of the response but only if there was a 
    # problem.
    print ("Error code: %s" % e.code)

If you check this with something like the Wireshark network protocol analazer, you can see that it is actually sending out a HEAD request, rather than a GET.

This is the HTTP request and response from the code above, as captured by Wireshark:

HEAD /doFeT HTTP/1.1
Accept-Encoding: identity
Host: bit.ly
Connection: close
User-Agent: Python-urllib/2.7

HTTP/1.1 301 Moved
Server: nginx
Date: Sun, 19 Feb 2012 13:20:56 GMT
Content-Type: text/html; charset=utf-8
Cache-control: private; max-age=90
Location: http://www.kidsidebyside.org/?p=445
MIME-Version: 1.0
Content-Length: 127
Connection: close
Set-Cookie: _bit=4f40f738-00153-02ed0-421cf10a;domain=.bit.ly;expires=Fri Aug 17 13:20:56 2012;path=/; HttpOnly

However, as mentioned in one of the comments in the other question, if the URL in question includes a redirect then urllib2 will do a GET request to the destination, not a HEAD. This could be a major shortcoming, if you really wanted to only make HEAD requests.

The request above involves a redirect. Here is request to the destination, as captured by Wireshark:

GET /2009/05/come-and-draw-the-circle-of-unity-with-us/ HTTP/1.1
Accept-Encoding: identity
Host: www.kidsidebyside.org
Connection: close
User-Agent: Python-urllib/2.7

An alternative to using urllib2 is to use Joe Gregorio's httplib2 library:

import httplib2

url = "http://bit.ly/doFeT"
http_interface = httplib2.Http()

try:
    response, content = http_interface.request(url, method="HEAD")
    print ("Response status: %d - %s" % (response.status, response.reason))

    # This will just display all the dictionary key-value pairs.  Replace this
    # line with something useful.
    response.__dict__

except httplib2.ServerNotFoundError, e:
    print (e.message)

This has the advantage of using HEAD requests for both the initial HTTP request and the redirected request to the destination URL.

Here's the first request:

HEAD /doFeT HTTP/1.1
Host: bit.ly
accept-encoding: gzip, deflate
user-agent: Python-httplib2/0.7.2 (gzip)

Here's the second request, to the destination:

HEAD /2009/05/come-and-draw-the-circle-of-unity-with-us/ HTTP/1.1
Host: www.kidsidebyside.org
accept-encoding: gzip, deflate
user-agent: Python-httplib2/0.7.2 (gzip)

PHP Error: Cannot use object of type stdClass as array (array and object issues)

StdClass object is accessed by using ->

foreach ($blogs as $blog) {
    $id         = $blog->id;
    $title  = $blog->title;
    $content    = $blog->content;
}

How can I make a .NET Windows Forms application that only runs in the System Tray?

It is very friendly framework for Notification Area Application... it is enough to add NotificationIcon to base form and change auto-generated code to code below:

public partial class Form1 : Form
{
    private bool hidden = false;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.ShowInTaskbar = false;
        //this.WindowState = FormWindowState.Minimized;
        this.Hide();
        hidden = true;
    }

    private void notifyIcon1_Click(object sender, EventArgs e)
    {
        if (hidden) // this.WindowState == FormWindowState.Minimized)
        {
            // this.WindowState = FormWindowState.Normal;
            this.Show();
            hidden = false;
        }
        else
        {
            // this.WindowState = FormWindowState.Minimized;
            this.Hide();
            hidden = true;
        }
    }
}

In an array of objects, fastest way to find the index of an object whose attributes match a search

var indices = [];
var IDs = [0, 1, 2, 3, 4];

for(var i = 0, len = array.length; i < len; i++) {
    for(var j = 0; j < IDs.length; j++) {
        if(array[i].id == ID) indices.push(i);
    }
}

How to do multiple arguments to map function where one remains the same in python?

In :nums = [1, 2, 3]

In :map(add, nums, [2]*len(nums))

Out:[3, 4, 5]

Notepad++ add to every line

To append different text to the end of each line, you can use the plugin ConyEdit to do this.
With ConyEdit running in the background, follow these steps.

  1. use the command line cc.gl a to get lines and store in an array named a.
  2. use the command line cc.aal //$a to append after each line, using the contents of array a.

Example
enter image description here

Any easy way to use icons from resources?

Forms maintain separate resource files (SomeForm.Designer.resx) added via the designer. To use icons embedded in another resource file requires codes. (this.Icone = Project.Resources.SomeIcon;)

How can I symlink a file in Linux?

There are two types of links:

symbolic links: Refer to a symbolic path indicating the abstract location of another file

hard links: Refer to the specific location of physical data.

In your case symlinks:

ln -s source target

you can refer to http://man7.org/linux/man-pages/man7/symlink.7.html

you can create too hard links

A hard link to a file is indistinguishable from the original directory entry; any changes to a file are effectively independent of the name used to reference the file. Hard links may not normally refer to directories and may not span file systems.

ln source link

Pandas read in table without headers

Previous answers were good and correct, but in my opinion, an extra names parameter will make it perfect, and it should be the recommended way, especially when the csv has no headers.

Solution

Use usecols and names parameters

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'])

Additional reading

or use header=None to explicitly tells people that the csv has no headers (anyway both lines are identical)

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'], header=None)

So that you can retrieve your data by

# with `names` parameter
df['colA']
df['colB'] 

instead of

# without `names` parameter
df[0]
df[1]

Explain

Based on read_csv, when names are passed explicitly, then header will be behaving like None instead of 0, so one can skip header=None when names exist.

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

You can build for source following the official OpenCV tutorial. The crucial part is to set the PYTHON3_EXECUTABLE, PYTHON_LIBRARY, PYTHON3_PACKAGES_PATH and PYTHON3_NUMPY_INCLUDE_DIRS parameters for python3.6. Here are all the steps:

  1. Clone the repo

    git clone https://github.com/opencv/opencv.git
    
  2. Create build directory

    cd ~/opencv
    mkdir build
    cd build
    
  3. Configure

    cmake -D CMAKE_BUILD_TYPE=RELEASE \
          -D CMAKE_INSTALL_PREFIX=/usr/local .. \
          -D PYTHON_INCLUDE_DIR=/usr/include/python3.6 \
          -D PYTHON_INCLUDE_DIR2=/usr/include/x86_64-linux-gnu/python3.6m \
          -D BUILD_NEW_PYTHON_SUPPORT=ON \
          -D BUILD_opencv_python3=ON \
          -D HAVE_opencv_python3=ON \
          -D INSTALL_PYTHON_EXAMPLES=ON \
          -D PYTHON3_EXECUTABLE=/usr/bin/python3.6 \
          -D PYTHON_DEFAULT_EXECUTABLE=/usr/bin/python3.6 \
          -D PYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.6m.so \
          -D PYTHON3_PACKAGES_PATH=/usr/lib/python3/dist-packages .. \
          -D PYTHON3_NUMPY_INCLUDE_DIRS=/home/user/.local/lib/python3.6/site-packages/numpy/core/include/
    
  4. Build

    make -j8
    
  5. Install libraries

    sudo make install
    
  6. Test

    python3
    import cv2
    

If you don't get the error "No module named cv2", then the installation was successful.

Note: If you don't know the path to numpy for the PYTHON3_NUMPY_INCLUDE_DIRS parameter, you can find it by executing import numpy and then numpy.__file__ in a python3 shell.

Python+OpenCV: cv2.imwrite

enter image description here enter image description here enter image description here

Alternatively, with MTCNN and OpenCV(other dependencies including TensorFlow also required), you can:

1 Perform face detection(Input an image, output all boxes of detected faces):

from mtcnn.mtcnn import MTCNN
import cv2

face_detector = MTCNN()

img = cv2.imread("Anthony_Hopkins_0001.jpg")
detect_boxes = face_detector.detect_faces(img)
print(detect_boxes)

[{'box': [73, 69, 98, 123], 'confidence': 0.9996458292007446, 'keypoints': {'left_eye': (102, 116), 'right_eye': (150, 114), 'nose': (129, 142), 'mouth_left': (112, 168), 'mouth_right': (146, 167)}}]

2 save all detected faces to separate files:

for i in range(len(detect_boxes)):
    box = detect_boxes[i]["box"]
    face_img = img[box[1]:(box[1] + box[3]), box[0]:(box[0] + box[2])]
    cv2.imwrite("face-{:03d}.jpg".format(i+1), face_img)

3 or Draw rectangles of all detected faces:

for box in detect_boxes:
    box = box["box"]
    pt1 = (box[0], box[1]) # top left
    pt2 = (box[0] + box[2], box[1] + box[3]) # bottom right
    cv2.rectangle(img, pt1, pt2, (0,255,0), 2)
cv2.imwrite("detected-boxes.jpg", img)

How to add an event after close the modal window?

If you're using version 3.x of Bootstrap, the correct way to do this now is:

$('#myModal').on('hidden.bs.modal', function (e) {
  // do something...
})

Scroll down to the events section to learn more.

http://getbootstrap.com/javascript/#modals-usage

This appears to remain unchanged for whenever version 4 releases (http://v4-alpha.getbootstrap.com/components/modal/#events), but if it does I'll be sure to update this post with the relevant information.

Smart way to truncate long strings

Note that this only needs to be done for Firefox.

All other browsers support a CSS solution (see support table):

p {
    white-space: nowrap;
    width: 100%;                   /* IE6 needs any width */
    overflow: hidden;              /* "overflow" value must be different from  visible"*/ 
    -o-text-overflow: ellipsis;    /* Opera < 11*/
    text-overflow:    ellipsis;    /* IE, Safari (WebKit), Opera >= 11, FF > 6 */
}

The irony is I got that code snippet from Mozilla MDC.

How to hide a button programmatically?

Try the below code -

playButton.setVisibility(View.INVISIBLE);

or -

playButton.setVisibility(View.GONE);

show it again with -

playButton.setVisibility(View.VISIBLE);

Setting DIV width and height in JavaScript

These are several ways to apply style to an element. Try any one of the examples below:

1. document.getElementById('div_register').className = 'wide';
  /* CSS */ .wide{width:500px;}
2. document.getElementById('div_register').setAttribute('class','wide');
3. document.getElementById('div_register').style.width = '500px';

How to refresh activity after changing language (Locale) inside application

The way we have done it was using Broadcasts:

  1. Send the broadcast every time the user changes language
  2. Register the broadcast receiver in the AppActivity.onCreate() and unregister in AppActivity.onDestroy()
  3. In BroadcastReceiver.onReceive() just restart the activity.

AppActivity is the parent activity which all other activities subclass.


Below is the snippet from my code, not tested outside the project, but should give you a nice idea.

When the user changes the language

sendBroadcast(new Intent("Language.changed"));

And in the parent activity

public class AppActivity extends Activity {

    /**
     * The receiver that will handle the change of the language.
     */
    private BroadcastReceiver mLangaugeChangedReceiver;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // ...
        // Other code here
        // ...

        // Define receiver
        mLangaugeChangedReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(final Context context, final Intent intent) {
                startActivity(getIntent());
                finish();
            }
        };

        // Register receiver
        registerReceiver(mLangaugeChangedReceiver, new IntentFilter("Language.changed"));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // ...
        // Other cleanup code here
        // ...

        // Unregister receiver
        if (mLangaugeChangedReceiver != null) {
            try {
                unregisterReceiver(mLangaugeChangedReceiver);
                mLangaugeChangedReceiver = null;
            } catch (final Exception e) {}
        }
    }
}

This will also refresh the activity which changed the language (if it subclasses the above activity).

This will make you lose any data, but if it is important you should already have taken care of this using Actvity.onSaveInstanceState() and Actvity.onRestoreInstanceState() (or similar).

Let me know your thoughts about this.

Cheers!

How can I run a PHP script inside a HTML file?

I'm not sure if this is what you wanted, but this is a very hackish way to include php. What you do is you put the php you want to run in another file, and then you include that file in an image. For example:

RunFromHTML.php

<?php
  $file = fopen("file.txt", "w");
  //This will create a file called file.txt,
  //provided that it has write access to your filesystem
  fwrite($file, "Hello World!");
  //This will write "Hello World!" into file.txt
  fclose($file);
  //Always remember to close your files!
?>

RunPhp.html

<html>
  <!--head should be here, but isn't for demonstration's sake-->
  <body>
    <img style="display: none;" src="RunFromHTML.php">
    <!--This will run RunFromHTML.php-->
  </body>
</html>

Now, after visiting RunPhp.html, you should find a file called file.txt in the same directory that you created the above two files, and the file should contain "Hello World!" inside of it.

RabbitMQ / AMQP: single queue, multiple consumers for same message?

RabbitMQ / AMQP: single queue, multiple consumers for same message and page refresh.

rabbit.on('ready', function () {    });
    sockjs_chat.on('connection', function (conn) {

        conn.on('data', function (message) {
            try {
                var obj = JSON.parse(message.replace(/\r/g, '').replace(/\n/g, ''));

                if (obj.header == "register") {

                    // Connect to RabbitMQ
                    try {
                        conn.exchange = rabbit.exchange(exchange, { type: 'topic',
                            autoDelete: false,
                            durable: false,
                            exclusive: false,
                            confirm: true
                        });

                        conn.q = rabbit.queue('my-queue-'+obj.agentID, {
                            durable: false,
                            autoDelete: false,
                            exclusive: false
                        }, function () {
                            conn.channel = 'my-queue-'+obj.agentID;
                            conn.q.bind(conn.exchange, conn.channel);

                            conn.q.subscribe(function (message) {
                                console.log("[MSG] ---> " + JSON.stringify(message));
                                conn.write(JSON.stringify(message) + "\n");
                            }).addCallback(function(ok) {
                                ctag[conn.channel] = ok.consumerTag; });
                        });
                    } catch (err) {
                        console.log("Could not create connection to RabbitMQ. \nStack trace -->" + err.stack);
                    }

                } else if (obj.header == "typing") {

                    var reply = {
                        type: 'chatMsg',
                        msg: utils.escp(obj.msga),
                        visitorNick: obj.channel,
                        customField1: '',
                        time: utils.getDateTime(),
                        channel: obj.channel
                    };

                    conn.exchange.publish('my-queue-'+obj.agentID, reply);
                }

            } catch (err) {
                console.log("ERROR ----> " + err.stack);
            }
        });

        // When the visitor closes or reloads a page we need to unbind from RabbitMQ?
        conn.on('close', function () {
            try {

                // Close the socket
                conn.close();

                // Close RabbitMQ           
               conn.q.unsubscribe(ctag[conn.channel]);

            } catch (er) {
                console.log(":::::::: EXCEPTION SOCKJS (ON-CLOSE) ::::::::>>>>>>> " + er.stack);
            }
        });
    });

Concatenating multiple text files into a single file in Bash

all of that is nasty....

ls | grep *.txt | while read file; do cat $file >> ./output.txt; done;

easy stuff.

Disable/Enable Submit Button until all forms have been filled

Put it inside a table and then do on her:

var tabPom = document.getElementById("tabPomId");
$(tabPom ).prop('disabled', true/false);

How do I set the path to a DLL file in Visual Studio?

Go through project properties -> Reference Paths

Then add folder with DLL's

"Connect failed: Access denied for user 'root'@'localhost' (using password: YES)" from php function

Is there a user account entry in the DB for root@localhost? In MySQL you can set different user account permissions by host. There could be several different accounts with the same name combined with the host they are connecting from. The most common are [email protected] and root@localhost. These can have different passwords and permissions. Make sure root@localhost exist and has the settings you expect.

I am willing to bet, based on your explanation, that this is the problem. Connecting from another PC uses a different account than root@localhost and the command line I think connects using [email protected].

How to send a HTTP OPTIONS request from the command line?

The curl installed by default in Debian supports HTTPS since a great while back. (a long time ago there were two separate packages, one with and one without SSL but that's not the case anymore)

OPTIONS /path

You can send an OPTIONS request with curl like this:

curl -i -X OPTIONS http://example.org/path

You may also use -v instead of -i to see more output.

OPTIONS *

To send a plain * (instead of the path, see RFC 7231) with the OPTIONS method, you need curl 7.55.0 or later as then you can run a command line like:

curl -i --request-target "*" -X OPTIONS http://example.org

How to select rows with no matching entry in another table?

I Dont Knew Which one Is Optimized (compared to @AdaTheDev ) but This one seems to be quicker when I use (atleast for me)

SELECT id  FROM  table_1 EXCEPT SELECT DISTINCT (table1_id) table1_id FROM table_2

If You want to get any other specific attribute you can use:

SELECT COUNT(*) FROM table_1 where id in (SELECT id  FROM  table_1 EXCEPT SELECT DISTINCT (table1_id) table1_id FROM table_2);

jQuery - how to write 'if not equal to' (opposite of ==)

The opposite of the == compare operator is !=.

Where are static methods and static variables stored in Java?

In addition to the Thomas's answer , static variable are stored in non heap area which is called Method Area.

Ansible: deploy on multiple hosts in the same time

In my case I needed the configuration stage to be blocking as a whole, but execute each role in parallel. I've tackled this issue using the following code:

echo webserver loadbalancer database | tr ' ' '\n' \
| xargs -I % -P 3 bash -c 'ansible-playbook $1.yml' -- %

the -P 3 argument in xargs makes sure that all the commands are ran in parallel, each command executes the respective playbook and the command as a whole blocks until all parts are finished.

What is the difference between tinyint, smallint, mediumint, bigint and int in MySQL?

They take up different amounts of space and they have different ranges of acceptable values.

Here are the sizes and ranges of values for SQL Server, other RDBMSes have similar documentation:

Turns out they all use the same specification (with a few minor exceptions noted below) but support various combinations of those types (Oracle not included because it has just a NUMBER datatype, see the above link):

             | SQL Server    MySQL   Postgres    DB2
---------------------------------------------------
tinyint      |     X           X                
smallint     |     X           X         X        X
mediumint    |                 X
int/integer  |     X           X         X        X 
bigint       |     X           X         X        X

And they support the same value ranges (with one exception below) and all have the same storage requirements:

            | Bytes    Range (signed)                               Range (unsigned)
--------------------------------------------------------------------------------------------
tinyint     | 1 byte   -128 to 127                                  0 to 255
smallint    | 2 bytes  -32768 to 32767                              0 to 65535
mediumint   | 3 bytes  -8388608 to 8388607                          0 to 16777215
int/integer | 4 bytes  -2147483648 to 2147483647                    0 to 4294967295
bigint      | 8 bytes  -9223372036854775808 to 9223372036854775807  0 to 18446744073709551615 

The "unsigned" types are only available in MySQL, and the rest just use the signed ranges, with one notable exception: tinyint in SQL Server is unsigned and has a value range of 0 to 255

how to get value of selected item in autocomplete

When autocomplete changes a value, it fires a autocompletechange event, not the change event

$(document).ready(function () {
    $('#tags').on('autocompletechange change', function () {
        $('#tagsname').html('You selected: ' + this.value);
    }).change();
});

Demo: Fiddle

Another solution is to use select event, because the change event is triggered only when the input is blurred

$(document).ready(function () {
    $('#tags').on('change', function () {
        $('#tagsname').html('You selected: ' + this.value);
    }).change();
    $('#tags').on('autocompleteselect', function (e, ui) {
        $('#tagsname').html('You selected: ' + ui.item.value);
    });
});

Demo: Fiddle

How to resize images proportionally / keeping the aspect ratio?

Resize to fit the container, get scale factor, scale down percentage control

_x000D_
_x000D_
 $(function () {
            let ParentHeight = 200;
            let ParentWidth = 300;
            $("#Parent").width(ParentWidth).height(ParentHeight);
            $("#ParentHeight").html(ParentHeight);
            $("#ParentWidth").html(ParentWidth);

            var RatioOfParent = ParentHeight / ParentWidth;
            $("#ParentAspectRatio").html(RatioOfParent);

            let ChildHeight = 2000;
            let ChildWidth = 4000;
            var RatioOfChild = ChildHeight / ChildWidth;
            $("#ChildAspectRatio").html(RatioOfChild);

            let ScaleHeight = ParentHeight / ChildHeight;
            let ScaleWidth = ParentWidth / ChildWidth;
            let Scale = Math.min(ScaleHeight, ScaleWidth);

            $("#ScaleFactor").html(Scale);
            // old scale
            //ChildHeight = ChildHeight * Scale;
            //ChildWidth = ChildWidth * Scale;

            // reduce scale by 10%, you can change the percentage
            let ScaleDownPercentage = 10;
            let CalculatedScaleValue = Scale * (ScaleDownPercentage / 100);
            $("#CalculatedScaleValue").html(CalculatedScaleValue);

            // new scale
            let NewScale = (Scale - CalculatedScaleValue);
            ChildHeight = ChildHeight * NewScale;
            ChildWidth = ChildWidth * NewScale;

            $("#Child").width(ChildWidth).height(ChildHeight);
            $("#ChildHeight").html(ChildHeight);
            $("#ChildWidth").html(ChildWidth);

        });
_x000D_
        #Parent {
            background-color: grey;
        }

        #Child {
            background-color: red;
        }
 
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Parent">
    <div id="Child"></div>
</div>

<table>
    <tr>
        <td>Parent Aspect Ratio</td>
        <td id="ParentAspectRatio"></td>
    </tr>
    <tr>
        <td>Child Aspect Ratio</td>
        <td id="ChildAspectRatio"></td>
    </tr>
    <tr>
        <td>Scale Factor</td>
        <td id="ScaleFactor"></td>
    </tr>
    <tr>
        <td>Calculated Scale Value</td>
        <td id="CalculatedScaleValue"></td>
    </tr>
    <tr>
        <td>Parent Height</td>
        <td id="ParentHeight"></td>
    </tr>
    <tr>
        <td>Parent Width</td>
        <td id="ParentWidth"></td>
    </tr>
    <tr>
        <td>Child Height</td>
        <td id="ChildHeight"></td>
    </tr>
    <tr>
        <td>Child Width</td>
        <td id="ChildWidth"></td>
    </tr>
</table>
_x000D_
_x000D_
_x000D_

What is the difference between Tomcat, JBoss and Glassfish?

jboss and glassfish include a servlet container(like tomcat), however the two application servers (jboss and glassfish) also provide a bean container (and a few other things aswell I imagine)

Convert Unicode data to int in python

In python, integers and strings are immutable and are passed by value. You cannot pass a string, or integer, to a function and expect the argument to be modified.

So to convert string limit="100" to a number, you need to do

limit = int(limit) # will return new object (integer) and assign to "limit"

If you really want to go around it, you can use a list. Lists are mutable in python; when you pass a list, you pass it's reference, not copy. So you could do:

def int_in_place(mutable):
    mutable[0] = int(mutable[0])

mutable = ["1000"]
int_in_place(mutable)
# now mutable is a list with a single integer

But you should not need it really. (maybe sometimes when you work with recursions and need to pass some mutable state).

How do I set vertical space between list items?

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

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

Check for internet connection with Swift

As of iOS 12, NWPathMonitor replaced Reachability. Use this:

import Network


struct Internet {
 
 private static let monitor = NWPathMonitor()
 
 static var active = false
 static var expensive = false
 
 /// Monitors internet connectivity changes. Updates with every change in connectivity.
 /// Updates variables for availability and if it's expensive (cellular).
 static func start() {
  guard monitor.pathUpdateHandler == nil else { return }
  
  monitor.pathUpdateHandler = { update in
   Internet.active = update.status == .satisfied ? true : false
   Internet.expensive = update.isExpensive ? true : false
  }
  
  monitor.start(queue: DispatchQueue(label: "InternetMonitor"))
 }
 
}

In use:

Internet.start()

if Internet.active {
 // do something
}
  
if Internet.expensive {
 // device is using Cellular data or WiFi hotspot
}

How to access List elements

Recursive solution to print all items in a list:

def printItems(l):
   for i in l:
      if isinstance(i,list):
         printItems(i)
      else:
         print i


l = [['vegas','London'],['US','UK']]
printItems(l)

Calculate the center point of multiple latitude/longitude coordinate pairs

Here is the python Version for finding center point. The lat1 and lon1 are latitude and longitude lists. it will retuen the latitude and longitude of center point.

def GetCenterFromDegrees(lat1,lon1):    
    if (len(lat1) <= 0):
    return false;

num_coords = len(lat1)

X = 0.0
Y = 0.0
Z = 0.0

for i in range (len(lat1)):
    lat = lat1[i] * np.pi / 180
    lon = lon1[i] * np.pi / 180

    a = np.cos(lat) * np.cos(lon)
    b = np.cos(lat) * np.sin(lon)
    c = np.sin(lat);

    X += a
    Y += b
    Z += c


X /= num_coords
Y /= num_coords
Z /= num_coords

lon = np.arctan2(Y, X)
hyp = np.sqrt(X * X + Y * Y)
lat = np.arctan2(Z, hyp)

newX = (lat * 180 / np.pi)
newY = (lon * 180 / np.pi)
return newX, newY

How to remove all .svn directories from my application directories

In Windows, you can use the following registry script to add "Delete SVN Folders" to your right click context menu. Run it on any directory containing those pesky files.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN]
@="Delete SVN Folders"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN\command]
@="cmd.exe /c \"TITLE Removing SVN Folders in %1 && COLOR 9A && FOR /r \"%1\" %%f IN (.svn) DO RD /s /q \"%%f\" \""

How to include Authorization header in cURL POST HTTP Request in PHP?

You have most of the code…

CURLOPT_HTTPHEADER for curl_setopt() takes an array with each header as an element. You have one element with multiple headers.

You also need to add the Authorization header to your $header array.

$header = array();
$header[] = 'Content-length: 0';
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: OAuth SomeHugeOAuthaccess_tokenThatIReceivedAsAString';

Loop inside React JSX

<tbody>
   numrows.map((row,index) => (
      return <ObjectRow key={index}/>
   )
</tbody>

Android activity life cycle - what are all these methods for?

I run some logs as per answers above and here is the output:

Starting Activity

On Activity Load (First Time)
————————————————————————————————————————————————
D/IndividualChatActivity: onCreate: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

Reload After BackPressed
————————————————————————————————————————————————
D/IndividualChatActivity: onCreate: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

OnMaximize(Circle Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onRestart: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

OnMaximize(Square Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onRestart: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

Stopping The Activity

On BackPressed
————————————————————————————————————————————————
D/IndividualChatActivity: onPause:
D/IndividualChatActivity: onStop: 
D/IndividualChatActivity: onDestroy: 

OnMinimize (Circle Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onPause: 
D/IndividualChatActivity: onStop: 

OnMinimize (Square Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onPause: 
D/IndividualChatActivity: onStop: 

Going To Another Activity
————————————————————————————————————————————————
D/IndividualChatActivity: onPause:
D/IndividualChatActivity: onStop: 

Close The App
————————————————————————————————————————————————
D/IndividualChatActivity: onDestroy: 

In my personal opinion only two are required onStart and onStop.

onResume seems to be in every instance of getting back, and onPause in every instance of leaving (except for closing the app).

How to get the ASCII value of a character

To get the ASCII code of a character, you can use the ord() function.

Here is an example code:

value = input("Your value here: ")
list=[ord(ch) for ch in value]
print(list)

Output:

Your value here: qwerty
[113, 119, 101, 114, 116, 121]

Selecting a Record With MAX Value

Note: An incorrect revision of this answer was edited out. Please review all answers.

A subselect in the WHERE clause to retrieve the greatest BALANCE aggregated over all rows. If multiple ID values share that balance value, all would be returned.

SELECT 
  ID,
  BALANCE
FROM CUSTOMERS
WHERE BALANCE = (SELECT MAX(BALANCE) FROM CUSTOMERS)

How to compare two JSON have the same properties without order?

We use the node-deep-equal project which implements the same deep-equal comparison as nodejs

A google serach for deep-equal on npm will show you many alternatives

How do I give text or an image a transparent background using CSS?

In order to make the background of an element semi-transparent, but have the content (text & images) of the element opaque, you need to write CSS code for that image, and you have to add one attribute called opacity with minimum value.

For example,

.image {
   position: relative;
   background-color: cyan;
   opacity: 0.7;
}

// The smaller the value, the more it will be transparent, ore the value less will be transparency.

How do I find out what is hammering my SQL Server?

I assume due diligence here that you confirmed the CPU is actually consumed by SQL process (perfmon Process category counters would confirm this). Normally for such cases you take a sample of the relevant performance counters and you compare them with a baseline that you established in normal load operating conditions. Once you resolve this problem I recommend you do establish such a baseline for future comparisons.

You can find exactly where is SQL spending every single CPU cycle. But knowing where to look takes a lot of know how and experience. Is is SQL 2005/2008 or 2000 ? Fortunately for 2005 and newer there are a couple of off the shelf solutions. You already got a couple good pointer here with John Samson's answer. I'd like to add a recommendation to download and install the SQL Server Performance Dashboard Reports. Some of those reports include top queries by time or by I/O, most used data files and so on and you can quickly get a feel where the problem is. The output is both numerical and graphical so it is more usefull for a beginner.

I would also recommend using Adam's Who is Active script, although that is a bit more advanced.

And last but not least I recommend you download and read the MS SQL Customer Advisory Team white paper on performance analysis: SQL 2005 Waits and Queues.

My recommendation is also to look at I/O. If you added a load to the server that trashes the buffer pool (ie. it needs so much data that it evicts the cached data pages from memory) the result would be a significant increase in CPU (sounds surprising, but is true). The culprit is usually a new query that scans a big table end-to-end.

String Array object in Java

Currently you can't access the arrays named name and country, because they are member variables of your Athelete class.

Based on what it looks like you're trying to do, this will not work.

These arrays belong in your main class.

C# get string from textbox

In C#, unlike java we do not have to use any method. TextBox property Text is used to get or set its text.

Get

string username = txtusername.Text;
string password = txtpassword.Text;

Set

txtusername.Text = "my_username";
txtpassword.Text = "12345";

Fatal error: Call to undefined function pg_connect()

You need to install the php-pgsql package or whatever it's called for your platform. Which I don't think you said by the way.

On Ubuntu and Debian:

sudo apt-get install php5-pgsql

How do I tell if a regular file does not exist in Bash?

To reverse a test, use "!". That is equivalent to the "not" logical operator in other languages. Try this:

if [ ! -f /tmp/foo.txt ];
then
    echo "File not found!"
fi

Or written in a slightly different way:

if [ ! -f /tmp/foo.txt ]
    then echo "File not found!"
fi

Or you could use:

if ! [ -f /tmp/foo.txt ]
    then echo "File not found!"
fi

Or, presing all together:

if ! [ -f /tmp/foo.txt ]; then echo "File not found!"; fi

Which may be written (using then "and" operator: &&) as:

[ ! -f /tmp/foo.txt ] && echo "File not found!"

Which looks shorter like this:

[ -f /tmp/foo.txt ] || echo "File not found!"

What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?

One more example of 'Variable is out of scope'

As I've seen that kind of questions a few times already, maybe one more example to what's illegal even if it might feel okay.

Consider this code:

if(somethingIsTrue()) {
  String message = "Everything is fine";
} else {
  String message = "We have an error";
}
System.out.println(message);

That's invalid code. Because neither of the variables named message is visible outside of their respective scope - which would be the surrounding brackets {} in this case.

You might say: "But a variable named message is defined either way - so message is defined after the if".

But you'd be wrong.

Java has no free() or delete operators, so it has to rely on tracking variable scope to find out when variables are no longer used (together with references to these variables of cause).

It's especially bad if you thought you did something good. I've seen this kind of error after "optimizing" code like this:

if(somethingIsTrue()) {
  String message = "Everything is fine";
  System.out.println(message);
} else {
  String message = "We have an error";
  System.out.println(message);
}

"Oh, there's duplicated code, let's pull that common line out" -> and there it it.

The most common way to deal with this kind of scope-trouble would be to pre-assign the else-values to the variable names in the outside scope and then reassign in if:

String message = "We have an error";
if(somethingIsTrue()) {
  message = "Everything is fine";
} 
System.out.println(message);

curl Failed to connect to localhost port 80

If anyone else comes across this and the accepted answer doesn't work (it didn't for me), check to see if you need to specify a port other than 80. In my case, I was running a rails server at localhost:3000 and was just using curl http://localhost, which was hitting port 80.

Changing the command to curl http://localhost:3000 is what worked in my case.

Cygwin Make bash command not found

You probably have not installed make. Restart the cygwin installer, search for make, select it and it should be installed. By default the cygwin installer does not install everything for what I remember.

How schedule build in Jenkins?

To build once a day between say 4PM to 6PM you can use

H H(15-17) * * *

Hibernate dialect for Oracle Database 11g?

use only org.hibernate.dialect.OracleDialect Remove 10g,9 etc.

Search for executable files using find command

I had the same issue, and the answer was in the dmenu source code: the stest utility made for that purpose. You can compile the 'stest.c' and 'arg.h' files and it should work. There is a man page for the usage, that I put there for convenience:

STEST(1)         General Commands Manual         STEST(1)

NAME
       stest - filter a list of files by properties

SYNOPSIS
       stest  [-abcdefghlpqrsuwx]  [-n  file]  [-o  file]
       [file...]

DESCRIPTION
       stest takes a list of files  and  filters  by  the
       files'  properties,  analogous  to test(1).  Files
       which pass all tests are printed to stdout. If  no
       files are given, stest reads files from stdin.

OPTIONS
       -a     Test hidden files.

       -b     Test that files are block specials.

       -c     Test that files are character specials.

       -d     Test that files are directories.

       -e     Test that files exist.

       -f     Test that files are regular files.

       -g     Test  that  files  have  their set-group-ID
              flag set.

       -h     Test that files are symbolic links.

       -l     Test the contents of a directory  given  as
              an argument.

       -n file
              Test that files are newer than file.

       -o file
              Test that files are older than file.

       -p     Test that files are named pipes.

       -q     No  files are printed, only the exit status
              is returned.

       -r     Test that files are readable.

       -s     Test that files are not empty.

       -u     Test that files have their set-user-ID flag
              set.

       -v     Invert  the  sense  of  tests, only failing
              files pass.

       -w     Test that files are writable.

       -x     Test that files are executable.

EXIT STATUS
       0      At least one file passed all tests.

       1      No files passed all tests.

       2      An error occurred.

SEE ALSO
       dmenu(1), test(1)

                        dmenu-4.6                STEST(1)

ProgressDialog in AsyncTask

Fixed by moving the view modifiers to onPostExecute so the fixed code is :

public class Soirees extends ListActivity {
    private List<Message> messages;
    private TextView tvSorties;

    //private MyProgressDialog dialog;
    @Override
    public void onCreate(Bundle icicle) {

        super.onCreate(icicle);

        setContentView(R.layout.sorties);

        tvSorties=(TextView)findViewById(R.id.TVTitle);
        tvSorties.setText("Programme des soirées");

        new ProgressTask(Soirees.this).execute();


   }


    private class ProgressTask extends AsyncTask<String, Void, Boolean> {
        private ProgressDialog dialog;
        List<Message> titles;
        private ListActivity activity;
        //private List<Message> messages;
        public ProgressTask(ListActivity activity) {
            this.activity = activity;
            context = activity;
            dialog = new ProgressDialog(context);
        }



        /** progress dialog to show user that the backup is processing. */

        /** application context. */
        private Context context;

        protected void onPreExecute() {
            this.dialog.setMessage("Progress start");
            this.dialog.show();
        }

            @Override
        protected void onPostExecute(final Boolean success) {
                List<Message> titles = new ArrayList<Message>(messages.size());
                for (Message msg : messages){
                    titles.add(msg);
                }
                MessageListAdapter adapter = new MessageListAdapter(activity, titles);
                activity.setListAdapter(adapter);
                adapter.notifyDataSetChanged();

                if (dialog.isShowing()) {
                dialog.dismiss();
            }

            if (success) {
                Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
            }
        }

        protected Boolean doInBackground(final String... args) {
            try{    
                BaseFeedParser parser = new BaseFeedParser();
                messages = parser.parse();


                return true;
             } catch (Exception e){
                Log.e("tag", "error", e);
                return false;
             }
          }


    }

}

@Vladimir, thx your code was very helpful.

How to set the JDK Netbeans runs on?

Thanks to KasunBG's tip, I found the solution in the "suggested" link, update the following file (replace 7.x with your Netbeans version) :

C:\Program Files\NetBeans 7.x\etc\netbeans.conf

Change the following line to point it where your java installation is :

netbeans_jdkhome="C:\Program Files\Java\jdk1.7xxxxx"

You may need Administrator privileges to edit netbeans.conf