Programs & Examples On #Freeimage

FreeImage is an Open Source library project for developers who would like to support popular graphics image formats like PNG, BMP, JPEG, TIFF and others as needed by today's multimedia applications.

Where value in column containing comma delimited values

WHERE
      MyColumn LIKE '%,' + @search + ',%' --middle
      OR
      MyColumn LIKE @search + ',%' --start
      OR
      MyColumn LIKE '%,' + @search --end
      OR 
      MyColumn =  @search --single (good point by Cheran S in comment)

ENOENT, no such file or directory

Tilde expansion is a shell thing. Write the proper pathname (probably /home/yourusername/Desktop/etcetcetc) or use
process.env.HOME + '/Desktop/blahblahblah'

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

Just a simple command below is enough.

mkdir a && touch !$/file.txt

Thx

unix diff side-to-side results?

From icdiff's homepage:

enter image description here

Your terminal can display color, but most diff tools don't make good use of it. By highlighting changes, icdiff can show you the differences between similar files without getting in the way. This is especially helpful for identifying and understanding small changes within existing lines.

Instead of trying to be a diff replacement for all circumstances, the goal of icdiff is to be a tool you can reach for to get a better picture of what changed when it's not immediately obvious from diff.

IMHO, its output is much more readable than diff -y.

Function overloading in Javascript - Best practices

There is no real function overloading in JavaScript since it allows to pass any number of parameters of any type. You have to check inside the function how many arguments have been passed and what type they are.

Specifying java version in maven - differences between properties and compiler plugin

None of the solutions above worked for me straight away. So I followed these steps:

  1. Add in pom.xml:
<properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
</properties>
  1. Go to Project Properties > Java Build Path, then remove the JRE System Library pointing to JRE1.5.

  2. Force updated the project.

PHP "php://input" vs $_POST

So I wrote a function that would get the POST data from the php://input stream.

So the challenge here was switching to PUT, DELETE OR PATCH request method, and still obtain the post data that was sent with that request.

I'm sharing this maybe for someone with a similar challenge. The function below is what I came up with and it works. I hope it helps!

    /**
     * @method Post getPostData
     * @return array
     * 
     * Convert Content-Disposition to a post data
     */
    function getPostData() : array
    {
        // @var string $input
        $input = file_get_contents('php://input');

        // continue if $_POST is empty
        if (strlen($input) > 0 && count($_POST) == 0 || count($_POST) > 0) :

            $postsize = "---".sha1(strlen($input))."---";

            preg_match_all('/([-]{2,})([^\s]+)[\n|\s]{0,}/', $input, $match);

            // update input
            if (count($match) > 0) $input = preg_replace('/([-]{2,})([^\s]+)[\n|\s]{0,}/', '', $input);

            // extract the content-disposition
            preg_match_all("/(Content-Disposition: form-data; name=)+(.*)/m", $input, $matches);

            // let's get the keys
            if (count($matches) > 0 && count($matches[0]) > 0)
            {
                $keys = $matches[2];

                foreach ($keys as $index => $key) :
                    $key = trim($key);
                    $key = preg_replace('/^["]/','',$key);
                    $key = preg_replace('/["]$/','',$key);
                    $key = preg_replace('/[\s]/','',$key);
                    $keys[$index] = $key;
                endforeach;

                $input = preg_replace("/(Content-Disposition: form-data; name=)+(.*)/m", $postsize, $input);

                $input = preg_replace("/(Content-Length: )+([^\n]+)/im", '', $input);

                // now let's get key value
                $inputArr = explode($postsize, $input);

                // @var array $values
                $values = [];

                foreach ($inputArr as $index => $val) :
                    $val = preg_replace('/[\n]/','',$val);

                    if (preg_match('/[\S]/', $val)) $values[$index] = trim($val);

                endforeach;

                // now combine the key to the values
                $post = [];

                // @var array $value
                $value = [];

                // update value
                foreach ($values as $i => $val) $value[] = $val;

                // push to post
                foreach ($keys as $x => $key) $post[$key] = isset($value[$x]) ? $value[$x] : '';

                if (is_array($post)) :

                    $newPost = [];

                    foreach ($post as $key => $val) :

                        if (preg_match('/[\[]/', $key)) :

                            $k = substr($key, 0, strpos($key, '['));
                            $child = substr($key, strpos($key, '['));
                            $child = preg_replace('/[\[|\]]/','', $child);
                            $newPost[$k][$child] = $val;

                        else:

                            $newPost[$key] = $val;

                        endif;

                    endforeach;

                    $_POST = count($newPost) > 0 ? $newPost : $post;

                endif;
            }

        endif;

        // return post array
        return $_POST;
    }

Force IE9 to emulate IE8. Possible?

You can use the document compatibility mode to do this, which is what you were trying.. However, thing to note is: It must appear in the Web page's header (the HEAD section) before all other elements, except for the title element and other meta elements Hope that was the issue.. Also, The X-UA-compatible header is not case sensitive Refer: http://msdn.microsoft.com/en-us/library/cc288325%28v=vs.85%29.aspx#SetMode

Edit: in case something happens to kill the msdn link, here is the content:

Specifying Document Compatibility Modes

You can use document modes to control the way Internet Explorer interprets and displays your webpage. To specify a specific document mode for your webpage, use the meta element to include an X-UA-Compatible header in your webpage, as shown in the following example.

<html>
<head>
  <!-- Enable IE9 Standards mode -->
  <meta http-equiv="X-UA-Compatible" content="IE=9" >
  <title>My webpage</title>
</head>
<body>
  <p>Content goes here.</p>
</body>
</html> 

If you view this webpage in Internet Explorer 9, it will be displayed in IE9 mode.

The following example specifies EmulateIE7 mode.

<html>
<head>
  <!-- Mimic Internet Explorer 7 -->
  <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" >
  <title>My webpage</title>
</head>
<body>
  <p>Content goes here.</p>
</body>
</html> 

In this example, the X-UA-Compatible header directs Internet Explorer to mimic the behavior of Internet Explorer 7 when determining how to display the webpage. This means that Internet Explorer will use the directive (or lack thereof) to choose the appropriate document type. Because this page does not contain a directive, the example would be displayed in IE5 (Quirks) mode.

Max parallel http connections in a browser?

The 2 concurrent requests is an intentional part of the design of many browsers. There is a standard out there that "good http clients" adhere to on purpose. Check out this RFC to see why.

How can I find out if I have Xcode commandline tools installed?

I was able to find my version of Xcode on maxOS Sierra using this command:

pkgutil --pkg-info=com.apple.pkg.CLTools_Executables | grep version

as per this answer.

Found a swap file by the name

.MERGE_MSG.swp is open in your git, you just need to delete this .swp file. In my case I used following command and it worked fine.

rm .MERGE_MSG.swp

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

Can jQuery get all CSS styles associated with an element?

@marknadal's solution wasn't grabbing hyphenated properties for me (e.g. max-width), but changing the first for loop in css2json() made it work, and I suspect performs fewer iterations:

for (var i = 0; i < css.length; i += 1) {
    s[css[i]] = css.getPropertyValue(css[i]);
}

Loops via length rather than in, retrieves via getPropertyValue() rather than toLowerCase().

Succeeded installing but could not start apache 2.4 on my windows 7 system

In my case, it was due to an IP address that Apache is listening to. Previously I have set it to 192.168.10.6 and recently Apache service is not running. I noticed that due to My laptop wifi changed recently and new IP is different. After fixing the wifi IP to laptop previous IP, Apache service is running again without any error.

Also if you don't want to change wifi IP then remove/comment that hardcode IP in httpd.conf file to resolve conflict.

MySQL > Table doesn't exist. But it does (or it should)

Had a similar problem with a ghost table. Thankfully had an SQL dump from before the failure.

In my case, I had to:

  1. Stop mySQL
  2. Move ib* files from /var/mysql off to a backup
  3. Delete /var/mysql/{dbname}
  4. Restart mySQL
  5. Recreate empty database
  6. Restore dump file

NOTE: Requires dump file.

How to enumerate an object's properties in Python?

I think it's worth showing the difference between the various options mentioned - often a picture is worth a thousand words.

>>> from pprint import pprint
>>> import inspect
>>>
>>> class a():
    x = 1               # static class member
    def __init__(self):
        self.y = 2      # static instance member
    @property
    def dyn_prop(self): # dynamic property
        print('DYNPROP WAS HERE')
        return 3
    def test(self):     # function member
        pass
    @classmethod
    def myclassmethod(cls): # class method; static methods behave the same
        pass

>>> i = a()
>>> pprint(i.__dict__)
{'y': 2}
>>> pprint(vars(i))
{'y': 2}
>>> pprint(dir(i))
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'dyn_prop',
 'myclassmethod',
 'test',
 'x',
 'y']
>>> pprint(inspect.getmembers(i))
DYNPROP WAS HERE
[('__class__', <class '__main__.a'>),
 ('__delattr__',
  <method-wrapper '__delattr__' of a object at 0x000001CB891BC7F0>),
 ('__dict__', {'y': 2}),
 ('__dir__', <built-in method __dir__ of a object at 0x000001CB891BC7F0>),
 ('__doc__', None),
 ('__eq__', <method-wrapper '__eq__' of a object at 0x000001CB891BC7F0>),
 ('__format__', <built-in method __format__ of a object at 0x000001CB891BC7F0>),
 ('__ge__', <method-wrapper '__ge__' of a object at 0x000001CB891BC7F0>),
 ('__getattribute__',
  <method-wrapper '__getattribute__' of a object at 0x000001CB891BC7F0>),
 ('__gt__', <method-wrapper '__gt__' of a object at 0x000001CB891BC7F0>),
 ('__hash__', <method-wrapper '__hash__' of a object at 0x000001CB891BC7F0>),
 ('__init__',
  <bound method a.__init__ of <__main__.a object at 0x000001CB891BC7F0>>),
 ('__init_subclass__',
  <built-in method __init_subclass__ of type object at 0x000001CB87CA6A70>),
 ('__le__', <method-wrapper '__le__' of a object at 0x000001CB891BC7F0>),
 ('__lt__', <method-wrapper '__lt__' of a object at 0x000001CB891BC7F0>),
 ('__module__', '__main__'),
 ('__ne__', <method-wrapper '__ne__' of a object at 0x000001CB891BC7F0>),
 ('__new__', <built-in method __new__ of type object at 0x00007FFCA630AB50>),
 ('__reduce__', <built-in method __reduce__ of a object at 0x000001CB891BC7F0>),
 ('__reduce_ex__',
  <built-in method __reduce_ex__ of a object at 0x000001CB891BC7F0>),
 ('__repr__', <method-wrapper '__repr__' of a object at 0x000001CB891BC7F0>),
 ('__setattr__',
  <method-wrapper '__setattr__' of a object at 0x000001CB891BC7F0>),
 ('__sizeof__', <built-in method __sizeof__ of a object at 0x000001CB891BC7F0>),
 ('__str__', <method-wrapper '__str__' of a object at 0x000001CB891BC7F0>),
 ('__subclasshook__',
  <built-in method __subclasshook__ of type object at 0x000001CB87CA6A70>),
 ('__weakref__', None),
 ('dyn_prop', 3),
 ('myclassmethod', <bound method a.myclassmethod of <class '__main__.a'>>),
 ('test', <bound method a.test of <__main__.a object at 0x000001CB891BC7F0>>),
 ('x', 1),
 ('y', 2)]

To summarize:

  • vars() and __dict__ only return instance-local properties;
  • dir() returns everything, but only as a list of string member names; dynamic properties are not called;
  • inspect.getmembers() returns everything, as a list of tuples (name, value); it actually runs dynamic properties, and accepts an optional predicate argument that can filter out members by value.

So my common-sense approach is typically to use dir() on the command line, and getmembers() in programs, unless specific performance considerations apply.

Note that, to keep things cleaner, I did not include __slots__ - if present, it was explicitly put there to be queried, and should be used directly. I also did not cover metaclasses, which can get a bit hairy (most people will never use them anyway).

Design Documents (High Level and Low Level Design Documents)

High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.

LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.

Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.

As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.

Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.

Change bullets color of an HTML list without using span

Try using this instead:

ul {
  color: red;
}

Fit background image to div

If what you need is the image to have the same dimensions of the div, I think this is the most elegant solution:

background-size: 100% 100%;

If not, the answer by @grc is the most appropriated one.

Source: http://www.w3schools.com/cssref/css3_pr_background-size.asp

Allow access permission to write in Program Files of Windows 7

It would be neater to create a folder named "c:\programs writable\" and put you app below that one. That way a jungle of low c-folders can be avoided.

The underlying trade-off is security versus ease-of-use. If you know what you are doing you want to be god on you own pc. If you must maintain healthy systems for your local anarchistic society, you may want to add some security.

convert '1' to '0001' in JavaScript

This is a clever little trick (that I think I've seen on SO before):

var str = "" + 1
var pad = "0000"
var ans = pad.substring(0, pad.length - str.length) + str

JavaScript is more forgiving than some languages if the second argument to substring is negative so it will "overflow correctly" (or incorrectly depending on how it's viewed):

That is, with the above:

  • 1 -> "0001"
  • 12345 -> "12345"

Supporting negative numbers is left as an exercise ;-)

Happy coding.

Webpack how to build production code and how to use it

Use these plugins to optimize your production build:

  new webpack.optimize.CommonsChunkPlugin('common'),
  new webpack.optimize.DedupePlugin(),
  new webpack.optimize.UglifyJsPlugin(),
  new webpack.optimize.AggressiveMergingPlugin()

I recently came to know about compression-webpack-plugin which gzips your output bundle to reduce its size. Add this as well in the above listed plugins list to further optimize your production code.

new CompressionPlugin({
      asset: "[path].gz[query]",
      algorithm: "gzip",
      test: /\.js$|\.css$|\.html$/,
      threshold: 10240,
      minRatio: 0.8
})

Server side dynamic gzip compression is not recommended for serving static client-side files because of heavy CPU usage.

Using OR in SQLAlchemy

From the tutorial:

from sqlalchemy import or_
filter(or_(User.name == 'ed', User.name == 'wendy'))

How can I bind a background color in WPF/XAML?

Important:

Make sure you're using System.Windows.Media.Brush and not System.Drawing.Brush

They're not compatible and you'll get binding errors.

The color enumeration you need to use is also different

System.Windows.Media.Colors.Aquamarine (class name is Colors) <--- use this one System.Drawing.Color.Aquamarine (class name is Color)

If in doubt use Snoop and inspect the element's background property to look for binding errors - or just look in your debug log.

Cannot find pkg-config error

For Ubuntu/Debian OS,

apt-get install -y pkg-config

For Redhat/Yum OS,

yum install -y pkgconfig

For Archlinux OS,

pacman -S pkgconf

jQuery UI Slider (setting programmatically)

One part of @gaurav solution worked for jQuery 2.1.3 and JQuery UI 1.10.2 with multiple sliders. My project is using four range sliders to filter data with this filter.js plugin. Other solutions were resetting the slider handles back to their starting end points just fine, but apparently they were not firing an event that filter.js understood. So here's how I looped through the sliders:

$("yourSliderSelection").each (function () {
    var hs = $(this); 
    var options = $(this).slider('option');

    //reset the ui
    $(this).slider( 'values', [ options.min, options.max ] ); 

    //refresh/trigger event so that filter.js can reset handling the data
    hs.slider('option', 'slide').call(
        hs, 
        null, 
        {
            handle: $('.ui-slider-handle', hs),
            values: [options.min, options.max]
        }
    );

});

The hs.slider() code resets the data, but not the UI in my scenario. Hope this helps others.

Angular routerLink does not navigate to the corresponding component

In my case I had line-wrapper in my VS code and, apparently, there was no space between end of closing quote belonging to [routerLink] and next attribute. Line-wrapper split this in two lines so missing space went unnoticed.

Create controller for partial view in ASP.NET MVC

It does not need its own controller. You can use

@Html.Partial("../ControllerName/_Testimonials.cshtml")

This allows you to render the partial from any page. Just make sure the relative path is correct.

Colors in JavaScript console

In Chrome & Firefox (+31) you can add CSS in console.log messages:

_x000D_
_x000D_
console.log('%c Oh my heavens! ', 'background: #222; color: #bada55');
_x000D_
_x000D_
_x000D_

Console color example in Chrome

The same can be applied for adding multiple CSS to same command. syntax for multi coloring chrome console messages

References

What does "res.render" do, and what does the html file look like?

What does res.render do and what does the html file look like?

res.render() function compiles your template (please don't use ejs), inserts locals there, and creates html output out of those two things.


Answering Edit 2 part.

// here you set that all templates are located in `/views` directory
app.set('views', __dirname + '/views');

// here you set that you're using `ejs` template engine, and the
// default extension is `ejs`
app.set('view engine', 'ejs');

// here you render `orders` template
response.render("orders", {orders: orders_json});

So, the template path is views/ (first part) + orders (second part) + .ejs (third part) === views/orders.ejs


Anyway, express.js documentation is good for what it does. It is API reference, not a "how to use node.js" book.

How to put a tooltip on a user-defined function

@will's method is the best. Just add few lines about the details for the people didn't use ExcelDNA before like me.

Download Excel-DNA IntelliSense from https://github.com/Excel-DNA/IntelliSense/releases

There are two version, one is for 64, check your Excel version. For my case, I'm using 64 version.

Open Excel/Developer/Add-Ins/Browse and select ExcelDna.IntelliSense64.xll.

Insert a new sheet, change name to "IntelliSense", add function description, as https://github.com/Excel-DNA/IntelliSense/wiki/Getting-Started

Then enjoy! :)

enter image description here

Completely cancel a rebase

In the case of a past rebase that you did not properly aborted, you now (Git 2.12, Q1 2017) have git rebase --quit

See commit 9512177 (12 Nov 2016) by Nguy?n Thái Ng?c Duy (pclouds). (Merged by Junio C Hamano -- gitster -- in commit 06cd5a1, 19 Dec 2016)

rebase: add --quit to cleanup rebase, leave everything else untouched

There are occasions when you decide to abort an in-progress rebase and move on to do something else but you forget to do "git rebase --abort" first. Or the rebase has been in progress for so long you forgot about it. By the time you realize that (e.g. by starting another rebase) it's already too late to retrace your steps. The solution is normally

rm -r .git/<some rebase dir>

and continue with your life.
But there could be two different directories for <some rebase dir> (and it obviously requires some knowledge of how rebase works), and the ".git" part could be much longer if you are not at top-dir, or in a linked worktree. And "rm -r" is very dangerous to do in .git, a mistake in there could destroy object database or other important data.

Provide "git rebase --quit" for this use case, mimicking a precedent that is "git cherry-pick --quit".


Before Git 2.27 (Q2 2020), The stash entry created by "git merge --autostash" to keep the initial dirty state were discarded by mistake upon "git rebase --quit", which has been corrected.

See commit 9b2df3e (28 Apr 2020) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 3afdeef, 29 Apr 2020)

rebase: save autostash entry into stash reflog on --quit

Signed-off-by: Denton Liu

In a03b55530a ("merge: teach --autostash option", 2020-04-07, Git v2.27.0 -- merge listed in batch #5), the --autostash option was introduced for git merge.

(See "Can “git pull” automatically stash and pop pending changes?")

Notably, when git merge --quit is run with an autostash entry present, it is saved into the stash reflog.

This is contrasted with the current behaviour of git rebase --quit where the autostash entry is simply just dropped out of existence.

Adopt the behaviour of git merge --quit in git rebase --quit and save the autostash entry into the stash reflog instead of just deleting it.

How to check whether a Button is clicked by using JavaScript

if(button.clicked==true) {
    console.log("Button Clicked");
} ==> // This Code Doesn't Work Properly So Please Use Below One // 


function check() { 
    console.log("Button Clicked");
}; // This Code Works Fine // 

var button= document.querySelector("button"); // Accessing The Button // 
button.addEventListener("click", check); // Adding event to call function when clicked // 

Spring Boot: Cannot access REST Controller on localhost (404)

for me, I was adding spring-web instead of the spring-boot-starter-web into my pom.xml

when i replace it from spring-web to spring-boot-starter-web, all maping is shown in the console log.

How to do Base64 encoding in node.js?

crypto now supports base64 (reference):

cipher.final('base64') 

So you could simply do:

var cipher = crypto.createCipheriv('des-ede3-cbc', encryption_key, iv);
var ciph = cipher.update(plaintext, 'utf8', 'base64');
ciph += cipher.final('base64');

var decipher = crypto.createDecipheriv('des-ede3-cbc', encryption_key, iv);
var txt = decipher.update(ciph, 'base64', 'utf8');
txt += decipher.final('utf8');

Codeigniter displays a blank page instead of error messages

Codeigniter doesn't seem to throw an error message when I was referencing a view that did not exist.

In my example I had within my controller:

$this->load->view('/admin/index/access_controls/groups/add');

Because the file did not exist, I got a blank "An error has occurred page". I changed the code to:

$this->load->view('/admin/access_controls/groups/add');

This was how I resolved the same issue you seem to be having, hope this helps someone some day.

How to find available directory objects on Oracle 11g system?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

Django templates: If false?

Just ran into this again (certain I had before and came up with a less-than-satisfying solution).

For a tri-state boolean semantic (for example, using models.NullBooleanField), this works well:

{% if test.passed|lower == 'false' %} ... {% endif %}

Or if you prefer getting excited over the whole thing...

{% if test.passed|upper == 'FALSE' %} ... {% endif %}

Either way, this handles the special condition where you don't care about the None (evaluating to False in the if block) or True case.

How should I do integer division in Perl?

Hope it works

int(9/4) = 2.

Thanks Manojkumar

Open Sublime Text from Terminal in macOS

if you have subl set up to be called from the command line, the proper command to open the current directory is:

subl .

"OS X Command Line" is a link on how to make sure everything is set up.

Please help me convert this script to a simple image slider

Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?

$('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

CSS:

.image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

JavaScript:

var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

http://jsfiddle.net/RmF57/

Assets file project.assets.json not found. Run a NuGet package restore

You will get required packages from "https://api.nuget.org/v3/index.json". Add this in Package Resources. Also make sure other packages are unchecked for time being. And Click Restore Nuget Package on Solution Explorer enter image description here

Load HTML file into WebView

In this case, using WebView#loadDataWithBaseUrl() is better than WebView#loadUrl()!

webView.loadDataWithBaseURL(url, 
        data,
        "text/html",
        "utf-8",
        null);

url: url/path String pointing to the directory all your JavaScript files and html links have their origin. If null, it's about:blank. data: String containing your hmtl file, read with BufferedReader for example

More info: WebView.loadDataWithBaseURL(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)

Get escaped URL parameter

What you really want is the jQuery URL Parser plugin. With this plugin, getting the value of a specific URL parameter (for the current URL) looks like this:

$.url().param('foo');

If you want an object with parameter names as keys and parameter values as values, you'd just call param() without an argument, like this:

$.url().param();

This library also works with other urls, not just the current one:

$.url('http://allmarkedup.com?sky=blue&grass=green').param();
$('#myElement').url().param(); // works with elements that have 'src', 'href' or 'action' attributes

Since this is an entire URL parsing library, you can also get other information from the URL, like the port specified, or the path, protocol etc:

var url = $.url('http://allmarkedup.com/folder/dir/index.html?item=value');
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'

It has other features as well, check out its homepage for more docs and examples.

Instead of writing your own URI parser for this specific purpose that kinda works in most cases, use an actual URI parser. Depending on the answer, code from other answers can return 'null' instead of null, doesn't work with empty parameters (?foo=&bar=x), can't parse and return all parameters at once, repeats the work if you repeatedly query the URL for parameters etc.

Use an actual URI parser, don't invent your own.

For those averse to jQuery, there's a version of the plugin that's pure JS.

1 = false and 0 = true?

I suspect it's just following the Linux / Unix standard for returning 0 on success.

Does it really say "1" is false and "0" is true?

How do you get the list of targets in a makefile?

I usually do:

grep install_targets Makefile

It would come back with something like:

install_targets = install-xxx1 install-xxx2 ... etc

I hope this helps

Adding blur effect to background in swift

For Swift 3 (iOS 10.0 and 8.0)

var darkBlur:UIBlurEffect = UIBlurEffect()

if #available(iOS 10.0, *) { //iOS 10.0 and above
    darkBlur = UIBlurEffect(style: UIBlurEffectStyle.prominent)//prominent,regular,extraLight, light, dark
} else { //iOS 8.0 and above
  darkBlur = UIBlurEffect(style: UIBlurEffectStyle.dark) //extraLight, light, dark
}
let blurView = UIVisualEffectView(effect: darkBlur)
blurView.frame = self.view.frame //your view that have any objects
blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(blurView)

Installing Java 7 on Ubuntu

Download java jdk<version>-linux-x64.tar.gz file from https://www.oracle.com/technetwork/java/javase/downloads/index.html.

Extract this file where you want. like: /home/java(Folder name created by user in home directory).

Now open terminal. Set path JAVA_HOME=path of your jdk folder(open jdk folder then right click on any folder, go to properties then copy the path using select all) and paste here.

Like: JAVA_HOME=/home/xxxx/java/JDK1.8.0_201

Let Ubuntu know where our JDK/JRE is located.

sudo update-alternatives --install /usr/bin/java java /home/xxxx/java/jdk1.8.0_201/bin/java 20000
sudo update-alternatives --install /usr/bin/javac javac /home/xxxx/java/jdk1.8.0_201/bin/javac 20000
sudo update-alternatives --install /usr/bin/javaws javaws /home/xxxx/java/jdk1.8.0_201/bin/javaws 20000

Tell Ubuntu that our installation i.e., jdk1.8.0_05 must be the default Java.

sudo update-alternatives --set java /home/xxxx/sipTest/jdk1.8.0_201/bin/java
sudo update-alternatives --set javac /home/xxxx/java/sipTest/jdk1.8.0_201/bin/javac
sudo update-alternatives --set javaws /home/xxxxx/sipTest/jdk1.8.0_201/bin/javaws

Now try:

$ sudo update-alternatives --config java

There are 3 choices for the alternative java (providing /usr/bin/java).

  Selection    Path                                  Priority   Status
------------------------------------------------------------
* 0            /usr/lib/jvm/java-6-oracle1/bin/java   1047      auto mode
  1            /usr/bin/gij-4.6                       1046      manual mode
  2            /usr/lib/jvm/java-6-oracle1/bin/java   1047      manual mode
  3            /usr/lib/jvm/jdk1.7.0_75/bin/java      1         manual mode

Press enter to keep the current choice [*], or type selection number: 3

update-alternatives: using /usr/lib/jvm/jdk1.7.0_75/bin/java to provide /usr/bin/java (java) in manual mode

Repeat the above for:

sudo update-alternatives --config javac
sudo update-alternatives --config javaws

Multi-dimensional associative arrays in JavaScript

It appears that for some applications, there is a far simpler approach to multi dimensional associative arrays in javascript.

  1. Given that the internal representation of all arrays are actually as objects of objects, it has been shown that the access time for numerically indexed elements is actually the same as for associative (text) indexed elements.

  2. the access time for first-level associative indexed elements does not rise as the number of actual elements increases.

Given this, there may be many cases where it is actually better to use a concatenated string approach to create the equivalence of a multidimensional elements. For example:

store['fruit']['apples']['granny']['price] = 10
store['cereal']['natural']['oats']['quack'] = 20

goes to:

store['fruit.apples.granny.price'] = 10
store['cereal.natural.oats.quack'] = 20

Advantages include:

  • no need to initialize sub-objects or figure out how to best combine objects
  • single-level access time. objects within objects need N times the access time
  • can use Object.keys() to extract all dimension information and..
  • can use the function regex.test(string) and the array.map function on the keys to pull out exactly what you want.
  • no hierarchy in the dimensions.
  • the "dot" is arbitrary - using underscore actually makes regex easier
  • there are lots of scripts for "flattening" JSON into and out of this format as well
  • can use all of the other nice array processing functions on keylist

How to convert array to a string using methods other than JSON?

serialize() is the function you are looking for. It will return a string representation of its input array or object in a PHP-specific internal format. The string may be converted back to its original form with unserialize().

But beware, that not all objects are serializable, or some may be only partially serializable and unable to be completely restored with unserialize().

$array = array(1,2,3,'foo');
echo serialize($array);

// Prints
a:4:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;s:3:"foo";}

How to get current SIM card number in Android?

You can use the TelephonyManager to do this:

TelephonyManager t = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); 
String number = t.getLine1Number();

Have you used

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

JavaScript + Unicode regexes

In JavaScript, \w and \d are ASCII, while \s is Unicode. Don't ask me why. JavaScript does support \p with Unicode categories, which you can use to emulate a Unicode-aware \w and \d.

For \d use \p{N} (numbers)

For \w use [\p{L}\p{N}\p{Pc}\p{M}] (letters, numbers, underscores, marks)

Update: Unfortunately, I was wrong about this. JavaScript does does not officially support \p either, though some implementations may still support this. The only Unicode support in JavaScript regexes is matching specific code points with \uFFFF. You can use those in ranges in character classes.

Retrieve column values of the selected row of a multicolumn Access listbox

Use listboxControl.Column(intColumn,intRow). Both Column and Row are zero-based.

Access 2013 - Cannot open a database created with a previous version of your application

As noted in another answer, the official word from Microsoft is to open an Access 97 file in Access 2003 and upgrade it to a newer file format. Unfortunately, from now on many people will have difficulty getting their hands on a legitimate copy of Access 2003 (or any other version prior to Access 2013, or whatever the latest version happens to be).

In that case, a possible workaround would be to

  • install a 32-bit version of SQL Server Express Edition, and then
  • have the SQL Server import utility use Jet* ODBC to import the tables into SQL Server.

I just tried that with a 32-bit version of SQL Server 2008 R2 Express Edition and it worked for me. Access 2013 adamantly refused to have anything to do with the Access 97 file, but SQL Server imported the tables without complaint.

At that point you could import the tables from SQL Server into an Access 2013 database. Or, if your goal was simply to get the data out of the Access 97 file then you could continue to work with it in SQL Server, or move it to some other platform, or whatever.

*Important: The import needs to be done using the older Jet ODBC driver ...

Microsoft Access Driver (*.mdb)

... which ships with Windows but is only available to 32-bit applications. The Access 2013 version of the newer Access Database Engine ("ACE") ODBC driver ...

Microsoft Access Driver (*.mdb, *.accdb)

also refuses to read Access 97 files (with the same error message cited in the question).

How to specify multiple conditions in an if statement in javascript

Here is an alternative way to do that.

const conditionsArray = [
    condition1, 
    condition2,
    condition3,
]

if (conditionsArray.indexOf(false) === -1) {
    "do somthing"
}

Or ES6

if (!conditionsArray.includes(false)) {
   "do somthing"
}

How do I create batch file to rename large number of files in a folder?

you can do this easily without manual editing or using fancy text editors. Here's a vbscript.

Set objFS = CreateObject("Scripting.FileSystemObject")
strFolder="c:\test"
Set objFolder = objFS.GetFolder(strFolder)
For Each strFile In objFolder.Files
    If objFS.GetExtensionName(strFile) = "jpg" Then    
        strFileName = strFile.Name
        If InStr(strFileName,"Vacation2010") > 0 Then           
            strNewFileName = Replace(strFileName,"Vacation2010","December")
            strFile.Name = strNewFileName
        End If 
    End If  
Next 

save as myscript.vbs and

C:\test> cscript //nologo myscript.vbs 

Can git undo a checkout of unstaged files

Dude,

lets say you're a very lucky guy just like I've been, go back to your editor and do an undo(command + Z for mac), you should see your lost content in the file. Hope it helped you. Of course, this will work only for existing files.

Typescript: How to extend two classes?

I found an up-to-date & unparalleled solution: https://www.npmjs.com/package/ts-mixer

You are welcome :)

How can I stop float left?

Okay I just realized the answer is to remove the first float left from the first DIV. Don't know why I didn't see that before.

Drop all tables command

To delete also views add 'view' keyword:

delete from sqlite_master where type in ('view', 'table', 'index', 'trigger');

How can I configure my makefile for debug and release builds?

You can use Target-specific Variable Values. Example:

CXXFLAGS = -g3 -gdwarf2
CCFLAGS = -g3 -gdwarf2

all: executable

debug: CXXFLAGS += -DDEBUG -g
debug: CCFLAGS += -DDEBUG -g
debug: executable

executable: CommandParser.tab.o CommandParser.yy.o Command.o
    $(CXX) -o output CommandParser.yy.o CommandParser.tab.o Command.o -lfl

CommandParser.yy.o: CommandParser.l 
    flex -o CommandParser.yy.c CommandParser.l
    $(CC) -c CommandParser.yy.c

Remember to use $(CXX) or $(CC) in all your compile commands.

Then, 'make debug' will have extra flags like -DDEBUG and -g where as 'make' will not.

On a side note, you can make your Makefile a lot more concise like other posts had suggested.

Adding link a href to an element using css

No. Its not possible to add link through css. But you can use jquery

$('.case').each(function() {
  var link = $(this).html();
  $(this).contents().wrap('<a href="example.com/script.php?id="></a>');
});

Here the demo: http://jsfiddle.net/r5uWX/1/

Bubble Sort Homework

The goal of bubble sort is to move the heavier items at the bottom in each round, while moving the lighter items up. In the inner loop, where you compare the elements, you don't have to iterate the whole list in each turn. The heaviest is already placed last. The swapped variable is an extra check so we can mark that the list is now sorted and avoid continuing with unnecessary calculations.

def bubble(badList):
    length = len(badList)
    for i in range(0,length):
        swapped = False
        for element in range(0, length-i-1):
            if badList[element] > badList[element + 1]:
                hold = badList[element + 1]
                badList[element + 1] = badList[element]
                badList[element] = hold
                swapped = True
        if not swapped: break

    return badList

Your version 1, corrected:

def bubble(badList):
    length = len(badList) - 1
    unsorted = True
    while unsorted:
        unsorted = False
        for element in range(0,length):
            #unsorted = False
            if badList[element] > badList[element + 1]:
                 hold = badList[element + 1]
                 badList[element + 1] = badList[element]
                 badList[element] = hold
                 unsorted = True
                 #print badList
             #else:
                 #unsorted = True

     return badList

Stop an input field in a form from being submitted

_x000D_
_x000D_
$('#serialize').click(function () {_x000D_
  $('#out').text(_x000D_
    $('form').serialize()_x000D_
  );_x000D_
});_x000D_
_x000D_
$('#exclude').change(function () {_x000D_
  if ($(this).is(':checked')) {_x000D_
    $('[name=age]').attr('form', 'fake-form-id');_x000D_
  } else {_x000D_
    $('[name=age]').removeAttr('form');    _x000D_
  }_x000D_
  _x000D_
  $('#serialize').click();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form action="/">_x000D_
  <input type="text" value="John" name="name">_x000D_
  <input type="number" value="100" name="age">_x000D_
</form>_x000D_
_x000D_
<input type="button" value="serialize" id="serialize">_x000D_
<label for="exclude">  _x000D_
  <input type="checkbox" value="exclude age" id="exclude">_x000D_
  exlude age_x000D_
</label>_x000D_
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

Python Write bytes to file

Write bytes and Create the file if not exists:

f = open('./put/your/path/here.png', 'wb')
f.write(data)
f.close()

wb means open the file in write binary mode.

Java method: Finding object in array list given a known attribute value

List<YourClass> list = ArrayList<YourClass>();


List<String> userNames = list.stream().map(m -> m.getUserName()).collect(Collectors.toList());

output: ["John","Alex"]

Bash script to calculate time elapsed

Either $(()) or $[] will work for computing the result of an arithmetic operation. You're using $() which is simply taking the string and evaluating it as a command. It's a bit of a subtle distinction. Hope this helps.

As tink pointed out in the comments on this answer, $[] is deprecated, and $(()) should be favored.

Can I escape a double quote in a verbatim string literal?

This should help clear up any questions you may have: C# literals

Here is a table from the linked content:

Regular literal Verbatim literal Resulting string
"Hello" @"Hello" Hello
"Backslash: \\" @"Backslash: \" Backslash: \
"Quote: \"" @"Quote: """ Quote: "
"CRLF:\r\nPost CRLF" @"CRLF:
Post CRLF"
CRLF:
Post CRLF

Difference between _self, _top, and _parent in the anchor tag target attribute

target="_blank"

Opens a new window and show the related data.

target="_self"

Opens the window in the same frame, it means existing window itself.

target="_top"

Opens the linked document in the full body of the window.

target="_parent"

Opens data in the size of parent window.

How to check the input is an integer or not in Java?

If the user input is a String then you can try to parse it as an integer using parseInt method, which throws NumberFormatException when the input is not a valid number string:

try {

    int intValue = Integer.parseInt(stringUserInput));
}(NumberFormatException e) {
    System.out.println("Input is not a valid integer");
}

Insert data using Entity Framework model

[HttpPost] // it use when you write logic on button click event

public ActionResult DemoInsert(EmployeeModel emp)
{
    Employee emptbl = new Employee();    // make object of table
    emptbl.EmpName = emp.EmpName;
    emptbl.EmpAddress = emp.EmpAddress;  // add if any field you want insert
    dbc.Employees.Add(emptbl);           // pass the table object 
    dbc.SaveChanges();

    return View();
}

How do I set ANDROID_SDK_HOME environment variable?

This worked for me:

  1. Open control panel
  2. click System
  3. Then go to Change Environment Variables
  4. Then click create a new environment variables
  5. Create a new variable named ANDROID_HOME path C:\Android\sdk

How to add new contacts in android

This is working fine for me:

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
            int rawContactInsertIndex = ops.size();

            ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
                    .withValue(RawContacts.ACCOUNT_TYPE, null)
                    .withValue(RawContacts.ACCOUNT_NAME, null).build());
            ops.add(ContentProviderOperation
                    .newInsert(Data.CONTENT_URI)
                    .withValueBackReference(Data.RAW_CONTACT_ID,rawContactInsertIndex)
                    .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
                    .withValue(StructuredName.DISPLAY_NAME, "Vikas Patidar") // Name of the person
                    .build());
            ops.add(ContentProviderOperation
                    .newInsert(Data.CONTENT_URI)
                    .withValueBackReference(
                            ContactsContract.Data.RAW_CONTACT_ID,   rawContactInsertIndex)
                    .withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
                    .withValue(Phone.NUMBER, "9999999999") // Number of the person
                    .withValue(Phone.TYPE, Phone.TYPE_MOBILE).build()); // Type of mobile number                    
            try
            {
                ContentProviderResult[] res = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
            }
            catch (RemoteException e)
            { 
                // error
            }
            catch (OperationApplicationException e) 
            {
                // error
            }       

Changing ImageView source

get ID of ImageView as

ImageView imgFp = (ImageView) findViewById(R.id.imgFp);

then Use

imgFp.setImageResource(R.drawable.fpscan);

to set source image programatically instead from XML.

Powershell equivalent of bash ampersand (&) for forking/running background processes

ps2> start-job {start-sleep 20}

i have not yet figured out how to get stdout in realtime, start-job requires you to poll stdout with get-job

update: i couldn't start-job to easily do what i want which is basically the bash & operator. here's my best hack so far

PS> notepad $profile #edit init script -- added these lines
function beep { write-host `a }
function ajp { start powershell {ant java-platform|out-null;beep} } #new window, stderr only, beep when done
function acjp { start powershell {ant clean java-platform|out-null;beep} }
PS> . $profile #re-load profile script
PS> ajp

How to implement authenticated routes in React Router 4?

Here is the simple clean protected route

const ProtectedRoute 
  = ({ isAllowed, ...props }) => 
     isAllowed 
     ? <Route {...props}/> 
     : <Redirect to="/authentificate"/>;
const _App = ({ lastTab, isTokenVerified })=> 
    <Switch>
      <Route exact path="/authentificate" component={Login}/>
      <ProtectedRoute 
         isAllowed={isTokenVerified} 
         exact 
         path="/secrets" 
         component={Secrets}/>
      <ProtectedRoute 
         isAllowed={isTokenVerified} 
         exact 
         path="/polices" 
         component={Polices}/>
      <ProtectedRoute 
         isAllowed={isTokenVerified} 
         exact 
         path="/grants" component={Grants}/>
      <Redirect from="/" to={lastTab}/>
    </Switch>

isTokenVerified is a method call to check the authorization token basically it returns boolean.

How to specify new GCC path for CMake

An alternative solution is to configure your project through cmake-gui, starting from a clean build directory. Among the options you have available at the beginning, there's the possibility to choose the exact path to the compilers

How do I show multiple recaptchas on a single page?

To add a bit to raphadko's answer: since you have multiple captchas (on one page), you can't use the (universal) g-recaptcha-response POST parameter (because it holds only one captcha's response). Instead, you should use grecaptcha.getResponse(opt_widget_id) call for each captcha. Here's my code (provided each captcha is inside its form):

HTML:

<form ... />

<div id="RecaptchaField1"></div>

<div class="field">
  <input type="hidden" name="grecaptcha" id="grecaptcha" />
</div>

</form>

and

<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>

JavaScript:

var CaptchaCallback = function(){
    var widgetId;

    $('[id^=RecaptchaField]').each(function(index, el) {

         widgetId = grecaptcha.render(el.id, {'sitekey' : 'your_site_key'});

         $(el).closest("form").submit(function( event ) {

            this.grecaptcha.value = "{\"" + index + "\" => \"" + grecaptcha.getResponse(widgetId) + "\"}"

         });
    });
};

Notice that I apply the event delegation (see refresh DOM after append element ) to all the dynamically modified elements. This binds every individual captha's response to its form submit event.

String.format() to format double in java

String.format("%1$,.2f", myDouble);

String.format automatically uses the default locale.

JVM option -Xss - What does it do exactly?

Each thread has a stack which used for local variables and internal values. The stack size limits how deep your calls can be. Generally this is not something you need to change.

ruby LoadError: cannot load such file

I created my own Gem, but I did it in a directory that is not in my load path:

$ pwd
/Users/myuser/projects
$ gem build my_gem/my_gem.gemspec

Then I ran irb and tried to load the Gem:

> require 'my_gem'
LoadError: cannot load such file -- my_gem

I used the global variable $: to inspect my load path and I realized I am using RVM. And rvm has specific directories in my load path $:. None of those directories included my ~/projects directory where I created the custom gem.

So one solution is to modify the load path itself:

$: << "/Users/myuser/projects/my_gem/lib"

Note that the lib directory is in the path, which holds the my_gem.rb file which will be required in irb:

> require 'my_gem'
 => true 

Now if you want to install the gem in RVM path, then you would need to run:

$ gem install my_gem

But it will need to be in a repository like rubygems.org.

$ gem push my_gem-0.0.0.gem
Pushing gem to RubyGems.org...
Successfully registered gem my_gem

How to find the index of an element in an array in Java?

This way should work, change "char" to "Character":

public static void main(String[] args){
  Character[] list = {'m', 'e', 'y'};
  System.out.println(Arrays.asList(list).indexOf('e')); // print "1"
}

Why does the 'int' object is not callable error occur when using the sum() function?

This means that somewhere else in your code, you have something like:

sum = 0

Which shadows the builtin sum (which is callable) with an int (which isn't).

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

Works for me: IntelliJ IDEA 13.1.1, JUnit4, Java 6

I changed the file in project path: [PROJECT_NAME].iml

Replaced:

  <library>
    <CLASSES>
      <root url="jar://$APPLICATION_HOME_DIR$/lib/junit-4.11.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>

By:

  <library name="JUnit4">
    <CLASSES>
      <root url="jar://$APPLICATION_HOME_DIR$/lib/junit-4.11.jar!/" />
      <root url="jar://$APPLICATION_HOME_DIR$/lib/hamcrest-core-1.3.jar!/" />
      <root url="jar://$APPLICATION_HOME_DIR$/lib/hamcrest-library-1.3.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>

So the final .iml file is:

<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
  <component name="NewModuleRootManager" inherit-compiler-output="true">
    <exclude-output />
    <content url="file://$MODULE_DIR$">
      <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/tests" isTestSource="true" />
    </content>
    <orderEntry type="inheritedJdk" />
    <orderEntry type="sourceFolder" forTests="false" />
    <orderEntry type="module-library">
      <library name="JUnit4">
        <CLASSES>
          <root url="jar://$APPLICATION_HOME_DIR$/lib/junit-4.11.jar!/" />
          <root url="jar://$APPLICATION_HOME_DIR$/lib/hamcrest-core-1.3.jar!/" />
          <root url="jar://$APPLICATION_HOME_DIR$/lib/hamcrest-library-1.3.jar!/" />
        </CLASSES>
        <JAVADOC />
        <SOURCES />
      </library>
    </orderEntry>
  </component>
</module>

P.S.: save the file and don't let to IntelliJ Idea reload it. Just once.

How can I decrypt MySQL passwords

Simply best way from linux server

sudo mysql --defaults-file=/etc/mysql/debian.cnf -e 'use mysql;UPDATE user SET password=PASSWORD("snippetbucket-technologies") WHERE user="root";FLUSH PRIVILEGES;'

This way work for any linux server, I had 100% sure on Debian and Ubuntu you win.

Show/hide image with JavaScript

You can do this with jquery just visit http://jquery.com/ to get the link then do something like this

<a id="show_image">Show Image</a>
<img id="my_images" style="display:none" src="http://myimages.com/img.png">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $('#show_image').on("click", function(){
         $('#my_images').show('slow');
      });
   });
</script>

or if you would like the link to turn the image on and off do this

<a id="show_image">Show Image</a>
<img id="my_images" style="display:none;" src="http://myimages.com/img.png">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $('#show_image').on("click", function(){
         $('#my_images').toggle();
      });
   });
</script>

How can I solve a connection pool problem between ASP.NET and SQL Server?

This problem I have encountered before. It ended up being an issue with the firewall. I just added a rule to the firewall. I had to open port 1433 so the SQL server can connect to the server.

Composer update memory limit

This error can occur especially when you are updating large libraries or libraries with a lot of dependencies. Composer can be quite memory hungry.

Be sure that your composer itself is updated to the latest version:

php composer.phar --self-update

You can increase the memory limit for composer temporarily by adding the composer memory limit environment variable:

COMPOSER_MEMORY_LIMIT=128MB php composer.phar update

Use the format “128M” for megabyte or “2G” for gigabyte. You can use the value “-1” to ignore the memory limit completely.

Another way would be to increase the PHP memory limit:

php -d memory_limit=512M composer.phar update ...

Converting a date string to a DateTime object using Joda Time library

Use DateTimeFormat:

DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime dt = formatter.parseDateTime(string);

Is there a command to restart computer into safe mode?

My first answer!

This will set the safemode switch:

bcdedit /set {current} safeboot minimal 

with networking:

bcdedit /set {current} safeboot network

then reboot the machine with

shutdown /r

to put back in normal mode via dos:

bcdedit /deletevalue {current} safeboot

How to get element by innerText

You can use a TreeWalker to go over the DOM nodes, and locate all text nodes that contain the text, and return their parents:

_x000D_
_x000D_
const findNodeByContent = (text, root = document.body) => {_x000D_
  const treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);_x000D_
_x000D_
  const nodeList = [];_x000D_
_x000D_
  while (treeWalker.nextNode()) {_x000D_
    const node = treeWalker.currentNode;_x000D_
_x000D_
    if (node.nodeType === Node.TEXT_NODE && node.textContent.includes(text)) {_x000D_
      nodeList.push(node.parentNode);_x000D_
    }_x000D_
  };_x000D_
_x000D_
  return nodeList;_x000D_
}_x000D_
_x000D_
const result = findNodeByContent('SearchingText');_x000D_
_x000D_
console.log(result);
_x000D_
<a ...>SearchingText</a>
_x000D_
_x000D_
_x000D_

Converting a Uniform Distribution to a Normal Distribution

The standard Python library module random has what you want:

normalvariate(mu, sigma)
Normal distribution. mu is the mean, and sigma is the standard deviation.

For the algorithm itself, take a look at the function in random.py in the Python library.

The manual entry is here

How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?

The command build in pipeline is there to trigger other jobs in jenkins.

Example on github

The job must exist in Jenkins and can be parametrized. As for the branch, I guess you can read it from git

How to customize listview using baseadapter

Create your own BaseAdapter class and use it as following.

 public class NotificationScreen extends Activity
{

@Override
protected void onCreate_Impl(Bundle savedInstanceState)
{
    setContentView(R.layout.notification_screen);

    ListView notificationList = (ListView) findViewById(R.id.notification_list);
    NotiFicationListAdapter notiFicationListAdapter = new NotiFicationListAdapter();
    notificationList.setAdapter(notiFicationListAdapter);

    homeButton = (Button) findViewById(R.id.home_button);

}

}

Make your own BaseAdapter class and its separate xml file.

public class NotiFicationListAdapter  extends BaseAdapter
{
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater=null;


public NotiFicationListAdapter(ArrayList data)
{
this.data=data;        
    inflater =(LayoutInflater)baseActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}



public int getCount() 
{
 return data.size();
}



public Object getItem(int position) 
{
 return position;
}



public long getItemId(int position) 
{
    return position;
}



public View getView(int position, View convertView, ViewGroup parent) 
{
View vi=convertView;
    if(convertView==null)

    vi = inflater.inflate(R.layout.notification_list_item, null);

    ImageView compleatImageView=(ImageView)vi.findViewById(R.id.complet_image);
    TextView name = (TextView)vi.findViewById(R.id.game_name); // name
    TextView email_id = (TextView)vi.findViewById(R.id.e_mail_id); // email ID
    TextView notification_message = (TextView)vi.findViewById(R.id.notification_message); // notification message



    compleatImageView.setBackgroundResource(R.id.address_book);
    name.setText(data.getIndex(position));
    email_id.setText(data.getIndex(position));
    notification_message.setTextdata.getIndex(position));

    return vi;
}

  }

BaseAdapter xml file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/inner_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_weight="4"
android:background="@drawable/list_view_frame"
android:gravity="center_vertical"
android:padding="5dp" >

<TextView
    android:id="@+id/game_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Game name"
    android:textColor="#FFFFFF"
    android:textSize="15dip"
    android:textStyle="bold"
    android:typeface="sans" />

<TextView
    android:id="@+id/e_mail_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/game_name"
    android:layout_marginTop="1dip"
    android:text="E-Mail Id"
    android:textColor="#FFFFFF"
    android:textSize="10dip" />

<TextView
    android:id="@+id/notification_message"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/game_name"
    android:layout_toRightOf="@id/e_mail_id"
    android:paddingLeft="5dp"
    android:text="Notification message"
    android:textColor="#FFFFFF"
    android:textSize="10dip" />



<ImageView
    android:id="@+id/complet_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_marginBottom="30dp"
    android:layout_marginRight="10dp"
    android:src="@drawable/complete_tag"
    android:visibility="invisible" />

</RelativeLayout>

Change it accordingly and use.

TypeError: 'builtin_function_or_method' object is not subscriptable

instead of writing listb.pop[0] write

listb.pop()[0]
         ^
         |

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

I experienced this error when trying to embed an iframe and then opening the site with Brave. The error went away when I changed to "Shields Down" for the site in question. Obviously, this is not a full solution, since anyone else visiting the site with Brave will run into the same issue. To actually resolve it I would need to do one of the other things listed on this page. But at least I now know where the problem lies.

How can I list all foreign keys referencing a given table in SQL Server?

I'd use the Database Diagramming feature in SQL Server Management Studio, but since you ruled that out - this worked for me in SQL Server 2008 (don't have 2005).

To get list of referring table and column names...

select 
    t.name as TableWithForeignKey, 
    fk.constraint_column_id as FK_PartNo, c.
    name as ForeignKeyColumn 
from 
    sys.foreign_key_columns as fk
inner join 
    sys.tables as t on fk.parent_object_id = t.object_id
inner join 
    sys.columns as c on fk.parent_object_id = c.object_id and fk.parent_column_id = c.column_id
where 
    fk.referenced_object_id = (select object_id 
                               from sys.tables 
                               where name = 'TableOthersForeignKeyInto')
order by 
    TableWithForeignKey, FK_PartNo

To get names of foreign key constraints

select distinct name from sys.objects where object_id in 
(   select fk.constraint_object_id from sys.foreign_key_columns as fk
    where fk.referenced_object_id = 
        (select object_id from sys.tables where name = 'TableOthersForeignKeyInto')
)

Use 'class' or 'typename' for template parameters?

According to Scott Myers, Effective C++ (3rd ed.) item 42 (which must, of course, be the ultimate answer) - the difference is "nothing".

Advice is to use "class" if it is expected T will always be a class, with "typename" if other types (int, char* whatever) may be expected. Consider it a usage hint.

Website screenshots

It's in Python, but going over the documentation and code you can see exactly how this is done. If you can run python, then it's a ready-made solution for you:

http://browsershots.org/

Note that everything can run on one machine for one platform, or one machine with virtual machines running the other platforms.

Free, open source, scroll to bottom of page for links to documentation, source code, and other information.

Table-level backup

Here are the steps you need. Step5 is important if you want the data. Step 2 is where you can select individual tables.

EDIT stack's version isn't quite readable... here's a full-size image http://i.imgur.com/y6ZCL.jpg

Here are the steps from John Sansom's answer

How do I run a VBScript in 32-bit mode on a 64-bit machine?

We can force vbscript always run with 32 bit mode by changing "system32" to "sysWOW64" in default value of key "Computer\HKLM\SOFTWARE]\Classes\VBSFile\Shell\Open\Command"

How to initialize a variable of date type in java?

Here's the Javadoc in Oracle's website for the Date class: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html
If you scroll down to "Constructor Summary," you'll see the different options for how a Date object can be instantiated. Like all objects in Java, you create a new one with the following:

Date firstDate = new Date(ConstructorArgsHere);

Now you have a bit of a choice. If you don't pass in any arguments, and just do this,

Date firstDate = new Date();

it will represent the exact date and time at which you called it. Here are some other constructors you may want to make use of:

Date firstDate1 = new Date(int year, int month, int date);
Date firstDate2 = new Date(int year, int month, int date, int hrs, int min);
Date firstDate3 = new Date(int year, int month, int date, int hrs, int min, int sec);

How to set commands output as a variable in a batch file

I most cases, creating a temporary file named after your variable name might be acceptable. (as you are probably using meaningful variables name...)

Here, my variable name is SSH_PAGEANT_AUTH_SOCK

dir /w "\\.\pipe\\"|find "pageant" > %temp%\SSH_PAGEANT_AUTH_SOCK && set /P SSH_PAGEANT_AUTH_SOCK=<%temp%\SSH_PAGEANT_AUTH_SOCK

Regex: Check if string contains at least one digit

you could use look-ahead assertion for this:

^(?=.*\d).+$

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

You need to fix your include_path system variable to point to the correct location.

To fix it edit the php.ini file. In that file you will find a line that says, "include_path = ...". (You can find out what the location of php.ini by running phpinfo() on a page.) Fix the part of the line that says, "\xampplite\php\pear\PEAR" to read "C:\xampplite\php\pear". Make sure to leave the semi-colons before and/or after the line in place.

Restart PHP and you should be good to go. To restart PHP in IIS you can restart the application pool assigned to your site or, better yet, restart IIS all together.

splitting a string into an array in C++ without using vector

#include <iostream>
#include <sstream>
#include <iterator>
#include <string>

using namespace std;

template <size_t N>
void splitString(string (&arr)[N], string str)
{
    int n = 0;
    istringstream iss(str);
    for (auto it = istream_iterator<string>(iss); it != istream_iterator<string>() && n < N; ++it, ++n)
        arr[n] = *it;
}

int main()
{
    string line = "test one two three.";
    string arr[4];

    splitString(arr, line);

    for (int i = 0; i < 4; i++)
       cout << arr[i] << endl;
}

How to execute python file in linux

Add this at the top of your file:

#!/usr/bin/python

This is a shebang. You can read more about it on Wikipedia.

After that, you must make the file executable via

chmod +x your_script.py

How to create a HTTP server in Android?

Another server you can try http://tjws.sf.net, actually it already provides Android enabled version.

How to convert image file data in a byte array to a Bitmap?

Just try this:

Bitmap bitmap = BitmapFactory.decodeFile("/path/images/image.jpg");
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* Ignored for PNGs */, blob);
byte[] bitmapdata = blob.toByteArray();

If bitmapdata is the byte array then getting Bitmap is done like this:

Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

Returns the decoded Bitmap, or null if the image could not be decoded.

What is the difference between declarative and imperative paradigm in programming?

Imperative programming
A programming language that requires programming discipline such as C/C++, Java, COBOL, FORTRAN, Perl and JavaScript. Programmers writing in such languages must develop a proper order of actions in order to solve the problem, based on a knowledge of data processing and programming.

Declarative programming
A computer language that does not require writing traditional programming logic; Users concentrate on defining the input and output rather than the program steps required in a procedural programming language such as C++ or Java.

Declarative programming examples are CSS, HTML, XML, XSLT, RegX.

Root user/sudo equivalent in Cygwin?

Use this to get an admin window with either bash or cmd running, from any directories context menue. Just right click on a directory name, and select the entry or hit the highlited button.

This is based on the chere tool and the unfortunately not working answer (for me) from link_boy. It works fine for me using Windows 8,

A side effect is the different color in the admin cmd window. To use this on bash, you can change the .bashrc file of the admin user.

I coudln't get the "background" version (right click into an open directory) to run. Feel free to add it.

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_bash]
@="&Bash Prompt Here"
"Icon"="C:\\cygwin\\Cygwin.ico"

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_bash\command]
@="C:\\cygwin\\bin\\bash -c \"/bin/xhere /bin/bash.exe '%L'\""

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_bash_root]
@="&Root Bash Prompt Here"
"Icon"="C:\\cygwin\\Cygwin.ico"
"HasLUAShield"=""

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_bash_root\command]
@="runas /savecred /user:administrator \"C:\\cygwin\\bin\\bash -c \\\"/bin/xhere /bin/bash.exe '%L'\\\"\""

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_cmd]
@="&Command Prompt Here"

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_cmd\command]
@="cmd.exe /k cd %L"
"HasLUAShield"=""

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_cmd_root]
@="Roo&t Command Prompt Here"
"HasLUAShield"=""

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_cmd_root\command]
@="runas /savecred /user:administrator \"cmd.exe /t:1E /k cd %L\""

How to grep for two words existing on the same line?

The main issue is that you haven't supplied the first grep with any input. You will need to reorder your command something like

grep "word1" logs | grep "word2"

If you want to count the occurences, then put a '-c' on the second grep.

box-shadow on bootstrap 3 container

You should give the container an id and use that in your custom css file (which should be linked after the bootstrap css):

#container { box-shadow: values }

When I catch an exception, how do I get the type, file, and line number?

Here is an example of showing the line number of where exception takes place.

import sys
try:
    print(5/0)
except Exception as e:
    print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)

print('And the rest of program continues')

How to find all the tables in MySQL with specific column names in them?

SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%wild%';

split string only on first instance of specified character

Replace the first instance with a unique placeholder then split from there.

"good_luck_buddy".replace(/\_/,'&').split('&')

["good","luck_buddy"]

This is more useful when both sides of the split are needed.

Representational state transfer (REST) and Simple Object Access Protocol (SOAP)

Well I'll begin with the second question: What are Web Services? , for obvious reasons.

WebServices are essentially pieces of logic(which you may vaguely refer to as a method) that expose certain functionality or data. The client implementing(technically speaking, consuming is the word) just needs to know what are the parameter(s) the method is going to accept and the type of data it is going to return(if at all it does).

The following Link says it all about REST & SOAP in an extremely lucid manner.

REST vs SOAP

If you also want to know when to choose what (REST or SOAP), all the more reason to go through it!

Switch focus between editor and integrated terminal in Visual Studio Code

While there are a lot of modal toggles and navigation shortcuts for VS Code, there isn't one specifically for "move from editor to terminal, and back again". However you can compose the two steps by overloading the key and using the when clause.

Open the keybindings.json from the editor: CMD-SHIFT-P -> Preferences: Open Keyboard Shortcuts File and add these entries:

// Toggle between terminal and editor focus
{ "key": "ctrl+`", "command": "workbench.action.terminal.focus"},
{ "key": "ctrl+`", "command": "workbench.action.focusActiveEditorGroup", "when": "terminalFocus"}

With these shortcuts I will focus between the editor and the Integrated Terminal using the same keystroke.

POST request with JSON body

I think cURL would be a good solution. This is not tested, but you can try something like this:

$body = '{
  "kind": "blogger#post",
  "blog": {
    "id": "8070105920543249955"
  },
  "title": "A new post",
  "content": "With <b>exciting</b> content..."
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/blogger/v3/blogs/8070105920543249955/posts/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Authorization: OAuth 2.0 token here"));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$result = curl_exec($ch);

How can I include css files using node, express, and ejs?

Use this in your server.js file

_x000D_
_x000D_
app.use(express.static('public'));
_x000D_
_x000D_
_x000D_

without the directory ( __dirname ) and then within your project folder create a new file and name it public then put all your static files inside it

How do I get a substring of a string in Python?

Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?

Maybe like myString[2:end]?

Yes, this actually works if you assign, or bind, the name,end, to constant singleton, None:

>>> end = None
>>> myString = '1234567890'
>>> myString[2:end]
'34567890'

Slice notation has 3 important arguments:

  • start
  • stop
  • step

Their defaults when not given are None - but we can pass them explicitly:

>>> stop = step = None
>>> start = 2
>>> myString[start:stop:step]
'34567890'

If leaving the second part means 'till the end', if you leave the first part, does it start from the start?

Yes, for example:

>>> start = None
>>> stop = 2
>>> myString[start:stop:step]
'12'

Note that we include start in the slice, but we only go up to, and not including, stop.

When step is None, by default the slice uses 1 for the step. If you step with a negative integer, Python is smart enough to go from the end to the beginning.

>>> myString[::-1]
'0987654321'

I explain slice notation in great detail in my answer to Explain slice notation Question.

SQL query to find Nth highest salary from a salary table

SELECT DISTINCT(column_name)
  FROM table_name 
  ORDER BY column_name DESC limit N-1,1;

where N represents the nth highest salary ..

Third highest salary :

SELECT DISTINCT(column_name)
 FROM table_name 
 ORDER BY column_name DESC limit 2,1;

Why is Ant giving me a Unsupported major.minor version error

If you're getting this error because you're purposefully trying to build to Java 6, but you have Java 7 elsewhere in Eclipse, then it may be because you are referencing a Java 7 tools.jar in a Java 6 environment.

You'll need to install the JDK 6 (not JRE) and add the JRE 6 tools.jar as a User Entry in the Classpath of the build configuration, listed above the JRE 7 tools.jar.

How can I get the selected VALUE out of a QCombobox?

if you are developing QGIS plugins then simply

self.dlg.cbo_load_net.currentIndex()

How to check if keras tensorflow backend is GPU or CPU version?

According to the documentation.

If you are running on the TensorFlow or CNTK backends, your code will automatically run on GPU if any available GPU is detected.

You can check what all devices are used by tensorflow by -

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

Also as suggested in this answer

import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

This will print whether your tensorflow is using a CPU or a GPU backend. If you are running this command in jupyter notebook, check out the console from where you have launched the notebook.

If you are sceptic whether you have installed the tensorflow gpu version or not. You can install the gpu version via pip.

pip install tensorflow-gpu

Why would one use nested classes in C++?

I don't use nested classes much, but I do use them now and then. Especially when I define some kind of data type, and I then want to define a STL functor designed for that data type.

For example, consider a generic Field class that has an ID number, a type code and a field name. If I want to search a vector of these Fields by either ID number or name, I might construct a functor to do so:

class Field
{
public:
  unsigned id_;
  string name_;
  unsigned type_;

  class match : public std::unary_function<bool, Field>
  {
  public:
    match(const string& name) : name_(name), has_name_(true) {};
    match(unsigned id) : id_(id), has_id_(true) {};
    bool operator()(const Field& rhs) const
    {
      bool ret = true;
      if( ret && has_id_ ) ret = id_ == rhs.id_;
      if( ret && has_name_ ) ret = name_ == rhs.name_;
      return ret;
    };
    private:
      unsigned id_;
      bool has_id_;
      string name_;
      bool has_name_;
  };
};

Then code that needs to search for these Fields can use the match scoped within the Field class itself:

vector<Field>::const_iterator it = find_if(fields.begin(), fields.end(), Field::match("FieldName"));

Installing PIL with pip

(Window) If Pilow not work try download pil at http://www.pythonware.com/products/pil/

Java using scanner enter key pressed

Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        Double d = scan.nextDouble();


        String newStr = "";
        Scanner charScanner = new Scanner( System.in ).useDelimiter( "(\\b|\\B)" ) ;
        while( charScanner.hasNext() ) { 
            String  c = charScanner.next();

            if (c.equalsIgnoreCase("\r")) {
                break;
            }
            else {
                newStr += c;    
            }
        }

        System.out.println("String: " + newStr);
        System.out.println("Int: " + i);
        System.out.println("Double: " + d);

This code works fine

Could pandas use column as index?

You can set the column index using index_col parameter available while reading from spreadsheet in Pandas.

Here is my solution:

  1. Firstly, import pandas as pd: import pandas as pd

  2. Read in filename using pd.read_excel() (if you have your data in a spreadsheet) and set the index to 'Locality' by specifying the index_col parameter.

    df = pd.read_excel('testexcel.xlsx', index_col=0)

    At this stage if you get a 'no module named xlrd' error, install it using pip install xlrd.

  3. For visual inspection, read the dataframe using df.head() which will print the following output sc

  4. Now you can fetch the values of the desired columns of the dataframe and print it

    sc2

HTTP status code 0 - Error Domain=NSURLErrorDomain?

The Response was Empty. Most of the case the codes will stats with 1xx, 2xx, 3xx, 4xx, 5xx.

List of HTTP status codes

How to change a css class style through Javascript?

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
        $("div").addClass(function(){
            return "par" ;
    });
});
</script>
<style>
.par {
    color: blue;
}
</style>
</head>
<body>
<div class="test">This is a paragraph.</div>
</body>
</html>

How do you get/set media volume (not ringtone volume) in Android?

If you happen to have a volume bar that you want to adjust –similar to what you see on iPhone's iPod app– here's how.

    @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    switch (keyCode) {
    case KeyEvent.KEYCODE_VOLUME_UP:
        audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
        //Raise the Volume Bar on the Screen
        volumeControl.setProgress( audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
                + AudioManager.ADJUST_RAISE);
        return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        //Adjust the Volume
        audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
        //Lower the VOlume Bar on the Screen
        volumeControl.setProgress(audioManager
                .getStreamVolume(AudioManager.STREAM_MUSIC)
                + AudioManager.ADJUST_LOWER);
        return true;
    default:
        return false;
    }

What is Teredo Tunneling Pseudo-Interface?

Is to do with IPv6

All the gory details here: http://www.microsoft.com/technet/network/ipv6/teredo.mspx

Some people have had issues with it, and disabled it, but as a general rule, if it aint broke...

Calling stored procedure with return value

ExecuteScalar(); will work, but an output parameter would be a superior solution.

What is the preferred/idiomatic way to insert into a map?

I just change the problem a little bit (map of strings) to show another interest of insert:

std::map<int, std::string> rancking;

rancking[0] = 42;  // << some compilers [gcc] show no error

rancking.insert(std::pair<int, std::string>(0, 42));// always a compile error

the fact that compiler shows no error on "rancking[1] = 42;" can have devastating impact !

Swift - How to convert String to Double

You can use StringEx. It extends String with string-to-number conversions including toDouble().

extension String {
    func toDouble() -> Double?
}

It verifies the string and fails if it can't be converted to double.

Example:

import StringEx

let str = "123.45678"
if let num = str.toDouble() {
    println("Number: \(num)")
} else {
    println("Invalid string")
}

How to set headers in http get request?

The Header field of the Request is public. You may do this :

req.Header.Set("name", "value")

Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

If embed no longer works for you, try with /v instead:

<iframe width="420" height="315" src="https://www.youtube.com/v/A6XUVjK9W4o" frameborder="0" allowfullscreen></iframe>

How to allocate aligned memory only using the standard library?

Perhaps they would have been satisfied with a knowledge of memalign? And as Jonathan Leffler points out, there are two newer preferable functions to know about.

Oops, florin beat me to it. However, if you read the man page I linked to, you'll most likely understand the example supplied by an earlier poster.

Comparing two maps

Quick Answer

You should use the equals method since this is implemented to perform the comparison you want. toString() itself uses an iterator just like equals but it is a more inefficient approach. Additionally, as @Teepeemm pointed out, toString is affected by order of elements (basically iterator return order) hence is not guaranteed to provide the same output for 2 different maps (especially if we compare two different maps).

Note/Warning: Your question and my answer assume that classes implementing the map interface respect expected toString and equals behavior. The default java classes do so, but a custom map class needs to be examined to verify expected behavior.

See: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

boolean equals(Object o)

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.

Implementation in Java Source (java.util.AbstractMap)

Additionally, java itself takes care of iterating through all elements and making the comparison so you don't have to. Have a look at the implementation of AbstractMap which is used by classes such as HashMap:

 // Comparison and hashing

    /**
     * Compares the specified object with this map for equality.  Returns
     * <tt>true</tt> if the given object is also a map and the two maps
     * represent the same mappings.  More formally, two maps <tt>m1</tt> and
     * <tt>m2</tt> represent the same mappings if
     * <tt>m1.entrySet().equals(m2.entrySet())</tt>.  This ensures that the
     * <tt>equals</tt> method works properly across different implementations
     * of the <tt>Map</tt> interface.
     *
     * <p>This implementation first checks if the specified object is this map;
     * if so it returns <tt>true</tt>.  Then, it checks if the specified
     * object is a map whose size is identical to the size of this map; if
     * not, it returns <tt>false</tt>.  If so, it iterates over this map's
     * <tt>entrySet</tt> collection, and checks that the specified map
     * contains each mapping that this map contains.  If the specified map
     * fails to contain such a mapping, <tt>false</tt> is returned.  If the
     * iteration completes, <tt>true</tt> is returned.
     *
     * @param o object to be compared for equality with this map
     * @return <tt>true</tt> if the specified object is equal to this map
     */
    public boolean equals(Object o) {
        if (o == this)
            return true;

        if (!(o instanceof Map))
            return false;
        Map<K,V> m = (Map<K,V>) o;
        if (m.size() != size())
            return false;

        try {
            Iterator<Entry<K,V>> i = entrySet().iterator();
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                K key = e.getKey();
                V value = e.getValue();
                if (value == null) {
                    if (!(m.get(key)==null && m.containsKey(key)))
                        return false;
                } else {
                    if (!value.equals(m.get(key)))
                        return false;
                }
            }
        } catch (ClassCastException unused) {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }

        return true;
    }

Comparing two different types of Maps

toString fails miserably when comparing a TreeMap and HashMap though equals does compare contents correctly.

Code:

public static void main(String args[]) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("2", "whatever2");
map.put("1", "whatever1");
TreeMap<String, Object> map2 = new TreeMap<String, Object>();
map2.put("2", "whatever2");
map2.put("1", "whatever1");

System.out.println("Are maps equal (using equals):" + map.equals(map2));
System.out.println("Are maps equal (using toString().equals()):"
        + map.toString().equals(map2.toString()));

System.out.println("Map1:"+map.toString());
System.out.println("Map2:"+map2.toString());
}

Output:

Are maps equal (using equals):true
Are maps equal (using toString().equals()):false
Map1:{2=whatever2, 1=whatever1}
Map2:{1=whatever1, 2=whatever2}

Get parent directory of running script

I Hope this will help you.

echo getcwd().'<br>'; // getcwd() will return current working directory
echo dirname(getcwd(),1).'<br>';
echo dirname(getcwd(),2).'<br>';
echo dirname(getcwd(),3).'<br>';

Output :

C:\wamp64\www\public_html\step
C:\wamp64\www\public_html
C:\wamp64\www
C:\wamp64

Regular expression to match a word or its prefix

Use this live online example to test your pattern:

enter image description here

Above screenshot taken from this live example: https://regex101.com/r/cU5lC2/1

Matching any whole word on the commandline.

I'll be using the phpsh interactive shell on Ubuntu 12.10 to demonstrate the PCRE regex engine through the method known as preg_match

Start phpsh, put some content into a variable, match on word.

el@apollo:~/foo$ phpsh

php> $content1 = 'badger'
php> $content2 = '1234'
php> $content3 = '$%^&'

php> echo preg_match('(\w+)', $content1);
1

php> echo preg_match('(\w+)', $content2);
1

php> echo preg_match('(\w+)', $content3);
0

The preg_match method used the PCRE engine within the PHP language to analyze variables: $content1, $content2 and $content3 with the (\w)+ pattern.

$content1 and $content2 contain at least one word, $content3 does not.

Match a specific words on the commandline without word bountaries

el@apollo:~/foo$ phpsh

php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'darty gun';
php> $gun4 = 'unicorn gun';

php> echo preg_match('(dart|fart)', $gun1);
1

php> echo preg_match('(dart|fart)', $gun2);
1

php> echo preg_match('(dart|fart)', $gun3);
1

php> echo preg_match('(dart|fart)', $gun4);
0

Variables gun1 and gun2 contain the string dart or fart which is correct, but gun3 contains darty and still matches, that is the problem. So onto the next example.

Match specific words on the commandline with word boundaries:

Word Boundaries can be force matched with \b, see: Visual analysis of what wordboundary is doing from jex.im/regulex

Regex Visual Image acquired from http://jex.im/regulex and https://github.com/JexCheng/regulex Example:

el@apollo:~/foo$ phpsh

php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'darty gun';
php> $gun4 = 'unicorn gun';

php> echo preg_match('(\bdart\b|\bfart\b)', $gun1);
1

php> echo preg_match('(\bdart\b|\bfart\b)', $gun2);
1

php> echo preg_match('(\bdart\b|\bfart\b)', $gun3);
0

php> echo preg_match('(\bdart\b|\bfart\b)', $gun4);
0

The \b asserts that we have a word boundary, making sure " dart " is matched, but " darty " isn't.

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

Why my regexp for hyphenated words doesn't work?

You can use this:

r'[a-z]+(?:-[a-z]+)*' 

How to equalize the scales of x-axis and y-axis in Python matplotlib?

Try something like:

import pylab as p
p.plot(x,y)
p.axis('equal')
p.show()

Print out the values of a (Mat) matrix in OpenCV C++

See the first answer to Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++
Then just loop over all the elements in cout << M.at<double>(0,0); rather than just 0,0

Or better still with the C++ interface:

cv::Mat M;
cout << "M = " << endl << " "  << M << endl << endl;

Setting the default Java character encoding

Solve this problem in my project. Hope it helps someone.

I use LIBGDX java framework and also had this issue in my android studio project. In Mac OS encoding is correct, but in Windows 10 special characters and symbols and also russian characters show as questions like: ????? and other incorrect symbols.

  1. Change in android studio project settings: File->Settings...->Editor-> File Encodings to UTF-8 in all three fields (Global Encoding, Project Encoding and Default below).

  2. In any java file set:

    System.setProperty("file.encoding","UTF-8");

  3. And for test print debug log:

    System.out.println("My project encoding is : "+ Charset.defaultCharset());

Printing 1 to 1000 without loop or conditionals

Function pointer (ab)use. No preprocessor magic to increase output. ANSI C.

#include <stdio.h>

int i=1;

void x10( void (*f)() ){
    f(); f(); f(); f(); f();
    f(); f(); f(); f(); f();
}

void I(){printf("%i ", i++);}
void D(){ x10( I ); }
void C(){ x10( D ); }
void M(){ x10( C ); }

int main(){
    M();
}

How do you add input from user into list in Python

code below allows user to input items until they press enter key to stop:

In [1]: items=[]
   ...: i=0
   ...: while 1:
   ...:     i+=1
   ...:     item=input('Enter item %d: '%i)
   ...:     if item=='':
   ...:         break
   ...:     items.append(item)
   ...: print(items)
   ...: 

Enter item 1: apple

Enter item 2: pear

Enter item 3: #press enter here
['apple', 'pear']

In [2]: 

Error: 'int' object is not subscriptable - Python

The problem is in the line,

int([x[age1]])

What you want is

x = int(age1)

You also need to convert the int to a string for the output...

print "Hi, " + name1+ " you will be 21 in: " + str(twentyone) + " years."

The complete script looks like,

name1 = raw_input("What's your name? ")
age1 = raw_input ("how old are you? ")
x = 0
x = int(age1)
twentyone = 21 - x
print "Hi, " + name1+ " you will be 21 in: " + str(twentyone) + " years."

Angular 4 - get input value

HTML Component

<input type="text" [formControl]="txtValue">

TS Component

public txtValue = new FormControl('', { validators:[Validators.required] });

We can use this method to save using API. LearnersModules is the module file on our Angular files SaveSampleExams is the service file is one function method.

>  this.service.SaveSampleExams(LearnersModules).subscribe(
>             (data) => {
>               this.dataSaved = true;
>               LearnersModules.txtValue = this.txtValue.value; 
>              });

Set Encoding of File to UTF8 With BOM in Sublime Text 3

Into the Preferences > Setting - Default

You will have the next by default:

// Display file encoding in the status bar
    "show_encoding": false

You could change it or like cdesmetz said set your user settings.

ASP.NET MVC Page Won't Load and says "The resource cannot be found"

Make sure you're not telling IIS to check and see if a file exists before serving it up. This one has bitten me a couple times. Do the following:

Open IIS manager. Right click on your MVC website and click properties. Open the Virtual Directory tab. Click the Configuration... button. Under Wildcard application maps, make sure you have a mapping to c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll. MAKE SURE "Verify the file exists" IS NOT CHECKED!

Java 32-bit vs 64-bit compatibility

Yes, Java bytecode (and source code) is platform independent, assuming you use platform independent libraries. 32 vs. 64 bit shouldn't matter.

jQuery removeClass wildcard

$('div').attr('class', function(i, c){
    return c.replace(/(^|\s)color-\S+/g, '');
});

Can HTML checkboxes be set to readonly?

When posting an HTML checkbox to the server, it has a string value of 'on' or ''.

Readonly does not stop the user editing the checkbox, and disabled stops the value being posted back.
One way around this is to have a hidden element to store the actual value and the displayed checkbox is a dummy which is disabled. This way the checkbox state is persisted between posts.

Here is a function to do this. It uses a string of 'T' or 'F' and you can change this any way you like. This has been used in an ASP page using server side VB script.

public function MakeDummyReadonlyCheckbox(i_strName, i_strChecked_TorF)

    dim strThisCheckedValue

    if (i_strChecked_TorF = "T") then
        strThisCheckedValue = " checked "
        i_strChecked_TorF = "on"
    else
        strThisCheckedValue = ""
        i_strChecked_TorF = ""
    end if

    MakeDummyReadonlyCheckbox = "<input type='hidden' id='" & i_strName & "' name='" & i_strName & "' " & _
        "value='" & i_strChecked_TorF & "'>" & _
    "<input type='checkbox' disabled id='" & i_strName & "Dummy' name='" & i_strName & "Dummy' " & _
        strThisCheckedValue & ">"   
end function

public function GetCheckbox(i_objCheckbox)

    select case trim(i_objCheckbox)

        case ""
            GetCheckbox = "F"

        case else
            GetCheckbox = "T"

    end select

end function

At the top of an ASP page you can pickup the persisted value...

strDataValue = GetCheckbox(Request.Form("chkTest"))

and when you want to output your checkbox you can do this...

response.write MakeDummyReadonlyCheckbox("chkTest", strDataValue)

I have tested this and it works just fine. It also does not rely upon JavaScript.

how to check redis instance version?

To support the answers given above, The details of the redis instance can be obtained by

$ redis-cli
$ INFO

This gives all the info you may need

# Server
redis_version:5.0.5
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:da75abdfe06a50f8
redis_mode:standalone
os:Linux 5.3.0-51-generic x86_64
arch_bits:64
multiplexing_api:epoll
atomicvar_api:atomic-builtin
gcc_version:7.5.0
process_id:14126
run_id:adfaeec5683d7381a2a175a2111f6159b6342830
tcp_port:6379
uptime_in_seconds:16860
uptime_in_days:0
hz:10
configured_hz:10
lru_clock:15766886
executable:/tmp/redis-5.0.5/src/redis-server
config_file:

# Clients
connected_clients:22
....More Verbose

The version lies in the second line :)

Android findViewById() in Custom View

View Custmv;

 private void initViews() {
        inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Custmv = inflater.inflate(R.layout.id_number_edit_text_custom, this, true);
        editText = (EditText) findViewById(R.id.id_number_custom);
        loadButton = (ImageButton) findViewById(R.id.load_data_button);
        loadButton.setVisibility(RelativeLayout.INVISIBLE);
        loadData();
    }

private void loadData(){
        loadButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText firstName = (EditText) Custmv.getParent().findViewById(R.id.display_name);
                firstName.setText("Some Text");
            }
        });
    }

try like this.

How do I resolve ClassNotFoundException?

I just did

1.Invalidate caches and restart

2.Rebuilt my project which solved the problem

Check if a variable exists in a list in Bash

Matvey is right, but you should quote $x and consider any kind of "spaces" (e.g. new line) with

[[ $list =~ (^|[[:space:]])"$x"($|[[:space:]]) ]] && echo 'yes' || echo 'no' 

so, i.e.

# list_include_item "10 11 12" "2"
function list_include_item {
  local list="$1"
  local item="$2"
  if [[ $list =~ (^|[[:space:]])"$item"($|[[:space:]]) ]] ; then
    # yes, list include item
    result=0
  else
    result=1
  fi
  return $result
}

end then

`list_include_item "10 11 12" "12"`  && echo "yes" || echo "no"

or

if `list_include_item "10 11 12" "1"` ; then
  echo "yes"
else 
  echo "no"
fi

Note that you must use "" in case of variables:

`list_include_item "$my_list" "$my_item"`  && echo "yes" || echo "no"

R - Markdown avoiding package loading messages

This is an old question, but here's another way to do it.

You can modify the R code itself instead of the chunk options, by wrapping the source call in suppressPackageStartupMessages(), suppressMessages(), and/or suppressWarnings(). E.g:

```{r echo=FALSE}
suppressWarnings(suppressMessages(suppressPackageStartupMessages({
source("C:/Rscripts/source.R")
})
```

You can also put those functions around your library() calls inside the "source.R" script.

Sort array by value alphabetically php

Note that sort() operates on the array in place, so you only need to call

sort($a);
doSomething($a);

This will not work;

$a = sort($a);
doSomething($a);

What are the differences between json and simplejson Python modules?

Another reason projects use simplejson is that the builtin json did not originally include its C speedups, so the performance difference was noticeable.

How can I select an element in a component template?

to get the immediate next sibling ,use this

event.source._elementRef.nativeElement.nextElementSibling

Twitter Bootstrap 3.0 how do I "badge badge-important" now

If using a SASS version (eg: thomas-mcdonald's one), then you may want to be slightly more dynamic (honor existing variables) and create all badge contexts using the same technique as used for labels:

// Colors
// Contextual variations of badges
// Bootstrap 3.0 removed contexts for badges, we re-introduce them, based on what is done for labels
.badge-default {
  @include label-variant($label-default-bg);
}

.badge-primary {
  @include label-variant($label-primary-bg);
}

.badge-success {
  @include label-variant($label-success-bg);
}

.badge-info {
  @include label-variant($label-info-bg);
}

.badge-warning {
  @include label-variant($label-warning-bg);
}

.badge-danger {
  @include label-variant($label-danger-bg);
}

The LESS equivalent should be straightforward.

How to subscribe to an event on a service in Angular2?

Using alpha 28, I accomplished programmatically subscribing to event emitters by way of the eventEmitter.toRx().subscribe(..) method. As it is not intuitive, it may perhaps change in a future release.

Is an anchor tag without the href attribute safe?

The tag is fine to use without an href attribute. Contrary to many of the answers here, there are actually standard reasons for creating an anchor when there is no href. Semantically, "a" means an anchor or a link. If you use it for anything following that meaning, then you are fine.

One standard use of the a tag without an href is to create named links. This allows you to use an anchor with name=blah and later on you can create an anchor with href=#blah to link to the named section of the current page. However, this has been deprecated because you can also use IDs in the same manner. As an example, you could use a header tag with id=header and later you could have an anchor pointing to href=#header.

My point, however, is not to suggest using the name property. Only to provide one use case where you don't need an href, and therefore reasoning why it is not required.

In Java, should I escape a single quotation mark (') in String (double quoted)?

It's best practice only to escape the quotes when you need to - if you can get away without escaping it, then do!

The only times you should need to escape are when trying to put " inside a string, or ' in a character:

String quotes = "He said \"Hello, World!\"";
char quote = '\'';

Escaping special characters in Java Regular Expressions

Agree with Gray, as you may need your pattern to have both litrals (\[, \]) and meta-characters ([, ]). so with some utility you should be able to escape all character first and then you can add meta-characters you want to add on same pattern.

set default schema for a sql query

What i sometimes do when i need a lot of tablenames ill just get them plus their schema from the INFORMATION_SCHEMA system table: value


select  TABLE_SCHEMA + '.' + TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME in
(*select your table names*)

Pass multiple optional parameters to a C# function

Use a parameter array with the params modifier:

public static int AddUp(params int[] values)
{
    int sum = 0;
    foreach (int value in values)
    {
        sum += value;
    }
    return sum;
}

If you want to make sure there's at least one value (rather than a possibly empty array) then specify that separately:

public static int AddUp(int firstValue, params int[] values)

(Set sum to firstValue to start with in the implementation.)

Note that you should also check the array reference for nullity in the normal way. Within the method, the parameter is a perfectly ordinary array. The parameter array modifier only makes a difference when you call the method. Basically the compiler turns:

int x = AddUp(4, 5, 6);

into something like:

int[] tmp = new int[] { 4, 5, 6 };
int x = AddUp(tmp);

You can call it with a perfectly normal array though - so the latter syntax is valid in source code as well.

Where to download Microsoft Visual c++ 2003 redistributable

Storm's answer is not correct. No hard feelings Storm, and apologies to the OP as I'm a bit late to the party here (wish I could have helped sooner, but I didn't run into the problem until today, or this stack overflow answer until I was figuring out a solution.)

The Visual C++ 2003 runtime was not available as a seperate download because it was included with the .NET 1.1 runtime.

If you install the .NET 1.1 runtime you will get msvcr71.dll installed, and in addition added to C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322.

The .NET 1.1 runtime is available here: http://www.microsoft.com/downloads/en/details.aspx?familyid=262d25e3-f589-4842-8157-034d1e7cf3a3&displaylang=en (23.1 MB)

If you are looking for a file that ends with a "P" such as msvcp71.dll, this indicates that your file was compiled against a C++ runtime (as opposed to a C runtime), in some situations I noticed these files were only installed when I installed the full SDK. If you need one of these files, you may need to install the full .NET 1.1 SDK as well, which is available here: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=9b3a2ca6-3647-4070-9f41-a333c6b9181d (106.2 MB)

After installing the SDK I now have both msvcr71.dll and msvcp71.dll in my System32 folder, and the application I'm trying to run (boomerang c++ decompiler) works fine without any missing DLL errors.

Also on a side note: be VERY aware of the difference between a Hotfix Update and a Regular Update. As noted in the linked KB932298 download (linked below by Storm): "Please be aware this Hotfix has not gone through full Microsoft product regression testing nor has it been tested in combination with other Hotfixes."

Hotfixes are NOT meant for general users, but rather users who are facing a very specific problem. As described in the article only install that Hotfix if you are have having specific daylight savings time issues with the rules that changed in 2007. -- Likely this was a pre-release for customers who "just couldn't wait" for the official update (probably for some business critical application) -- for regular users Windows Update should be all you need.

Thanks, and I hope this helps others who run into this issue!

Get class name using jQuery

If you're going to use the split function to extract the class names, then you're going to have to compensate for potential formatting variations that could produce unexpected results. For example:

" myclass1  myclass2 ".split(' ').join(".")

produces

".myclass1..myclass2."

I think you're better off using a regular expression to match on set of allowable characters for class names. For example:

" myclass1  myclass2  ".match(/[\d\w-_]+/g);

produces

["myclass1", "myclass2"]

The regular expression is probably not complete, but hopefully you understand my point. This approach mitigates the possibility of poor formatting.

IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager

If you have crash with popBackStack() or popBackStackImmediate() method please try fixt with:

        if (!fragmentManager.isStateSaved()) {
            fragmentManager.popBackStackImmediate();
        }

This is worked for me as well.

Android Lint contentDescription warning

Since it is only a warning you can suppress it. Go to your XML's Graphical Layout and do this:

  1. Click on the right top corner red button

    enter image description here

  2. Select "Disable Issue Type" (for example)

    enter image description here

How do I enumerate the properties of a JavaScript object?

Python's dict has 'keys' method, and that is really useful. I think in JavaScript we can have something this:

function keys(){
    var k = [];
    for(var p in this) {
        if(this.hasOwnProperty(p))
            k.push(p);
    }
    return k;
}
Object.defineProperty(Object.prototype, "keys", { value : keys, enumerable:false });

EDIT: But the answer of @carlos-ruana works very well. I tested Object.keys(window), and the result is what I expected.

EDIT after 5 years: it is not good idea to extend Object, because it can conflict with other libraries that may want to use keys on their objects and it will lead unpredictable behavior on your project. @carlos-ruana answer is the correct way to get keys of an object.

reading HttpwebResponse json response, C#

I'd use RestSharp - https://github.com/restsharp/RestSharp

Create class to deserialize to:

public class MyObject {
    public string Id { get; set; }
    public string Text { get; set; }
    ...
}

And the code to get that object:

RestClient client = new RestClient("http://whatever.com");
RestRequest request = new RestRequest("path/to/object");
request.AddParameter("id", "123");

// The above code will make a request URL of 
// "http://whatever.com/path/to/object?id=123"
// You can pick and choose what you need

var response = client.Execute<MyObject>(request);

MyObject obj = response.Data;

Check out http://restsharp.org/ to get started.

How do I get the browser scroll position in jQuery?

It's better to use $(window).scroll() rather than $('#Eframe').on("mousewheel")

$('#Eframe').on("mousewheel") will not trigger if people manually scroll using up and down arrows on the scroll bar or grabbing and dragging the scroll bar itself.

$(window).scroll(function(){
    var scrollPos = $(document).scrollTop();
    console.log(scrollPos);
});

If #Eframe is an element with overflow:scroll on it and you want it's scroll position. I think this should work (I haven't tested it though).

$('#Eframe').scroll(function(){
    var scrollPos = $('#Eframe').scrollTop();
    console.log(scrollPos);
});

Statically rotate font-awesome icons

In case someone else stumbles upon this question and wants it here is the SASS mixin I use.

@mixin rotate($deg: 90){
    $sDeg: #{$deg}deg;

    -webkit-transform: rotate($sDeg);
    -moz-transform: rotate($sDeg);
    -ms-transform: rotate($sDeg);
    -o-transform: rotate($sDeg);
    transform: rotate($sDeg);
}

Process.start: how to get the output?

Alright, for anyone who wants both Errors and Outputs read, but gets deadlocks with any of the solutions, provided in other answers (like me), here is a solution that I built after reading MSDN explanation for StandardOutput property.

Answer is based on T30's code:

static void runCommand()
{
    //* Create your Process
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = "/c DIR";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    //* Set ONLY ONE handler here.
    process.ErrorDataReceived += new DataReceivedEventHandler(ErrorOutputHandler);
    //* Start process
    process.Start();
    //* Read one element asynchronously
    process.BeginErrorReadLine();
    //* Read the other one synchronously
    string output = process.StandardOutput.ReadToEnd();
    Console.WriteLine(output);
    process.WaitForExit();
}

static void ErrorOutputHandler(object sendingProcess, DataReceivedEventArgs outLine) 
{
    //* Do your stuff with the output (write to console/log/StringBuilder)
    Console.WriteLine(outLine.Data);
}

"Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application

[Joke mode on]

You can fix this by adding this:

https://github.com/donavon/undefined-is-a-function

import { undefined } from 'undefined-is-a-function';
// Fixed! undefined is now a function.

[joke mode off]

How to break long string to multiple lines

You cannot use the VB line-continuation character inside of a string.

SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & _
"','" & txtContractStartDate.Value &  _
"','" & txtSeatNo.Value & _
"','" & txtFloor.Value & "','" & txtLeaves.Value & "')"

Are multiple `.gitignore`s frowned on?

You can have multiple .gitignore, each one of course in its own directory.
To check which gitignore rule is responsible for ignoring a file, use git check-ignore: git check-ignore -v -- afile.

And you can have different version of a .gitignore file per branch: I have already seen that kind of configuration for ensuring one branch ignores a file while the other branch does not: see this question for instance.

If your repo includes several independent projects, it would be best to reference them as submodules though.
That would be the actual best practices, allowing each of those projects to be cloned independently (with their respective .gitignore files), while being referenced by a specific revision in a global parent project.
See true nature of submodules for more.


Note that, since git 1.8.2 (March 2013) you can do a git check-ignore -v -- yourfile in order to see which gitignore run (from which .gitignore file) is applied to 'yourfile', and better understand why said file is ignored.
See "which gitignore rule is ignoring my file?"

How to set a header in an HTTP response?

In my Controller, I merely added an HttpServletResponse parameter and manually added the headers, no filter or intercept required and it works fine:

httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
httpServletResponse.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, X-Auth-Token, X-Csrf-Token, WWW-Authenticate, Authorization");
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "false");
httpServletResponse.setHeader("Access-Control-Max-Age", "3600");

Find which rows have different values for a given column in Teradata SQL

Personally, I would print them to a file using Perl or Python in the format

<COL_NAME>:  <COL_VAL>

for each row so that the file has as many lines as there are columns. Then I'd do a diff between the two files, assuming you are on Unix or compare them using some equivalent utilty on another OS. If you have multiple recordsets (i.e. more than one row), I would prepend to each file row and then the file would have NUM_DB_ROWS * NUM_COLS lines

What does jQuery.fn mean?

In jQuery, the fn property is just an alias to the prototype property.

The jQuery identifier (or $) is just a constructor function, and all instances created with it, inherit from the constructor's prototype.

A simple constructor function:

function Test() {
  this.a = 'a';
}
Test.prototype.b = 'b';

var test = new Test(); 
test.a; // "a", own property
test.b; // "b", inherited property

A simple structure that resembles the architecture of jQuery:

(function() {
  var foo = function(arg) { // core constructor
    // ensure to use the `new` operator
    if (!(this instanceof foo))
      return new foo(arg);
    // store an argument for this example
    this.myArg = arg;
    //..
  };

  // create `fn` alias to `prototype` property
  foo.fn = foo.prototype = {
    init: function () {/*...*/}
    //...
  };

  // expose the library
  window.foo = foo;
})();

// Extension:

foo.fn.myPlugin = function () {
  alert(this.myArg);
  return this; // return `this` for chainability
};

foo("bar").myPlugin(); // alerts "bar"

JavaScript to scroll long page to DIV

I personally found Josh's jQuery-based answer above to be the best I saw, and worked perfectly for my application... of course, I was already using jQuery... I certainly wouldn't have included the whole jQ library just for that one purpose.

Cheers!

EDIT: OK... so mere seconds after posting this, I saw another answer just below mine (not sure if still below me after an edit) that said to use:

document.getElementById('your_element_ID_here').scrollIntoView();

This works perfectly and in so much less code than the jQuery version! I had no idea that there was a built-in function in JS called .scrollIntoView(), but there it is! So, if you want the fancy animation, go jQuery. Quick n' dirty... use this one!

jQuery: enabling/disabling datepicker

I have a single-page app in our company intranet where certain date fields need to be "blocked" under certain circumstances. Those date fields have a datepicker binding.

Making the fields read-only wasn't enough to block the fields, as datepicker still triggers when the field receives focus.

Disabling the field (or disabling datepicker) have side effects with serialize() or serializeArray().

One of the options was to unbind datepicker from those fields and making them "normal" fields. But one easiest solution is to make the field (or fields) read-only and to avoid datepicker from acting when receive focus.

$('#datefield').attr('readonly',true).datepicker("option", "showOn", "off");

Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php

If you want to read large files, you should read them bit by bit instead of reading them at once.
It’s simple math: If you read a 1 MB large file at once, than at least 1 MB of memory is needed at the same time to hold the data.

So you should read them bit by bit using fopen & fread.

Get push notification while App in foreground iOS

For anyone might be interested, I ended up creating a custom view that looks like the system push banner on the top but adds a close button (small blue X) and an option to tap the message for custom action. It also supports the case of more than one notification arrived before the user had time to read/dismiss the old ones (With no limit to how many can pile up...)

Link to GitHub: AGPushNote

The usage is basically on-liner:

[AGPushNoteView showWithNotificationMessage:@"John Doe sent you a message!"];

And it looks like this on iOS7 (iOS6 have an iOS6 look and feel...)

enter image description here

check if a string matches an IP address pattern in python?

One more validation without re:

def validip(ip):
    return ip.count('.') == 3 and  all(0<=int(num)<256 for num in ip.rstrip().split('.'))

for i in ('123.233.42.12','3234.23.453.353','-2.23.24.234','1.2.3.4'):
    print i,validip(i)

What's the difference between F5 refresh and Shift+F5 in Google Chrome browser?

The difference is not just for Chrome but for most of the web browsers.

enter image description here

F5 refreshes the web page and often reloads the same page from the cached contents of the web browser. However, reloading from cache every time is not guaranteed and it also depends upon the cache expiry.

Shift + F5 forces the web browser to ignore its cached contents and retrieve a fresh copy of the web page into the browser.

Shift + F5 guarantees loading of latest contents of the web page.
However, depending upon the size of page, it is usually slower than F5.

You may want to refer to: What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?