Programs & Examples On #Fifo

Any structure in which the First object In is the First object Out. Synonyms include queue, and pipe.

FIFO class in Java

Not sure what you call FIFO these days since Queue is FILO, but when I was a student we used the Stack<E> with the simple push, pop, and a peek... It is really that simple, no need for complicating further with Queue and whatever the accepted answer suggests.

How to extract numbers from a string and get an array of ints?

What about to use replaceAll java.lang.String method:

    String str = "qwerty-1qwerty-2 455 f0gfg 4";      
    str = str.replaceAll("[^-?0-9]+", " "); 
    System.out.println(Arrays.asList(str.trim().split(" ")));

Output:

[-1, -2, 455, 0, 4]

Description

[^-?0-9]+
  • [ and ] delimites a set of characters to be single matched, i.e., only one time in any order
  • ^ Special identifier used in the beginning of the set, used to indicate to match all characters not present in the delimited set, instead of all characters present in the set.
  • + Between one and unlimited times, as many times as possible, giving back as needed
  • -? One of the characters “-” and “?”
  • 0-9 A character in the range between “0” and “9”

Alter table add multiple columns ms sql

Take out the parentheses and the curly braces, neither are required when adding columns.

Adding a SVN repository in Eclipse

At my day job I sit behind a corporate firewall protecting and caching web traffic (among other things). For the most part it stays out of the way. But sometimes it rears its ugly head and stands firmly in the path of what I am trying to do.

Earlier this week I was trying to look at a cool new general validation system for ColdFusion called Validat, put out by the great guys at Alagad. They don't have a download on the RIAForge site yet, but the files are available via SVN. I loaded up the subclipse plugin into my Eclipse, restarted and began adding the Validat SVN repository. I started getting errors abou the "RA layer request failed" and "svn: PROPFIND request failed on /Validat/trunk", followed by an error about not being able to connect to the SVN server.

I already had Eclipse setup with my proxy settings, so I thought I was doing something wrong or Alagad didn't actually have the subversion repository up-and-available. After going home that night, I tried it from home and wa-la it worked. Stupid proxy server! So the subclipse plugin won't use the Eclipse proxy settings. (Can that be fixed please!). After digging around the subclipse help site and being redirected to the collab.net help, then unproductively searching through the eclipse workspace, plugins, and configuration folders for the settings file, I was finally able to figure out how to set up subclipse to use the proxy server.

In my Windows development environment, I opened the following file: C:\Documents and Settings\MyUserId\Application Data\Subversion\servers in my favorite text editor. Near the bottom of that file is a [global] section with http-proxy-host and http-proxy-port settings. I uncommented those two lines, modified them for my corporate proxy server, went back to the SVN Repository view in Eclipse, refreshed the Validat repository and Boom! it worked!

from http://www.mkville.com/blog/index.cfm/2007/11/8/Using-Subclipse-Behind-a-Proxy-Server

How can I get Maven to stop attempting to check for updates for artifacts from a certain group from maven-central-repo?

Update: I should have probably started with this as your projects are SNAPSHOTs. It is part of the SNAPSHOT semantics that Maven will check for updates on each build. Being a SNAPSHOT means that it is volatile and subject to change so updates should be checked for. However it's worth pointing out that the Maven super POM configures central to have snapshots disabled, so Maven shouldn't ever check for updates for SNAPSHOTs on central unless you've overridden that in your own pom/settings.


You can configure Maven to use a mirror for the central repository, this will redirect all requests that would normally go to central to your internal repository.

In your settings.xml you would add something like this to set your internal repository as as mirror for central:

<mirrors>
  <mirror>
    <id>ibiblio.org</id>
    <name>ibiblio Mirror of http://repo1.maven.org/maven2/</name>
    <url>http://path/to/my/repository</url>
    <mirrorOf>central</mirrorOf>
  </mirror>
</mirrors>

If you are using a repository manager like Nexus for your internal repository. You can set up a proxy repository for proxy central, so any requests that would normally go to Central are instead sent to your proxy repository (or a repository group containing the proxy), and subsequent requests are cached in the internal repository manager. You can even set the proxy cache timeout to -1, so it will never request for contents from central that are already on the proxy repository.


A more basic solution if you are only working with local repositories is to set the updatePolicy for the central repository to "never", this means Maven will only ever check for artifacts that aren't already in the local repository. This can then be overridden at the command line when needed by using the -U switch to force Maven to check for updates.

You would configure the repository (in your pom or a profile in the settings.xml) as follows:

<repository>
  <id>central</id>
  <url>http://repo1.maven.org/maven2</url>
  <updatePolicy>never</updatePolicy>
</repository>

How to change the server port from 3000?

Using Angular 4 and the cli that came with it I was able to start the server with $npm start -- --port 8000. That worked ok: ** NG Live Development Server is listening on localhost:8000, open your browser on http://localhost:8000 **

Got the tip from Here

enter image description here enter image description here

c++ and opencv get and set pixel color to Mat

I would not use .at for performance reasons.

Define a struct:

//#pragma pack(push, 2) //not useful (see comments below)
struct RGB {
    uchar blue;
    uchar green;
    uchar red;  };

And then use it like this on your cv::Mat image:

RGB& rgb = image.ptr<RGB>(y)[x];

image.ptr(y) gives you a pointer to the scanline y. And iterate through the pixels with loops of x and y

Check if a folder exist in a directory and create them using C#

using System.IO;
...

Directory.CreateDirectory(@"C:\MP_Upload");

Directory.CreateDirectory does exactly what you want: It creates the directory if it does not exist yet. There's no need to do an explicit check first.

Any and all directories specified in path are created, unless they already exist or unless some part of path is invalid. The path parameter specifies a directory path, not a file path. If the directory already exists, this method does nothing.

(This also means that all directories along the path are created if needed: CreateDirectory(@"C:\a\b\c\d") suffices, even if C:\a does not exist yet.)


Let me add a word of caution about your choice of directory, though: Creating a folder directly below the system partition root C:\ is frowned upon. Consider letting the user choose a folder or creating a folder in %APPDATA% or %LOCALAPPDATA% instead (use Environment.GetFolderPath for that). The MSDN page of the Environment.SpecialFolder enumeration contains a list of special operating system folders and their purposes.

Change button text from Xcode?

Another way to toggle:

- (IBAction)signOnClick:(id)sender
{
    if ([_signOnButton.titleLabel.text isEqualToString:@"Sign off"])
    {
        [sender setTitle:@"Sign on" forState:UIControlStateNormal];
    }
    else
    {
        [sender setTitle:@"Sign off" forState:UIControlStateNormal];
    }
}

How do I create an array of strings in C?

I was missing somehow more dynamic array of strings, where amount of strings could be varied depending on run-time selection, but otherwise strings should be fixed.

I've ended up of coding code snippet like this:

#define INIT_STRING_ARRAY(...)          \
    {                                   \
        char* args[] = __VA_ARGS__;     \
        ev = args;                      \
        count = _countof(args);         \
    }

void InitEnumIfAny(String& key, CMFCPropertyGridProperty* item)
{
    USES_CONVERSION;
    char** ev = nullptr;
    int count = 0;

    if( key.Compare("horizontal_alignment") )
        INIT_STRING_ARRAY( { "top", "bottom" } )

    if (key.Compare("boolean"))
        INIT_STRING_ARRAY( { "yes", "no" } )

    if( ev == nullptr )
        return;

    for( int i = 0; i < count; i++)
        item->AddOption(A2T(ev[i]));

    item->AllowEdit(FALSE);
}

char** ev picks up pointer to array strings, and count picks up amount of strings using _countof function. (Similar to sizeof(arr) / sizeof(arr[0])).

And there is extra Ansi to unicode conversion using A2T macro, but that might be optional for your case.

Use of var keyword in C#

I only use var when it's clear to see what type is used.

For example, I would use var in this case, because you can see immediately that x will be of the type "MyClass":

var x = new MyClass();

I would NOT use var in cases like this, because you have to drag the mouse over the code and look at the tooltip to see what type MyFunction returns:

var x = MyClass.MyFunction();

Especially, I never use var in cases where the right side is not even a method, but only a value:

var x = 5;

(because the compiler can't know if I want a byte, short, int or whatever)

Putting GridView data in a DataTable

protected void btnExportExcel_Click(object sender, EventArgs e)
{
    DataTable _datatable = new DataTable();
    for (int i = 0; i < grdReport.Columns.Count; i++)
    {
        _datatable.Columns.Add(grdReport.Columns[i].ToString());
    }
    foreach (GridViewRow row in grdReport.Rows)
    {
        DataRow dr = _datatable.NewRow();
        for (int j = 0; j < grdReport.Columns.Count; j++)
        {
            if (!row.Cells[j].Text.Equals("&nbsp;"))
                dr[grdReport.Columns[j].ToString()] = row.Cells[j].Text;
        }

        _datatable.Rows.Add(dr);
    }
    ExportDataTableToExcel(_datatable);
}

Change background image opacity

Responding to an earlier comment, you can change the background by variable in the "container" example if the CSS is in your php page and not in the css style sheet.

$bgimage = '[some image url];
background-image: url('<?php echo $bgimage; ?>');

Determine Pixel Length of String in Javascript/jQuery?

Put it in an absolutely-positioned div then use clientWidth to get the displayed width of the tag. You can even set the visibility to "hidden" to hide the div:

<div id="text" style="position:absolute;visibility:hidden" >This is some text</div>
<input type="button" onclick="getWidth()" value="Go" />
<script type="text/javascript" >
    function getWidth() {
        var width = document.getElementById("text").clientWidth;
        alert(" Width :"+  width);
    }
</script>

JQuery .each() backwards

I present you with the cleanest way ever, in the form of the world's smallest jquery plugin:

jQuery.fn.reverse = [].reverse;

Usage:

$('jquery-selectors-go-here').reverse().each(function () {
    //business as usual goes here
});

-All credit to Michael Geary in his post here: http://www.mail-archive.com/[email protected]/msg04261.html

C# equivalent of C++ map<string,double>

The closest equivalent of C++ std::map<> (a tree internally) is C# OrderedDictionary<> (a tree internally), while C# OrderedDictionary<> is missing some very important methods from C++ std::map<>, namely: std::map::find, std::map::lower_bound, std::map::upper_bound, std::map::equal_range, and std::map iterators, which are basically the backbone for the previous 4 methods.

Why those 4 methods are important? Because it gives us the ability to locate the "whereabouts" of a given key, in addition to only being able to check if a key exists, or the SortedDictionary is guaranteed to be ordered.

What is "whereabouts" of a key in a std::map? The key doesn't necessarily have to exist in the collection, we want to know the location the key might be at, usually between two iterators pointing to two adjacent existing keys respectively in the collection, so we can operate on the range the key falls into in a O(logN) complexity. Without such 4 methods (with iterators), one has to do an O(N) iteration through the collection every time a range is queried against a key.

If statement within Where clause

You can't use IF like that. You can do what you want with AND and OR:

SELECT t.first_name,
       t.last_name,
       t.employid,
       t.status
  FROM employeetable t
 WHERE ((status_flag = STATUS_ACTIVE   AND t.status = 'A')
     OR (status_flag = STATUS_INACTIVE AND t.status = 'T')
     OR (source_flag = SOURCE_FUNCTION AND t.business_unit = 'production')
     OR (source_flag = SOURCE_USER     AND t.business_unit = 'users'))
   AND t.first_name LIKE firstname
   AND t.last_name  LIKE lastname
   AND t.employid   LIKE employeeid;

Using NSPredicate to filter an NSArray based on NSDictionary keys

NSPredicate is only available in iPhone 3.0.

You won't notice that until try to run on device.

Most efficient way to append arrays in C#?

Concatenating arrays is simple using linq extensions which come standard with .Net 4

Biggest thing to remember is that linq works with IEnumerable<T> objects, so in order to get an array back as your result then you must use the .ToArray() method at the end

Example of concatenating two byte arrays:

byte[] firstArray = {2,45,79,33};
byte[] secondArray = {55,4,7,81};
byte[] result = firstArray.Concat(secondArray).ToArray();

Array.size() vs Array.length

The .size() method is deprecated as of jQuery 1.8. Use the .length property instead

See: https://api.jquery.com/size/

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

When I find myself thinking about using Manager or Helper in a class name, I consider it a code smell that means I haven't found the right abstraction yet and/or I'm violating the single responsibility principle, so refactoring and putting more effort into design often makes naming much easier.

But even well-designed classes don't (always) name themselves, and your choices partly depend on whether you're creating business model classes or technical infrastructure classes.

Business model classes can be hard, because they're different for every domain. There are some terms I use a lot, like Policy for strategy classes within a domain (e.g., LateRentalPolicy), but these usually flow from trying to create a "ubiquitous language" that you can share with business users, designing and naming classes so they model real-world ideas, objects, actions, and events.

Technical infrastructure classes are a bit easier, because they describe domains we know really well. I prefer to incorporate design pattern names into the class names, like InsertUserCommand, CustomerRepository, or SapAdapter. I understand the concern about communicating implementation instead of intent, but design patterns marry these two aspects of class design - at least when you're dealing with infrastructure, where you want the implementation design to be transparent even while you're hiding the details.

Remove all whitespaces from NSString

- (NSString *)removeWhitespaces {
  return [[self componentsSeparatedByCharactersInSet:
                    [NSCharacterSet whitespaceCharacterSet]]
      componentsJoinedByString:@""];
}

Populate dropdown select with array using jQuery

The solution I used was to create a javascript function that uses jquery:

This will populate a dropdown object on the HTML page. Please let me know where this can be optimized - but works fine as is.

function util_PopulateDropDownListAndSelect(sourceListObject, sourceListTextFieldName, targetDropDownName, valueToSelect)
{
    var options = '';

    // Create the list of HTML Options
    for (i = 0; i < sourceListObject.List.length; i++)
    {
        options += "<option value='" + sourceListObject.List[i][sourceListTextFieldName] + "'>" + sourceListObject.List[i][sourceListTextFieldName] + "</option>\r\n";
    }

    // Assign the options to the HTML Select container
    $('select#' + targetDropDownName)[0].innerHTML = options;

    // Set the option to be Selected
    $('#' + targetDropDownName).val(valueToSelect);

    // Refresh the HTML Select so it displays the Selected option
    $('#' + targetDropDownName).selectmenu('refresh')
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Creating a BAT file for python script

i did this and works: i have my project in D: and my batch file is in the desktop, if u have it in the same drive just ignore the first line and change de D directory in the second line

in the second line change the folder of the file, put your folder

in the third line change the name of the file

D: cd D:\python_proyects\example_folder\ python example_file.py

How to convert string to Title Case in Python?

def capitalizeWords(s):
  return re.sub(r'\w+', lambda m:m.group(0).capitalize(), s)

re.sub can take a function for the "replacement" (rather than just a string, which is the usage most people seem to be familiar with). This repl function will be called with an re.Match object for each match of the pattern, and the result (which should be a string) will be used as a replacement for that match.

A longer version of the same thing:

WORD_RE = re.compile(r'\w+')

def capitalizeMatch(m):
  return m.group(0).capitalize()

def capitalizeWords(s):
  return WORD_RE.sub(capitalizeMatch, s)

This pre-compiles the pattern (generally considered good form) and uses a named function instead of a lambda.

Obtaining ExitCode using Start-Process and WaitForExit instead of -Wait

Or try adding this...

$code = @"
[DllImport("kernel32.dll")]
public static extern int GetExitCodeProcess(IntPtr hProcess, out Int32 exitcode);
"@
$type = Add-Type -MemberDefinition $code -Name "Win32" -Namespace Win32 -PassThru
[Int32]$exitCode = 0
$type::GetExitCodeProcess($process.Handle, [ref]$exitCode)

By using this code, you can still let PowerShell take care of managing redirected output/error streams, which you cannot do using System.Diagnostics.Process.Start() directly.

Python unittest - opposite of assertRaises?

I am the original poster and I accepted the above answer by DGH without having first used it in the code.

Once I did use I realised that it needed a little tweaking to actually do what I needed it to do (to be fair to DGH he/she did say "or something similar" !).

I thought it was worth posting the tweak here for the benefit of others:

    try:
        a = Application("abcdef", "")
    except pySourceAidExceptions.PathIsNotAValidOne:
        pass
    except:
        self.assertTrue(False)

What I was attempting to do here was to ensure that if an attempt was made to instantiate an Application object with a second argument of spaces the pySourceAidExceptions.PathIsNotAValidOne would be raised.

I believe that using the above code (based heavily on DGH's answer) will do that.

CakePHP select default value in SELECT input

If you are using cakephp version 3.0 and above, then you can add default value in select input using empty attribute as given in below example.

echo $this->Form->input('category_id', ['options'=>$categories,'empty'=>'Choose']);

Java: Reading integers from a file into an array

You might have confusions between the different line endings. A Windows file will end each line with a carriage return and a line feed. Some programs on Unix will read that file as if it had an extra blank line between each line, because it will see the carriage return as an end of line, and then see the line feed as another end of line.

How to switch to other branch in Source Tree to commit the code?

  1. Go to the log view (to be able to go here go to View -> log view).
  2. Double click on the line with the branch label stating that branch. Automatically, it will switch branch. (A prompt will dropdown and say switching branch.)
  3. If you have two or more branches on the same line, it will ask you via prompt which branch you want to switch. Choose the specific branch from the dropdown and click ok.

To determine which branch you are now on, look at the side bar, under BRANCHES, you are in the branch that is in BOLD LETTERS.

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

Including more than one reference to Jquery library is the reason for the error Only Include one reference to the Jquery library and that will resolve the issue

How to dynamically change a web page's title?

The code is
document.title = 'test'

Javascript: set label text

For a dynamic approach, if your labels are always in front of your text areas:

$(object).prev("label").text(charsleft);

How to change the color of winform DataGridview header?

The way to do this is to set the EnableHeadersVisualStyles flag for the data grid view to False, and set the background colour via the ColumnHeadersDefaultCellStyle.BackColor property. For example, to set the background colour to blue, use the following (or set in the designer if you prefer):

_dataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;
_dataGridView.EnableHeadersVisualStyles = false;

If you do not set the EnableHeadersVisualStyles flag to False, then the changes you make to the style of the header will not take effect, as the grid will use the style from the current users default theme. The MSDN documentation for this property is here.

Show only two digit after decimal

First thing that should pop in a developer head while formatting a number into char sequence should be care of such details like do it will be possible to reverse the operation.

And other aspect is providing proper result. So you want to truncate the number or round it.

So before you start you should ask your self, am i interested on the value or not.

To achieve your goal you have multiple options but most of them refer to Format and Formatter, but i just suggest to look in this answer.

Breaking out of a nested loop

Did you even look at the break keyword? O.o

This is just pseudo-code, but you should be able to see what I mean:

<?php
for(...) {
    while(...) {
        foreach(...) {
            break 3;
        }
    }
}

If you think about break being a function like break(), then it's parameter would be the number of loops to break out of. As we are in the third loop in the code here, we can break out of all three.

Manual: http://php.net/break

What's the difference of $host and $http_host in Nginx

$host is a variable of the Core module.

$host

This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.

This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.

$http_host is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER (ref).

$http_HEADER

The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;


Summarizing:

  • $http_host equals always the HTTP_HOST request header.
  • $host equals $http_host, lowercase and without the port number (if present), except when HTTP_HOST is absent or is an empty value. In that case, $host equals the value of the server_name directive of the server which processed the request.

How to decorate a class?

That's not a good practice and there is no mechanism to do that because of that. The right way to accomplish what you want is inheritance.

Take a look into the class documentation.

A little example:

class Employee(object):

    def __init__(self, age, sex, siblings=0):
        self.age = age
        self.sex = sex    
        self.siblings = siblings

    def born_on(self):    
        today = datetime.date.today()

        return today - datetime.timedelta(days=self.age*365)


class Boss(Employee):    
    def __init__(self, age, sex, siblings=0, bonus=0):
        self.bonus = bonus
        Employee.__init__(self, age, sex, siblings)

This way Boss has everything Employee has, with also his own __init__ method and own members.

Why SpringMVC Request method 'GET' not supported?

I also had the same issue. I changed it to the following and it worked.

Java :

@RequestMapping(value = "/test", method = RequestMethod.GET)

HTML code:

  <form action="<%=request.getContextPath() %>/test" method="GET">
    <input type="submit" value="submit"> 
    </form>

By default if you do not specify http method in a form it uses GET. To use POST method you need specifically state it.

Hope this helps.

SQLite - UPSERT *not* INSERT or REPLACE

This answer has be updated and so the comments below no longer apply.

2018-05-18 STOP PRESS.

UPSERT support in SQLite! UPSERT syntax was added to SQLite with version 3.24.0 (pending) !

UPSERT is a special syntax addition to INSERT that causes the INSERT to behave as an UPDATE or a no-op if the INSERT would violate a uniqueness constraint. UPSERT is not standard SQL. UPSERT in SQLite follows the syntax established by PostgreSQL.

enter image description here

alternatively:

Another completely different way of doing this is: In my application I set my in memory rowID to be long.MaxValue when I create the row in memory. (MaxValue will never be used as an ID you will won't live long enough.... Then if rowID is not that value then it must already be in the database so needs an UPDATE if it is MaxValue then it needs an insert. This is only useful if you can track the rowIDs in your app.

How get all values in a column using PHP?

PHP 5 >= 5.5.0, PHP 7

Use array_column on the result array

$column = array_column($result, 'names');

Resizing image in Java

Resize image with high quality:

private static InputStream resizeImage(InputStream uploadedInputStream, String fileName, int width, int height) {

        try {
            BufferedImage image = ImageIO.read(uploadedInputStream);
            Image originalImage= image.getScaledInstance(width, height, Image.SCALE_DEFAULT);

            int type = ((image.getType() == 0) ? BufferedImage.TYPE_INT_ARGB : image.getType());
            BufferedImage resizedImage = new BufferedImage(width, height, type);

            Graphics2D g2d = resizedImage.createGraphics();
            g2d.drawImage(originalImage, 0, 0, width, height, null);
            g2d.dispose();
            g2d.setComposite(AlphaComposite.Src);
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            ImageIO.write(resizedImage, fileName.split("\\.")[1], byteArrayOutputStream);
            return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        } catch (IOException e) {
            // Something is going wrong while resizing image
            return uploadedInputStream;
        }
    }

Set background image in CSS using jquery

You have to remove the semicolon in the css rule string:

$(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat");

Strangest language feature

A very tiny thing that annoyed me in COBOL was that there was no dedicated modulo operation. Instead you could do a division specifying that you only wanted whole number results and store the rest in a different variable. Since COBOL is very sensitive when it comes to variables that means that you ended up with a variable you didn't really need, i.e. the actual result of the division. This is the story of how I once named a variable "USELESS" - that was the most appropriate name I could think of.

Video file formats supported in iPhone

The short answer is the iPhone supports H.264 video, High profile and AAC audio, in container formats .mov, .mp4, or MPEG Segment .ts. MPEG Segment files are used for HTTP Live Streaming.

  • For maximum compatibility with Android and desktop browsers, use H.264 + AAC in an .mp4 container.
  • For extended length videos longer than 10 minutes you must use HTTP Live Streaming, which is H.264 + AAC in a series of small .ts container files (see App Store Review Guidelines rule 2.5.7).

Video

On the iPhone, H.264 is the only game in town. [1]

There are several different feature tiers or "profiles" available in H.264. All modern iPhones (3GS and above) support the High profile. These profiles are basically three different levels of algorithm "tricks" used to compress the video. More tricks give better compression, but require more CPU or dedicated hardware to decode. This is a table that lists the differences between the different profiles.

[1] Interestingly, Apple's own Facetime uses the newer H.265 (HEVC) video codec. However right now (August 2017) there is no Apple-provided library that gives access to a HEVC codec to developers. This is expected to change at some point.

In talking about what video format the iPhone supports, a distinction should be made between what the hardware can support, and what the (much lower) limits are for playback when streaming over a network.

The only data given about hardware video support by Apple about the current generation of iPhones (SE, 6S, 6S Plus, 7, 7 Plus) is that they support

4K [3840x2160] video recording at 30 fps

1080p [1920x1080] HD video recording at 30 fps or 60 fps.

Obviously the phone can play back what it can record, so we can guess that 3840x2160 at 30 fps and 1920x1080 at 60 fps represent design limits of the phone. In addition, the screen size on the 6S Plus and 7 Plus is 1920x1080. So if you're interested in playback on the phone, it doesn't make sense to send over more pixels then the screen can draw.

However, streaming video is a different matter. Since networks are slow and video is huge, it's typical to use lower resolutions, bitrates, and frame rates than the device's theoretical maximum.

The most detailed document giving recommendations for streaming is TN2224 Best Practices for Creating and Deploying HTTP Live Streaming Media for Apple Devices. Figure 3 in that document gives a table of recommended streaming parameters:

Table of Apple recommended video encoding settings This table is from May 2016.

As you can see, Apple recommends the relatively low resolution of 768x432 as the highest recommended resolution for streaming over a cellular network. Of course this is just a recommendation and YMMV.

Audio

The question is about video, but that video generally has one or more audio tracks with it. The iPhone supports a few audio formats, but the most modern and by far most widely used is AAC. The iPhone 7 / 7 Plus, 6S Plus / 6S, SE all support AAC bitrates of 8 to 320 Kbps.

Container

The audio and video tracks go inside a container. The purpose of the container is to combine (interleave) the different tracks together, to store metadata, and to support seeking. The iPhone supports

  1. QuickTime .mov,
  2. MP4, and
  3. MPEG-TS.

The .mov and .mp4 file formats are closely related (.mp4 is in fact based on .mov), however .mp4 is an ISO standard that has much wider support.

As noted above, you have to use MPEG-TS for videos longer than 10 minutes.

Simple way to find if two different lists contain exactly the same elements?

It depends on what concrete List class you are using. The abstract class AbstractCollection has a method called containsAll(Collection) that takes another collection ( a List is a collection) and:

Returns true if this collection contains all of the elements in the specified collection.

So if an ArrayList is being passed in you can call this method to see if they are exactly the same.

       List foo = new ArrayList();
    List bar = new ArrayList();
    String str = "foobar";

    foo.add(str);
    bar.add(str);

    foo.containsAll(bar);

The reason for containsAll() is because it iterates through the first list looking for the match in the second list. So if they are out of order equals() will not pick it up.

EDIT: I just want to make a comment here about the amortized running time of performing the various options being offered. Is running time important? Sure. Is it the only thing you should consider? No.

The cost of copying EVERY single element from your lists into other lists takes time, and it also takes up a good chunk of memory (effectively doubling the memory you are using).

So if memory in your JVM isn't a concern (which it should generally be) then you still need to consider the time it takes to copy every element from two lists into two TreeSets. Remember it is sorting every element as it enters them.

My final advice? You need to consider your data set and how many elements you have in your data set, and also how large each object in your data set is before you can make a good decision here. Play around with them, create one each way and see which one runs faster. It's a good exercise.

Android - running a method periodically using postDelayed() call

Why don't you create service and put logic in onCreate(). In this case even if you press back button service will keep on executing. and once you enter into application it will not call onCreate() again. Rather it will call onStart()

How to use table variable in a dynamic sql statement?

Well, I figured out the way and thought to share with the people out there who might run into the same problem.

Let me start with the problem I had been facing,

I had been trying to execute a Dynamic Sql Statement that used two temporary tables I declared at the top of my stored procedure, but because that dynamic sql statment created a new scope, I couldn't use the temporary tables.

Solution:

I simply changed them to Global Temporary Variables and they worked.

Find my stored procedure underneath.

CREATE PROCEDURE RAFCustom_Room_GetRelatedProducts
-- Add the parameters for the stored procedure here
@PRODUCT_SKU nvarchar(15) = Null

AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON;

IF OBJECT_ID('tempdb..##RelPro', 'U') IS NOT NULL
BEGIN
    DROP TABLE ##RelPro
END

Create Table ##RelPro
(
    RowID int identity(1,1),
    ID int,
    Item_Name nvarchar(max),
    SKU nvarchar(max),
    Vendor nvarchar(max),
    Product_Img_180 nvarchar(max),
    rpGroup int,
    Assoc_Item_1 nvarchar(max),
    Assoc_Item_2 nvarchar(max),
    Assoc_Item_3 nvarchar(max),
    Assoc_Item_4 nvarchar(max),
    Assoc_Item_5 nvarchar(max),
    Assoc_Item_6 nvarchar(max),
    Assoc_Item_7 nvarchar(max),
    Assoc_Item_8 nvarchar(max),
    Assoc_Item_9 nvarchar(max),
    Assoc_Item_10 nvarchar(max)
);

Begin
    Insert ##RelPro(ID, Item_Name, SKU, Vendor, Product_Img_180, rpGroup)

    Select distinct zp.ProductID, zp.Name, zp.SKU,
        (Select m.Name From ZNodeManufacturer m(nolock) Where m.ManufacturerID = zp.ManufacturerID),
        'http://s0001.server.com/is/sw11/DG/' + 
        (Select m.Custom1 From ZNodeManufacturer m(nolock) Where m.ManufacturerID = zp.ManufacturerID) +
        '_' + zp.SKU + '_3?$SC_3243$', ep.RoomID
    From Product zp(nolock) Inner Join RF_ExtendedProduct ep(nolock) On ep.ProductID = zp.ProductID
    Where zp.ActiveInd = 1 And SUBSTRING(zp.SKU, 1, 2) <> 'GC' AND zp.Name <> 'PLATINUM' AND zp.SKU = (Case When @PRODUCT_SKU Is Not Null Then @PRODUCT_SKU Else zp.SKU End)
End

declare @curr_row int = 0,
        @tot_rows int= 0,
        @sku nvarchar(15) = null;

IF OBJECT_ID('tempdb..##TSku', 'U') IS NOT NULL
BEGIN
    DROP TABLE ##TSku
END
Create Table ##TSku (tid int identity(1,1), relsku nvarchar(15));

Select @curr_row = (Select MIN(RowId) From ##RelPro);
Select @tot_rows = (Select MAX(RowId) From ##RelPro);

while @curr_row <= @tot_rows
Begin
    select @sku = SKU from ##RelPro where RowID = @curr_row;

    truncate table ##TSku;

    Insert ##TSku(relsku)
    Select distinct top(10) tzp.SKU From Product tzp(nolock) INNER JOIN 
    [INTRANET].raf_FocusAssociatedItem assoc(nolock) ON assoc.associatedItemID = tzp.SKU
    Where (assoc.isActive=1) And (tzp.ActiveInd = 1) AND (assoc.productID = @sku)

    declare @curr_row1 int = (Select Min(tid) From ##TSku),
            @tot_rows1 int = (Select Max(tid) From ##TSku);

    If(@tot_rows1 <> 0)
    Begin
        While @curr_row1 <= @tot_rows1
        Begin
            declare @col_name nvarchar(15) = null,
                    @sqlstat nvarchar(500) = null;
            set @col_name =  'Assoc_Item_' + Convert(nvarchar(2), @curr_row1);
            set @sqlstat = 'update ##RelPro set ' + @col_name + ' = (Select relsku From ##TSku Where tid = ' + Convert(nvarchar(2), @curr_row1) + ') Where RowID = ' + Convert(nvarchar(2), @curr_row);
            Exec(@sqlstat);
            set @curr_row1 = @curr_row1 + 1;
        End
    End
    set @curr_row = @curr_row + 1;
End

Select * From ##RelPro;

END GO

Make DateTimePicker work as TimePicker only in WinForms

...or alternatively if you only want to show a portion of the time value use "Custom":

timePicker = new DateTimePicker();
timePicker.Format = DateTimePickerFormat.Custom;
timePicker.CustomFormat = "HH:mm"; // Only use hours and minutes
timePicker.ShowUpDown = true;

INNER JOIN ON vs WHERE clause

If you are often programming dynamic stored procedures, you will fall in love with your second example (using where). If you have various input parameters and lots of morph mess, then that is the only way. Otherwise, they both will run the same query plan so there is definitely no obvious difference in classic queries.

loop through json array jquery

I dont think youre returning json object from server. just a string.

you need the dataType of the return object to be json

How to read the value of a private field from a different class in Java?

As oxbow_lakes mentions, you can use reflection to get around the access restrictions (assuming your SecurityManager will let you).

That said, if this class is so badly designed that it makes you resort to such hackery, maybe you should look for an alternative. Sure this little hack might be saving you a few hours now, but how much will it cost you down the road?

Return string Input with parse.string

You don't need to parse the string, it's defined as a string already.

Just do:

    private static String getStringInput (String prompt) {
     String input = EZJ.getUserInput(prompt);
     return input;
    }

Android Completely transparent Status Bar?

I found fiddling with styles.xml and activity to be too cumbersome hence created a common utility method which has below options set

Java

Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
window.setStatusBarColor(Color.TRANSPARENT);

Kotlin DSL

activity.window.apply {
    clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
    addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
    decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
    statusBarColor = Color.TRANSPARENT
}

And that's all it took to achieve transparent status bar. Hope this helps.

Sorting list based on values from another list

You can create a pandas Series, using the primary list as data and the other list as index, and then just sort by the index:

import pandas as pd
pd.Series(data=X,index=Y).sort_index().tolist()

output:

['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']

Get the filePath from Filename using Java

You can use the Path api:

Path p = Paths.get(yourFileNameUri);
Path folder = p.getParent();

Paging UICollectionView by cells, not screen

Approach 1: Collection View

flowLayout is UICollectionViewFlowLayout property

override func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

    if let collectionView = collectionView {

        targetContentOffset.memory = scrollView.contentOffset
        let pageWidth = CGRectGetWidth(scrollView.frame) + flowLayout.minimumInteritemSpacing

        var assistanceOffset : CGFloat = pageWidth / 3.0

        if velocity.x < 0 {
            assistanceOffset = -assistanceOffset
        }

        let assistedScrollPosition = (scrollView.contentOffset.x + assistanceOffset) / pageWidth

        var targetIndex = Int(round(assistedScrollPosition))


        if targetIndex < 0 {
            targetIndex = 0
        }
        else if targetIndex >= collectionView.numberOfItemsInSection(0) {
            targetIndex = collectionView.numberOfItemsInSection(0) - 1
        }

        print("targetIndex = \(targetIndex)")

        let indexPath = NSIndexPath(forItem: targetIndex, inSection: 0)

        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
    }
}

Approach 2: Page View Controller

You could use UIPageViewController if it meets your requirements, each page would have a separate view controller.

Is it possible to create a File object from InputStream

If you do not want to use other library, here is a simple function to convert InputStream to OutputStream.

public static void copyStream(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while ((read = in.read(buffer)) != -1) {
        out.write(buffer, 0, read);
    }
}

Now you can easily write an Inputstream into file by using FileOutputStream-

FileOutputStream out = new FileOutputStream(outFile);
copyStream (inputStream, out);
out.close();

How to set password for Redis?

i couldnt find though what i should add exactly to the configuration file to set up the password.

Configuration file should be located at /etc/redis/redis.conf and password can be set up in SECURITY section which should be located between REPLICATION and LIMITS section. Password setup is done using the requirepass directive. For more information try to look at AUTH command description.

Complexities of binary tree traversals

O(n),I would say . I am doing for a balanced tree,applicable for all the trees. Assuming that you use recursion,

T(n) = 2*T(n/2) + 1 ----------> (1)

T(n/2) for left sub-tree and T(n/2) for right sub-tree and '1' for verifying the base case.

On Simplifying (1) you can prove that the traversal(either inorder or preorder or post order) is of order O(n).

How to change the sender's name or e-mail address in mutt?

For a one time change you can do this:

export EMAIL='[email protected]'; mutt -s "Elvis is dead" [email protected]

Can I start the iPhone simulator without "Build and Run"?

Use Spotlight.

But only the last simulator will be opened. If you used iPad Air 2 last time, Spotlight will open it. If you wanna open iPhone 6s this time, that's a problem.

How to add a boolean datatype column to an existing table in sql?

Below query worked for me with default value false;

ALTER TABLE cti_contract_account ADD ready_to_audit BIT DEFAULT 0 NOT NULL;

Best way to store chat messages in a database?

There's nothing wrong with saving the whole history in the database, they are prepared for that kind of tasks.

Actually you can find here in Stack Overflow a link to an example schema for a chat: example

If you are still worried for the size, you could apply some optimizations to group messages, like adding a buffer to your application that you only push after some time (like 1 minute or so); that way you would avoid having only 1 line messages

How to use hex color values

Here's a Swift extension on UIColor that takes a hex string:

import UIKit

extension UIColor {

    convenience init(hexString: String) {
        // Trim leading '#' if needed
        var cleanedHexString = hexString
        if hexString.hasPrefix("#") {
//            cleanedHexString = dropFirst(hexString) // Swift 1.2
            cleanedHexString = String(hexString.characters.dropFirst()) // Swift 2
        }

        // String -> UInt32
        var rgbValue: UInt32 = 0
        NSScanner(string: cleanedHexString).scanHexInt(&rgbValue)

        // UInt32 -> R,G,B
        let red = CGFloat((rgbValue >> 16) & 0xff) / 255.0
        let green = CGFloat((rgbValue >> 08) & 0xff) / 255.0
        let blue = CGFloat((rgbValue >> 00) & 0xff) / 255.0

        self.init(red: red, green: green, blue: blue, alpha: 1.0)
    }

}

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

If you want to stick to an array then this way you can make use. But its not good as compared to List and not recommended. However it will solve your problem.

import java.util.Scanner;

public class ArrayModify {

    public static void main(String[] args) {
        int[] list;
        String st;
        String[] stNew;
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter Numbers: "); // If user enters 5 6 7 8 9 
        st = scan.nextLine();
        stNew = st.split("\\s+");
        list = new int[stNew.length]; // Sets array size to 5

        for (int i = 0; i < stNew.length; i++){
            list[i] =  Integer.parseInt(stNew[i]);
            System.out.println("You Enterred: " + list[i]);
        }
    }
}

Access camera from a browser

**SIMPLE JAVASCRIPT VANILLA **

_x000D_
_x000D_
var video = document.querySelector("#videoElement");

if (navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia({ video: true })
        .then(function (stream) {
            video.srcObject = stream;
        })
        .catch(function (err0r) {
            console.log("Something went wrong!");
        });
}
_x000D_
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta content="stuff, to, help, search, engines, not" name="keywords">
<meta content="What this page is about." name="description">
<meta content="Display Webcam Stream" name="title">
<title>Display Webcam Stream</title>
<style>
  #container{
   align-self: center;
   margin-left: 350px;
   align-items: center;
   justify-content: center;
position: relative;
    width: 1000px;
    height: 1000px;
       background-color: black;
       padding: 3px;
  }
  #videoElement{
    transform: rotate(90deg);
   align-self: center;
   height: 50a0px;
   left: 20;
   width: 700px;
   position:absolute;
   padding: 1px;
   top: 120px;
  }
</style>
</head>
  
<body>
<div id="container">
    <video autoplay="true" id="videoElement">
    </video>
</div>
<script src="index.js">

</script>
</body>
</html>
_x000D_
_x000D_
_x000D_

Formula to determine brightness of RGB color

For clarity, the formulas that use a square root need to be

sqrt(coefficient * (colour_value^2))

not

sqrt((coefficient * colour_value))^2

The proof of this lies in the conversion of a R=G=B triad to greyscale R. That will only be true if you square the colour value, not the colour value times coefficient. See Nine Shades of Greyscale

Extract parameter value from url using regular expressions

You almost had it, just need to escape special regex chars:

regex = /http\:\/\/www\.youtube\.com\/watch\?v=([\w-]{11})/;

url = 'http://www.youtube.com/watch?v=Ahg6qcgoay4';
id = url.match(regex)[1]; // id = 'Ahg6qcgoay4'

Edit: Fix for regex by soupagain.

(WAMP/XAMP) send Mail using SMTP localhost

Here's the steps to achieve this:

  • Download the sendmail.zip through this link

    • Now, extract the folder and put it to C:/wamp/. Make sure that these four files are present: sendmail.exe, libeay32.dll, ssleay32.ddl and sendmail.ini.
    • Open sendmail.ini and set the configuration as follows:

    • smtp_server=smtp.gmail.com

    • smtp_port=465
    • smtp_ssl=ssl
    • default_domain=localhost
    • error_logfile=error.log
    • debug_logfile=debug.log
    • auth_username=[your_gmail_account_username]@gmail.com
    • auth_password=[your_gmail_account_password]
    • pop3_server=
    • pop3_username=
    • pop3_password=
    • force_sender=
    • force_recipient=
    • hostname=localhost

    • Access your email account. Click the Gear Tool > Settings > Forwarding and POP/IMAP > IMAP access. Click "Enable IMAP", then save your changes.

    • Run your WAMP Server. Enable ssl_module under Apache Module.

    • Next, enable php_openssl and php_sockets under PHP.

    • Open php.ini and configure it as the codes below. Basically, you just have to set the sendmail_path.

[mail function]
; For Win32 only.
; http://php.net/smtp
;SMTP =
; http://php.net/smtp-port
;smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = [email protected]
; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = "C:\wamp\sendmail\sendmail.exe -t -i"
  • Restart Wamp Server

I hope this will work for you..

How to echo print statements while executing a sql script

What about using mysql -v to put mysql client in verbose mode ?

How do I remove/delete a folder that is not empty?

Base on kkubasik's answer, check if folder exists before remove, more robust

import shutil
def remove_folder(path):
    # check if folder exists
    if os.path.exists(path):
         # remove if exists
         shutil.rmtree(path)
    else:
         # throw your exception to handle this special scenario
         raise XXError("your exception") 
remove_folder("/folder_name")

List Git commits not pushed to the origin yet

how to determine if a commit with particular hash have been pushed to the origin already?

# list remote branches that contain $commit
git branch -r --contains $commit

How do you see the entire command history in interactive Python?

A simple function to get the history similar to unix/bash version.

Hope it helps some new folks.

def ipyhistory(lastn=None):
    """
    param: lastn Defaults to None i.e full history. If specified then returns lastn records from history.
           Also takes -ve sequence for first n history records.
    """
    import readline
    assert lastn is None or isinstance(lastn, int), "Only integers are allowed."
    hlen = readline.get_current_history_length()
    is_neg = lastn is not None and lastn < 0
    if not is_neg:
        flen = len(str(hlen)) if not lastn else len(str(lastn))
        for r in range(1,hlen+1) if not lastn else range(1, hlen+1)[-lastn:]:
            print(": ".join([str(r if not lastn else r + lastn - hlen ).rjust(flen), readline.get_history_item(r)]))
    else:
        flen = len(str(-hlen))
        for r in range(1, -lastn + 1):
            print(": ".join([str(r).rjust(flen), readline.get_history_item(r)]))

Snippet: Tested with Python3. Let me know if there are any glitches with python2. Samples:

Full History : ipyhistory()

Last 10 History: ipyhistory(10)

First 10 History: ipyhistory(-10)

Hope it helps fellas.

Python check if list items are integers?

Fast, simple, but maybe not always right:

>>> [x for x in mylist if x.isdigit()]
['1', '2', '3', '4']

More traditional if you need to get numbers:

new_list = []
for value in mylist:
    try:
        new_list.append(int(value))
    except ValueError:
        continue

Note: The result has integers. Convert them back to strings if needed, replacing the lines above with:

try:
    new_list.append(str(int(value)))

Add a properties file to IntelliJ's classpath

I have the same problem and it annoys me tremendously!!

I have always thought I was surposed to do as answer 2. That used to work in Intellij 9 (now using 10).

However I figured out that by adding these line to my maven pom file helps:

<build>
  ...
  <resources>
    <resource>
      <directory>src/main/resources</directory>
    </resource>
  </resources>
  ...
</build>

utf-8 special characters not displaying

set meta tag in head as

 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> 

use the link http://www.i18nqa.com/debug/utf8-debug.html to replace the symbols character you want.

then use str_replace like

    $find = array('“', '’', '…', '—', '–', '‘', 'é', 'Â', '•', 'Ëœ', 'â€'); // en dash
                        $replace = array('“', '’', '…', '—', '–', '‘', 'é', '', '•', '˜', '”');
$content = str_replace($find, $replace, $content);

Its the method i use and help alot. Thanks!

maven "cannot find symbol" message unhelpful

This occurs because of this issue also i.e repackaging which you defined in POM file.

Remove this from pom file under maven plugin. It will work

<executions>
    <execution>
        <goals>
             <goal>repackage</goal>
        </goals>
    </execution>
</executions>

Why is Maven downloading the maven-metadata.xml every time?

I suppose because you didn't specify plugin version so it triggers the download of associated metadata in order to get the last one.

Otherwise did you try to force local repo usage using -o ?

PostgreSQL Exception Handling

Use the DO statement, a new option in version 9.0:

DO LANGUAGE plpgsql
$$
BEGIN
CREATE TABLE "Logs"."Events"
    (
        EventId BIGSERIAL NOT NULL PRIMARY KEY,
        PrimaryKeyId bigint NOT NULL,
        EventDateTime date NOT NULL DEFAULT(now()),
        Action varchar(12) NOT NULL,
        UserId integer NOT NULL REFERENCES "Office"."Users"(UserId),
        PrincipalUserId varchar(50) NOT NULL DEFAULT(user)
    );

    CREATE TABLE "Logs"."EventDetails"
    (
        EventDetailId BIGSERIAL NOT NULL PRIMARY KEY,
        EventId bigint NOT NULL REFERENCES "Logs"."Events"(EventId),
        Resource varchar(64) NOT NULL,
        OldVal varchar(4000) NOT NULL,
        NewVal varchar(4000) NOT NULL
    );

    RAISE NOTICE 'Task completed sucessfully.';    
END;
$$;

System.Net.WebException: The remote name could not be resolved:

It's probably caused by a local network connectivity issue (but also a DNS error is possible). Unfortunately HResult is generic, however you can determine the exact issue catching HttpRequestException and then inspecting InnerException: if it's a WebException then you can check the WebException.Status property, for example WebExceptionStatus.NameResolutionFailure should indicate a DNS resolution problem.


It may happen, there isn't much you can do.

What I'd suggest to always wrap that (network related) code in a loop with a try/catch block (as also suggested here for other fallible operations). Handle known exceptions, wait a little (say 1000 msec) and try again (for say 3 times). Only if failed all times then you can quit/report an error to your users. Very raw example like this:

private const int NumberOfRetries = 3;
private const int DelayOnRetry = 1000;

public static async Task<HttpResponseMessage> GetFromUrlAsync(string url) {
    using (var client = new HttpClient()) {
        for (int i=1; i <= NumberOfRetries; ++i) {
            try {
                return await client.GetAsync(url); 
            }
            catch (Exception e) when (i < NumberOfRetries) {
                await Task.Delay(DelayOnRetry);
            }
        }
    }
}

Windows.history.back() + location.reload() jquery

It will have already gone back before it executes the reload.

You would be better off to replace:

window.history.back();
location.reload(); 

with:

window.location.replace("pagehere.html");

How to check for null/empty/whitespace values with a single test?

SELECT column_name from table_name
WHERE RTRIM(ISNULL(column_name, '')) LIKE ''

ISNULL(column_name, '') will return '' if column_name is NULL, otherwise it will return column_name.

UPDATE

In Oracle, you can use NVL to achieve the same results.

SELECT column_name from table_name
WHERE RTRIM(NVL(column_name, '')) LIKE ''

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

self.automaticallyAdjustsScrollViewInsets = NO;

try, you can deal with it!

angular 2 ngIf and CSS transition/animation

    trigger('slideIn', [
      state('*', style({ 'overflow-y': 'hidden' })),
      state('void', style({ 'overflow-y': 'hidden' })),
      transition('* => void', [
        style({ height: '*' }),
        animate(250, style({ height: 0 }))
      ]),
      transition('void => *', [
        style({ height: '0' }),
        animate(250, style({ height: '*' }))
      ])
    ])

How to add option to select list in jQuery

Your code fails because you are executing a method (addOption) on the jQuery object (and this object does not support the method)

You can use the standard Javascript function like this:

$("#dropListBuilding")[0].options.add( new Option("My Text","My Value") )

Select the first row by group

You can use duplicated to do this very quickly.

test[!duplicated(test$id),]

Benchmarks, for the speed freaks:

ju <- function() test[!duplicated(test$id),]
gs1 <- function() do.call(rbind, lapply(split(test, test$id), head, 1))
gs2 <- function() do.call(rbind, lapply(split(test, test$id), `[`, 1, ))
jply <- function() ddply(test,.(id),function(x) head(x,1))
jdt <- function() {
  testd <- as.data.table(test)
  setkey(testd,id)
  # Initial solution (slow)
  # testd[,lapply(.SD,function(x) head(x,1)),by = key(testd)]
  # Faster options :
  testd[!duplicated(id)]               # (1)
  # testd[, .SD[1L], by=key(testd)]    # (2)
  # testd[J(unique(id)),mult="first"]  # (3)
  # testd[ testd[,.I[1L],by=id] ]      # (4) needs v1.8.3. Allows 2nd, 3rd etc
}

library(plyr)
library(data.table)
library(rbenchmark)

# sample data
set.seed(21)
test <- data.frame(id=sample(1e3, 1e5, TRUE), string=sample(LETTERS, 1e5, TRUE))
test <- test[order(test$id), ]

benchmark(ju(), gs1(), gs2(), jply(), jdt(),
    replications=5, order="relative")[,1:6]
#     test replications elapsed relative user.self sys.self
# 1   ju()            5    0.03    1.000      0.03     0.00
# 5  jdt()            5    0.03    1.000      0.03     0.00
# 3  gs2()            5    3.49  116.333      2.87     0.58
# 2  gs1()            5    3.58  119.333      3.00     0.58
# 4 jply()            5    3.69  123.000      3.11     0.51

Let's try that again, but with just the contenders from the first heat and with more data and more replications.

set.seed(21)
test <- data.frame(id=sample(1e4, 1e6, TRUE), string=sample(LETTERS, 1e6, TRUE))
test <- test[order(test$id), ]
benchmark(ju(), jdt(), order="relative")[,1:6]
#    test replications elapsed relative user.self sys.self
# 1  ju()          100    5.48    1.000      4.44     1.00
# 2 jdt()          100    6.92    1.263      5.70     1.15

Difference between Iterator and Listiterator?

the following is that the difference between iterator and listIterator

iterator :

boolean hasNext();
E next();
void remove();

listIterator:

boolean hasNext();
E next();
boolean hasPrevious();
E previous();
int nextIndex();
int previousIndex();
void remove();
void set(E e);
void add(E e);

What is the easiest way to encrypt a password when I save it to the registry?

I have looked all over for a good example of encryption and decryption process but most were overly complex.

Anyhow there are many reasons someone may want to decrypt some text values including passwords. The reason I need to decrypt the password on the site I am working on currently is because they want to make sure when someone is forced to change their password when it expires that we do not let them change it with a close variant of the same password they used in the last x months.

So I wrote up a process that will do this in a simplified manner. I hope this code is beneficial to someone. For all I know I may end up using this at another time for a different company/site.

public string GenerateAPassKey(string passphrase)
    {
        // Pass Phrase can be any string
        string passPhrase = passphrase;
        // Salt Value can be any string(for simplicity use the same value as used for the pass phrase)
        string saltValue = passphrase;
        // Hash Algorithm can be "SHA1 or MD5"
        string hashAlgorithm = "SHA1";
        // Password Iterations can be any number
        int passwordIterations = 2;
        // Key Size can be 128,192 or 256
        int keySize = 256;
        // Convert Salt passphrase string to a Byte Array
        byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
        // Using System.Security.Cryptography.PasswordDeriveBytes to create the Key
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
        //When creating a Key Byte array from the base64 string the Key must have 32 dimensions.
        byte[] Key = pdb.GetBytes(keySize / 11);
        String KeyString = Convert.ToBase64String(Key);

        return KeyString;
    }

 //Save the keystring some place like your database and use it to decrypt and encrypt
//any text string or text file etc. Make sure you dont lose it though.

 private static string Encrypt(string plainStr, string KeyString)        
    {            
        RijndaelManaged aesEncryption = new RijndaelManaged();
        aesEncryption.KeySize = 256;
        aesEncryption.BlockSize = 128;
        aesEncryption.Mode = CipherMode.ECB;
        aesEncryption.Padding = PaddingMode.ISO10126;
        byte[] KeyInBytes = Encoding.UTF8.GetBytes(KeyString);
        aesEncryption.Key = KeyInBytes;
        byte[] plainText = ASCIIEncoding.UTF8.GetBytes(plainStr);
        ICryptoTransform crypto = aesEncryption.CreateEncryptor();
        byte[] cipherText = crypto.TransformFinalBlock(plainText, 0, plainText.Length);
        return Convert.ToBase64String(cipherText);
    }

 private static string Decrypt(string encryptedText, string KeyString) 
    {
        RijndaelManaged aesEncryption = new RijndaelManaged(); 
        aesEncryption.KeySize = 256;
        aesEncryption.BlockSize = 128; 
        aesEncryption.Mode = CipherMode.ECB;
        aesEncryption.Padding = PaddingMode.ISO10126;
        byte[] KeyInBytes = Encoding.UTF8.GetBytes(KeyString);
        aesEncryption.Key = KeyInBytes;
        ICryptoTransform decrypto = aesEncryption.CreateDecryptor(); 
        byte[] encryptedBytes = Convert.FromBase64CharArray(encryptedText.ToCharArray(), 0, encryptedText.Length); 
        return ASCIIEncoding.UTF8.GetString(decrypto.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length)); 
    }

 String KeyString = GenerateAPassKey("PassKey");
 String EncryptedPassword = Encrypt("25Characterlengthpassword!", KeyString);
 String DecryptedPassword = Decrypt(EncryptedPassword, KeyString);

how to setup ssh keys for jenkins to publish via ssh

For Windows:

  1. Install the necessary plugins for the repository (ex: GitHub install GitHub and GitHub Authentication plugins) in Jenkins.
  2. You can generate a key with Putty key generator, or by running the following command in git bash: $ ssh-keygen -t rsa -b 4096 -C [email protected]
  3. Private key must be OpenSSH. You can convert your private key to OpenSSH in putty key generator
  4. SSH keys come in pairs, public and private. Public keys are inserted in the repository to be cloned. Private keys are saved as credentials in Jenkins
  5. You need to copy the SSH URL not the HTTPS to work with ssh keys.

How to group time by hour or by 10 minutes

The original answer the author gave works pretty well. Just to extend this idea, you can do something like

group by datediff(minute, 0, [Date])/10

which will allow you to group by a longer period then 60 minutes, say 720, which is half a day etc.

What's the best way to iterate an Android Cursor?

Initially cursor is not on the first row show using moveToNext() you can iterate the cursor when record is not exist then it return false,unless it return true,

while (cursor.moveToNext()) {
    ...
}

How to step through Python code to help debug issues?

Yes! There's a Python debugger called pdb just for doing that!

You can launch a Python program through pdb by using pdb myscript.py or python -m pdb myscript.py.

There are a few commands you can then issue, which are documented on the pdb page.

Some useful ones to remember are:

  • b: set a breakpoint
  • c: continue debugging until you hit a breakpoint
  • s: step through the code
  • n: to go to next line of code
  • l: list source code for the current file (default: 11 lines including the line being executed)
  • u: navigate up a stack frame
  • d: navigate down a stack frame
  • p: to print the value of an expression in the current context

If you don't want to use a command line debugger, some IDEs like Pydev, Wing IDE or PyCharm have a GUI debugger. Wing and PyCharm are commercial products, but Wing has a free "Personal" edition, and PyCharm has a free community edition.

Exclude all transitive dependencies of a single dependency

Use the latest maven in your classpath.. It will remove the duplicate artifacts and keep the latest maven artifact..

Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties

As BMSAndroidDroid said, this problem may be caused by a wrong build path configuration.

If you included some libraries to your build path, then move the libraries, the build path will conserve the wrong references, will not found the libraries during compilation and you will get an error.

To fix it, right click on your project folder > build path > configure build path Then take a look to the library tab, and remove the old libraries.

Fatal error: Uncaught Error: Call to undefined function mysql_connect()

As other answers suggest... Some guy (for whatever reason) decided that your old code should not work when you upgrade your PHP, because he knows better than you and don't care about what your code does or how simple it is for you to upgrade.

Well, if you can't upgrade your project overnight you can

downgrade your version of PHP to whatever version that worked

or...

use a shim (kind of polyfill) such as https://github.com/dshafik/php7-mysql-shim or https://github.com/dotpointer/mysql-shim, and then find a place for include_once("choice_shim.php"); somewhere in your code

That will keep your old PHP code up and running until you are in a mood to update...

How to convert a hex string to hex number

Use format string

intNum = 123
print "0x%x"%(intNum)

or hex function.

intNum = 123
print hex(intNum)

Difference between \n and \r?

Just to add to the confusion, I've been working on a simple text editor using a TextArea element in an HTML page in a browser. In anticipation of compatibility woes with respect to CR/LF, I wrote the code to check the platform, and use whichever newline convention was applicable to the platform.

However, I discovered something interesting when checking the actual characters contained in the TextArea, via a small JavaScript function that generates the hex data corresponding to the characters.

For the test, I typed in the following text:

Hello, World[enter]

Goodbye, Cruel World[enter]

When I examined the text data, the byte sequence I obtained was this:

48 65 6c 6c 6f 2c 20 57 6f 72 6c 64 0a 47 6f 6f 64 62 79 65 2c 20 43 72 75 65 6c 20 57 6f 72 6c 64 0a

Now, most people looking at this, and seeing 0a but no 0d bytes, would think that this output was obtained on a Unix/Linux platform. But, here's the rub: this sequence I obtained in Google Chrome on Windows 7 64-bit.

So, if you're using a TextArea element and examining the text, CHECK the output as I've done above, to make sure what actual character bytes are returned from your TextArea. I've yet to see if this differs on other platforms or other browsers, but it's worth bearing in mind if you're performing text processing via JavaScript, and you need to make that text processing platform independent.

The conventions covered in above posts apply to console output, but HTML elements, it appears, adhere to the UNIX/Linux convention. Unless someone discovers otherwise on a different platform/browser.

Android M - check runtime permission - how to determine if the user checked "Never ask again"?

Once the user has marked "Do not ask again," the question can not be displayed again. But it can be explained to the user that he has previously denied the permission and must grant permission in the settings. And reference him to the settings, with the following code:

@Override
public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) {

    if (grantResults.length > 0
            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        // now, you have permission go ahead
        // TODO: something

    } else {

        if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                Manifest.permission.READ_CALL_LOG)) {
            // now, user has denied permission (but not permanently!)

        } else {

            // now, user has denied permission permanently!

            Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "You have previously declined this permission.\n" +
                "You must approve this permission in \"Permissions\" in the app settings on your device.", Snackbar.LENGTH_LONG).setAction("Settings", new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + BuildConfig.APPLICATION_ID)));

            }
        });
        View snackbarView = snackbar.getView();
        TextView textView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);
        textView.setMaxLines(5);  //Or as much as you need
        snackbar.show();

        }

    }
    return;
}

SQL QUERY replace NULL value in a row with a value from the previous known value

Here's a MySQL solution:

UPDATE mytable
SET number = (@n := COALESCE(number, @n))
ORDER BY date;

This is concise, but won't necessary work in other brands of RDBMS. For other brands, there might be a brand-specific solution that is more relevant. That's why it's important to tell us the brand you're using.

It's nice to be vendor-independent, as @Pax commented, but failing that, it's also nice to use your chosen brand of database to its fullest advantage.


Explanation of the above query:

@n is a MySQL user variable. It starts out NULL, and is assigned a value on each row as the UPDATE runs through rows. Where number is non-NULL, @n is assigned the value of number. Where number is NULL, the COALESCE() defaults to the previous value of @n. In either case, this becomes the new value of the number column and the UPDATE proceeds to the next row. The @n variable retains its value from row to row, so subsequent rows get values that come from the prior row(s). The order of the UPDATE is predictable, because of MySQL's special use of ORDER BY with UPDATE (this is not standard SQL).

Dialog to pick image from gallery or from camera

If you want to get the image from gallery or capture the image and set it to the imageview in portrait mode then following code will help you..

In onCreate()

imageViewRound.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            selectImage();
        }
    });




    private void selectImage() {
    Constants.iscamera = true;
    final CharSequence[] items = { "Take Photo", "Choose from Library",
            "Cancel" };

     TextView title = new TextView(context);
     title.setText("Add Photo!");
        title.setBackgroundColor(Color.BLACK);
        title.setPadding(10, 15, 15, 10);
        title.setGravity(Gravity.CENTER);
        title.setTextColor(Color.WHITE);
        title.setTextSize(22);


    AlertDialog.Builder builder = new AlertDialog.Builder(
            AddContactActivity.this);



    builder.setCustomTitle(title);

    // builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Take Photo")) {
                // Intent intent = new
                // Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                Intent intent = new Intent(
                        android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                /*
                 * File photo = new
                 * File(Environment.getExternalStorageDirectory(),
                 * "Pic.jpg"); intent.putExtra(MediaStore.EXTRA_OUTPUT,
                 * Uri.fromFile(photo)); imageUri = Uri.fromFile(photo);
                 */
                // startActivityForResult(intent,TAKE_PICTURE);

                Intent intents = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

                intents.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

                // start the image capture Intent
                startActivityForResult(intents, TAKE_PICTURE);

            } else if (items[item].equals("Choose from Library")) {
                Intent intent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(
                        Intent.createChooser(intent, "Select Picture"),
                        SELECT_PICTURE);
            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}




    @SuppressLint("NewApi")
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
    case SELECT_PICTURE:
        Bitmap bitmap = null;
        if (resultCode == RESULT_OK) {
            if (data != null) {


                try {
                    Uri selectedImage = data.getData();
                    String[] filePath = { MediaStore.Images.Media.DATA };
                    Cursor c = context.getContentResolver().query(
                            selectedImage, filePath, null, null, null);
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePath[0]);
                    String picturePath = c.getString(columnIndex);
                    c.close();
                    imageViewRound.setVisibility(View.VISIBLE);
                    // Bitmap thumbnail =
                    // (BitmapFactory.decodeFile(picturePath));
                    Bitmap thumbnail = decodeSampledBitmapFromResource(
                            picturePath, 500, 500);

                    // rotated
                    Bitmap thumbnail_r = imageOreintationValidator(
                            thumbnail, picturePath);
                    imageViewRound.setBackground(null);
                    imageViewRound.setImageBitmap(thumbnail_r);
                    IsImageSet = true;
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        break;
    case TAKE_PICTURE:
        if (resultCode == RESULT_OK) {

            previewCapturedImage();

        }

        break;
    }

}



 @SuppressLint("NewApi")
private void previewCapturedImage() {
    try {
        // hide video preview

        imageViewRound.setVisibility(View.VISIBLE);

        // bimatp factory
        BitmapFactory.Options options = new BitmapFactory.Options();

        // downsizing image as it throws OutOfMemory Exception for larger
        // images
        options.inSampleSize = 8;

        final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
                options);

        Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, 500, 500,
                false);

        // rotated
        Bitmap thumbnail_r = imageOreintationValidator(resizedBitmap,
                fileUri.getPath());

        imageViewRound.setBackground(null);
        imageViewRound.setImageBitmap(thumbnail_r);
        IsImageSet = true;
        Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG)
                .show();
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}






    // for roted image......
private Bitmap imageOreintationValidator(Bitmap bitmap, String path) {

    ExifInterface ei;
    try {
        ei = new ExifInterface(path);
        int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL);
        switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
            bitmap = rotateImage(bitmap, 90);
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            bitmap = rotateImage(bitmap, 180);
            break;
        case ExifInterface.ORIENTATION_ROTATE_270:
            bitmap = rotateImage(bitmap, 270);
            break;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return bitmap;
}



private Bitmap rotateImage(Bitmap source, float angle) {

    Bitmap bitmap = null;
    Matrix matrix = new Matrix();
    matrix.postRotate(angle);
    try {
        bitmap = Bitmap.createBitmap(source, 0, 0, source.getWidth(),
                source.getHeight(), matrix, true);
    } catch (OutOfMemoryError err) {
        source.recycle();
        Date d = new Date();
        CharSequence s = DateFormat
                .format("MM-dd-yy-hh-mm-ss", d.getTime());
        String fullPath = Environment.getExternalStorageDirectory()
                + "/RYB_pic/" + s.toString() + ".jpg";
        if ((fullPath != null) && (new File(fullPath).exists())) {
            new File(fullPath).delete();
        }
        bitmap = null;
        err.printStackTrace();
    }
    return bitmap;
}




public static Bitmap decodeSampledBitmapFromResource(String pathToFile,
        int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(pathToFile, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth,
            reqHeight);

    Log.e("inSampleSize", "inSampleSize______________in storage"
            + options.inSampleSize);
    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(pathToFile, options);
}




public static int calculateInSampleSize(BitmapFactory.Options options,
        int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        // Calculate ratios of height and width to requested height and
        // width
        final int heightRatio = Math.round((float) height
                / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value, this will
        // guarantee
        // a final image with both dimensions larger than or equal to the
        // requested height and width.
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;

    }

    return inSampleSize;
}




public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}






private static File getOutputMediaFile(int type) {

    // External sdcard location
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            IMAGE_DIRECTORY_NAME);

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
                    + IMAGE_DIRECTORY_NAME + " directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
    } else {
        return null;
    }

    return mediaFile;
}






public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

Hope This will help you....!!!

If targetSdkVersion is higher than 24, then FileProvider is used to grant access.

Create an xml file(Path: res\xml) provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

Add a Provider in AndroidManifest.xml

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths"/>
</provider>

and replace

return Uri.fromFile(getOutputMediaFile(type));

To

               return FileProvider.getUriForFile(this,  BuildConfig.APPLICATION_ID + ".provider", getOutputMediaFile(type));

Is it possible to specify proxy credentials in your web.config?

Directory Services/LDAP lookups can be used to serve this purpose. It involves some changes at infrastructure level, but most production environments have such provision

how to show alternate image if source image is not found? (onerror working in IE but not in mozilla)

I think this is very nice and short

<img src="imagenotfound.gif" alt="Image not found" onerror="this.src='imagefound.gif';" />

But, be careful. The user's browser will be stuck in an endless loop if the onerror image itself generates an error.


EDIT To avoid endless loop, remove the onerror from it at once.

<img src="imagenotfound.gif" alt="Image not found" onerror="this.onerror=null;this.src='imagefound.gif';" />

By calling this.onerror=null it will remove the onerror then try to get the alternate image.


NEW I would like to add a jQuery way, if this can help anyone.

<script>
$(document).ready(function()
{
    $(".backup_picture").on("error", function(){
        $(this).attr('src', './images/nopicture.png');
    });
});
</script>

<img class='backup_picture' src='./images/nonexistent_image_file.png' />

You simply need to add class='backup_picture' to any img tag that you want a backup picture to load if it tries to show a bad image.

Node.js - use of module.exports as a constructor

At the end, Node is about Javascript. JS has several way to accomplished something, is the same thing to get an "constructor", the important thing is to return a function.

This way actually you are creating a new function, as we created using JS on Web Browser environment for example.

Personally i prefer the prototype approach, as Sukima suggested on this post: Node.js - use of module.exports as a constructor

How can a query multiply 2 cell for each row MySQL?

this was my solution:

i was looking for how to display the result not to calculate...

so. in this case. there is no column TOTAL in the database, but there is a total on the webpage...

 <td><?php echo $row['amount1'] * $row['amount2'] ?></td>

also this was needed first...

<?php 
   $conn=mysql_connect('localhost','testbla','adminbla');
mysql_select_db("testa",$conn);

$query1 = "select * from info2";
$get=mysql_query($query1);
while($row=mysql_fetch_array($get)){
   ?>

SQL JOIN and different types of JOINs

What is SQL JOIN ?

SQL JOIN is a method to retrieve data from two or more database tables.

What are the different SQL JOINs ?

There are a total of five JOINs. They are :

  1. JOIN or INNER JOIN
  2. OUTER JOIN

     2.1 LEFT OUTER JOIN or LEFT JOIN
     2.2 RIGHT OUTER JOIN or RIGHT JOIN
     2.3 FULL OUTER JOIN or FULL JOIN

  3. NATURAL JOIN
  4. CROSS JOIN
  5. SELF JOIN

1. JOIN or INNER JOIN :

In this kind of a JOIN, we get all records that match the condition in both tables, and records in both tables that do not match are not reported.

In other words, INNER JOIN is based on the single fact that: ONLY the matching entries in BOTH the tables SHOULD be listed.

Note that a JOIN without any other JOIN keywords (like INNER, OUTER, LEFT, etc) is an INNER JOIN. In other words, JOIN is a Syntactic sugar for INNER JOIN (see: Difference between JOIN and INNER JOIN).

2. OUTER JOIN :

OUTER JOIN retrieves

Either, the matched rows from one table and all rows in the other table Or, all rows in all tables (it doesn't matter whether or not there is a match).

There are three kinds of Outer Join :

2.1 LEFT OUTER JOIN or LEFT JOIN

This join returns all the rows from the left table in conjunction with the matching rows from the right table. If there are no columns matching in the right table, it returns NULL values.

2.2 RIGHT OUTER JOIN or RIGHT JOIN

This JOIN returns all the rows from the right table in conjunction with the matching rows from the left table. If there are no columns matching in the left table, it returns NULL values.

2.3 FULL OUTER JOIN or FULL JOIN

This JOIN combines LEFT OUTER JOIN and RIGHT OUTER JOIN. It returns rows from either table when the conditions are met and returns NULL value when there is no match.

In other words, OUTER JOIN is based on the fact that: ONLY the matching entries in ONE OF the tables (RIGHT or LEFT) or BOTH of the tables(FULL) SHOULD be listed.

Note that `OUTER JOIN` is a loosened form of `INNER JOIN`.

3. NATURAL JOIN :

It is based on the two conditions :

  1. the JOIN is made on all the columns with the same name for equality.
  2. Removes duplicate columns from the result.

This seems to be more of theoretical in nature and as a result (probably) most DBMS don't even bother supporting this.

4. CROSS JOIN :

It is the Cartesian product of the two tables involved. The result of a CROSS JOIN will not make sense in most of the situations. Moreover, we won't need this at all (or needs the least, to be precise).

5. SELF JOIN :

It is not a different form of JOIN, rather it is a JOIN (INNER, OUTER, etc) of a table to itself.

JOINs based on Operators

Depending on the operator used for a JOIN clause, there can be two types of JOINs. They are

  1. Equi JOIN
  2. Theta JOIN

1. Equi JOIN :

For whatever JOIN type (INNER, OUTER, etc), if we use ONLY the equality operator (=), then we say that the JOIN is an EQUI JOIN.

2. Theta JOIN :

This is same as EQUI JOIN but it allows all other operators like >, <, >= etc.

Many consider both EQUI JOIN and Theta JOIN similar to INNER, OUTER etc JOINs. But I strongly believe that its a mistake and makes the ideas vague. Because INNER JOIN, OUTER JOIN etc are all connected with the tables and their data whereas EQUI JOIN and THETA JOIN are only connected with the operators we use in the former.

Again, there are many who consider NATURAL JOIN as some sort of "peculiar" EQUI JOIN. In fact, it is true, because of the first condition I mentioned for NATURAL JOIN. However, we don't have to restrict that simply to NATURAL JOINs alone. INNER JOINs, OUTER JOINs etc could be an EQUI JOIN too.

Iterating through directories with Python

From python >= 3.5 onward, you can use **, glob.iglob(path/**, recursive=True) and it seems the most pythonic solution, i.e.:

import glob, os

for filename in glob.iglob('/pardadox-music/**', recursive=True):
    if os.path.isfile(filename): # filter dirs
        print(filename)

Output:

/pardadox-music/modules/her1.mod
/pardadox-music/modules/her2.mod
...

Notes:
1 - glob.iglob

glob.iglob(pathname, recursive=False)

Return an iterator which yields the same values as glob() without actually storing them all simultaneously.

2 - If recursive is True, the pattern '**' will match any files and zero or more directories and subdirectories.

3 - If the directory contains files starting with . they won’t be matched by default. For example, consider a directory containing card.gif and .card.gif:

>>> import glob
>>> glob.glob('*.gif') ['card.gif'] 
>>> glob.glob('.c*')['.card.gif']

4 - You can also use rglob(pattern), which is the same as calling glob() with **/ added in front of the given relative pattern.

How can one pull the (private) data of one's own Android app?

adb backup will write an Android-specific archive:

adb backup  -f myAndroidBackup.ab  com.corp.appName

This archive can be converted to tar format using:

dd if=myAndroidBackup.ab bs=4K iflag=skip_bytes skip=24 | openssl zlib -d > myAndroidBackup.tar

Reference:

http://nelenkov.blogspot.ca/2012/06/unpacking-android-backups.html

Search for "Update" at that link.


Alternatively, use Android backup extractor to extract files from the Android backup (.ab) file.

How to set the value of a hidden field from a controller in mvc

if you are not using model as per your question you can do like this

@Html.Hidden("hdnFlag" , new {id = "hdnFlag", value = "hdnFlag_value" })

else if you are using model (considering passing model has hdnFlag property), you can use this approch

@Html.HiddenFor(model => model.hdnFlag, new { value = Model.hdnFlag})

How to get the filename without the extension from a path in Python?

import os
list = []
def getFileName( path ):
for file in os.listdir(path):
    #print file
    try:
        base=os.path.basename(file)
        splitbase=os.path.splitext(base)
        ext = os.path.splitext(base)[1]
        if(ext):
            list.append(base)
        else:
            newpath = path+"/"+file
            #print path
            getFileName(newpath)
    except:
        pass
return list

getFileName("/home/weexcel-java3/Desktop/backup")
print list

How do I search within an array of hashes by hash values in ruby?

(Adding to previous answers (hope that helps someone):)

Age is simpler but in case of string and with ignoring case:

  • Just to verify the presence:

@fathers.any? { |father| father[:name].casecmp("john") == 0 } should work for any case in start or anywhere in the string i.e. for "John", "john" or "JoHn" and so on.

  • To find first instance/index:

@fathers.find { |father| father[:name].casecmp("john") == 0 }

  • To select all such indices:

@fathers.select { |father| father[:name].casecmp("john") == 0 }

Need to find a max of three numbers in java

Two things: Change the variables x, y, z as int and call the method as Math.max(Math.max(x,y),z) as it accepts two parameters only.

In Summary, change below:

    String x = keyboard.nextLine();
    String y = keyboard.nextLine();
    String z = keyboard.nextLine();
    int max = Math.max(x,y,z);

to

    int x = keyboard.nextInt();
    int y = keyboard.nextInt();
    int z = keyboard.nextInt();
    int max =  Math.max(Math.max(x,y),z);

Responsive timeline UI with Bootstrap3

_x000D_
_x000D_
.timeline {_x000D_
  list-style: none;_x000D_
  padding: 20px 0 20px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.timeline:before {_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  position: absolute;_x000D_
  content: " ";_x000D_
  width: 3px;_x000D_
  background-color: #eeeeee;_x000D_
  left: 50%;_x000D_
  margin-left: -1.5px;_x000D_
}_x000D_
_x000D_
.timeline > li {_x000D_
  margin-bottom: 20px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.timeline > li:before,_x000D_
.timeline > li:after {_x000D_
  content: " ";_x000D_
  display: table;_x000D_
}_x000D_
_x000D_
.timeline > li:after {_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
.timeline > li:before,_x000D_
.timeline > li:after {_x000D_
  content: " ";_x000D_
  display: table;_x000D_
}_x000D_
_x000D_
.timeline > li:after {_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
.timeline > li > .timeline-panel {_x000D_
  width: 46%;_x000D_
  float: left;_x000D_
  border: 1px solid #d4d4d4;_x000D_
  border-radius: 2px;_x000D_
  padding: 20px;_x000D_
  position: relative;_x000D_
  -webkit-box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175);_x000D_
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175);_x000D_
}_x000D_
_x000D_
.timeline > li > .timeline-panel:before {_x000D_
  position: absolute;_x000D_
  top: 26px;_x000D_
  right: -15px;_x000D_
  display: inline-block;_x000D_
  border-top: 15px solid transparent;_x000D_
  border-left: 15px solid #ccc;_x000D_
  border-right: 0 solid #ccc;_x000D_
  border-bottom: 15px solid transparent;_x000D_
  content: " ";_x000D_
}_x000D_
_x000D_
.timeline > li > .timeline-panel:after {_x000D_
  position: absolute;_x000D_
  top: 27px;_x000D_
  right: -14px;_x000D_
  display: inline-block;_x000D_
  border-top: 14px solid transparent;_x000D_
  border-left: 14px solid #fff;_x000D_
  border-right: 0 solid #fff;_x000D_
  border-bottom: 14px solid transparent;_x000D_
  content: " ";_x000D_
}_x000D_
_x000D_
.timeline > li > .timeline-badge {_x000D_
  color: #fff;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
  line-height: 50px;_x000D_
  font-size: 1.4em;_x000D_
  text-align: center;_x000D_
  position: absolute;_x000D_
  top: 16px;_x000D_
  left: 50%;_x000D_
  margin-left: -25px;_x000D_
  background-color: #999999;_x000D_
  z-index: 100;_x000D_
  border-top-right-radius: 50%;_x000D_
  border-top-left-radius: 50%;_x000D_
  border-bottom-right-radius: 50%;_x000D_
  border-bottom-left-radius: 50%;_x000D_
}_x000D_
_x000D_
.timeline > li.timeline-inverted > .timeline-panel {_x000D_
  float: right;_x000D_
}_x000D_
_x000D_
.timeline > li.timeline-inverted > .timeline-panel:before {_x000D_
  border-left-width: 0;_x000D_
  border-right-width: 15px;_x000D_
  left: -15px;_x000D_
  right: auto;_x000D_
}_x000D_
_x000D_
.timeline > li.timeline-inverted > .timeline-panel:after {_x000D_
  border-left-width: 0;_x000D_
  border-right-width: 14px;_x000D_
  left: -14px;_x000D_
  right: auto;_x000D_
}_x000D_
_x000D_
.timeline-badge.primary {_x000D_
  background-color: #2e6da4 !important;_x000D_
}_x000D_
_x000D_
.timeline-badge.success {_x000D_
  background-color: #3f903f !important;_x000D_
}_x000D_
_x000D_
.timeline-badge.warning {_x000D_
  background-color: #f0ad4e !important;_x000D_
}_x000D_
_x000D_
.timeline-badge.danger {_x000D_
  background-color: #d9534f !important;_x000D_
}_x000D_
_x000D_
.timeline-badge.info {_x000D_
  background-color: #5bc0de !important;_x000D_
}_x000D_
_x000D_
.timeline-title {_x000D_
  margin-top: 0;_x000D_
  color: inherit;_x000D_
}_x000D_
_x000D_
.timeline-body > p,_x000D_
.timeline-body > ul {_x000D_
  margin-bottom: 0;_x000D_
}_x000D_
_x000D_
.timeline-body > p + p {_x000D_
  margin-top: 5px;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="page-header">_x000D_
    <h1 id="timeline">Timeline</h1>_x000D_
  </div>_x000D_
  <ul class="timeline">_x000D_
    <li>_x000D_
      <div class="timeline-badge"><i class="glyphicon glyphicon-check"></i></div>_x000D_
      <div class="timeline-panel">_x000D_
         <p><small class="text-muted"><i class="glyphicon glyphicon-time"></i> 11 hours ago via Twitter</small></p>_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
          <p><small class="text-muted"><i class="glyphicon glyphicon-time"></i> 11 hours ago via Twitter</small></p>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li class="timeline-inverted">_x000D_
      <div class="timeline-badge warning"><i class="glyphicon glyphicon-credit-card"></i></div>_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
          <p>Suco de cevadiss, é um leite divinis, qui tem lupuliz, matis, aguis e fermentis. Interagi no mé, cursus quis, vehicula ac nisi. Aenean vel dui dui. Nullam leo erat, aliquet quis tempus a, posuere ut mi. Ut scelerisque neque et turpis posuere_x000D_
            pulvinar pellentesque nibh ullamcorper. Pharetra in mattis molestie, volutpat elementum justo. Aenean ut ante turpis. Pellentesque laoreet mé vel lectus scelerisque interdum cursus velit auctor. Lorem ipsum dolor sit amet, consectetur adipiscing_x000D_
            elit. Etiam ac mauris lectus, non scelerisque augue. Aenean justo massa.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li>_x000D_
      <div class="timeline-badge danger"><i class="glyphicon glyphicon-credit-card"></i></div>_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li class="timeline-inverted">_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li>_x000D_
      <div class="timeline-badge info"><i class="glyphicon glyphicon-floppy-disk"></i></div>_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
          <hr>_x000D_
          <div class="btn-group">_x000D_
            <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">_x000D_
              <i class="glyphicon glyphicon-cog"></i> <span class="caret"></span>_x000D_
            </button>_x000D_
            <ul class="dropdown-menu" role="menu">_x000D_
              <li><a href="#">Action</a></li>_x000D_
              <li><a href="#">Another action</a></li>_x000D_
              <li><a href="#">Something else here</a></li>_x000D_
              <li class="divider"></li>_x000D_
              <li><a href="#">Separated link</a></li>_x000D_
            </ul>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li>_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li class="timeline-inverted">_x000D_
      <div class="timeline-badge success"><i class="glyphicon glyphicon-thumbs-up"></i></div>_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://codepen.io/bsngr/pen/Ifvbi/

How to add a form load event (currently not working)

You got half of the answer! Now that you created the event handler, you need to hook it to the form so that it actually gets called when the form is loading. You can achieve that by doing the following:

 public class ProgramViwer : Form{
  public ProgramViwer()
  {
       InitializeComponent();
       Load += new EventHandler(ProgramViwer_Load);
  }
  private void ProgramViwer_Load(object sender, System.EventArgs e)
  {
       formPanel.Controls.Clear();
       formPanel.Controls.Add(wel);
  }
}

Python + Django page redirect

This should work in most versions of django, I am using it in 1.6.5:

from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
urlpatterns = patterns('',
    ....
    url(r'^(?P<location_id>\d+)/$', lambda x, location_id: HttpResponseRedirect(reverse('dailyreport_location', args=[location_id])), name='location_stats_redirect'),
    ....
)

You can still use the name of the url pattern instead of a hard coded url with this solution. The location_id parameter from the url is passed down to the lambda function.

MySQL: Curdate() vs Now()

For questions like this, it is always worth taking a look in the manual first. Date and time functions in the mySQL manual

CURDATE() returns the DATE part of the current time. Manual on CURDATE()

NOW() returns the date and time portions as a timestamp in various formats, depending on how it was requested. Manual on NOW().

How to make an app's background image repeat

Expanding on plowman's answer, here is the non-deprecated version of changing the background image with java.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bitmap bmp = BitmapFactory.decodeResource(getResources(),
            R.drawable.texture);
    BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(),bmp);
    bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT,
            Shader.TileMode.REPEAT);
    setBackground(bitmapDrawable);
}

TypeError: 'float' object is not callable

You have forgotten a * between -3.7 and (prof[x]).

Thus:

for x in range(len(prof)):
    PB = 2.25 * (1 - math.pow(math.e, (-3.7 * (prof[x])/2.25))) * (math.e, (0/2.25)))

Also, there seems to be missing an ( as I count 6 times ( and 7 times ), and I think (math.e, (0/2.25)) is missing a function call (probably math.pow, but thats just a wild guess).

Resource u'tokenizers/punkt/english.pickle' not found

I faced same issue. After downloading everything, still 'punkt' error was there. I searched package on my windows machine at C:\Users\vaibhav\AppData\Roaming\nltk_data\tokenizers and I can see 'punkt.zip' present there. I realized that somehow the zip has not been extracted into C:\Users\vaibhav\AppData\Roaming\nltk_data\tokenizers\punk. Once I extracted the zip, it worked like music.

Python: Binding Socket: "Address already in use"

socket.socket() should run before socket.bind() and use REUSEADDR as said

<embed> vs. <object>

Some other options:

<object type="application/pdf" data="filename.pdf" width="100%" height="100%">
</object>

<object type="application/pdf" data="#request.localhost#_includes/filename.pdf" 
        width="100%" height="100%">
  <param name="src" value="#request.localhost#_includes/filename.pdf">
</object>

How to start IIS Express Manually

Or you simply manage it like full IIS by using Jexus Manager for IIS Express, an open source project I work on

https://jexusmanager.com

Jexus Manager for IIS Express

Start a site and the process will be launched for you.

Vbscript list all PDF files in folder and subfolders

The file extension may be case sentive...but the code works.

Set objFSO = CreateObject("Scripting.FileSystemObject")
  objStartFolder = "C:\Dev\"

  Set objFolder = objFSO.GetFolder(objStartFolder)
  Wscript.Echo objFolder.Path

  Set colFiles = objFolder.Files

  For Each objFile in colFiles
  strFileName = objFile.Name

  If objFSO.GetExtensionName(strFileName) = "pdf" Then
      Wscript.Echo objFile.Name
  End If

  Next
  Wscript.Echo

  ShowSubfolders objFSO.GetFolder(objStartFolder)

  Sub ShowSubFolders(Folder)
     For Each Subfolder in Folder.SubFolders
          Wscript.Echo Subfolder.Path
          Set objFolder = objFSO.GetFolder(Subfolder.Path)
          Set colFiles = objFolder.Files
          For Each objFile in colFiles
              Wscript.Echo objFile.Name
          Next
          Wscript.Echo
          ShowSubFolders Subfolder
      Next
  End Sub

vertical-align: middle with Bootstrap 2

As well as the previous answers are you could always use the Pull attrib as well:


    <ol class="row" id="possibilities">
       <li class="span6">
         <div class="row">
           <div class="span3">
             <p>some text here</p>
             <p>Text Here too</p>
           </div>
         <figure class="span3 pull-right"><img src="img/screenshots/options.png" alt="Some text" /></figure>
        </div>
 </li>
 <li class="span6">
     <div class="row">
         <figure class="span3"><img src="img/qrcode.png" alt="Some text" /></figure>
         <div class="span3">
             <p>Some text</p>
             <p>Some text here too.</p>
         </div>
     </div>
 </li>

How do I prevent Conda from activating the base environment by default?

If you want to keep your bashrc simple, you can remove all the conda init generated clutter, and keep only a single line:

. "/Users/geoff/anaconda2/etc/profile.d/conda.sh"

See Recommended change to enable conda in your shell.

This will make the conda command available without activating the base environment.

If you want to use your bashrc on other systems where conda is not installed in the same path, you can keep the if/fi lines as well to avoid error messages, i.e.:

if [ -f "/Users/geoff/anaconda2/etc/profile.d/conda.sh" ]; then
    . "/Users/geoff/anaconda2/etc/profile.d/conda.sh"
fi

How to avoid Python/Pandas creating an index in a saved csv?

If you want no index, read file using:

import pandas as pd
df = pd.read_csv('file.csv', index_col=0)

save it using

df.to_csv('file.csv', index=False)

Change background color of edittext in android

Here the best way

First : make new xml file in res/drawable name it rounded_edit_text then paste this:

<?xml version="1.0" encoding="utf-8"?>
<shape  xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle" android:padding="10dp">
    <solid android:color="#F9966B" />
    <corners
        android:bottomRightRadius="15dp"
        android:bottomLeftRadius="15dp"
        android:topLeftRadius="15dp"
        android:topRightRadius="15dp" />
</shape>

Second: in res/layout copy and past following code (code of EditText)

<EditText
    android:id="@+id/txtdoctor"
    android:layout_width="match_parent"
    android:layout_height="30dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:background="@drawable/rounded_edit_text"
    android:ems="10" >
    <requestFocus />
</EditText>

jQuery .on('change', function() {} not triggering for dynamically created inputs

you can use:

$('body').ready(function(){
   $(document).on('change', '#elemID', function(){
      // do something
   });
});

It works with me.

Understanding Bootstrap's clearfix class

.clearfix is defined in less/mixins.less. Right above its definition is a comment with a link to this article:

A new micro clearfix hack

The article explains how it all works.

UPDATE: Yes, link-only answers are bad. I knew this even at the time that I posted this answer, but I didn't feel like copying and pasting was OK due to copyright, plagiarism, and what have you. However, I now feel like it's OK since I have linked to the original article. I should also mention the author's name, though, for credit: Nicolas Gallagher. Here is the meat of the article (note that "Thierry’s method" is referring to Thierry Koblentz’s “clearfix reloaded”):

This “micro clearfix” generates pseudo-elements and sets their display to table. This creates an anonymous table-cell and a new block formatting context that means the :before pseudo-element prevents top-margin collapse. The :after pseudo-element is used to clear the floats. As a result, there is no need to hide any generated content and the total amount of code needed is reduced.

Including the :before selector is not necessary to clear the floats, but it prevents top-margins from collapsing in modern browsers. This has two benefits:

  • It ensures visual consistency with other float containment techniques that create a new block formatting context, e.g., overflow:hidden

  • It ensures visual consistency with IE 6/7 when zoom:1 is applied.

N.B.: There are circumstances in which IE 6/7 will not contain the bottom margins of floats within a new block formatting context. Further details can be found here: Better float containment in IE using CSS expressions.

The use of content:" " (note the space in the content string) avoids an Opera bug that creates space around clearfixed elements if the contenteditable attribute is also present somewhere in the HTML. Thanks to Sergio Cerrutti for spotting this fix. An alternative fix is to use font:0/0 a.

Legacy Firefox

Firefox < 3.5 will benefit from using Thierry’s method with the addition of visibility:hidden to hide the inserted character. This is because legacy versions of Firefox need content:"." to avoid extra space appearing between the body and its first child element, in certain circumstances (e.g., jsfiddle.net/necolas/K538S/.)

Alternative float-containment methods that create a new block formatting context, such as applying overflow:hidden or display:inline-block to the container element, will also avoid this behaviour in legacy versions of Firefox.

Can you autoplay HTML5 videos on the iPad?

Just set

webView.mediaPlaybackRequiresUserAction = NO;

The autoplay works for me on iOS.

How do I redirect to another webpage?

This works with jQuery:

$(window).attr("location", "http://google.fr");

Multiple conditions with CASE statements

It's not a cut and paste. The CASE expression must return a value, and you are returning a string containing SQL (which is technically a value but of a wrong type). This is what you wanted to write, I think:

SELECT * FROM [Purchasing].[Vendor] WHERE  
CASE
  WHEN @url IS null OR @url = '' OR @url = 'ALL'
    THEN PurchasingWebServiceURL LIKE '%'
  WHEN @url = 'blank'
    THEN PurchasingWebServiceURL = ''
  WHEN @url = 'fail'
    THEN PurchasingWebServiceURL NOT LIKE '%treyresearch%'
  ELSE PurchasingWebServiceURL = '%' + @url + '%' 
END

I also suspect that this might not work in some dialects, but can't test now (Oracle, I'm looking at you), due to not having booleans.

However, since @url is not dependent on the table values, why not make three different queries, and choose which to evaluate based on your parameter?

Does SVG support embedding of bitmap images?

I posted a fiddle here, showing data, remote and local images embedded in SVG, inside an HTML page:

http://jsfiddle.net/MxHPq/

<!DOCTYPE html>
<html>
<head>
    <title>SVG embedded bitmaps in HTML</title>
    <style>

        body{
            background-color:#999;
            color:#666;
            padding:10px;
        }

        h1{
            font-weight:normal;
            font-size:24px;
            margin-top:20px;
            color:#000;
        }

        h2{
            font-weight:normal;
            font-size:20px;
            margin-top:20px;
        }

        p{
            color:#FFF;
            }

        svg{
            margin:20px;
            display:block;
            height:100px;
        }

    </style>
</head>

<body>
    <h1>SVG embedded bitmaps in HTML</h1>
    <p>The trick appears to be ensuring the image has the correct width and height atttributes</p>

    <h2>Example 1: Embedded data</h2>
    <svg id="example1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <image x="0" y="0" width="5" height="5" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="/>
    </svg>

    <h2>Example 2: Remote image</h2>
    <svg id="example2" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <image x="0" y="0" width="275" height="95" xlink:href="http://www.google.co.uk/images/srpr/logo3w.png" />
    </svg>

    <h2>Example 3: Local image</h2>
    <svg id="example3" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <image x="0" y="0" width="136" height="23" xlink:href="/img/logo.png" />
    </svg>


</body>
</html>

MSVCP140.dll missing

Your friend's PC is missing the runtime support DLLs for your program:

codeigniter, result() vs. result_array()

result() returns Object type data. . . . result_array() returns Associative Array type data.

PHPmailer sending HTML CODE

just you need to pass true as an argument to IsHTML() function.

No module named 'openpyxl' - Python 3.4 - Ubuntu

In order to keep track of dependency issues, I like to use the conda installer, which simply boils down to:

conda install openpyxl

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

Check if you have entered the correct URL Mapping as specified in the Web.xml

For example:

In the web.xml, your servlet declaration maybe:

<servlet>
        <servlet-name>ControllerA</servlet-name>
        <servlet-class>PackageName.ControllerA</servlet-class>
</servlet>

<servlet-mapping>
        <servlet-name>ControllerA</servlet-name>
        <url-pattern>/theController</url-pattern>
</servlet-mapping>

What this snippet does is <url-pattern>/theController</url-pattern>will set the name that will be used to call the servlet from the front end (eg: form) through the URL. Therefore when you reference the servlet in the front end, in order to ensure that the request goes to the servlet "ControllerA", it should refer the specified URL Pattern "theController" from the form.

eg:

<form action="theController" method="POST">
</form>

Logger slf4j advantages of formatting with {} instead of string concatenation

Short version: Yes it is faster, with less code!

String concatenation does a lot of work without knowing if it is needed or not (the traditional "is debugging enabled" test known from log4j), and should be avoided if possible, as the {} allows delaying the toString() call and string construction to after it has been decided if the event needs capturing or not. By having the logger format a single string the code becomes cleaner in my opinion.

You can provide any number of arguments. Note that if you use an old version of sljf4j and you have more than two arguments to {}, you must use the new Object[]{a,b,c,d} syntax to pass an array instead. See e.g. http://slf4j.org/apidocs/org/slf4j/Logger.html#debug(java.lang.String, java.lang.Object[]).

Regarding the speed: Ceki posted a benchmark a while back on one of the lists.

Exception : AAPT2 error: check logs for details

If you are seeking a way to get to the heart of the issue. Android studio contains a feature within the edit configurations panel that simplifies this possible. By clicking on the "app" tag (It is typically to the left of the top run button)

You will open the option to edit configurations. From there create an instance of the gradle option to yourself.

The core features are actually the gradle project as well as the task. Connect the task to your debug initiative.

When you run your app through this setting, Android will spit out detailed errors(That we all wish would appear more often) and these errros will point directly a what needs to be resolved.

How can I increment a char?

In Python 2.x, just use the ord and chr functions:

>>> ord('c')
99
>>> ord('c') + 1
100
>>> chr(ord('c') + 1)
'd'
>>> 

Python 3.x makes this more organized and interesting, due to its clear distinction between bytes and unicode. By default, a "string" is unicode, so the above works (ord receives Unicode chars and chr produces them).

But if you're interested in bytes (such as for processing some binary data stream), things are even simpler:

>>> bstr = bytes('abc', 'utf-8')
>>> bstr
b'abc'
>>> bstr[0]
97
>>> bytes([97, 98, 99])
b'abc'
>>> bytes([bstr[0] + 1, 98, 99])
b'bbc'

Remote origin already exists on 'git push' to a new repository

You should change the name of the remote repository to something else.

git remote add origin [email protected]:myname/oldrep.git

to

git remote add neworigin [email protected]:myname/oldrep.git

I think this should work.

Yes, these are for repository init and adding a new remote. Just with a change of name.

using jQuery .animate to animate a div from right to left?

Here's a minimal answer that shows your example working:

<html>
<head>
<title>hello.world.animate()</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"
    type="text/javascript"></script>
<style type="text/css">
#coolDiv {
    position: absolute;
    top: 0;
    right: 0;
    width: 200px;
    background-color: #ccc;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
    // this way works fine for Firefox, but 
    // Chrome and Safari can't do it.
    $("#coolDiv").animate({'left':0}, "slow");
    // So basically if you *start* with a right position
    // then stick to animating to another right position
    // to do that, get the window width minus the width of your div:
$("#coolDiv").animate({'right':($('body').innerWidth()-$('#coolDiv').width())}, 'slow');
    // sorry that's so ugly!
});
</script>
</head>
<body>
    <div style="" id="coolDiv">HELLO</div>
</body>
</html>

Original Answer:

You have:

$("#coolDiv").animate({"left":"0px", "slow");

Corrected:

$("#coolDiv").animate({"left":"0px"}, "slow");

Documentation: http://api.jquery.com/animate/

jQuery to retrieve and set selected option value of html select element

$( "#myId option:selected" ).text(); will give you the text that you selected in the drop down element. either way you can change it to .val(); to get the value of it . check the below coding

<select id="myId">
    <option value="1">Mr</option>
    <option value="2">Mrs</option>
    <option value="3">Ms</option>`
    <option value="4">Dr</option>
    <option value="5">Prof</option>
</select>

YAML mapping values are not allowed in this context

This is valid YAML:

jobs:
 - name: A
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120
 - name: B
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120

Note, that every '-' starts new element in the sequence. Also, indentation of keys in the map should be exactly same.

How do you create a Spring MVC project in Eclipse?

This is the easiest way :

step 1) install Spring Tool Suite (STS) for eclipse (version 3.7.0RELEASE or above) To do this you can go to Help >> eclipse market place , then type Spring Tool suite in search box.

step 2) now go to file >> new >> spring project as shown in the image below enter image description here

step 3)now choose the template as "spring MVC Project" and give a name to your project on the top as shown below ( I named it 'SpringProject') enter image description here

step 4)now give a base package name like this enter image description here

and that is . The project will be created in a few minutes and Now you can right click on it and run on server.

Shortcut for changing font size

Be sure to check out the VS 2010 Beta that was just released. The new editor should have this.

Is 'bool' a basic datatype in C++?

Yes, bool is a built-in type.

WIN32 is C code, not C++, and C does not have a bool, so they provide their own typedef BOOL.

How to align the checkbox and label in same line in html?

Use this in your li style.

style="text-align-last: left;"

How can I suppress column header output for a single SQL statement?

Invoke mysql with the -N (the alias for -N is --skip-column-names) option:

mysql -N ...
use testdb;
select * from names;

+------+-------+
|    1 | pete  |
|    2 | john  |
|    3 | mike  |
+------+-------+
3 rows in set (0.00 sec)

Credit to ErichBSchulz for pointing out the -N alias.

To remove the grid (the vertical and horizontal lines) around the results use -s (--silent). Columns are separated with a TAB character.

mysql -s ...
use testdb;
select * from names;

id  name
1   pete
2   john
3   mike

To output the data with no headers and no grid just use both -s and -N.

mysql -sN ...

Eclipse and Windows newlines

There is a handy bash utility - dos2unix - which is a DOS/MAC to UNIX text file format converter, that if not already installed on your distro, should be able to be easily installed via a package manager. dos2unix man page

Palindrome check in Javascript

SHORTEST CODE (31 chars)(ES6):

p=s=>s==[...s].reverse().join``
p('racecar'); //true

Keep in mind short code isn't necessarily the best. Readability and efficiency can matter more.

jQuery + client-side template = "Syntax error, unrecognized expression"

As the official document: As of 1.9, a string is only considered to be HTML if it starts with a less-than ("<") character. The Migrate plugin can be used to restore the pre-1.9 behavior.

If a string is known to be HTML but may start with arbitrary text that is not an HTML tag, pass it to jQuery.parseHTML() which will return an array of DOM nodes representing the markup. A jQuery collection can be created from this, for example: $($.parseHTML(htmlString)). This would be considered best practice when processing HTML templates for example. Simple uses of literal strings such as $("<p>Testing</p>").appendTo("body") are unaffected by this change.

How do I get the title of the current active window using c#?

Loop over Application.Current.Windows[] and find the one with IsActive == true.

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

It's an eclipse setup issue, not a Jersey issue.

From this thread ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer

Right click your eclipse project Properties -> Deployment Assembly -> Add -> Java Build Path Entries -> Gradle Dependencies -> Finish.

So Eclipse wasn't using the Gradle dependencies when Apache was starting .

How can I set my Cygwin PATH to find javac?

To bring more prominence to the useful comment by @johanvdw:

If you want to ensure your your javac file path is always know when cygwin starts, you may edit your .bash_profile file. In this example you would add export PATH=$PATH:"/cygdrive/C/Program Files/Java/jdk1.6.0_23/bin/" somewhere in the file.

When Cygwin starts, it'll search directories in PATH and this one for executable files to run.

How to Completely Uninstall Xcode and Clear All Settings

Run this to find all instances of Xcode in your filesystem:

for i in find / -name Xcode -print; do echo $i; done

Printing out a linked list using toString

A very simple solution is to override the toString() method in the Node. Then, you can call print by passing LinkedList's head. You don't need to implement any kind of loop.

Code:

public class LinkedListNode {
    ...

    //New
    @Override
    public String toString() {
        return String.format("Node(%d, next = %s)", data, next);
    }
} 


public class LinkedList {

    public static void main(String[] args) {

        LinkedList l = new LinkedList();
        l.insertFront(0);
        l.insertFront(1);
        l.insertFront(2);
        l.insertFront(3);

        //New
        System.out.println(l.head);
    }
}

String Array object in Java

I think you are a little messed up with what you doing. Athlete is an object, athlete has a name, i has a city where he lives. Athlete can dive.

public class Athlete {

private String name;
private String city;

public Athlete (String name, String city){
this.name = name;
this.city = city;
}
--create method dive, (i am not sure what exactly i has to do)
public void dive (){} 
}




public class Main{
public static void main (String [] args){

String name = in.next(); //enter name from keyboad
String city = in.next(); //enter city form keybord

--create a new object athlete and pass paramenters name and city into the object
Athlete a = new Athlete (name, city);

}
}

One command to create a directory and file inside it linux command

Below commands I tried on Windows 10 machine with git-bash. And that worked for me. Let's say I want to create a directory named "Files" and under this directory I want to have "file1.txt,file2.txt,file3.txt" ..etc files

mkdir Files && touch $_/file1.txt $_/file2.txt $_/file3.txt

Java: Literal percent sign in printf statement

Escaped percent sign is double percent (%%):

System.out.printf("2 out of 10 is %d%%", 20);

How to replace <span style="font-weight: bold;">foo</span> by <strong>foo</strong> using PHP and regex?

$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);

Note: only work for your example.

Storing money in a decimal column - what precision and scale?

4 decimal places would give you the accuracy to store the world's smallest currency sub-units. You can take it down further if you need micropayment (nanopayment?!) accuracy.

I too prefer DECIMAL to DBMS-specific money types, you're safer keeping that kind of logic in the application IMO. Another approach along the same lines is simply to use a [long] integer, with formatting into ¤unit.subunit for human readability (¤ = currency symbol) done at the application level.

Node.JS: Getting error : [nodemon] Internal watch failed: watch ENOSPC

Try this....

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p?

Will defiantly work

What is difference between 'git reset --hard HEAD~1' and 'git reset --soft HEAD~1'?

This is the main difference between use git reset --hard and git reset --soft:

--soft

Does not touch the index file or the working tree at all (but resets the head to , just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.

--hard

Resets the index and working tree. Any changes to tracked files in the working tree since are discarded.

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

Calling a method every x minutes

I based this on @asawyer's answer. He doesn't seem to get a compile error, but some of us do. Here is a version which the C# compiler in Visual Studio 2010 will accept.

var timer = new System.Threading.Timer(
    e => MyMethod(),  
    null, 
    TimeSpan.Zero, 
    TimeSpan.FromMinutes(5));

sqlalchemy filter multiple columns

You can simply call filter multiple times:

query = meta.Session.query(User).filter(User.firstname.like(searchVar1)). \
                                 filter(User.lastname.like(searchVar2))

How do I handle ImeOptions' done button click?

More details on how to set the OnKeyListener, and have it listen for the Done button.

First add OnKeyListener to the implements section of your class. Then add the function defined in the OnKeyListener interface:

/*
 * Respond to soft keyboard events, look for the DONE press on the password field.
 */
public boolean onKey(View v, int keyCode, KeyEvent event)
{
    if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
        (keyCode == KeyEvent.KEYCODE_ENTER))
    {
        // Done pressed!  Do something here.
    }
    // Returning false allows other listeners to react to the press.
    return false;
}

Given an EditText object:

EditText textField = (EditText)findViewById(R.id.MyEditText);
textField.setOnKeyListener(this);

How do I use ROW_NUMBER()?

You can use Row_Number for limit query result.

Example:

SELECT * FROM (
    select row_number() OVER (order by createtime desc) AS ROWINDEX,* 
    from TABLENAME ) TB
WHERE TB.ROWINDEX between 0 and 10

-- With above query, I will get PAGE 1 of results from TABLENAME.

UILabel font size?

**You can set font size by these properties **

timedisplayLabel= [[UILabel alloc]initWithFrame:CGRectMake(70, 194, 180, 60)];

[timedisplayLabel setTextAlignment:NSTextAlignmentLeft];

[timedisplayLabel setBackgroundColor:[UIColor clearColor]];

[timedisplayLabel setAdjustsFontSizeToFitWidth:YES];

[timedisplayLabel setTextColor:[UIColor blackColor]];

[timedisplayLabel setUserInteractionEnabled:NO];

[timedisplayLabel setFont:[UIFont fontWithName:@"digital-7" size:60]];

timedisplayLabel.layer.shadowColor =[[UIColor whiteColor ]CGColor ];

timedisplayLabel.layer.shadowOffset=(CGSizeMake(0, 0));

timedisplayLabel.layer.shadowOpacity=1;

timedisplayLabel.layer.shadowRadius=3.0;

timedisplayLabel.layer.masksToBounds=NO;

timedisplayLabel.shadowColor=[UIColor darkGrayColor];

timedisplayLabel.shadowOffset=CGSizeMake(0, 2);

How to change color and font on ListView

Create a CustomAdapter and in that you have the getView() so there if you want to change the listview background color use this :

v.setBackgroundColor(Color.CYAN);

If you want to change the textColor then do this :

tv.setTextColor(Color.RED);

and for the textSize :

tv.setTextSize(20);

where 'v' is the listview and 'tv' is the textview

Is it possible to interactively delete matching search pattern in Vim?

http://vim.wikia.com/wiki/Search_and_replace

Try this search and replace:

:%s/foo/bar/gc

Change each 'foo' to 'bar', but ask for confirmation first.

Press y or n to change or keep your text.

Why should I use an IDE?

The short answer as to why I use an IDE is laziness.

I'm a lazy soul who doesn't like to do things a difficult way when there is an easy way to do it instead. IDE's make life easy and so appeal to us lazy folk.

As I type code, the IDE automatically checks the validity of the code, I can highlight a method and hit F1 to get help, right click and select "go to to definition" to jump straight to where it is defined. I hit one button and the application, with debugger automatically attached is launched for me. And so the list goes on. All the things that a developer does on a day to day basis is gathered under one roof.

There is no need to use an IDE. It is just much harder work not to.

SQL SERVER: Get total days between two dates

You can try this MSDN link

DATEDIFF ( datepart , startdate , enddate )
SELECT DATEDIFF(DAY, '1/1/2011', '3/1/2011')

Hashset vs Treeset

Message Edit ( complete rewrite ) When order does not matter, that's when. Both should give Log(n) - it would be of utility to see if either is over five percent faster than the other. HashSet can give O(1) testing in a loop should reveal whether it is.

How do I convert NSMutableArray to NSArray?

i was search for the answer in swift 3 and this question was showed as first result in search and i get inspired the answer from it so here is the swift 3 code

let array: [String] = nsMutableArrayObject.copy() as! [String]

Guid is all 0's (zeros)?

Can't tell you how many times this has caught. me.

Guid myGuid = Guid.NewGuid(); 

How do I make entire div a link?

the html:

 <a class="xyz">your content</a>

the css:

.xyz{
  display: block;
}

This will make the anchor be a block level element like a div.

Generate Java classes from .XSD files...?

Using Eclipse IDE:-

  1. copy the xsd into a new/existing project.
  2. Make sure you have JAXB required JARs in you classpath. You can download one here.
  3. Right click on the XSD file -> Generate -> JAXB classes.

Write to custom log file from a Bash script

logger logs to syslog facilities. If you want the message to go to a particular file you have to modify the syslog configuration accordingly. You could add a line like this:

local7.*   -/var/log/mycustomlog

and restart syslog. Then you can log like this:

logger -p local7.info "information message"
logger -p local7.err "error message"

and the messages will appear in the desired logfile with the correct log level.

Without making changes to the syslog configuration you could use logger like this:

logger -s "foo bar" >> /var/log/mycustomlog

That would instruct logger to print the message to STDERR as well (in addition to logging it to syslog), so you could redirect STDERR to a file. However, it would be utterly pointless, because the message is already logged via syslog anyway (with the default priority user.notice).

Django - what is the difference between render(), render_to_response() and direct_to_template()?

Rephrasing Yuri, Fábio, and Frosts answers for the Django noob (i.e. me) - almost certainly a simplification, but a good starting point?

  • render_to_response() is the "original", but requires you putting context_instance=RequestContext(request) in nearly all the time, a PITA.

  • direct_to_template() is designed to be used just in urls.py without a view defined in views.py but it can be used in views.py to avoid having to type RequestContext

  • render() is a shortcut for render_to_response() that automatically supplies context_instance=Request.... Its available in the django development version (1.2.1) but many have created their own shortcuts such as this one, this one or the one that threw me initially, Nathans basic.tools.shortcuts.py

Google Maps v2 - set both my location and zoom in

Try in this way -

public class SummaryMapActivity extends FragmentActivity implements LocationListener{

 private GoogleMap mMap;
 private LocationManager locationManager;
 private static final long MIN_TIME = 400;
 private static final float MIN_DISTANCE = 1000;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.summary_mapview);

    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
        }
    }
    mMap.setMyLocationEnabled(true);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this); 


}

@Override
public void onLocationChanged(Location location) {
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 15);
    mMap.animateCamera(cameraUpdate);
    locationManager.removeUpdates(this);

}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

}

HTML5 and frameborder

How about using the same for technique for "fooling" the validator with Javascript by sticking a target attribute in XHTML <a onclick="this.target='_blank'">?

  • onsomething = " this.frameborder = '0' "

<iframe onload = " this.frameborder='0' " src="menu.html" id="menu"> </iframe>

Or getElementsByTagName]("iframe")1 adding this attribute for all iframes on the page?

Haven't tested this because I've done something which means that nothing is working in IE less than 9! :) So while I'm sorting that out ... :)

Center image in div horizontally

Every solution posted here assumes that you know the dimensions of your img, which is not a common scenario. Also, planting the dimensions into the solution is painful.

Simply set:

/* for the img inside your div */
display: block;
margin-left: auto;
margin-right: auto;

or

/* for the img inside your div */
display: block;
margin: 0 auto;

That's all.

Note, that you'll also have to set an initial min-width for your outer div.

Is it better to use path() or url() in urls.py for django 2.0?

The new django.urls.path() function allows a simpler, more readable URL routing syntax. For example, this example from previous Django releases:

url(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive)

could be written as:

path('articles/<int:year>/', views.year_archive)

The django.conf.urls.url() function from previous versions is now available as django.urls.re_path(). The old location remains for backwards compatibility, without an imminent deprecation. The old django.conf.urls.include() function is now importable from django.urls so you can use:

from django.urls import include, path, re_path

in the URLconfs. For further reading django doc

Difference between save and saveAndFlush in Spring data jpa

On saveAndFlush, changes will be flushed to DB immediately in this command. With save, this is not necessarily true, and might stay just in memory, until flush or commit commands are issued.

But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.

In your case, you probably use some sort of transactions mechanism, which issues commit command for you if everything works out fine.

startForeground fail after upgrade to Android 8.1

This worked for me. In my service class, I created the notification channel for android 8.1 as below:

public class Service extends Service {

    public static final String NOTIFICATION_CHANNEL_ID_SERVICE = "com.package.MyService";
    public static final String NOTIFICATION_CHANNEL_ID_INFO = "com.package.download_info";

    @Override
    public void onCreate() {

        super.onCreate();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_SERVICE, "App Service", NotificationManager.IMPORTANCE_DEFAULT));
            nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_INFO, "Download Info", NotificationManager.IMPORTANCE_DEFAULT));
        } else {
            Notification notification = new Notification();
            startForeground(1, notification);
        }
    }
}

Note: Create the channel where you are creating the Notification for Build.VERSION.SDK_INT >= Build.VERSION_CODES.O

How do I release memory used by a pandas dataframe?

As noted in the comments, there are some things to try: gc.collect (@EdChum) may clear stuff, for example. At least from my experience, these things sometimes work and often don't.

There is one thing that always works, however, because it is done at the OS, not language, level.

Suppose you have a function that creates an intermediate huge DataFrame, and returns a smaller result (which might also be a DataFrame):

def huge_intermediate_calc(something):
    ...
    huge_df = pd.DataFrame(...)
    ...
    return some_aggregate

Then if you do something like

import multiprocessing

result = multiprocessing.Pool(1).map(huge_intermediate_calc, [something_])[0]

Then the function is executed at a different process. When that process completes, the OS retakes all the resources it used. There's really nothing Python, pandas, the garbage collector, could do to stop that.

The SQL OVER() clause - when and why is it useful?

prkey   whatsthat               cash   
890    "abb                "   32  32
43     "abbz               "   2   34
4      "bttu               "   1   35
45     "gasstuff           "   2   37
545    "gasz               "   5   42
80009  "hoo                "   9   51
2321   "ibm                "   1   52
998    "krk                "   2   54
42     "kx-5010            "   2   56
32     "lto                "   4   60
543    "mp                 "   5   65
465    "multipower         "   2   67
455    "O.N.               "   1   68
7887   "prem               "   7   75
434    "puma               "   3   78
23     "retractble         "   3   81
242    "Trujillo's stuff   "   4   85

That's a result of query. Table used as source is the same exept that it has no last column. This column is a moving sum of third one.

Query:

SELECT prkey,whatsthat,cash,SUM(cash) over (order by whatsthat)
    FROM public.iuk order by whatsthat,prkey
    ;

(table goes as public.iuk)

sql version:  2012

It's a little over dbase(1986) level, I don't know why 25+ years has been needed to finish it up.

How to get Text BOLD in Alert or Confirm box?

Maybe you coul'd use UTF8 bold chars.

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

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

Why is the GETDATE() an invalid identifier

Use ORACLE equivalent of getdate() which is sysdate . Read about here. Getdate() belongs to SQL Server , will not work on Oracle.

Other option is current_date

How to check if a textbox is empty using javascript

Whatever method you choose is not freeing you from performing the same validation on at the back end.

How to use Selenium with Python?

You just need to get selenium package imported, that you can do from command prompt using the command

pip install selenium

When you have to use it in any IDE just import this package, no other documentation required to be imported

For Eg :

import selenium 
print(selenium.__filepath__)

This is just a general command you may use in starting to check the filepath of selenium