Programs & Examples On #X264

x264 is a free software library and application for encoding video streams into the H.264/MPEG-4 AVC format, and is is released under the terms of the GNU GPL.

What steps are needed to stream RTSP from FFmpeg?

You can use FFserver to stream a video using RTSP.

Just change console syntax to something like this:

ffmpeg -i space.mp4 -vcodec libx264 -tune zerolatency -crf 18 http://localhost:1234/feed1.ffm

Create a ffserver.config file (sample) where you declare HTTPPort, RTSPPort and SDP stream. Your config file could look like this (some important stuff might be missing):

HTTPPort 1234
RTSPPort 1235

<Feed feed1.ffm>
        File /tmp/feed1.ffm
        FileMaxSize 2M
        ACL allow 127.0.0.1
</Feed>

<Stream test1.sdp>
    Feed feed1.ffm
    Format rtp
    Noaudio
    VideoCodec libx264
    AVOptionVideo flags +global_header
    AVOptionVideo me_range 16
    AVOptionVideo qdiff 4
    AVOptionVideo qmin 10
    AVOptionVideo qmax 51
    ACL allow 192.168.0.0 192.168.255.255
</Stream>

With such setup you can watch the stream with i.e. VLC by typing:

rtsp://192.168.0.xxx:1235/test1.sdp

Here is the FFserver documentation.

How to create a video from images with FFmpeg?

See the Create a video slideshow from images – FFmpeg

If your video does not show the frames correctly If you encounter problems, such as the first image is skipped or only shows for one frame, then use the fps video filter instead of -r for the output framerate

ffmpeg -r 1/5 -i img%03d.png -c:v libx264 -vf fps=25 -pix_fmt yuv420p out.mp4

Alternatively the format video filter can be added to the filter chain to replace -pix_fmt yuv420p like "fps=25,format=yuv420p". The advantage of this method is that you can control which filter goes first

ffmpeg -r 1/5 -i img%03d.png -c:v libx264 -vf "fps=25,format=yuv420p" out.mp4

I tested below parameters, it worked for me

"e:\ffmpeg\ffmpeg.exe" -r 1/5 -start_number 0 -i "E:\images\01\padlock%3d.png" -c:v libx264 -vf "fps=25,format=yuv420p" e:\out.mp4

below parameters also worked but it always skips the first image

"e:\ffmpeg\ffmpeg.exe" -r 1/5 -start_number 0 -i "E:\images\01\padlock%3d.png" -c:v libx264 -r 30 -pix_fmt yuv420p e:\out.mp4

making a video from images placed in different folders

First, add image paths to imagepaths.txt like below.

# this is a comment details https://trac.ffmpeg.org/wiki/Concatenate

file 'E:\images\png\images__%3d.jpg'
file 'E:\images\jpg\images__%3d.jpg'

Sample usage as follows;

"h:\ffmpeg\ffmpeg.exe" -y -r 1/5 -f concat -safe 0 -i "E:\images\imagepaths.txt" -c:v libx264 -vf "fps=25,format=yuv420p" "e:\out.mp4"

-safe 0 parameter prevents Unsafe file name error

Related links

FFmpeg making a video from images placed in different folders

FFMPEG An Intermediate Guide/image sequence

Concatenate – FFmpeg

Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space

A saw a different post that also had diacritical marks, which is great

s.replace(/[^a-zA-Z0-9À-ž\s]/g, "")

Playing m3u8 Files with HTML Video Tag

You can use video js library for easily play HLS video's. It allows to directly play videos

<!-- CSS  -->
 <link href="https://vjs.zencdn.net/7.2.3/video-js.css" rel="stylesheet">


<!-- HTML -->
<video id='hls-example'  class="video-js vjs-default-skin" width="400" height="300" controls>
<source type="application/x-mpegURL" src="http://www.streambox.fr/playlists/test_001/stream.m3u8">
</video>


<!-- JS code -->
<!-- If you'd like to support IE8 (for Video.js versions prior to v7) -->
<script src="https://vjs.zencdn.net/ie8/ie8-version/videojs-ie8.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/videojs-contrib-hls/5.14.1/videojs-contrib-hls.js"></script>
<script src="https://vjs.zencdn.net/7.2.3/video.js"></script>

<script>
var player = videojs('hls-example');
player.play();
</script>

GitHub Video Js

ffmpeg - Converting MOV files to MP4

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

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

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

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

Xcode 6 Storyboard the wrong size?

I had this issue in xcode 6 and there is a way to resolve the resize conflicts. If you select your view, at the bottom you will see an icon that looks like |-Δ-|. If you click on it, you're project will resize for different devices.

HTML anchor tag with Javascript onclick event

You can even try below option:

<a href="javascript:show_more_menu();">More >>></a>

Difference between staticmethod and classmethod

I think a better question is "When would you use @classmethod vs @staticmethod?"

@classmethod allows you easy access to private members that are associated to the class definition. this is a great way to do singletons, or factory classes that control the number of instances of the created objects exist.

@staticmethod provides marginal performance gains, but I have yet to see a productive use of a static method within a class that couldn't be achieved as a standalone function outside the class.

How to detect DIV's dimension changed?

Only the window object generates a "resize" event. The only way I know of to do what you want to do is to run an interval timer that periodically checks the size.

Write values in app.config file

Try the following code:

    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    config.AppSettings.Settings.Add("YourKey", "YourValue");
    config.Save(ConfigurationSaveMode.Minimal);

It worked for me :-)

Pass multiple parameters in Html.BeginForm MVC

There are two options here.

  1. a hidden field within the form, or
  2. Add it to the route values parameter in the begin form method.

Edit

@Html.Hidden("clubid", ViewBag.Club.id)

or

 @using(Html.BeginForm("action", "controller",
                       new { clubid = @Viewbag.Club.id }, FormMethod.Post, null)

How to get a resource id with a known resource name?

Kotlin Version via Extension Function

To find a resource id by its name In Kotlin, add below snippet in a kotlin file:

ExtensionFunctions.kt

import android.content.Context
import android.content.res.Resources

fun Context.resIdByName(resIdName: String?, resType: String): Int {
    resIdName?.let {
        return resources.getIdentifier(it, resType, packageName)
    }
    throw Resources.NotFoundException()
}


Usage

Now all resource ids are accessible wherever you have a context reference using resIdByName method:

val drawableResId = context.resIdByName("ic_edit_black_24dp", "drawable")
val stringResId = context.resIdByName("title_home", "string")
.
.
.    

What's the difference between all the Selection Segues?

For those who prefer a bit more practical learning, select the segue in dock, open the attribute inspector and switch between different kinds of segues (dropdown "Kind"). This will reveal options specific for each of them: for example you can see that "present modally" allows you to choose a transition type etc.

How to increase an array's length

If you don't want or cannot use ArrayList, then there is a utility method:

Arrays.copyOf() 

that will allow you to specify new size, while preserving the elements.

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

I think the problem is with the datatype of the data you are passing Caused by: java.sql.SQLException: Invalid column type: 1111 check the datatypes you pass with the actual column datatypes may be there can be some mismatch or some constraint violation with null

Uncaught ReferenceError: $ is not defined error in jQuery

Change the order you're including your scripts (jQuery first):

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="./javascript.js"></script>
<script
    src="http://maps.googleapis.com/maps/api/js?key=YOUR_APIKEY&sensor=false">
</script>

Difference between fprintf, printf and sprintf?

sprintf: Writes formatted data to a character string in memory instead of stdout

Syntax of sprintf is:

#include <stdio.h>
int sprintf (char *string, const char *format
[,item [,item]…]);

Here,

String refers to the pointer to a buffer in memory where the data is to be written.

Format refers to pointer to a character string defining the format.

Each item is a variable or expression specifying the data to write.

The value returned by sprintf is greater than or equal to zero if the operation is successful or in other words the number of characters written, not counting the terminating null character is returned and returns a value less than zero if an error occurred.

printf: Prints to stdout

Syntax for printf is:

printf format [argument]…

The only difference between sprintf() and printf() is that sprintf() writes data into a character array, while printf() writes data to stdout, the standard output device.

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

This happens to me, since I am designing my database, I notice that I change my seed on my main table, now the relational table has no foreign key on the main table.

So I need to truncate both tables, and it now works!

Detect click outside Angular component

u can call event function like (focusout) or (blur) then u put your code

<div tabindex=0 (blur)="outsideClick()">raw data </div>
 

 outsideClick() {
  alert('put your condition here');
   }

How do I clear a search box with an 'x' in bootstrap 3?

To get something like this

input with clear button

with Bootstrap 3 and Jquery use the following HTML code:

<div class="btn-group">
  <input id="searchinput" type="search" class="form-control">
  <span id="searchclear" class="glyphicon glyphicon-remove-circle"></span>
</div>

and some CSS:

#searchinput {
    width: 200px;
}
#searchclear {
    position: absolute;
    right: 5px;
    top: 0;
    bottom: 0;
    height: 14px;
    margin: auto;
    font-size: 14px;
    cursor: pointer;
    color: #ccc;
}

and Javascript:

$("#searchclear").click(function(){
    $("#searchinput").val('');
});

Of course you have to write more Javascript for whatever functionality you need, e.g. to hide the 'x' if the input is empty, make Ajax requests and so on. See http://www.bootply.com/121508

Double precision - decimal places

In most contexts where double values are used, calculations will have a certain amount of uncertainty. The difference between 1.33333333333333300 and 1.33333333333333399 may be less than the amount of uncertainty that exists in the calculations. Displaying the value of "2/3 + 2/3" as "1.33333333333333" is apt to be more meaningful than displaying it as "1.33333333333333319", since the latter display implies a level of precision that doesn't really exist.

In the debugger, however, it is important to uniquely indicate the value held by a variable, including essentially-meaningless bits of precision. It would be very confusing if a debugger displayed two variables as holding the value "1.333333333333333" when one of them actually held 1.33333333333333319 and the other held 1.33333333333333294 (meaning that, while they looked the same, they weren't equal). The extra precision shown by the debugger isn't apt to represent a numerically-correct calculation result, but indicates how the code will interpret the values held by the variables.

MySQL IF ELSEIF in select query

I found a bug in MySQL 5.1.72 when using the nested if() functions .... the value of column variables (e.g. qty_1) is blank inside the second if(), rendering it useless. Use the following construct instead:

case 
  when qty_1<='23' then price
  when '23'>qty_1 && qty_2<='23' then price_2
  when '23'>qty_2 && qty_3<='23' then price_3
  when '23'>qty_3 then price_4
  else 1
end

Force IE10 to run in IE10 Compatibility View?

See here:

https://softwareengineering.stackexchange.com/questions/194687/how-the-compatibility-view-in-ie-works-behind-the-scenes

Use

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE10">

I just tried it and it showed IE10 compatibility mode in the debug window.

angular.service vs angular.factory

The factory pattern is more flexible as it can return functions and values as well as objects.

There isn't a lot of point in the service pattern IMHO, as everything it does you can just as easily do with a factory. The exceptions might be:

  • If you care about the declared type of your instantiated service for some reason - if you use the service pattern, your constructor will be the type of the new service.
  • If you already have a constructor function that you're using elsewhere that you also want to use as a service (although probably not much use if you want to inject anything into it!).

Arguably, the service pattern is a slightly nicer way to create a new object from a syntax point of view, but it's also more costly to instantiate. Others have indicated that angular uses "new" to create the service, but this isn't quite true - it isn't able to do that because every service constructor has a different number of parameters. What angular actually does is use the factory pattern internally to wrap your constructor function. Then it does some clever jiggery pokery to simulate javascript's "new" operator, invoking your constructor with a variable number of injectable arguments - but you can leave out this step if you just use the factory pattern directly, thus very slightly increasing the efficiency of your code.

Laravel eloquent update record without loading from database

You can also use firstOrCreate OR firstOrNew

// Retrieve the Post by the attributes, or create it if it doesn't exist...
$post = Post::firstOrCreate(['id' => 3]);
// OR
// Retrieve the Post by the attributes, or instantiate a new instance...
$post = Post::firstOrNew(['id' => 3]); 

// update record
$post->title = "Updated title";
$post->save();

Hope it will help you :)

Temporarily switch working copy to a specific Git commit

First, use git log to see the log, pick the commit you want, note down the sha1 hash that is used to identify the commit. Next, run git checkout hash. After you are done, git checkout original_branch. This has the advantage of not moving the HEAD, it simply switches the working copy to a specific commit.

Editing in the Chrome debugger

Chrome DevTools has a Snippets panel where you can create and edit JavaScript code as you would in an editor, and execute it. Open DevTools, then select the Sources panel, then select the Snippets tab.

https://developers.google.com/web/tools/chrome-devtools/snippets

enter image description here

VB.NET Switch Statement GoTo Case

you should declare label first use this :

    Select Case parameter 
        Case "userID"
                    ' does something here.
            Case "packageID"
                    ' does something here.
            Case "mvrType" 
                    If otherFactor Then 
                            ' does something here. 
                    Else 
                            GoTo else
                    End If 

            Case Else 
else :
                    ' does some processing... 
                    Exit Select 
    End Select

swift UITableView set rowHeight

Problem Cause:
The problem is that the cell has not been created yet. TableView first calculates the height for row and then populates the data for each row, so the rows array has not been created when heightForRow method gets called. So your app is trying to access a memory location which it does not have the permission to and therefor you get the EXC_BAD_ACCESS message.

How to achieve self sizing TableViewCell in UITableView:
Just set proper constraints for your views contained in TableViewCell's view in StoryBoard. Remember you shouldn't set height constraints to TableViewCell's root view, its height should be properly computable by the height of its subviews -- This is like what you do to set proper constraints for UIScrollView. This way your cells will get different heights according to their subviews. No additional action needed

How can I mock requests and the response?

Here is what worked for me:

import mock
@mock.patch('requests.get', mock.Mock(side_effect = lambda k:{'aurl': 'a response', 'burl' : 'b response'}.get(k, 'unhandled request %s'%k)))

Extract time from moment js object

This is the good way using formats:

const now = moment()
now.format("hh:mm:ss K") // 1:00:00 PM
now.format("HH:mm:ss") // 13:00:00

Red more about moment sring format

How to launch another aspx web page upon button click?

Edited and fixed (thanks to Shredder)

If you mean you want to open a new tab, try the below:

protected void Page_Load(object sender, EventArgs e)
{
    this.Form.Target = "_blank";
}

protected void Button1_Click(object sender, EventArgs e)
{

    Response.Redirect("Otherpage.aspx");
}

This will keep the original page to stay open and cause the redirects on the current page to affect the new tab only.

-J

Pass values of checkBox to controller action in asp.net mvc4

I hope this somewhat helps.

Create a viewmodel for your view. This will represent the true or false (checked or unchecked) values of your checkboxes.

public class UsersViewModel
{
    public bool IsAdmin { get; set; }
    public bool ManageFiles { get; set; }
    public bool ManageNews { get; set; }
}

Next, create your controller and have it pass the view model to your view.

public IActionResult Users()
{
     var viewModel = new UsersViewModel();
     return View(viewModel);
}

Lastly, create your view and reference your view model. Use @Html.CheckBoxFor(x => x) to display checkboxes and hold their values.

@model Website.Models.UsersViewModel
<div class="form-check">
    @Html.CheckBoxFor(x => x.IsAdmin)
    <label class="form-check-label" for="defaultCheck1">
           Admin
    </label>
</div>
          

When you post/save data from your view, the view model will contain the values of the checkboxes. Be sure to include the viewmodel as a parameter in the method/controller that is called to save your data.

I hope this makes sense and helps. This is my first answer, so apologies if lacking.

@import vs #import - iOS 7

Nice answer you can find in book Learning Cocoa with Objective-C (ISBN: 978-1-491-90139-7)

Modules are a new means of including and linking files and libraries into your projects. To understand how modules work and what benefits they have, it is important to look back into the history of Objective-C and the #import statement Whenever you want to include a file for use, you will generally have some code that looks like this:

#import "someFile.h"

Or in the case of frameworks:

#import <SomeLibrary/SomeFile.h>

Because Objective-C is a superset of the C programming language, the #import state- ment is a minor refinement upon C’s #include statement. The #include statement is very simple; it copies everything it finds in the included file into your code during compilation. This can sometimes cause significant problems. For example, imagine you have two header files: SomeFileA.h and SomeFileB.h; SomeFileA.h includes SomeFileB.h, and SomeFileB.h includes SomeFileA.h. This creates a loop, and can confuse the coimpiler. To deal with this, C programmers have to write guards against this type of event from occurring.

When using #import, you don’t need to worry about this issue or write header guards to avoid it. However, #import is still just a glorified copy-and-paste action, causing slow compilation time among a host of other smaller but still very dangerous issues (such as an included file overriding something you have declared elsewhere in your own code.)

Modules are an attempt to get around this. They are no longer a copy-and-paste into source code, but a serialised representation of the included files that can be imported into your source code only when and where they’re needed. By using modules, code will generally compile faster, and be safer than using either #include or #import.

Returning to the previous example of importing a framework:

#import <SomeLibrary/SomeFile.h>

To import this library as a module, the code would be changed to:

@import SomeLibrary;

This has the added bonus of Xcode linking the SomeLibrary framework into the project automatically. Modules also allow you to only include the components you really need into your project. For example, if you want to use the AwesomeObject component in the AwesomeLibrary framework, normally you would have to import everything just to use the one piece. However, using modules, you can just import the specific object you want to use:

@import AwesomeLibrary.AwesomeObject;

For all new projects made in Xcode 5, modules are enabled by default. If you want to use modules in older projects (and you really should) they will have to be enabled in the project’s build settings. Once you do that, you can use both #import and @import statements in your code together without any concern.

Pandas: Return Hour from Datetime Column Directly

Now we can use:

sales['time_hour'] = sales['timestamp'].apply(lambda x: x.hour)

Carousel with Thumbnails in Bootstrap 3.0

@Skelly 's answer is correct. It won't let me add a comment (<50 rep)... but to answer your question on his answer: In the example he linked, if you add

col-xs-3 

class to each of the thumbnails, like this:

class="col-md-3 col-xs-3"

then it should stay the way you want it when sized down to phone width.

How to open a specific port such as 9090 in Google Compute Engine

Here is the command-line approach to answer this question:

gcloud compute firewall-rules create <rule-name> --allow tcp:9090 --source-tags=<list-of-your-instances-names> --source-ranges=0.0.0.0/0 --description="<your-description-here>"

This will open the port 9090 for the instances that you name. Omitting --source-tags and --source-ranges will apply the rule to all instances. More details are in the Gcloud documentation and the firewall-rule create command manual

The previous answers are great, but Google recommends using the newer gcloud commands instead of the gcutil commands.

PS: To get an idea of Google's firewall rules, run gcloud compute firewall-rules list and view all your firewall rules

Can I display the value of an enum with printf()?

enum A { foo, bar } a;
a = foo;
printf( "%d", a );   // see comments below

How to create loading dialogs in Android?

Today things have changed a little.

Now we avoid use ProgressDialog to show spinning progress:

enter image description here

If you want to put in your app a spinning progress you should use an Activity indicators:

http://developer.android.com/design/building-blocks/progress.html#activity

How to merge a specific commit in Git

In my use case we had a similar need for CI CD. We used git flow with develop and master branches. Developers are free to merge their changes directly to develop or via a pull request from a feature branch. However to master we merge only the stable commits from the develop branch in an automated way via Jenkins.

In this case doing cherry-pick is not a good option. However we create a local-branch from the commit-id then merge that local-branch to master and perform mvn clean verify(we use maven). If success then release production version artifact to nexus using maven release plugin with localCheckout=true option and pushChanges=false. Finally when everything is success then push the changes and tag to origin.

A sample code snippet:

Assuming you are on master if done manually. However on jenkins, when you checkout the repo you will be on the default branch(master if configured).

git pull  // Just to pull any changes.
git branch local-<commitd-id> <commit-id>  // Create a branch from the given commit-id
git merge local-<commit-id>  // Merge that local branch to master.
mvn clean verify   // Verify if the code is build able
mvn <any args> release:clean release:prepare release:perform // Release artifacts
git push origin/master  // Push the local changes performed above to origin.
git push origin <tag>  // Push the tag to origin

This will give you a full control with a fearless merge or conflict hell.

Feel free to advise in case there is any better option.

How to check if a String contains any of some strings

Here's a LINQ solution which is virtually the same but more scalable:

new[] { "a", "b", "c" }.Any(c => s.Contains(c))

How can I recursively find all files in current and subfolders based on wildcard matching?

Piping find into grep is often more convenient; it gives you the full power of regular expressions for arbitrary wildcard matching.

For example, to find all files with case insensitive string "foo" in the filename:

~$ find . -print | grep -i foo

onSaveInstanceState () and onRestoreInstanceState ()

It is not necessary that onRestoreInstanceState will always be called after onSaveInstanceState.

Note that : onRestoreInstanceState will always be called, when activity is rotated (when orientation is not handled) or open your activity and then open other apps so that your activity instance is cleared from memory by OS.

How can I use a custom font in Java?

Here is how I did it!

//create the font

try {
    //create the font to use. Specify the size!
    Font customFont = Font.createFont(Font.TRUETYPE_FONT, new File("Fonts\\custom_font.ttf")).deriveFont(12f);
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    //register the font
    ge.registerFont(customFont);
} catch (IOException e) {
    e.printStackTrace();
} catch(FontFormatException e) {
    e.printStackTrace();
}

//use the font
yourSwingComponent.setFont(customFont);

Counting repeated characters in a string in Python

Grand Performance Comparison

Scroll to the end for a TL;DR graph

Since I had "nothing better to do" (understand: I had just a lot of work), I decided to do a little performance contest. I assembled the most sensible or interesting answers and did some simple timeit in CPython 3.5.1 on them. I tested them with only one string, which is a typical input in my case:

>>> s = 'ZDXMZKMXFDKXZFKZ'
>>> len(s)
16

Be aware that results might vary for different inputs, be it different length of the string or different number of distinct characters, or different average number of occurrences per character.


Don't reinvent the wheel

Python has made it simple for us. The collections.Counter class does exactly what we want and a lot more. Its usage is by far the simplest of all the methods mentioned here.

taken from @oefe, nice find

>>> timeit('Counter(s)', globals=locals())
8.208566107001388

Counter goes the extra mile, which is why it takes so long.

¿Dictionary, comprende?

Let's try using a simple dict instead. First, let's do it declaratively, using dict comprehension.

I came up with this myself...

>>> timeit('{c: s.count(c) for c in s}', globals=locals())
4.551155784000002

This will go through s from beginning to end, and for each character it will count the number of its occurrences in s. Since s contains duplicate characters, the above method searches s several times for the same character. The result is naturally always the same. So let's count the number of occurrences just once for each character.

I came up with this myself, and so did @IrshadBhat

>>> timeit('{c: s.count(c) for c in set(s)}', globals=locals())
3.1484066140001232

Better. But we still have to search through the string to count the occurrences. One search for each distinct character. That means we're going to read the string more than once. We can do better than that! But for that, we have to get off our declarativist high horse and descend into an imperative mindset.

Exceptional code

AKA Gotta catch 'em all!

inspired by @anthony

>>> timeit('''
... d = {}
... for c in s:
...   try:
...     d[c] += 1
...   except KeyError:
...     d[c] = 1
... ''', globals=locals())
3.7060273620008957

Well, it was worth a try. If you dig into the Python source (I can't say with certainty because I have never really done that), you will probably find that when you do except ExceptionType, Python has to check whether the exception raised is actually of ExceptionType or some other type. Just for the heck of it, let's see how long will it take if we omit that check and catch all exceptions.

made by @anthony

>>> timeit('''
... d = {}
... for c in s:
...   try:
...     d[c] += 1
...   except:
...     d[c] = 1
... ''', globals=locals())
3.3506563019982423

It does save some time, so one might be tempted to use this as some sort of optimization.
Don't do that! Or actually do. Do it now:

INTERLUDE 1

import time
while True:
  try:
    time.sleep(1)
  except:
    print("You're trapped in your own trap!")

You see? It catches KeyboardInterrupt, besides other things. In fact, it catches all the exceptions there are. Including ones you might not have even heard about, like SystemExit.

INTERLUDE 2

import sys
try:
  print("Goodbye. I'm going to die soon.")
  sys.exit()
except:
  print('BACK FROM THE DEAD!!!')

Now back to counting letters and numbers and other characters.

Playing catch-up

Exceptions aren't the way to go. You have to try hard to catch up with them, and when you finally do, they just throw up on you and then raise their eyebrows like it's your fault. Luckily brave fellows have paved our way so we can do away with exceptions, at least in this little exercise.

The dict class has a nice method – get – which allows us to retrieve an item from a dictionary, just like d[k]. Except when the key k is not in the dictionary, it can return a default value. Let's use that method instead of fiddling with exceptions.

credit goes to @Usman

>>> timeit('''
... d = {}
... for c in s:
...   d[c] = d.get(c, 0) + 1
... ''', globals=locals())
3.2133633289995487

Almost as fast as the set-based dict comprehension. On larger inputs, this one would probably be even faster.

Use the right tool for the job

For at least mildly knowledgeable Python programmer, the first thing that comes to mind is probably defaultdict. It does pretty much the same thing as the version above, except instead of a value, you give it a value factory. That might cause some overhead, because the value has to be "constructed" for each missing key individually. Let's see how it performs.

hope @AlexMartelli won't crucify me for from collections import defaultdict

>>> timeit('''
... dd = defaultdict(int)
... for c in s:
...   dd[c] += 1
... ''', globals=locals())
3.3430528169992613

Not that bad. I'd say the increase in execution time is a small tax to pay for the improved readability. However, we also favor performance, and we will not stop here. Let's take it further and prepopulate the dictionary with zeros. Then we won't have to check every time if the item is already there.

hats off to @sqram

>>> timeit('''
... d = dict.fromkeys(s, 0)
... for c in s:
...   d[c] += 1
... ''', globals=locals())
2.6081761489986093

That's good. Over three times as fast as Counter, yet still simple enough. Personally, this is my favorite in case you don't want to add new characters later. And even if you do, you can still do it. It's just less convenient than it would be in other versions:

d.update({ c: 0 for c in set(other_string) - d.keys() })


Practicality beats purity (except when it's not really practical)

Now a bit different kind of counter. @IdanK has come up with something interesting. Instead of using a hash table (a.k.a. dictionary a.k.a. dict), we can avoid the risk of hash collisions and consequent overhead of their resolution. We can also avoid the overhead of hashing the key, and the extra unoccupied table space. We can use a list. The ASCII values of characters will be indices and their counts will be values. As @IdanK has pointed out, this list gives us constant time access to a character's count. All we have to do is convert each character from str to int using the built-in function ord. That will give us an index into the list, which we will then use to increment the count of the character. So what we do is this: we initialize the list with zeros, do the job, and then convert the list into a dict. This dict will only contain those characters which have non-zero counts, in order to make it compliant with other versions.

As a side note, this technique is used in a linear-time sorting algorithm known as count sort or counting sort. It's very efficient, but the range of values being sorted is limited, since each value has to have its own counter. To sort a sequence of 32-bit integers, 4.3 billion counters would be needed.

>>> timeit('''
... counts = [0 for _ in range(256)]
... for c in s:
...   counts[ord(c)] += 1
... d = {chr(i): count for i,count in enumerate(counts) if count != 0}
... ''', globals=locals())
25.438595562001865

Ouch! Not cool! Let's try and see how long it takes when we omit building the dictionary.

>>> timeit('''
... counts = [0 for _ in range(256)]
... for c in s:
...   counts[ord(c)] += 1
... ''', globals=locals())
10.564866792999965

Still bad. But wait, what's [0 for _ in range(256)]? Can't we write it more simply? How about [0] * 256? That's cleaner. But will it perform better?

>>> timeit('''
... counts = [0] * 256
... for c in s:
...   counts[ord(c)] += 1
... ''', globals=locals())
3.290163638001104

Considerably. Now let's put the dictionary back in.

>>> timeit('''
... counts = [0] * 256
... for c in s:
...   counts[ord(c)] += 1
... d = {chr(i): count for i,count in enumerate(counts) if count != 0}
... ''', globals=locals())
18.000623562998953

Almost six times slower. Why does it take so long? Because when we enumerate(counts), we have to check every one of the 256 counts and see if it's zero. But we already know which counts are zero and which are not.

>>> timeit('''
... counts = [0] * 256
... for c in s:
...   counts[ord(c)] += 1
... d = {c: counts[ord(c)] for c in set(s)}
... ''', globals=locals())
5.826531438000529

It probably won't get much better than that, at least not for such a small input. Plus it's only usable for 8-bit EASCII characters. ? ?????!

And the winner is...

>>> timeit('''
... d = {}
... for c in s:
...   if c in d:
...     d[c] += 1
...   else:
...     d[c] = 1
... ''', globals=locals())
1.8509794599995075

Yep. Even if you have to check every time whether c is in d, for this input it's the fastest way. No pre-population of d will make it faster (again, for this input). It's a lot more verbose than Counter or defaultdict, but also more efficient.


That's all folks

This little exercise teaches us a lesson: when optimizing, always measure performance, ideally with your expected inputs. Optimize for the common case. Don't presume something is actually more efficient just because its asymptotic complexity is lower. And last but not least, keep readability in mind. Try to find a compromise between "computer-friendly" and "human-friendly".



UPDATE

I have been informed by @MartijnPieters of the function collections._count_elements available in Python 3.

Help on built-in function _count_elements in module _collections:

_count_elements(...)
    _count_elements(mapping, iterable) -> None

    Count elements in the iterable, updating the mappping

This function is implemented in C, so it should be faster, but this extra performance comes at a price. The price is incompatibility with Python 2 and possibly even future versions, since we're using a private function.

From the documentation:

[...] a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

That said, if you still want to save those 620 nanoseconds per iteration:

>>> timeit('''
... d = {}
... _count_elements(d, s)
... ''', globals=locals())
1.229239897998923



UPDATE 2: Large strings

I thought it might be a good idea to re-run the tests on some larger input, since a 16 character string is such a small input that all the possible solutions were quite comparably fast (1,000 iterations in under 30 milliseconds).

I decided to use the complete works of Shakespeare as a testing corpus, which turned out to be quite a challenge (since it's over 5MiB in size ). I just used the first 100,000 characters of it, and I had to limit the number of iterations from 1,000,000 to 1,000.

import urllib.request
url = 'https://ocw.mit.edu/ans7870/6/6.006/s08/lecturenotes/files/t8.shakespeare.txt'
s = urllib.request.urlopen(url).read(100_000)

collections.Counter was really slow on a small input, but the tables have turned

Counter(s)

=> 7.63926783799991

Naïve T(n2) time dictionary comprehension simply doesn't work

{c: s.count(c) for c in s}

=> 15347.603935000052s (tested on 10 iterations; adjusted for 1000)

Smart T(n) time dictionary comprehension works fine

{c: s.count(c) for c in set(s)}

=> 8.882608592999986

Exceptions are clumsy and slow

d = {}
for c in s:
  try:
    d[c] += 1
  except KeyError:
    d[c] = 1

=> 21.26615508399982

Omitting the exception type check doesn't save time (since the exception is only thrown a few times)

d = {}
for c in s:
  try:
    d[c] += 1
  except:
    d[c] = 1

=> 21.943328911999743

dict.get looks nice but runs slow

d = {}
for c in s:
  d[c] = d.get(c, 0) + 1

=> 28.530086210000007

collections.defaultdict isn't very fast either

dd = defaultdict(int)
for c in s:
  dd[c] += 1

=> 19.43012963199999

dict.fromkeys requires reading the (very long) string twice

d = dict.fromkeys(s, 0)
for c in s:
  d[c] += 1

=> 22.70960557699999

Using list instead of dict is neither nice nor fast

counts = [0 for _ in range(256)]
for c in s:
  counts[ord(c)] += 1

d = {chr(i): count for i,count in enumerate(counts) if count != 0}

=> 26.535474792000002

Leaving out the final conversion to dict doesn't help

counts = [0 for _ in range(256)]
for c in s:
  counts[ord(c)] += 1

=> 26.27811567400005

It doesn't matter how you construct the list, since it's not the bottleneck

counts = [0] * 256
for c in s:
  counts[ord(c)] += 1

=> 25.863524940000048


counts = [0] * 256
for c in s:
  counts[ord(c)] += 1

d = {chr(i): count for i,count in enumerate(counts) if count != 0}

=> 26.416733378000004

If you convert list to dict the "smart" way, it's even slower (since you iterate over the string twice)

counts = [0] * 256
for c in s:
  counts[ord(c)] += 1

d = {c: counts[ord(c)] for c in set(s)}

=> 29.492915620000076

The dict.__contains__ variant may be fast for small strings, but not so much for big ones

d = {}
for c in s:
  if c in d:
    d[c] += 1
  else:
    d[c] = 1

=> 23.773295123000025

collections._count_elements is about as fast as collections.Counter (which uses _count_elements internally)

d = {}
_count_elements(d, s)

=> 7.5814381919999505


Final verdict: Use collections.Counter unless you cannot or don't want to :)



Appendix: NumPy

The numpy package provides a method numpy.unique which accomplishes (almost) precisely what we want.

The way this method works is very different from all the above methods:

  • It first sorts a copy of the input using Quicksort, which is an O(n2) time operation in the worst case, albeit O(n log n) on average and O(n) in the best case.

  • Then it creates a "mask" array containing True at indices where a run of the same values begins, viz. at indices where the value differs from the previous value. Repeated values produce False in the mask. Example: [5,5,5,8,9,9] produces a mask [True, False, False, True, True, False].

  • This mask is then used to extract the unique values from the sorted input - unique_chars in the code below. In our example, they would be [5, 8, 9].

  • Positions of the True values in the mask are taken into an array, and the length of the input is appended at the end of this array. For the above example, this array would be [0, 3, 4, 6].

  • For this array, differences between its elements are calculated, eg. [3, 1, 2]. These are the respective counts of the elements in the sorted array - char_counts in the code below.

  • Finally, we create a dictionary by zipping unique_chars and char_counts: {5: 3, 8: 1, 9: 2}.


import numpy as np

def count_chars(s):
  # The following statement needs to be changed for different input types.
  # Our input `s` is actually of type `bytes`, so we use `np.frombuffer`.
  # For inputs of type `str`, change `np.frombuffer` to `np.fromstring`
  #  or transform the input into a `bytes` instance.
  arr = np.frombuffer(s, dtype=np.uint8)

  unique_chars, char_counts = np.unique(arr, return_counts=True)

  return dict(zip(unique_chars, char_counts))

For the test input (first 100,000 characters of the complete works of Shakespeare), this method performs better than any other tested here. But note that on a different input, this approach might yield worse performance than the other methods. Pre-sortedness of the input and number of repetitions per element are important factors affecting the performance.

count_chars(s)

=> 2.960809530000006


If you are thinking about using this method because it's over twice as fast as collections.Counter, consider this:

  • collections.Counter has linear time complexity. numpy.unique is linear at best, quadratic at worst.

  • The speedup is not really that significant - you save ~3.5 milliseconds per iteration on an input of length 100,000.

  • Using numpy.unique obviously requires numpy.

That considered, it seems reasonable to use Counter unless you need to be really fast. And in that case, you better know what you're doing or else you'll end up being slower with numpy than without it.



Appendix 2: A somewhat useful plot

I ran the 13 different methods above on prefixes of the complete works of Shakespeare and made an interactive plot. Note that in the plot, both prefixes and durations are displayed in logarithmic scale (the used prefixes are of exponentially increasing length). Click on the items in the legend to show/hide them in the plot.

Interactive plot (click!)

Click to open!

Most popular screen sizes/resolutions on Android phones

Another alternative to see popular android resolutions or aspect ratios is Unity statistics:

LATEST UNITY STATISTICS (on 2019.06 return http503) web arhive

Top on 2017-01:

Display Resolutions:

  • 1280 x 720: 28.9%
  • 1920 x 1080: 21.4%
  • 800 x 480: 10.3%
  • 854 x 480: 9.7%
  • 960 x 540: 8.9%
  • 1024 x 600: 7.8%
  • 1280 x 800: 5.0%
  • 2560 x 1440: 2.4%
  • 480 x 320: 1.2%
  • 1920 x 1200: 0.8%
  • 1024 x 768: 0.8%

Display Aspect Ratios:

  • 16:9: 72.4%
  • 5:3: 18.2%
  • 16:10: 6.2%
  • 4:3: 1.7%
  • 3:2: 1.2%
  • 5:4: 0.1%

How to split the filename from a full path in batch?

@echo off
Set filename="C:\Documents and Settings\All Users\Desktop\Dostips.cmd"
call :expand %filename%
:expand
set filename=%~nx1
echo The name of the file is %filename%
set folder=%~dp1
echo It's path is %folder%

Better naming in Tuple classes than "Item1", "Item2"

Reproducing my answer from this post as it is a better fit here.

Starting C# v7.0, now it is possible to name the tuple properties which earlier used to default to predefined names like Item1, Item2 and so on.

Naming the properties of Tuple Literals:

var myDetails = (MyName: "RBT_Yoga", MyAge: 22, MyFavoriteFood: "Dosa");
Console.WriteLine($"Name - {myDetails.MyName}, Age - {myDetails.MyAge}, Passion - {myDetails.MyFavoriteFood}");

The output on console:

Name - RBT_Yoga, Age - 22, Passion - Dosa

Returning Tuple (having named properties) from a method:

static void Main(string[] args)
{
    var empInfo = GetEmpInfo();
    Console.WriteLine($"Employee Details: {empInfo.firstName}, {empInfo.lastName}, {empInfo.computerName}, {empInfo.Salary}");
}

static (string firstName, string lastName, string computerName, int Salary) GetEmpInfo()
{
    //This is hardcoded just for the demonstration. Ideally this data might be coming from some DB or web service call
    return ("Rasik", "Bihari", "Rasik-PC", 1000);
}

The output on console:

Employee Details: Rasik, Bihari, Rasik-PC, 1000

Creating a list of Tuples having named properties

var tupleList = new List<(int Index, string Name)>
{
    (1, "cow"),
    (5, "chickens"),
    (1, "airplane")
};

foreach (var tuple in tupleList)
    Console.WriteLine($"{tuple.Index} - {tuple.Name}");

Output on console:

1 - cow 5 - chickens 1 - airplane

I hope I've covered everything. In case, there is anything which I've missed then please give me a feedback in comments.

Note: My code snippets are using string interpolation feature of C# v7 as detailed here.

Calculating arithmetic mean (one type of average) in Python

Instead of casting to float you can do following

def mean(nums):
    return sum(nums, 0.0) / len(nums)

or using lambda

mean = lambda nums: sum(nums, 0.0) / len(nums)

UPDATES: 2019-12-15

Python 3.8 added function fmean to statistics module. Which is faster and always returns float.

Convert data to floats and compute the arithmetic mean.

This runs faster than the mean() function and it always returns a float. The data may be a sequence or iterable. If the input dataset is empty, raises a StatisticsError.

fmean([3.5, 4.0, 5.25])

4.25

New in version 3.8.

How do you configure HttpOnly cookies in tomcat / java webapps?

httpOnly is supported as of Tomcat 6.0.19 and Tomcat 5.5.28.

See the changelog entry for bug 44382.

The last comment for bug 44382 states, "this has been applied to 5.5.x and will be included in 5.5.28 onwards." However, it does not appear that 5.5.28 has been released.

The httpOnly functionality can be enabled for all webapps in conf/context.xml:

<Context useHttpOnly="true">
...
</Context>

My interpretation is that it also works for an individual context by setting it on the desired Context entry in conf/server.xml (in the same manner as above).

SQL SERVER, SELECT statement with auto generate row id

You can do this directly in SQL2000, as per Microsoft's page: http://support.microsoft.com/default.aspx?scid=kb;en-us;186133

 select rank=count(*), a1.au_lname, a1.au_fname
   from authors a1, authors a2
   where a1.au_lname + a1.au_fname >= a2.au_lname + a2.au_fname
   group by a1.au_lname, a1.au_fname
   order by rank

The only problem with this approach is that (As Jeff says on SQL Server Central) it's a triangular join. So, if you have ten records this will be quick, if you have a thousand records it will be slow, and with a million records it may never complete!

See here for a better explanation of triangular joins: http://www.sqlservercentral.com/articles/T-SQL/61539/


What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

Kotlin:

You can also use CountDownTimer:

class Timer {
    companion object {
        @JvmStatic
        fun call(ms: Long, f: () -> Unit) {
            object : CountDownTimer(ms,ms){
                override fun onFinish() { f() }
                override fun onTick(millisUntilFinished: Long) {}
            }.start()
        }
    }
}

And in your code:

Timer.call(5000) { /*Whatever you want to execute after 5000 ms*/ }

iOS 7: UITableView shows under status bar

Adding to the top answer:

after the 2nd method did not initially seem to work I did some additional tinkering and have found the solution.

TLDR; the top answer's 2nd solution almost works, but for some versions of xCode ctrl+dragging to "Top Layout Guide" and selecting Vertical Spacing does nothing. However, by first adjusting the size of the Table View and then selecting "Top Space to Top Layout Guide" works


  1. Drag a blank ViewController onto the storyboard. View Controller

  2. Drag a UITableView object into the View. (Not UITableViewController). Position it in the very center using the blue layout guides.

Table View Center Image

  1. Drag a UITableViewCell into the TableView. This will be your prototype reuse cell, so don't forget to set it's Reuse Identifier under the Attributes tab or you'll get a crash.

Add Table View Cell Reuse Identifier

  1. Create your custom subclass of UIViewController, and add the <UITableViewDataSource, UITableViewDelegate> protocols. Don't forget to set your storyboard's ViewController to this class in the Identity Inspector.

  2. Create an outlet for your TableView in your implementation file, and name it "tableView"

Create Outlet tableView

  1. Right click the TableView and drag both the dataSource and the delegate to your ViewController.

dataSource delegate

Now for the part of not clipping into the status bar.

  1. Grab the top edge of your Table View and move it down to one of the dashed blue auto-layout guides that are near the top

resize

  1. Now, you can control drag from the Table View to the top and select Top Space to Top Layout Guide

Top Space to Top Layout Guide

  1. It will give you an error about ambiguous layout of TableView, just Add Missing Constraints and your done.

Add Missing Constraints

Now you can set up your table view like normal, and it won't clip the status bar!

How do I configure Apache 2 to run Perl CGI scripts?

If you have successfully installed Apache web server and Perl please follow the following steps to run cgi script using perl on ubuntu systems.

Before starting with CGI scripting it is necessary to configure apache server in such a way that it recognizes the CGI directory (where the cgi programs are saved) and allow for the execution of programs within that directory.

  1. In Ubuntu cgi-bin directory usually resides in path /usr/lib , if not present create the cgi-bin directory using the following command.cgi-bin should be in this path itself.

     mkdir /usr/lib/cgi-bin
    
  2. Issue the following command to check the permission status of the directory.

     ls -l /usr/lib | less
    

Check whether the permission looks as “drwxr-xr-x 2 root root 4096 2011-11-23 09:08 cgi- bin” if yes go to step 3.

If not issue the following command to ensure the appropriate permission for our cgi-bin directory.

     sudo chmod 755 /usr/lib/cgi-bin
     sudo chmod root.root /usr/lib/cgi-bin
  1. Give execution permission to cgi-bin directory

     sudo chmod 755 /usr/lib/cgi-bin
    

Thus your cgi-bin directory is ready to go. This is where you put all your cgi scripts for execution. Our next step is configure apache to recognize cgi-bin directory and allow execution of all programs in it as cgi scripts.

Configuring Apache to run CGI script using perl

  1. A directive need to be added in the configuration file of apache server so it knows the presence of CGI and the location of its directories. Initially go to location of configuration file of apache and open it with your favorite text editor

    cd /etc/apache2/sites-available/ 
    sudo gedit 000-default.conf
    
  2. Copy the below content to the file 000-default.conf between the line of codes “DocumentRoot /var/www/html/” and “ErrorLog $ {APACHE_LOG_DIR}/error.log”

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
    AllowOverride None
    Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
    Require all granted
    

  3. Restart apache server with the following code

    sudo service apache2 restart
    
  4. Now we need to enable cgi module which is present in newer versions of ubuntu by default

    sudo a2enmod cgi.load
    sudo a2enmod cgid.load
    
  5. At this point we can reload the apache webserver so that it reads the configuration files again.

    sudo service apache2 reload
    

The configuration part of apache is over now let us check it with a sample cgi perl program.

Testing it out

  1. Go to the cgi-bin directory and create a cgi file with extension .pl

    cd /usr/lib/cgi-bin/
    sudo gedit test.pl
    
  2. Copy the following code on test.pl and save it.

    #!/usr/bin/perl -w
    print “Content-type: text/html\r\n\r\n”;
    print “CGI working perfectly!! \n”;
    
  3. Now give the test.pl execution permission.

    sudo chmod 755 test.pl
    
  4. Now open that file in your web browser http://Localhost/cgi-bin/test.pl

  5. If you see the output “CGI working perfectly” you are ready to go.Now dump all your programs into the cgi-bin directory and start using them.

NB: Don't forget to give your new programs in cgi-bin, chmod 755 permissions so as to run it successfully without any internal server errors.

Reason: no suitable image found

This resolved my error-

Re-downloading the WWDR (Apple Worldwide Developer Relations Certification Authority), set to Use System Default as option.

How to assign the output of a command to a Makefile variable

Use the Make shell builtin like in MY_VAR=$(shell echo whatever)

me@Zack:~$make
MY_VAR IS whatever

me@Zack:~$ cat Makefile 
MY_VAR := $(shell echo whatever)

all:
    @echo MY_VAR IS $(MY_VAR)

How to export SQL Server database to MySQL?

You can use MySQL Workbench which provides a way to quickly migrate data and applications from Microsoft SQL Server to MySQL employing less time and effort.

This tool has a lot of cool features like:

  • Database migrations - enables migrations from Microsoft SQL Server, Sybase ASE and PostgreSQL.
  • Migration project management - allows migrations to be configured, copied, edited, executed and scheduled.

Read more http://www.mysql.com/products/workbench/migrate/

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

Using deadlydog's scheme,

Y => X => A => B,

my problem was when I built Y, the assemblies (A and B, all 15 of them) from X were not showing up in Y's bin folder.

I got it resolved by removing the reference X from Y, save, build, then re-add X reference (a project reference), and save, build, and A and B started showing up in Y's bin folder.

Cannot open backup device. Operating System error 5

In order to find out which user you need to give permission to do the restore process, you can follow the following steps:

You need to go to your server where SQL Server is installed. Find SQL Server Configuration Manager

enter image description here

Next, you need to go to "SQL Server Services"

enter image description here

Under your SQL Server (MSSQLSERVER) instance there will be an account with column "Logon As", in my case it is NT Service\MSSQLSERVER.

That is the account which you need to add under Security tab of your source .bak location and give that user the "Read" permissions so that the backup file can be read.

Let's say your backup file is present at "D:\Shared" folder, then you need to give permissions like this:

enter image description here

Can't perform a React state update on an unmounted component

I had this warning possibly because of calling setState from an effect hook (This is discussed in these 3 issues linked together).

Anyway, upgrading the react version removed the warning.

What is attr_accessor in Ruby?

Simply attr-accessor creates the getter and setter methods for the specified attributes

c# Best Method to create a log file

You might want to use the Event Log ! Here's how to access it from C# http://support.microsoft.com/kb/307024/en

But whatever is the method that you will use, I'd recommend to output to a file every time something is appended to the log rather than when your process exits, so you won't lose data in the case of crash or if your process is killed.

Make javascript alert Yes/No Instead of Ok/Cancel

"Confirm" in Javascript stops the whole process until it gets a mouse response on its buttons. If that is what you are looking for, you can refer jquery-ui but if you have nothing running behind your process while receiving the response and you control the flow programatically, take a look at this. You will have to hard-code everything by yourself but you have complete command over customization. https://www.w3schools.com/howto/howto_css_modals.asp

"dd/mm/yyyy" date format in excel through vba

I got it

Cells(1, 1).Value = StartDate
Cells(1, 1).NumberFormat = "dd/mm/yyyy"

Basically, I need to set the cell format, instead of setting the date.

Parser Error when deploy ASP.NET application

Very old question here, but I ran into the same error and none of the provided answers solved the issue.

My issue occurred because I manually changed the namespace and assembly names of the project after initial creation. Took me a little bit to notice that the namespace in the Inherits attribute didn't match the updated namespace.

Updating that namespace in the Global.asax markup to match the apps namespace fixed the error for me.

How to unset a JavaScript variable?

I am bit confused. If all you are wanting is for a variables value to not pass to another script then there is no need to delete the variable from the scope. Simply nullify the variable then explicit check if it is or is not null. Why go through the trouble of deleting the variable from scope? What purpose does this server that nullifying can not?

foo = null;
if(foo === null) or if(foo !== null)

How to get full REST request body using Jersey?

It does seem you would have to use a MessageBodyReader here. Here's an example, using jdom:

import org.jdom.Document;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.MediaType;
import javax.ws.rs.ext.MultivaluedMap;
import java.lang.reflect.Type;
import java.lang.annotation.Annotation;
import java.io.InputStream;

@Provider // this annotation is necessary!
@ConsumeMime("application/xml") // this is a hint to the system to only consume xml mime types
public class XMLMessageBodyReader implements MessageBodyReader<Document> {
  private SAXBuilder builder = new SAXBuilder();

  public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    // check if we're requesting a jdom Document
    return Document.class.isAssignableFrom(type);
  }

  public Document readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) {
    try {
      return builder.build(entityStream);
    }
    catch (Exception e) {
      // handle error somehow
    }
  } 
}

Add this class to the list of resources your jersey deployment will process (usually configured via web.xml, I think). You can then use this reader in one of your regular resource classes like this:

@Path("/somepath") @POST
public void handleXMLData(Document doc) {
  // do something with the document
}

I haven't verified that this works exactly as typed, but that's the gist of it. More reading here:

Determine if variable is defined in Python

For this particular case it's better to do a = None instead of del a. This will decrement reference count to object a was (if any) assigned to and won't fail when a is not defined. Note, that del statement doesn't call destructor of an object directly, but unbind it from variable. Destructor of object is called when reference count became zero.

javascript toISOString() ignores timezone offset

It will be very helpful to get current date and time.

var date=new Date();
  var today=new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString().replace(/T/, ' ').replace(/\..+/, '');  

CSS styling in Django forms

For larger form instead of writing css classed for every field you could to this

class UserRegistration(forms.ModelForm):
   # list charfields

   class Meta:
      model = User
      fields = ('username', 'first_name', 'last_name', 'email', 'password', 'password2')

   def __init__(self, *args, **kwargs):
      super(UserRegistration, self).__init__(*args, **kwargs)
      for field in self.fields:
         self.fields[field].widget.attrs['class'] = 'form-control'

How to parse a text file with C#

One way that I've found really useful in situations like this is to go old-school and use the Jet OLEDB provider, together with a schema.ini file to read large tab-delimited files in using ADO.Net. Obviously, this method is really only useful if you know the format of the file to be imported.

public void ImportCsvFile(string filename)
{
    FileInfo file = new FileInfo(filename);

    using (OleDbConnection con = 
            new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
            file.DirectoryName + "\";
            Extended Properties='text;HDR=Yes;FMT=TabDelimited';"))
    {
        using (OleDbCommand cmd = new OleDbCommand(string.Format
                                  ("SELECT * FROM [{0}]", file.Name), con))
        {
            con.Open();

            // Using a DataReader to process the data
            using (OleDbDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    // Process the current reader entry...
                }
            }

            // Using a DataTable to process the data
            using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd))
            {
                DataTable tbl = new DataTable("MyTable");
                adp.Fill(tbl);

                foreach (DataRow row in tbl.Rows)
                {
                    // Process the current row...
                }
            }
        }
    }
} 

Once you have the data in a nice format like a datatable, filtering out the data you need becomes pretty trivial.

Checking Maven Version

Type the command mvn -version directly in your maven directory, you probably haven't added it to your PATH. Here are explained details of how to add maven to your PATH variable (I guess you use Windows because you are talking about CMD).

Prevent scroll-bar from adding-up to the Width of page on Chrome

I can't add comment for the first answer and it's been a long time... but that demo has a problem:

if(b.prop('scrollHeight')>b.height()){
    normalw = window.innerWidth;
    scrollw = normalw - b.width();
    $('#container').css({marginRight:'-'+scrollw+'px'});
}

b.prop('scrollHeight') always equals b.height(),

I think it should be like this:

if(b.prop('scrollHeight')>window.innerHeight) ...

At last I recommend a method:

html {
 overflow-y: scroll;
}

:root {
  overflow-y: auto;
  overflow-x: hidden;
}

:root body {
  position: absolute;
}

body {
 width: 100vw;
 overflow: hidden;
}

Label word wrapping

Ironically, turning off AutoSize by setting it to false allowed me to get the label control dimensions to size it both vertically and horizontally which effectively allows word-wrapping to occur.

Can I make 'git diff' only the line numbers AND changed file names?

On git version 2.17.1, there isn't a built-in flag to achieve this purpose.

Here's an example command to filter out the filename and line numbers from an unified diff:

git diff --unified=0 | grep -Po '^diff --cc \K.*|^@@@( -[0-9]+,[0-9]+){2} \+\K[0-9]+(?=(,[0-9]+)? @@@)' | paste -s -d':'

For example, the unified diff:

$ git diff --unified=0
diff --cc foobar
index b436f31,df63c58..0000000
--- a/foobar
+++ b/foobar
@@@ -1,2 -1,2 +1,6 @@@ Line abov
++<<<<<<< HEAD
 +bar
++=======
+ foo
++>>>>>>> Commit message

Will result in:

? git diff --unified=0 | grep -Po '^diff --cc \K.*|^@@@( -[0-9]+,[0-9]+){2} \+\K[0-9]+(?=(,[0-9]+)? @@@)' | paste -s -d':'
foobar:1

To match the output of commands in common grep match results:

$ git diff --unified=0 | grep -Po '^diff --cc \K.*|^@@@( -[0-9]+,[0-9]+){2} \+\K[0-9]+(?=(,[0-9]+)? )| @@@.*' | sed -e '0~3{s/ @@@[ ]\?//}' | sed '2~3 s/$/\n1/g' | sed "N;N;N;s/\n/:/g"
foobar:1:1:Line abov
  1. grep -Po '^diff --cc \K.*|^@@@( -[0-9]+,[0-9]+){2} \+\K[0-9]+(?=(,[0-9]+)? ): Match filename from diff --cc <filename> OR Match line number from @@@ <from-file-range> <from-file-range> <to-file-range> OR Match remaining text after @@@.
  2. sed -e '0~3{s/ @@@[ ]\?//}': Remove @@@[ ]\? from every 3rd line to get the optional 1 line context before ++<<<<<<< HEAD.
  3. sed '2~3 s/$/\n1/g': Add \n1 every 3 lines between the 2nd and 3rd line for the column number.
  4. sed "N;N;N;s/\n/:/g": Join every 3 lines with a :.

How to find rows that have a value that contains a lowercase letter

I've done something like this to find out the lower cases.

SELECT *
FROM YourTable
  where BINARY_CHECKSUM(lower(ColumnName)) = BINARY_CHECKSUM(ColumnName)

Set EditText cursor color

Here @Jared Rummler's programatic setCursorDrawableColor() version adapted to work also on Android 9 Pie.

@SuppressWarnings({"JavaReflectionMemberAccess", "deprecation"})
public static void setCursorDrawableColor(EditText editText, int color) {

    try {
        Field cursorDrawableResField = TextView.class.getDeclaredField("mCursorDrawableRes");
        cursorDrawableResField.setAccessible(true);
        int cursorDrawableRes = cursorDrawableResField.getInt(editText);
        Field editorField = TextView.class.getDeclaredField("mEditor");
        editorField.setAccessible(true);
        Object editor = editorField.get(editText);
        Class<?> clazz = editor.getClass();
        Resources res = editText.getContext().getResources();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            Field drawableForCursorField = clazz.getDeclaredField("mDrawableForCursor");
            drawableForCursorField.setAccessible(true);
            Drawable drawable = res.getDrawable(cursorDrawableRes);
            drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
            drawableForCursorField.set(editor, drawable);
        } else {
            Field cursorDrawableField = clazz.getDeclaredField("mCursorDrawable");
            cursorDrawableField.setAccessible(true);
            Drawable[] drawables = new Drawable[2];
            drawables[0] = res.getDrawable(cursorDrawableRes);
            drawables[1] = res.getDrawable(cursorDrawableRes);
            drawables[0].setColorFilter(color, PorterDuff.Mode.SRC_IN);
            drawables[1].setColorFilter(color, PorterDuff.Mode.SRC_IN);
            cursorDrawableField.set(editor, drawables);
        }
    } catch (Throwable t) {
        Log.w(TAG, t);
    }
}

AngularJS ngClass conditional

Angular JS provide this functionality in ng-class Directive. In which you can put condition and also assign conditional class. You can achieve this in two different ways.

Type 1

<div ng-class="{0:'one', 1:'two',2:'three'}[status]"></div>

In this code class will be apply according to value of status value

if status value is 0 then apply class one

if status value is 1 then apply class two

if status value is 2 then apply class three


Type 2

<div ng-class="{1:'test_yes', 0:'test_no'}[status]"></div>

In which class will be apply by value of status

if status value is 1 or true then it will add class test_yes

if status value is 0 or false then it will add class test_no

display Java.util.Date in a specific format

You can use simple date format in Java using the code below

SimpleDateFormat simpledatafo = new SimpleDateFormat("dd/MM/yyyy");
Date newDate = new Date();
String expectedDate= simpledatafo.format(newDate);

How do you clone a Git repository into a specific folder?

Basic Git Repository Cloning

You clone a repository with

git clone [url]

For example, if you want to clone the Stanford University Drupal Open Framework Git library called open_framework, you can do so like this:

$ git clone git://github.com/SU-SWS/open_framework.git

That creates a directory named open_framework (at your current local file system location), initializes a .git directory inside it, pulls down all the data for that repository, and checks out a working copy of the latest version. If you go into the newly created open_framework directory, you’ll see the project files in there, ready to be worked on or used.

Cloning a Repository Into a Specific Local Folder

If you want to clone the repository into a directory named something other than open_framework, you can specify that as the next command-line option:

$ git clone git:github.com/SU-SWS/open_framework.git mynewtheme

That command does the same thing as the previous one, but the target directory is called mynewtheme.

Git has a number of different transfer protocols you can use. The previous example uses the git:// protocol, but you may also see http(s):// or user@server:/path.git, which uses the SSH transfer protocol.

How to get commit history for just one branch?

You can use only git log --oneline

width:auto for <input> fields

"Is there a definition of exactly what width:auto does mean? The CSS spec seems vague to me, but maybe I missed the relevant section."

No one actually answered the above part of the original poster's question.

Here's the answer: http://www.456bereastreet.com/archive/201112/the_difference_between_widthauto_and_width100/

As long as the value of width is auto, the element can have horizontal margin, padding and border without becoming wider than its container...

On the other hand, if you specify width:100%, the element’s total width will be 100% of its containing block plus any horizontal margin, padding and border... This may be what you want, but most likely it isn’t.

To visualise the difference I made an example: http://www.456bereastreet.com/lab/width-auto/

HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK

You could try to reinstall the ca-certificates package, or explicitly allow the certificate in question as described here.

How to plot data from multiple two column text files with legends in Matplotlib?

Assume your file looks like this and is named test.txt (space delimited):

1 2
3 4
5 6
7 8

Then:

#!/usr/bin/python

import numpy as np
import matplotlib.pyplot as plt

with open("test.txt") as f:
    data = f.read()

data = data.split('\n')

x = [row.split(' ')[0] for row in data]
y = [row.split(' ')[1] for row in data]

fig = plt.figure()

ax1 = fig.add_subplot(111)

ax1.set_title("Plot title...")    
ax1.set_xlabel('your x label..')
ax1.set_ylabel('your y label...')

ax1.plot(x,y, c='r', label='the data')

leg = ax1.legend()

plt.show()

Example plot:

I find that browsing the gallery of plots on the matplotlib site helpful for figuring out legends and axes labels.

How to add Class in <li> using wp_nav_menu() in Wordpress?

HERE WordPress add custom class in wp_nav_menu links

OR you can add class <li class='my_own_class'><a href=''>Link</a></li> from admin panel:

  1. Go to YOURSITEURL/wp-admin/nav-menus.php

  2. open SCREEN OPTIONS

  3. make checked CSS CLASSES, then you will see CSS Classes (optional) field in each menu link.

Server cannot set status after HTTP headers have been sent IIS7.5

I remember the part from this exception : "Cannot modify header information - headers already sent by" occurring in PHP. It occurred when the headers were already sent in the redirection phase and any other output was generated e.g.:

echo "hello"; header("Location:http://stackoverflow.com");

Pardon me and do correct me if I am wrong but I am still learning MS Technologies and I was trying to help.

jQuery equivalent to Prototype array.last()

SugarJS

It's not jQuery but another library you may find useful in addition to jQuery: Try SugarJS.

Sugar is a Javascript library that extends native objects with helpful methods. It is designed to be intuitive, unobtrusive, and let you do more with less code.

With SugarJS, you can do:

[1,2,3,4].last()    //  => 4

That means, your example does work out of the box:

var array = [1,2,3,4];
var lastEl = array.last();    //  => 4

More Info

how to kill the tty in unix

Try this:

skill -KILL -v pts/6

skill -KILL -v pts/9

skill -KILL -v pts/10

Installing SciPy with pip

On Fedora, this works:

sudo yum install -y python-pip
sudo yum install -y lapack lapack-devel blas blas-devel 
sudo yum install -y blas-static lapack-static
sudo pip install numpy
sudo pip install scipy

If you get any public key errors while downloading, add --nogpgcheck as parameter to yum, for example: yum --nogpgcheck install blas-devel

On Fedora 23 onwards, use dnf instead of yum.

CMake not able to find OpenSSL library

Note for Fedora 27 users: I had to install openssl-devel package to run the cmake successfully.

sudo dnf install openssl-devel

How to change the color of a CheckBox?

you can set android theme of the checkbox to get the color you want in your styles.xml add :

<style name="checkBoxStyle" parent="Base.Theme.AppCompat">
    <item name="colorAccent">CHECKEDHIGHLIGHTCOLOR</item>
    <item name="android:textColorSecondary">UNCHECKEDCOLOR</item>
</style>

then in your layout file :

<CheckBox
     android:theme="@style/checkBoxStyle"
     android:id="@+id/chooseItemCheckBox"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"/>

unlike using android:buttonTint="@color/CHECK_COLOR" this method works under Api 23

npm command to uninstall or prune unused packages in Node.js

If you're not worried about a couple minutes time to do so, a solution would be to rm -rf node_modules and npm install again to rebuild the local modules.

Most efficient way to remove special characters from string

Why do you think that your method is not efficient? It's actually one of the most efficient ways that you can do it.

You should of course read the character into a local variable or use an enumerator to reduce the number of array accesses:

public static string RemoveSpecialCharacters(this string str) {
   StringBuilder sb = new StringBuilder();
   foreach (char c in str) {
      if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '.' || c == '_') {
         sb.Append(c);
      }
   }
   return sb.ToString();
}

One thing that makes a method like this efficient is that it scales well. The execution time will be relative to the length of the string. There is no nasty surprises if you would use it on a large string.

Edit:
I made a quick performance test, running each function a million times with a 24 character string. These are the results:

Original function: 54.5 ms.
My suggested change: 47.1 ms.
Mine with setting StringBuilder capacity: 43.3 ms.
Regular expression: 294.4 ms.

Edit 2: I added the distinction between A-Z and a-z in the code above. (I reran the performance test, and there is no noticable difference.)

Edit 3:
I tested the lookup+char[] solution, and it runs in about 13 ms.

The price to pay is, of course, the initialization of the huge lookup table and keeping it in memory. Well, it's not that much data, but it's much for such a trivial function...

private static bool[] _lookup;

static Program() {
   _lookup = new bool[65536];
   for (char c = '0'; c <= '9'; c++) _lookup[c] = true;
   for (char c = 'A'; c <= 'Z'; c++) _lookup[c] = true;
   for (char c = 'a'; c <= 'z'; c++) _lookup[c] = true;
   _lookup['.'] = true;
   _lookup['_'] = true;
}

public static string RemoveSpecialCharacters(string str) {
   char[] buffer = new char[str.Length];
   int index = 0;
   foreach (char c in str) {
      if (_lookup[c]) {
         buffer[index] = c;
         index++;
      }
   }
   return new string(buffer, 0, index);
}

How to save user input into a variable in html and js

I mean a prompt script would work if the variable was not needed for the HTML aspect, even then in certain situations, a function could be used.

_x000D_
_x000D_
var save_user_input = prompt('what needs to be saved?');
//^ makes a variable of the prompt's answer
if (save_user_input == null) {
//^ if the answer is null, it is nothing
//however, if it is nothing, it is cancelled (as seen below). If it is "null" it is what the user said, then assigned to the variable(i think), but also null as in nothing in the prompt answer window, but ok pressed. So you cant do an or "null" (which would look like: if (save_user_input == null || "null") {)because (I also don't really know if this is right) the variable is "null". Very confusing
alert("cancelled");
//^ alerts the user the cancel button was pressed. No long explanation this time.
}
//^ is an end for the if (i got stumped as to why it wasn’t working and then realised this. very important to remember.)
else {
alert(save_user_input + " is what you said");
//^ alerts the user the variable and adds the string " is what you said" on the end
}
_x000D_
_x000D_
_x000D_

Passing html values into javascript functions

Simply put id attribute in your input text field -

<input type="text" maxlength="3" name="value" id="value" />

How to print without newline or space?

Using functools.partial to create a new function called printf

>>> import functools

>>> printf = functools.partial(print, end="")

>>> printf("Hello world\n")
Hello world

Easy way to wrap a function with default parameters.

Warning: Permanently added the RSA host key for IP address

If you are accessing your repositories over the SSH protocol, you will receive a warning message each time your client connects to a new IP address for github.com. As long as the IP address from the warning is in the range of IP addresses , you shouldn't be concerned. Specifically, the new addresses that are being added this time are in the range from 192.30.252.0 to 192.30.255.255. The warning message looks like this:

Warning: Permanently added the RSA host key for IP address '$IP' to the list of 

https://github.com/blog/1606-ip-address-changes

Sorting string array in C#

This code snippet is working properly enter image description here

How to extract a floating number from a string

Another approach that may be more readable is simple type conversion. I've added a replacement function to cover instances where people may enter European decimals:

>>> for possibility in "Current Level: -13.2 db or 14,2 or 3".split():
...     try:
...         str(float(possibility.replace(',', '.')))
...     except ValueError:
...         pass
'-13.2'
'14.2'
'3.0'

This has disadvantages too however. If someone types in "1,000", this will be converted to 1. Also, it assumes that people will be inputting with whitespace between words. This is not the case with other languages, such as Chinese.

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

How can I find all matches to a regular expression in Python?

Use re.findall or re.finditer instead.

re.findall(pattern, string) returns a list of matching strings.

re.finditer(pattern, string) returns an iterator over MatchObject objects.

Example:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']

[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']

MongoDB what are the default user and password?

For MongoDB earlier than 2.6, the command to add a root user is addUser (e.g.)

db.addUser({user:'admin',pwd:'<password>',roles:["root"]})

Remove NA values from a vector

I ran a quick benchmark comparing the two base approaches and it turns out that x[!is.na(x)] is faster than na.omit. User qwr suggested I try purrr::dicard also - this turned out to be massively slower (though I'll happily take comments on my implementation & test!)

microbenchmark::microbenchmark(
  purrr::map(airquality,function(x) {x[!is.na(x)]}), 
  purrr::map(airquality,na.omit),
  purrr::map(airquality, ~purrr::discard(.x, .p = is.na)),
  times = 1e6)

Unit: microseconds
                                                     expr    min     lq      mean median      uq       max neval cld
 purrr::map(airquality, function(x) {     x[!is.na(x)] })   66.8   75.9  130.5643   86.2  131.80  541125.5 1e+06 a  
                          purrr::map(airquality, na.omit)   95.7  107.4  185.5108  129.3  190.50  534795.5 1e+06  b 
  purrr::map(airquality, ~purrr::discard(.x, .p = is.na)) 3391.7 3648.6 5615.8965 4079.7 6486.45 1121975.4 1e+06   c

For reference, here's the original test of x[!is.na(x)] vs na.omit:

microbenchmark::microbenchmark(
    purrr::map(airquality,function(x) {x[!is.na(x)]}), 
    purrr::map(airquality,na.omit), 
    times = 1000000)


Unit: microseconds
                                              expr  min   lq      mean median    uq      max neval cld
 map(airquality, function(x) {     x[!is.na(x)] }) 53.0 56.6  86.48231   58.1  64.8 414195.2 1e+06  a 
                          map(airquality, na.omit) 85.3 90.4 134.49964   92.5 104.9 348352.8 1e+06   b

How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?

Here's a handy helper to prevent making the annoying GCD call over and over again:

public func delay(bySeconds seconds: Double, dispatchLevel: DispatchLevel = .main, closure: @escaping () -> Void) {
    let dispatchTime = DispatchTime.now() + seconds
    dispatchLevel.dispatchQueue.asyncAfter(deadline: dispatchTime, execute: closure)
}

public enum DispatchLevel {
    case main, userInteractive, userInitiated, utility, background
    var dispatchQueue: DispatchQueue {
        switch self {
        case .main:                 return DispatchQueue.main
        case .userInteractive:      return DispatchQueue.global(qos: .userInteractive)
        case .userInitiated:        return DispatchQueue.global(qos: .userInitiated)
        case .utility:              return DispatchQueue.global(qos: .utility)
        case .background:           return DispatchQueue.global(qos: .background)
        }
    }
}

Now you simply delay your code on the Main thread like this:

delay(bySeconds: 1.5) { 
    // delayed code
}

If you want to delay your code to different thread:

delay(bySeconds: 1.5, dispatchLevel: .background) { 
    // delayed code that will run on background thread
}

If you prefer a Framework that also has some more handy features then checkout HandySwift. You can add it to your project via Carthage then use it exactly like in the examples above:

import HandySwift    

delay(bySeconds: 1.5) { 
    // delayed code
}

How to set thymeleaf th:field value from other variable

You could approach this method.

Instead of using th:field use html id & name. Set value using th:value

<input class="form-control"
           type="text"
           th:value="${client.name}" id="clientName" name="clientName" />

Hope this will help you

Difference between jar and war in Java

A .war file has a specific structure in terms of where certain files will be. Other than that, yes, it's just a .jar.

Javascript checkbox onChange

Use an onclick event, because every click on a checkbox actually changes it.

How to deal with bad_alloc in C++?

You can catch it like any other exception:

try {
  foo();
}
catch (const std::bad_alloc&) {
  return -1;
}

Quite what you can usefully do from this point is up to you, but it's definitely feasible technically.



In general you cannot, and should not try, to respond to this error. bad_alloc indicates that a resource cannot be allocated because not enough memory is available. In most scenarios your program cannot hope to cope with that, and terminating soon is the only meaningful behaviour.

Worse, modern operating systems often over-allocate: on such systems, malloc and new can return a valid pointer even if there is not enough free memory left – std::bad_alloc will never be thrown, or is at least not a reliable sign of memory exhaustion. Instead, attempts to access the allocated memory will then result in a segmentation fault, which is not catchable (you can handle the segmentation fault signal, but you cannot resume the program afterwards).

The only thing you could do when catching std::bad_alloc is to perhaps log the error, and try to ensure a safe program termination by freeing outstanding resources (but this is done automatically in the normal course of stack unwinding after the error gets thrown if the program uses RAII appropriately).

In certain cases, the program may attempt to free some memory and try again, or use secondary memory (= disk) instead of RAM but these opportunities only exist in very specific scenarios with strict conditions:

  1. The application must ensure that it runs on a system that does not overcommit memory, i.e. it signals failure upon allocation rather than later.
  2. The application must be able to free memory immediately, without any further accidental allocations in the meantime.

It’s exceedingly rare that applications have control over point 1 — userspace applications never do, it’s a system-wide setting that requires root permissions to change.1

OK, so let’s assume you’ve fixed point 1. What you can now do is for instance use a LRU cache for some of your data (probably some particularly large business objects that can be regenerated or reloaded on demand). Next, you need to put the actual logic that may fail into a function that supports retry — in other words, if it gets aborted, you can just relaunch it:

lru_cache<widget> widget_cache;

double perform_operation(int widget_id) {
    std::optional<widget> maybe_widget = widget_cache.find_by_id(widget_id);
    if (not maybe_widget) {
        maybe_widget = widget_cache.store(widget_id, load_widget_from_disk(widget_id));
    }
    return maybe_widget->frobnicate();
}

…

for (int num_attempts = 0; num_attempts < MAX_NUM_ATTEMPTS; ++num_attempts) {
    try {
        return perform_operation(widget_id);
    } catch (std::bad_alloc const&) {
        if (widget_cache.empty()) throw; // memory error elsewhere.
        widget_cache.remove_oldest();
    }
}

// Handle too many failed attempts here.

But even here, using std::set_new_handler instead of handling std::bad_alloc provides the same benefit and would be much simpler.


1 If you’re creating an application that does control point 1, and you’re reading this answer, please shoot me an email, I’m genuinely curious about your circumstances.


What is the C++ Standard specified behavior of new in c++?

The usual notion is that if new operator cannot allocate dynamic memory of the requested size, then it should throw an exception of type std::bad_alloc.
However, something more happens even before a bad_alloc exception is thrown:

C++03 Section 3.7.4.1.3: says

An allocation function that fails to allocate storage can invoke the currently installed new_handler(18.4.2.2), if any. [Note: A program-supplied allocation function can obtain the address of the currently installed new_handler using the set_new_handler function (18.4.2.3).] If an allocation function declared with an empty exception-specification (15.4), throw(), fails to allocate storage, it shall return a null pointer. Any other allocation function that fails to allocate storage shall only indicate failure by throw-ing an exception of class std::bad_alloc (18.4.2.1) or a class derived from std::bad_alloc.

Consider the following code sample:

#include <iostream>
#include <cstdlib>

// function to call if operator new can't allocate enough memory or error arises
void outOfMemHandler()
{
    std::cerr << "Unable to satisfy request for memory\n";

    std::abort();
}

int main()
{
    //set the new_handler
    std::set_new_handler(outOfMemHandler);

    //Request huge memory size, that will cause ::operator new to fail
    int *pBigDataArray = new int[100000000L];

    return 0;
}

In the above example, operator new (most likely) will be unable to allocate space for 100,000,000 integers, and the function outOfMemHandler() will be called, and the program will abort after issuing an error message.

As seen here the default behavior of new operator when unable to fulfill a memory request, is to call the new-handler function repeatedly until it can find enough memory or there is no more new handlers. In the above example, unless we call std::abort(), outOfMemHandler() would be called repeatedly. Therefore, the handler should either ensure that the next allocation succeeds, or register another handler, or register no handler, or not return (i.e. terminate the program). If there is no new handler and the allocation fails, the operator will throw an exception.

What is the new_handler and set_new_handler?

new_handler is a typedef for a pointer to a function that takes and returns nothing, and set_new_handler is a function that takes and returns a new_handler.

Something like:

typedef void (*new_handler)();
new_handler set_new_handler(new_handler p) throw();

set_new_handler's parameter is a pointer to the function operator new should call if it can't allocate the requested memory. Its return value is a pointer to the previously registered handler function, or null if there was no previous handler.

How to handle out of memory conditions in C++?

Given the behavior of newa well designed user program should handle out of memory conditions by providing a proper new_handlerwhich does one of the following:

Make more memory available: This may allow the next memory allocation attempt inside operator new's loop to succeed. One way to implement this is to allocate a large block of memory at program start-up, then release it for use in the program the first time the new-handler is invoked.

Install a different new-handler: If the current new-handler can't make any more memory available, and of there is another new-handler that can, then the current new-handler can install the other new-handler in its place (by calling set_new_handler). The next time operator new calls the new-handler function, it will get the one most recently installed.

(A variation on this theme is for a new-handler to modify its own behavior, so the next time it's invoked, it does something different. One way to achieve this is to have the new-handler modify static, namespace-specific, or global data that affects the new-handler's behavior.)

Uninstall the new-handler: This is done by passing a null pointer to set_new_handler. With no new-handler installed, operator new will throw an exception ((convertible to) std::bad_alloc) when memory allocation is unsuccessful.

Throw an exception convertible to std::bad_alloc. Such exceptions are not be caught by operator new, but will propagate to the site originating the request for memory.

Not return: By calling abort or exit.

Regular expressions inside SQL Server

stored value in DB is: 5XXXXXX [where x can be any digit]

You don't mention data types - if numeric, you'll likely have to use CAST/CONVERT to change the data type to [n]varchar.

Use:

WHERE CHARINDEX(column, '5') = 1
  AND CHARINDEX(column, '.') = 0 --to stop decimals if needed
  AND ISNUMERIC(column) = 1

References:

i have also different cases like XXXX7XX for example, so it has to be generic.

Use:

WHERE PATINDEX('%7%', column) = 5
  AND CHARINDEX(column, '.') = 0 --to stop decimals if needed
  AND ISNUMERIC(column) = 1

References:

Regex Support

SQL Server 2000+ supports regex, but the catch is you have to create the UDF function in CLR before you have the ability. There are numerous articles providing example code if you google them. Once you have that in place, you can use:

  • 5\d{6} for your first example
  • \d{4}7\d{2} for your second example

For more info on regular expressions, I highly recommend this website.

What does appending "?v=1" to CSS and JavaScript URLs in link and script tags do?

As you can read before, the ?v=1 ensures that your browser gets the version 1 of the file. When you have a new version, you just have to append a different version number and the browser will forget about the old version and loads the new one.

There is a gulp plugin which takes care of version your files during the build phase, so you don't have to do it manually. It's handy and you can easily integrate it in you build process. Here's the link: gulp-annotate

How to loop through files matching wildcard in batch file

Assuming you have two programs that process the two files, process_in.exe and process_out.exe:

for %%f in (*.in) do (
    echo %%~nf
    process_in "%%~nf.in"
    process_out "%%~nf.out"
)

%%~nf is a substitution modifier, that expands %f to a file name only. See other modifiers in https://technet.microsoft.com/en-us/library/bb490909.aspx (midway down the page) or just in the next answer.

Styling Password Fields in CSS

When I needed to create similar dots in input[password] I use a custom font in base64 (with 2 glyphs see above 25CF and 2022)

SCSS styles

@font-face {
  font-family: 'pass';
  font-style: normal;
  font-weight: 400;
  src: url(data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAATsAA8AAAAAB2QAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAABWAAAABwAAAAcg9+z70dERUYAAAF0AAAAHAAAAB4AJwANT1MvMgAAAZAAAAA/AAAAYH7AkBhjbWFwAAAB0AAAAFkAAAFqZowMx2N2dCAAAAIsAAAABAAAAAQAIgKIZ2FzcAAAAjAAAAAIAAAACAAAABBnbHlmAAACOAAAALkAAAE0MwNYJ2hlYWQAAAL0AAAAMAAAADYPA2KgaGhlYQAAAyQAAAAeAAAAJAU+ATJobXR4AAADRAAAABwAAAAcCPoA6mxvY2EAAANgAAAAEAAAABAA5gFMbWF4cAAAA3AAAAAaAAAAIAAKAE9uYW1lAAADjAAAARYAAAIgB4hZ03Bvc3QAAASkAAAAPgAAAE5Ojr8ld2ViZgAABOQAAAAGAAAABuK7WtIAAAABAAAAANXulPUAAAAA1viLwQAAAADW+JM4eNpjYGRgYOABYjEgZmJgBEI2IGYB8xgAA+AANXjaY2BifMg4gYGVgYVBAwOeYEAFjMgcp8yiFAYHBl7VP8wx/94wpDDHMIoo2DP8B8kx2TLHACkFBkYA8/IL3QB42mNgYGBmgGAZBkYGEEgB8hjBfBYGDyDNx8DBwMTABmTxMigoKKmeV/3z/z9YJTKf8f/X/4/vP7pldosLag4SYATqhgkyMgEJJnQFECcMOGChndEAfOwRuAAAAAAiAogAAQAB//8AD3jaY2BiUGJgYDRiWsXAzMDOoLeRkUHfZhM7C8Nbo41srHdsNjEzAZkMG5lBwqwg4U3sbIx/bDYxgsSNBRUF1Y0FlZUYBd6dOcO06m+YElMa0DiGJIZUxjuM9xjkGRhU2djZlJXU1UDQ1MTcDASNjcTFQFBUBGjYEkkVMJCU4gcCKRTeHCk+fn4+KSllsJiUJEhMUgrMUQbZk8bgz/iA8SRR9qzAY087FjEYD2QPDDAzMFgyAwC39TCRAAAAeNpjYGRgYADid/fqneL5bb4yyLMwgMC1H90HIfRkCxDN+IBpFZDiYGAC8QBbSwuceNpjYGRgYI7594aBgcmOAQgYHzAwMqACdgBbWQN0AAABdgAiAAAAAAAAAAABFAAAAj4AYgI+AGYB9AAAAAAAKgAqACoAKgBeAJIAmnjaY2BkYGBgZ1BgYGIAAUYGBNADEQAFQQBaAAB42o2PwUrDQBCGvzVV9GAQDx485exBY1CU3PQgVgIFI9prlVqDwcZNC/oSPoKP4HNUfQLfxYN/NytCe5GwO9/88+/MBAh5I8C0VoAtnYYNa8oaXpAn9RxIP/XcIqLreZENnjwvyfPieVVdXj2H7DHxPJH/2/M7sVn3/MGyOfb8SWjOGv4K2DRdctpkmtqhos+D6ISh4kiUUXDj1Fr3Bc/Oc0vPqec6A8aUyu1cdTaPZvyXyqz6Fm5axC7bxHOv/r/dnbSRXCk7+mpVrOqVtFqdp3NKxaHUgeod9cm40rtrzfrt2OyQa8fppCO9tk7d1x0rpiQcuDuRkjjtkHt16ctbuf/radZY52/PnEcphXpZOcofiEZNcQAAeNpjYGIAg///GBgZsAF2BgZGJkZmBmaGdkYWRla29JzKggxD9tK8TAMDAxc2D0MLU2NjENfI1M0ZACUXCrsAAAABWtLiugAA) format('woff');
}

input.password {
  font-family: 'pass', 'Roboto', Helvetica, Arial, sans-serif ;
  font-size: 18px;
  &::-webkit-input-placeholder {
    transform: scale(0.77);
    transform-origin: 0 50%;
  }
  &::-moz-placeholder {
    font-size: 14px;
    opacity: 1;
  }
  &:-ms-input-placeholder {
    font-size: 14px;
    font-family: 'Roboto', Helvetica, Arial, sans-serif;
  }

After that, I got identical display input[password]

How to re-render flatlist?

For quick and simple solution Try:

  1. set extra data to a boolean value.

    extraData={this.state.refresh}

  2. Toggle the value of boolean state when you want to re-render/refresh list

    this.setState({ 
        refresh: !this.state.refresh
    })
    

Import txt file and having each line as a list

Create a list of lists:

with open("/path/to/file") as file:
    lines = []
    for line in file:
        # The rstrip method gets rid of the "\n" at the end of each line
        lines.append(line.rstrip().split(","))

How to use the PRINT statement to track execution as stored procedure is running?

Can I just ask about the long term need for this facility - is it for debuging purposes?

If so, then you may want to consider using a proper debugger, such as the one found in Visual Studio, as this allows you to step through the procedure in a more controlled way, and avoids having to constantly add/remove PRINT statement from the procedure.

Just my opinion, but I prefer the debugger approach - for code and databases.

How to split data into training/testing sets using sample function

My solution is basically the same as dickoa's but a little easier to interpret:

data(mtcars)
n = nrow(mtcars)
trainIndex = sample(1:n, size = round(0.7*n), replace=FALSE)
train = mtcars[trainIndex ,]
test = mtcars[-trainIndex ,]

Standard Android menu icons, for example refresh

You can get the icons from the android sdk they are in this folder

$android-sdk\platforms\android-xx\data\res

Getting the current Fragment instance in the viewpager

I have used the following:

 int index = vpPager.getCurrentItem();
 MyPagerAdapter adapter = ((MyPagerAdapter)vpPager.getAdapter());
 MyFragment suraVersesFragment = (MyFragment)adapter.getRegisteredFragment(index);

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

I came to this question via Google, searching for a way to convert an already loaded image to grayscale.

Here is a way to do it with SciPy:

import scipy.misc
import scipy.ndimage

# Load an example image
# Use scipy.ndimage.imread(file_name, mode='L') if you have your own
img = scipy.misc.face()

# Convert the image
R = img[:, :, 0]
G = img[:, :, 1]
B = img[:, :, 2]
img_gray = R * 299. / 1000 + G * 587. / 1000 + B * 114. / 1000

# Show the image
scipy.misc.imshow(img_gray)

How to start rails server?

in rails 2.3.X,just type following command to start rails server on linux

script/server

and for more help read "README" file which is already created in rails project folder

Decimal to Hexadecimal Converter in Java

One possible solution:

import java.lang.StringBuilder;

class Test {
  private static final int sizeOfIntInHalfBytes = 8;
  private static final int numberOfBitsInAHalfByte = 4;
  private static final int halfByte = 0x0F;
  private static final char[] hexDigits = { 
    '0', '1', '2', '3', '4', '5', '6', '7', 
    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  };

  public static String decToHex(int dec) {
    StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes);
    hexBuilder.setLength(sizeOfIntInHalfBytes);
    for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i)
    {
      int j = dec & halfByte;
      hexBuilder.setCharAt(i, hexDigits[j]);
      dec >>= numberOfBitsInAHalfByte;
    }
    return hexBuilder.toString(); 
  }

  public static void main(String[] args) {
     int dec = 305445566;
     String hex = decToHex(dec);
     System.out.println(hex);       
  }
}

Output:

1234BABE

Anyway, there is a library method for this:

String hex = Integer.toHexString(dec);

tomcat - CATALINA_BASE and CATALINA_HOME variables

I can't say I know the best practice, but here's my perspective.

Are you using these variables for anything?

Personally, I haven't needed to change neither, on Linux nor Windows, in environments varying from development to production. Unless you are doing something particular that relies on them, chances are you could leave them alone.

catalina.sh sets the variables that Tomcat needs to work out of the box. It also says that CATALINA_BASE is optional:

#   CATALINA_HOME   May point at your Catalina "build" directory.
#
#   CATALINA_BASE   (Optional) Base directory for resolving dynamic portions
#                   of a Catalina installation.  If not present, resolves to
#                   the same directory that CATALINA_HOME points to.

I'm pretty sure you'll find out whether or not your setup works when you start your server.

Hibernate Union alternatives

I have to agree with Vladimir. I too looked into using UNION in HQL and couldn't find a way around it. The odd thing was that I could find (in the Hibernate FAQ) that UNION is unsupported, bug reports pertaining to UNION marked 'fixed', newsgroups of people saying that the statements would be truncated at UNION, and other newsgroups of people reporting it works fine... After a day of mucking with it, I ended up porting my HQL back to plain SQL, but doing it in a View in the database would be a good option. In my case, parts of the query were dynamically generated, so I had to build the SQL in the code instead.

How to convert date to timestamp?

You need just to reverse your date digit and change - with ,:

new Date(2012,01,26).getTime(); // 02 becomes 01 because getMonth() method returns the month (from 0 to 11)

In your case:

var myDate="26-02-2012";
myDate=myDate.split("-");
new Date(parseInt(myDate[2], 10), parseInt(myDate[1], 10) - 1 , parseInt(myDate[0]), 10).getTime();

P.S. UK locale does not matter here.

Print the contents of a DIV

i used Bill Paetzke answer to print a div contain images but it didn't work with google chrome

i just needed to add this line myWindow.onload=function(){ to make it work and here is the full code

<html>
<head>
    <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js"> </script>
    <script type="text/javascript">
        function PrintElem(elem) {
            Popup($(elem).html());
        }

        function Popup(data) {
            var myWindow = window.open('', 'my div', 'height=400,width=600');
            myWindow.document.write('<html><head><title>my div</title>');
            /*optional stylesheet*/ //myWindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
            myWindow.document.write('</head><body >');
            myWindow.document.write(data);
            myWindow.document.write('</body></html>');
            myWindow.document.close(); // necessary for IE >= 10

            myWindow.onload=function(){ // necessary if the div contain images

                myWindow.focus(); // necessary for IE >= 10
                myWindow.print();
                myWindow.close();
            };
        }
    </script>
</head>
<body>
    <div id="myDiv">
        This will be printed.
        <img src="image.jpg"/>
    </div>
    <div>
        This will not be printed.
    </div>
    <div id="anotherDiv">
        Nor will this.
    </div>
    <input type="button" value="Print Div" onclick="PrintElem('#myDiv')" />
</body>
</html>

also if someone just need to print a div with id he doesn't need to load jquery

here is pure javascript code to do this

<html>
<head>
    <script type="text/javascript">
        function PrintDiv(id) {
            var data=document.getElementById(id).innerHTML;
            var myWindow = window.open('', 'my div', 'height=400,width=600');
            myWindow.document.write('<html><head><title>my div</title>');
            /*optional stylesheet*/ //myWindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
            myWindow.document.write('</head><body >');
            myWindow.document.write(data);
            myWindow.document.write('</body></html>');
            myWindow.document.close(); // necessary for IE >= 10

            myWindow.onload=function(){ // necessary if the div contain images

                myWindow.focus(); // necessary for IE >= 10
                myWindow.print();
                myWindow.close();
            };
        }
    </script>
</head>
<body>
    <div id="myDiv">
        This will be printed.
        <img src="image.jpg"/>
    </div>
    <div>
        This will not be printed.
    </div>
    <div id="anotherDiv">
        Nor will this.
    </div>
    <input type="button" value="Print Div" onclick="PrintDiv('myDiv')" />
</body>
</html>

i hope this can help someone

How to host a Node.Js application in shared hosting

You should look for a hosting company that provides such feature, but standard simple static+PHP+MySQL hosting won't let you use node.js.

You need either find a hosting designed for node.js or buy a Virtual Private Server and install it yourself.

Can an ASP.NET MVC controller return an Image?

To expland on Dyland's response slightly:

Three classes implement the FileResult class:

System.Web.Mvc.FileResult
      System.Web.Mvc.FileContentResult
      System.Web.Mvc.FilePathResult
      System.Web.Mvc.FileStreamResult

They're all fairly self explanatory:

  • For file path downloads where the file exists on disk, use FilePathResult - this is the easiest way and avoids you having to use Streams.
  • For byte[] arrays (akin to Response.BinaryWrite), use FileContentResult.
  • For byte[] arrays where you want the file to download (content-disposition: attachment), use FileStreamResult in a similar way to below, but with a MemoryStream and using GetBuffer().
  • For Streams use FileStreamResult. It's called a FileStreamResult but it takes a Stream so I'd guess it works with a MemoryStream.

Below is an example of using the content-disposition technique (not tested):

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult GetFile()
    {
        // No need to dispose the stream, MVC does it for you
        string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "myimage.png");
        FileStream stream = new FileStream(path, FileMode.Open);
        FileStreamResult result = new FileStreamResult(stream, "image/png");
        result.FileDownloadName = "image.png";
        return result;
    }

How to pad zeroes to a string?

>>> '99'.zfill(5)
'00099'
>>> '99'.rjust(5,'0')
'00099'

if you want the opposite:

>>> '99'.ljust(5,'0')
'99000'

error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

If you use Unicode Character Set, but the entry wasn't set, you can specify /ENTRY:"wWinMainCRTStartup"

Best practices for SQL varchar column length

The best value is the one that is right for the data as defined in the underlying domain.

For some domains, VARCHAR(10) is right for the Name attribute, for other domains VARCHAR(255) might be the best choice.

Checking that a List is not empty in Hamcrest

This is fixed in Hamcrest 1.3. The below code compiles and does not generate any warnings:

// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, is(not(empty())));

But if you have to use older version - instead of bugged empty() you could use:

hasSize(greaterThan(0))
(import static org.hamcrest.number.OrderingComparison.greaterThan; or
import static org.hamcrest.Matchers.greaterThan;)

Example:

// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, hasSize(greaterThan(0)));

The most important thing about above solutions is that it does not generate any warnings. The second solution is even more useful if you would like to estimate minimum result size.

How to use requirements.txt to install all dependencies in a python project

pip install -r requirements.txt for python 2.x

pip3 install -r requirements.txt for python 3.x (in case multiple versions are installed)

How to get two or more commands together into a batch file

if I understand you right (not sure), the start parameter /D should help you:

start "cmd" /D %PathName% %comd%

/D sets the start-directory (see start /?)

remove inner shadow of text input

This is the solution for mobile safari:

-webkit-appearance: none;

as suggested here: Remove textarea inner shadow on Mobile Safari (iPhone)

Python JSON encoding

Python lists translate to JSON arrays. What it is giving you is a perfectly valid JSON string that could be used in a Javascript application. To get what you expected, you would need to use a dict:

>>> json.dumps({'apple': 'cat', 'banana':'dog', 'pear':'fish'})
'{"pear": "fish", "apple": "cat", "banana": "dog"}'

Replace words in a string - Ruby

First, you don't declare the type in Ruby, so you don't need the first string.

To replace a word in string, you do: sentence.gsub(/match/, "replacement").

How to check if a database exists in SQL Server?

From a Microsoft's script:

DECLARE @dbname nvarchar(128)
SET @dbname = N'Senna'

IF (EXISTS (SELECT name 
FROM master.dbo.sysdatabases 
WHERE ('[' + name + ']' = @dbname 
OR name = @dbname)))

-- code mine :)
PRINT 'db exists'

Which header file do you include to use bool type in c in linux?

bool is just a macro that expands to _Bool. You can use _Bool with no #include very much like you can use int or double; it is a C99 keyword.

The macro is defined in <stdbool.h> along with 3 other macros.

The macros defined are

  • bool: macro expands to _Bool
  • false: macro expands to 0
  • true: macro expands to 1
  • __bool_true_false_are_defined: macro expands to 1

Why do people say that Ruby is slow?

First of all, do you care about what others say about the language you like? When it does the job it has to do, you're fine.

OO isn't the fastest way to execute code, but it does help in creating the code. Smart code is always faster than dumb code and useless loops. I'm an DBA and see a lot of these useless loops, drop them, use better code and queries and application is faster, much faster. Do you care about the last microsecond? You might have languages optimized for speed, others just do the job they have to do and can be maintained by many different programmers.

It's all just a choice.

Notification bar icon turns white in Android 5 Lollipop

Another option is to take advantage of version-specific drawable (mipmap) directories to supply different graphics for Lollipop and above.

In my app, the "v21" directories contain icons with transparent text while the other directories contain non-transparent version (for versions of Android older than Lollipop).

File system

Which should look something like this:

Android Studio

This way, you don't need to check for version numbers in code, e.g.

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.mipmap.ic_notification)
        .setContentTitle(title)
        .setContentText(message)
        .setAutoCancel(true)
        .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

Likewise, you can reference "ic_notification" (or whatever you choose to call it) in your GCM payload if you use the "icon" attribute.

https://developers.google.com/cloud-messaging/http-server-ref#notification-payload-support

Excel function to get first word from sentence in other cell

I found this on exceljet.net and works for me:

=LEFT(B4,FIND(" ",B4)-1)

django admin - add custom form fields that are not part of the model

Django 2.1.1 The primary answer got me halfway to answering my question. It did not help me save the result to a field in my actual model. In my case I wanted a textfield that a user could enter data into, then when a save occurred the data would be processed and the result put into a field in the model and saved. While the original answer showed how to get the value from the extra field, it did not show how to save it back to the model at least in Django 2.1.1

This takes the value from an unbound custom field, processes, and saves it into my real description field:

class WidgetForm(forms.ModelForm):
    extra_field = forms.CharField(required=False)

    def processData(self, input):
        # example of error handling
        if False:
            raise forms.ValidationError('Processing failed!')

        return input + " has been processed"

    def save(self, commit=True):
        extra_field = self.cleaned_data.get('extra_field', None)

        # self.description = "my result" note that this does not work

        # Get the form instance so I can write to its fields
        instance = super(WidgetForm, self).save(commit=commit)

        # this writes the processed data to the description field
        instance.description = self.processData(extra_field)

        if commit:
            instance.save()

        return instance

    class Meta:
        model = Widget
        fields = "__all__"

Initializing C# auto-properties

Update - the answer below was written before C# 6 came along. In C# 6 you can write:

public class Foo
{
    public string Bar { get; set; } = "bar";
}

You can also write read-only automatically-implemented properties, which are only writable in the constructor (but can also be given a default initial value):

public class Foo
{
    public string Bar { get; }

    public Foo(string bar)
    {
        Bar = bar;
    }
}

It's unfortunate that there's no way of doing this right now. You have to set the value in the constructor. (Using constructor chaining can help to avoid duplication.)

Automatically implemented properties are handy right now, but could certainly be nicer. I don't find myself wanting this sort of initialization as often as a read-only automatically implemented property which could only be set in the constructor and would be backed by a read-only field.

This hasn't happened up until and including C# 5, but is being planned for C# 6 - both in terms of allowing initialization at the point of declaration, and allowing for read-only automatically implemented properties to be initialized in a constructor body.

Execute method on startup in Spring

What we have done was extending org.springframework.web.context.ContextLoaderListener to print something when the context starts.

public class ContextLoaderListener extends org.springframework.web.context.ContextLoaderListener
{
    private static final Logger logger = LoggerFactory.getLogger( ContextLoaderListener.class );

    public ContextLoaderListener()
    {
        logger.info( "Starting application..." );
    }
}

Configure the subclass then in web.xml:

<listener>
    <listener-class>
        com.mycomp.myapp.web.context.ContextLoaderListener
    </listener-class>
</listener>

What is System, out, println in System.out.println() in Java

System is a final class from the java.lang package.

out is a class variable of type PrintStream declared in the System class.

println is a method of the PrintStream class.

How to see the CREATE VIEW code for a view in PostgreSQL?

If you want an ANSI SQL-92 version:

select view_definition from information_schema.views where table_name = 'view_name';

Send response to all clients except sender

Other cases

io.of('/chat').on('connection', function (socket) {
    //sending to all clients in 'room' and you
    io.of('/chat').in('room').emit('message', "data");
};

Turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server

As the error information said first please try to increase the timeout value in the both the client side and service side as following:

<basicHttpBinding>
    <binding name="basicHttpBinding_ACRMS" maxBufferSize="2147483647"
      maxReceivedMessageSize="2147483647"
      openTimeout="00:20:00" 
      receiveTimeout="00:20:00" closeTimeout="00:20:00"
      sendTimeout="00:20:00">
      <readerQuotas maxDepth="32" maxStringContentLength="2097152"
        maxArrayLength="2097152" maxBytesPerRead="4006" maxNameTableCharCount="16384" />
    </binding>

Then please do not forget to apply this binding configuration to the endpoint by doing the following:

<endpoint address="" binding="basicHttpBinding" 
      bindingConfiguration="basicHttpBinding_ACRMS"
      contract="MonitorRAM.IService1" />

If the above can not help, it will be better if you can try to upload your main project here, then I want to have a test in my side.

How to check if a string array contains one string in JavaScript?

Create this function prototype:

Array.prototype.contains = function ( needle ) {
   for (i in this) {
      if (this[i] == needle) return true;
   }
   return false;
}

and then you can use following code to search in array x

if (x.contains('searchedString')) {
    // do a
}
else
{
      // do b
}

Best way to update data with a RecyclerView adapter

RecyclerView's Adapter doesn't come with many methods otherwise available in ListView's adapter. But your swap can be implemented quite simply as:

class MyRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
   List<Data> data;
   ...

    public void swap(ArrayList<Data> datas)
    {
        data.clear();
        data.addAll(datas);
        notifyDataSetChanged();     
    }
}

Also there is a difference between

list.clear();
list.add(data);

and

list = newList;

The first is reusing the same list object. The other is dereferencing and referencing the list. The old list object which can no longer be reached will be garbage collected but not without first piling up heap memory. This would be the same as initializing new adapter everytime you want to swap data.

JDBC ResultSet: I need a getDateTime, but there is only getDate and getTimeStamp

this worked:

    Date date = null;
    String dateStr = rs.getString("doc_date");
    if (dateStr != null) {
        date = dateFormat.parse(dateStr);
    }

using SimpleDateFormat.

Error running android: Gradle project sync failed. Please fix your project and try again

it looks different from one situation to another. for me i did an installation and update a lot of things that the sdk manager said to then i had this problem. all i did was: from file -> Invalidate caches/Restart (a dialog will pop-up) choose Invalidate and restart.

after the restart is done. everything was fixed but i needed to create a new emulator and delete the old one. (android studio 1.3.1) (one professional must edit this to be more understandable) . . . Here everything was fine, but your machines also needs restart because some system files are changed, to sync them we have to restart the system.

How can I have a newline in a string in sh?

  1. The only simple alternative is to actually type a new line in the variable:

    $ STR='new
    line'
    $ printf '%s' "$STR"
    new
    line
    

    Yes, that means writing Enter where needed in the code.

  2. There are several equivalents to a new line character.

    \n           ### A common way to represent a new line character.
    \012         ### Octal value of a new line character.
    \x0A         ### Hexadecimal value of a new line character.
    

    But all those require "an interpretation" by some tool (POSIX printf):

    echo -e "new\nline"           ### on POSIX echo, `-e` is not required.
    printf 'new\nline'            ### Understood by POSIX printf.
    printf 'new\012line'          ### Valid in POSIX printf.
    printf 'new\x0Aline'       
    printf '%b' 'new\0012line'    ### Valid in POSIX printf.
    

    And therefore, the tool is required to build a string with a new-line:

    $ STR="$(printf 'new\nline')"
    $ printf '%s' "$STR"
    new
    line
    
  3. In some shells, the sequence $' is an special shell expansion. Known to work in ksh93, bash and zsh:

    $ STR=$'new\nline'
    
  4. Of course, more complex solutions are also possible:

    $ echo '6e65770a6c696e650a' | xxd -p -r
    new
    line
    

    Or

    $ echo "new line" | sed 's/ \+/\n/g'
    new
    line
    

Replace Default Null Values Returned From Left Outer Join

MySQL

COALESCE(field, 'default')

For example:

  SELECT
    t.id,
    COALESCE(d.field, 'default')
  FROM
     test t
  LEFT JOIN
     detail d ON t.id = d.item

Also, you can use multiple columns to check their NULL by COALESCE function. For example:

mysql> SELECT COALESCE(NULL, 1, NULL);
        -> 1
mysql> SELECT COALESCE(0, 1, NULL);
        -> 0
mysql> SELECT COALESCE(NULL, NULL, NULL);
        -> NULL

Do I commit the package-lock.json file created by npm 5?

Yes, it's a standard practice to commit package-lock.json.

The main reason for committing package-lock.json is that everyone in the project is on the same package version.

Pros:

  • If you follow strict versioning and don't allow updating to major versions automatically to save yourself from backward-incompatible changes in third-party packages committing package-lock helps a lot.
  • If you update a particular package, it gets updated in package-lock.json and everyone using the repository gets updated to that particular version when they take the pull of your changes.

Cons:

  • It can make your pull requests look ugly :)

npm install won't make sure that everyone in the project is on the same package version. npm ci will help with this.

XCOPY switch to create specified directory if it doesn't exist?

Answer to use "/I" is working but with little trick - in target you must end with character \ to tell xcopy that target is directory and not file!

Example:

xcopy "$(TargetDir)$(TargetName).dll" "$(SolutionDir)_DropFolder" /F /R /Y /I

does not work and return code 2, but this one:

xcopy "$(TargetDir)$(TargetName).dll" "$(SolutionDir)_DropFolder\" /F /R /Y /I

Command line arguments used in my sample:

/F - Displays full source & target file names

/R - This will overwrite read-only files

/Y - Suppresses prompting to overwrite an existing file(s)

/I - Assumes that destination is directory (but must ends with \)

List all kafka topics

to see that topic if we run the list topic command:

$ bin/kafka-topics.sh --list --zookeeper localhost:2181

To check if the data is landing in Kafka:

$ bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic twitterstream --from-beginning

warning: incompatible implicit declaration of built-in function ‘xyz’

I met these warnings on mempcpy function. Man page says this function is a GNU extension and synopsis shows:

#define _GNU_SOURCE
#include <string.h>

When #define is added to my source before the #include, declarations for the GNU extensions are made visible and warnings disappear.

Cannot connect to local SQL Server with Management Studio

Try to see, if the service "SQL Server (MSSQLSERVER)" it's started, this solved my problem.

How to use Git Revert

The reason reset and revert tend to come up a lot in the same conversations is because different version control systems use them to mean different things.

In particular, people who are used to SVN or P4 who want to throw away uncommitted changes to a file will often reach for revert before being told that they actually want reset.

Similarly, the revert equivalent in other VCSes is often called rollback or something similar - but "rollback" can also mean "I want to completely discard the last few commits", which is appropriate for reset but not revert. So, there's a lot of confusion where people know what they want to do, but aren't clear on which command they should be using for it.

As for your actual questions about revert...

Okay, you're going to use git revert but how?

git revert first-bad-commit..last-bad-commit

And after running git revert do you have to do something else after? Do you have to commit the changes revert made or does revert directly commit to the repo or what??

By default, git revert prompts you for a commit message and then commits the results. This can be overridden. I quote the man page:

--edit

With this option, git revert will let you edit the commit message prior to committing the revert. This is the default if you run the command from a terminal.

--no-commit

Usually the command automatically creates some commits with commit log messages stating which commits were reverted. This flag applies the changes necessary to revert the named commits to your working tree and the index, but does not make the commits. In addition, when this option is used, your index does not have to match the HEAD commit. The revert is done against the beginning state of your index.

This is useful when reverting more than one commits' effect to your index in a row.

In particular, by default it creates a new commit for each commit you're reverting. You can use revert --no-commit to create changes reverting all of them without committing those changes as individual commits, then commit at your leisure.

RedirectToAction with parameter

If one want to Show error message for [httppost] then he/she can try by passing an ID using

return RedirectToAction("LogIn", "Security", new { @errorId = 1 });

for Details like this

 public ActionResult LogIn(int? errorId)
        {
            if (errorId > 0)
            {
                ViewBag.Error = "UserName Or Password Invalid !";
            }
            return View();
        }

[Httppost]
public ActionResult LogIn(FormCollection form)
        {
            string user= form["UserId"];
            string password = form["Password"];
            if (user == "admin" && password == "123")
            {
               return RedirectToAction("Index", "Admin");
            }
            else
            {
                return RedirectToAction("LogIn", "Security", new { @errorId = 1 });
            }
}

Hope it works fine.

How to get html table td cell value by JavaScript?

I gave the table an id so I could find it. On onload (when the page is loaded by the browser), I set onclick event handlers to all rows of the table. Those handlers alert the content of the first cell.

<!DOCTYPE html>
<html>
    <head>
        <script>
            var p = {
                onload: function() {
                    var rows = document.getElementById("mytable").rows;
                    for(var i = 0, ceiling = rows.length; i < ceiling; i++) {
                        rows[i].onclick = function() {
                            alert(this.cells[0].innerHTML);
                        }
                    }
                }
            };
        </script>
    </head>
    <body onload="p.onload()">
        <table id="mytable">
            <tr>
                <td>0</td>
                <td>row 1 cell 2</td>
            </tr>
            <tr>
                <td>1</td>
                <td>row 2 cell 2</td>
            </tr>
        </table>    
    </body>
</html> 

python: how to identify if a variable is an array or a scalar

Combining @jamylak and @jpaddison3's answers together, if you need to be robust against numpy arrays as the input and handle them in the same way as lists, you should use

import numpy as np
isinstance(P, (list, tuple, np.ndarray))

This is robust against subclasses of list, tuple and numpy arrays.

And if you want to be robust against all other subclasses of sequence as well (not just list and tuple), use

import collections
import numpy as np
isinstance(P, (collections.Sequence, np.ndarray))

Why should you do things this way with isinstance and not compare type(P) with a target value? Here is an example, where we make and study the behaviour of NewList, a trivial subclass of list.

>>> class NewList(list):
...     isThisAList = '???'
... 
>>> x = NewList([0,1])
>>> y = list([0,1])
>>> print x
[0, 1]
>>> print y
[0, 1]
>>> x==y
True
>>> type(x)
<class '__main__.NewList'>
>>> type(x) is list
False
>>> type(y) is list
True
>>> type(x).__name__
'NewList'
>>> isinstance(x, list)
True

Despite x and y comparing as equal, handling them by type would result in different behaviour. However, since x is an instance of a subclass of list, using isinstance(x,list) gives the desired behaviour and treats x and y in the same manner.

Can I grep only the first n lines of a file?

You can use the following line:

head -n 10 /path/to/file | grep [...]

How to increment an iterator by 2?

If you don't have a modifiable lvalue of an iterator, or it is desired to get a copy of a given iterator (leaving the original one unchanged), then C++11 comes with new helper functions - std::next / std::prev:

std::next(iter, 2);          // returns a copy of iter incremented by 2
std::next(std::begin(v), 2); // returns a copy of begin(v) incremented by 2
std::prev(iter, 2);          // returns a copy of iter decremented by 2

Change values of select box of "show 10 entries" of jquery datatable

 $('#tblSub1View').dataTable({
                    "bJQueryUI": true,
                    "sPaginationType": "full_numbers",
                    "bDestroy": true,
                    "aoColumnDefs": [{
                        'bSortable': false,
                        'aTargets': [0, 1]
                    }],
                    "aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
                    "iDisplayLength": 10,
                });

How to specify line breaks in a multi-line flexbox layout?

I just want to throw this answer in the mix, intended as a reminder that – given the right conditions – you sometimes don't need to overthink the issue at hand. What you want might be achievable with flex: wrap and max-width instead of :nth-child.

_x000D_
_x000D_
ul {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  max-width: 420px;
  list-style-type: none;
  background-color: tomato;
  margin: 0 auto;
  padding: 0;
}

li {
  display: inline-block;
  background-color: #ccc;
  border: 1px solid #333;
  width: 23px;
  height: 23px;
  text-align: center;
  font-size: 1rem;
  line-height: 1.5;
  margin: 0.2rem;
  flex-shrink: 0;
}
_x000D_
<div class="root">
  <ul>
    <li>A</li>
    <li>B</li>
    <li>C</li>
    <li>D</li>
    <li>E</li>
    <li>F</li>
    <li>G</li>
    <li>H</li>
    <li>I</li>
    <li>J</li>
    <li>K</li>
    <li>L</li>
    <li>M</li>
    <li>N</li>
    <li>O</li>
    <li>P</li>
    <li>Q</li>
    <li>R</li>
    <li>S</li>
    <li>T</li>
    <li>U</li>
    <li>V</li>
    <li>W</li>
    <li>X</li>
    <li>Y</li>
    <li>Z</li>
  </ul>
</div>
_x000D_
_x000D_
_x000D_

https://jsfiddle.net/age3qp4d/

How to change node.js's console font color?

If you want to change the colors directly yourself without a module try

console.log('\x1b[36m', 'sometext' ,'\x1b[0m');

First \x1b[36m to change the colors to 36 and then back to terminal color 0.

Here's a list of ANSI color codes

Read from a gzip file in python

Try gzipping some data through the gzip libary like this...

import gzip
content = "Lots of content here"
f = gzip.open('Onlyfinnaly.log.gz', 'wb')
f.write(content)
f.close()

... then run your code as posted ...

import gzip
f=gzip.open('Onlyfinnaly.log.gz','rb')
file_content=f.read()
print file_content

This method worked for me as for some reason the gzip library fails to read some files.

how to make a cell of table hyperlink

Try this:

HTML:

<table width="200" border="1" class="table">
    <tr>
        <td><a href="#">&nbsp;</a></td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
    </tr>
</table>

CSS:

.table a
{
    display:block;
    text-decoration:none;
}

I hope it will work fine.

Adding Git-Bash to the new Windows Terminal

That's how I've added mine in profiles json table,

{
    "guid": "{00000000-0000-0000-ba54-000000000002}",
    "name": "Git",
    "commandline": "C:/Program Files/Git/bin/bash.exe --login",
    "icon": "%PROGRAMFILES%/Git/mingw64/share/git/git-for-windows.ico",
    "startingDirectory": "%USERPROFILE%",
    "hidden": false
}

IE Driver download location Link for Selenium

Use the below link to download IE Driver latest version

IE Driver

Create mysql table directly from CSV file using the CSV Storage engine?

I adopted the script from shiplu.mokadd.im to fit my needs. Whom it interests:

#!/bin/bash
if [ "$#" -lt 2 ]; then
    if [ "$#" -lt 1 ]; then 
        echo "usage: $0 [path to csv file] <table name> > [sql filename]"
        exit 1
    fi
    TABLENAME=$1
else
    TABLENAME=$2
fi
echo "CREATE TABLE $TABLENAME ( "
FIRSTLINE=$(head -1 $1)
# convert lowercase characters to uppercase
FIRSTLINE=$(echo $FIRSTLINE | tr '[:lower:]' '[:upper:]')
# remove spaces
FIRSTLINE=$(echo $FIRSTLINE | sed -e 's/ /_/g')
# add tab char to the beginning of line
FIRSTLINE=$(echo "\t$FIRSTLINE")
# add tabs and newline characters
FIRSTLINE=$(echo $FIRSTLINE | sed -e 's/,/,\\n\\t/g')
# add VARCHAR
FIRSTLINE=$(echo $FIRSTLINE | sed -e 's/,/ VARCHAR(255),/g')
# print out result
echo -e $FIRSTLINE" VARCHAR(255));"

jquery <a> tag click event

That's because your hidden fields have duplicate IDs, so jQuery only returns the first in the set. Give them classes instead, like .uid and grab them via:

var uids = $(".uid").map(function() {
    return this.value;
}).get();

Demo: http://jsfiddle.net/karim79/FtcnJ/

EDIT: say your output looks like the following (notice, IDs have changed to classes)

<fieldset><legend>John Smith</legend>
<img src='foo.jpg'/><br>
<a href="#" class="aaf">add as friend</a>
<input name="uid" type="hidden" value='<?php echo $row->uid;?>' class="uid">
</fieldset>

You can target the 'uid' relative to the clicked anchor like this:

$("a.aaf").click(function() {
    alert($(this).next('.uid').val());
});

Important: do not have any duplicate IDs. They will cause problems. They are invalid, bad and you should not do it.

Plot logarithmic axes with matplotlib in python

First of all, it's not very tidy to mix pylab and pyplot code. What's more, pyplot style is preferred over using pylab.

Here is a slightly cleaned up code, using only pyplot functions:

from matplotlib import pyplot

a = [ pow(10,i) for i in range(10) ]

pyplot.subplot(2,1,1)
pyplot.plot(a, color='blue', lw=2)
pyplot.yscale('log')
pyplot.show()

The relevant function is pyplot.yscale(). If you use the object-oriented version, replace it by the method Axes.set_yscale(). Remember that you can also change the scale of X axis, using pyplot.xscale() (or Axes.set_xscale()).

Check my question What is the difference between ‘log’ and ‘symlog’? to see a few examples of the graph scales that matplotlib offers.

int to hex string

Try the following:

ToString("X4")

See The X format specifier on MSDN.

How to elegantly check if a number is within a range?

I would do a Range object, something like this:

public class Range<T> where T : IComparable
{
    public T InferiorBoundary{get;private set;}
    public T SuperiorBoundary{get;private set;}

    public Range(T inferiorBoundary, T superiorBoundary)
    {
        InferiorBoundary = inferiorBoundary;
        SuperiorBoundary = superiorBoundary;
    }

    public bool IsWithinBoundaries(T value){
        return InferiorBoundary.CompareTo(value) > 0 && SuperiorBoundary.CompareTo(value) < 0;
    }
}

Then you use it this way:

Range<int> myRange = new Range<int>(1,999);
bool isWithinRange = myRange.IsWithinBoundaries(3);

That way you can reuse it for another type.

How to import Angular Material in project?

Install & Add Material to Angular Projects

There is an automatic/easy way of adding Material to Angular Projects. Use the Angular CLI's install schematic to set up your Angular Material project by running the following command:

ng add @angular/material

The ng add command will additionally perform the following configurations:

  • Add project dependencies to package.json
  • Add the Roboto font to your index.html
  • Add the Material Design icon font to your index.html
  • Add a few global CSS styles to:
    • Remove margins from body
    • Set height: 100% on html and body
    • Set Roboto as the default application font

You're done! Angular Material is now configured to be used in your application.

Read more about this here

Make page to tell browser not to cache/preserve input values

From a Stack Overflow reference

It did not work with value="" if the browser already saves the value so you should add.

For an input tag there's the attribute autocomplete you can set:

<input type="text" autocomplete="off" />

You can use autocomplete for a form too.

maven compilation failure

I had a similar problem, and never find anything on the web after excessive searching.

I reviewed the pom.xml file and in the dependencies I changed the scope of the <dependency> it: <scope>test</scope> to <scope>compile</scope> .

Previously I was using it only for tests but I change the project's structure and never knew I hve to change this.

test: This scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases.

compile: This is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects.

Here is a reference from Apache Maven Docs: https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Scope

How to test an Internet connection with bash?

Similarly to @Jesse's answer, this option might be much faster than any solution using ping and perhaps slightly more efficient than @Jesse's answer.

find /sys/class/net/ -maxdepth 1 -mindepth 1 ! -name "*lo*" -exec sh -c 'cat "$0"/carrier 2>&1' {} \; | grep -q '1'

Explenation:

This command uses find with -exec to run command on all files not named *lo* in /sys/class/net/. These should be links to directories containing information about the available network interfaces on your machine.

The command being ran is an sh command that checks the contents of the file carrier in those directories. The value of $interface/carrier has 3 meanings - Quoting:

It seems there are three states:

  • ./carrier not readable (for instance when the interface is disabled in Network Manager).
  • ./carrier contain "1" (when the interface is activated and it is connected to a WiFi network)
  • ./carrier contain "0" (when the interface is activated and it is not connected to a WiFi network)

The first option is not taken care of in @Jesse's answer. The sh command striped out is:

# Note: $0 == $interface
cat "$0"/carrier 2>&1

cat is being used to check the contents of carrier and redirect all output to standard output even when it fails because the file is not readable. If grep -q finds "1" among those files it means there is at least 1 interface connected. The exit code of grep -q will be the final exit code.

Usage

For example, using this command's exit status, you can use it start a gnubiff in your ~/.xprofile only if you have an internet connection.

online() {
    find /sys/class/net/ -maxdepth 1 -mindepth 1 ! -name "*lo*" -exec sh -c 'cat "$0"/carrier 2>&1 > /dev/null | grep -q "1" && exit 0' {} \;
}
online && gnubiff --systemtray --noconfigure &

Reference

Escape double quote in VB string

Escaping quotes in VB6 or VBScript strings is simple in theory although often frightening when viewed. You escape a double quote with another double quote.

An example:

"c:\program files\my app\app.exe"

If I want to escape the double quotes so I could pass this to the shell execute function listed by Joe or the VB6 Shell function I would write it:

escapedString = """c:\program files\my app\app.exe"""

How does this work? The first and last quotes wrap the string and let VB know this is a string. Then each quote that is displayed literally in the string has another double quote added in front of it to escape it.

It gets crazier when you are trying to pass a string with multiple quoted sections. Remember, every quote you want to pass has to be escaped.

If I want to pass these two quoted phrases as a single string separated by a space (which is not uncommon):

"c:\program files\my app\app.exe" "c:\documents and settings\steve"

I would enter this:

escapedQuoteHell = """c:\program files\my app\app.exe"" ""c:\documents and settings\steve"""

I've helped my sysadmins with some VBScripts that have had even more quotes.

It's not pretty, but that's how it works.

Eclipse: How to build an executable jar with external jar?

As a good practice you can use an Ant Script (Eclipse comes with it) to generate your JAR file. Inside this JAR you can have all dependent libs.

You can even set the MANIFEST's Class-path header to point to files in your filesystem, it's not a good practice though.

Ant build.xml script example:

<project name="jar with libs" default="compile and build" basedir=".">
<!-- this is used at compile time -->
<path id="example-classpath">
    <pathelement location="${root-dir}" />
    <fileset dir="D:/LIC/xalan-j_2_7_1" includes="*.jar" />
</path>

<target name="compile and build">
    <!-- deletes previously created jar -->
    <delete file="test.jar" />

    <!-- compile your code and drop .class into "bin" directory -->
    <javac srcdir="${basedir}" destdir="bin" debug="true" deprecation="on">
        <!-- this is telling the compiler where are the dependencies -->
        <classpath refid="example-classpath" />
    </javac>

    <!-- copy the JARs that you need to "bin" directory  -->
    <copy todir="bin">
        <fileset dir="D:/LIC/xalan-j_2_7_1" includes="*.jar" />
    </copy>

    <!-- creates your jar with the contents inside "bin" (now with your .class and .jar dependencies) -->
    <jar destfile="test.jar" basedir="bin" duplicate="preserve">
        <manifest>
            <!-- Who is building this jar? -->
            <attribute name="Built-By" value="${user.name}" />
            <!-- Information about the program itself -->
            <attribute name="Implementation-Vendor" value="ACME inc." />
            <attribute name="Implementation-Title" value="GreatProduct" />
            <attribute name="Implementation-Version" value="1.0.0beta2" />
            <!-- this tells which class should run when executing your jar -->
            <attribute name="Main-class" value="ApplyXPath" />
        </manifest>
    </jar>
</target>

Update MongoDB field using value of another field

Regarding this answer, the snapshot function is deprecated in version 3.6, according to this update. So, on version 3.6 and above, it is possible to perform the operation this way:

db.person.find().forEach(
    function (elem) {
        db.person.update(
            {
                _id: elem._id
            },
            {
                $set: {
                    name: elem.firstname + ' ' + elem.lastname
                }
            }
        );
    }
);

Combine two (or more) PDF's

PDFsharp seems to allow merging multiple PDF documents into one.

And the same is also possible with ITextSharp.

How can I send large messages with Kafka (over 15MB)?

You need to override the following properties:

Broker Configs($KAFKA_HOME/config/server.properties)

  • replica.fetch.max.bytes
  • message.max.bytes

Consumer Configs($KAFKA_HOME/config/consumer.properties)
This step didn't work for me. I add it to the consumer app and it was working fine

  • fetch.message.max.bytes

Restart the server.

look at this documentation for more info: http://kafka.apache.org/08/configuration.html

How to display errors for my MySQLi query?

mysqli_error()

As in:

$sql = "Your SQL statement here";
$result = mysqli_query($conn, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($conn), E_USER_ERROR);

Trigger error is better than die because you can use it for development AND production, it's the permanent solution.

Eclipse Optimize Imports to Include Static Imports

If you highlight the method Assert.assertEquals(val1, val2) and hit Ctrl + Shift + M (Add Import), it will add it as a static import, at least in Eclipse 3.4.

Google Play Services Library update and missing symbol @integer/google_play_services_version

The problem for me was that the library project and the project using play services were in different directories. So just:

  • 1.Add the files to the same workspace then remove the library.
  • 2.Restart eclipse
  • 3.Add the library project again
  • 4.Clear

How to select only 1 row from oracle sql?

select a.user from (select user from users order by user) a where rownum = 1

will perform the best, another option is:

select a.user 
from ( 
select user, 
row_number() over (order by user) user_rank, 
row_number() over (partition by dept order by user) user_dept_rank 
from users 
) a 
where a.user_rank = 1 or user_dept_rank = 2

in scenarios where you want different subsets, but I guess you could also use RANK() But, I also like row_number() over(...) since no grouping is required.

How do I activate C++ 11 in CMake?

CMake 3.1 introduced the CMAKE_CXX_STANDARD variable that you can use. If you know that you will always have CMake 3.1 or later available, you can just write this in your top-level CMakeLists.txt file, or put it right before any new target is defined:

set (CMAKE_CXX_STANDARD 11)

If you need to support older versions of CMake, here is a macro I came up with that you can use:

macro(use_cxx11)
  if (CMAKE_VERSION VERSION_LESS "3.1")
    if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
      set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11")
    endif ()
  else ()
    set (CMAKE_CXX_STANDARD 11)
  endif ()
endmacro(use_cxx11)

The macro only supports GCC right now, but it should be straight-forward to expand it to other compilers.

Then you could write use_cxx11() at the top of any CMakeLists.txt file that defines a target that uses C++11.

CMake issue #15943 for clang users targeting macOS

If you are using CMake and clang to target macOS there is a bug that can cause the CMAKE_CXX_STANDARD feature to simply not work (not add any compiler flags). Make sure that you do one of the following things:

  • Use cmake_minimum_required to require CMake 3.0 or later, or

  • Set policy CMP0025 to NEW with the following code at the top of your CMakeLists.txt file before the project command:

      # Fix behavior of CMAKE_CXX_STANDARD when targeting macOS.
      if (POLICY CMP0025)
        cmake_policy(SET CMP0025 NEW)
      endif ()
    

How to use Git and Dropbox together?

I don't think that using Git and Dropbox is the way to go... Just think about the features of both:

Git:

  • Allows you to have a central repository
  • Allows you to have your own repository with your own changes
  • Allows you to send and receive changes from the central repository
  • Allows multiple persons to change the same files and them merges them or asks you to merge them if it can't do it
  • Has web and desktop clients to allow access to the central repository

Dropbox:

  • Keeps everything in a central repository
  • Allows you to have your own versions of the files in the server
  • Forces you to send and receive changes from the central repository
  • If multiple persons change the same files, the first file committed is replaced with later commits, and no merge occurs which is troublesome (and definitely its biggest disadvantage)
  • Has web and desktop clients to allow access to the central repository.

And if you're worried with sharing some of your files, why not cipher them? And then you could get the biggest advantage of Dropbox to Git, that is, to have public and private files...

What's HTML character code 8203?

If you're seeing these in a source be aware that it may be someone attempting to fingerprint text documents to reveal who is leaking information. It also may be an attempt to bypass a spam filter by making the same looking information different on a byte-by-byte level.

See my article on mitigating fingerprinting if you're interested in learning more.

how to draw directed graphs using networkx in python?

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()
G.add_node("A")
G.add_node("B")
G.add_node("C")
G.add_node("D")
G.add_node("E")
G.add_node("F")
G.add_node("G")
G.add_edge("A","B")
G.add_edge("B","C")
G.add_edge("C","E")
G.add_edge("C","F")
G.add_edge("D","E")
G.add_edge("F","G")

print(G.nodes())
print(G.edges())

pos = nx.spring_layout(G)

nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edge_color='r', arrows = True)

plt.show()

Command to get time in milliseconds

On OS X, where date does not support the %N flag, I recommend installing coreutils using Homebrew. This will give you access to a command called gdate that will behave as date does on Linux systems.

brew install coreutils

For a more "native" experience, you can always add this to your .bash_aliases:

alias date='gdate'

Then execute

$ date +%s%N

Gradle DSL method not found: 'runProguard'

If you are migrating to 1.0.0 you need to change the following properties.

In the Project's build.gradle file you need to replace minifyEnabled.

Hence your new build type should be

buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'        
    }
}

Also make sure that gradle version is 1.0.0 like

classpath 'com.android.tools.build:gradle:1.0.0'

in the build.gradle file.

This should solve the problem.

Source: http://tools.android.com/tech-docs/new-build-system/migrating-to-1-0-0

For each row return the column name of the largest value

If you're interested in a data.table solution, here's one. It's a bit tricky since you prefer to get the id for the first maximum. It's much easier if you'd rather want the last maximum. Nevertheless, it's not that complicated and it's fast!

Here I've generated data of your dimensions (26746 * 18).

Data

set.seed(45)
DF <- data.frame(matrix(sample(10, 26746*18, TRUE), ncol=18))

data.table answer:

require(data.table)
DT <- data.table(value=unlist(DF, use.names=FALSE), 
            colid = 1:nrow(DF), rowid = rep(names(DF), each=nrow(DF)))
setkey(DT, colid, value)
t1 <- DT[J(unique(colid), DT[J(unique(colid)), value, mult="last"]), rowid, mult="first"]

Benchmarking:

# data.table solution
system.time({
DT <- data.table(value=unlist(DF, use.names=FALSE), 
            colid = 1:nrow(DF), rowid = rep(names(DF), each=nrow(DF)))
setkey(DT, colid, value)
t1 <- DT[J(unique(colid), DT[J(unique(colid)), value, mult="last"]), rowid, mult="first"]
})
#   user  system elapsed 
#  0.174   0.029   0.227 

# apply solution from @thelatemail
system.time(t2 <- colnames(DF)[apply(DF,1,which.max)])
#   user  system elapsed 
#  2.322   0.036   2.602 

identical(t1, t2)
# [1] TRUE

It's about 11 times faster on data of these dimensions, and data.table scales pretty well too.


Edit: if any of the max ids is okay, then:

DT <- data.table(value=unlist(DF, use.names=FALSE), 
            colid = 1:nrow(DF), rowid = rep(names(DF), each=nrow(DF)))
setkey(DT, colid, value)
t1 <- DT[J(unique(colid)), rowid, mult="last"]

How to perform a LEFT JOIN in SQL Server between two SELECT statements?

Try this:

SELECT user.userID, edge.TailUser, edge.Weight 
FROM user
LEFT JOIN edge ON edge.HeadUser = User.UserID
WHERE edge.HeadUser=5043

OR

AND edge.HeadUser=5043

instead of WHERE clausule.