Programs & Examples On #Django middleware

Middleware is a framework of hooks into Django’s request/response processing. It’s a light, low-level “plugin” system for globally altering Django’s input and/or output.

Drop shadow on a div container?

CSS3 has a box-shadow property. Vendor prefixes are required at the moment for maximum browser compatibility.

div.box-shadow {
    -webkit-box-shadow: 2px 2px 4px 1px #fff;
    box-shadow: 2px 2px 4px 1px #fff;
}

There is a generator available at css3please.

How can I delay a method call for 1 second?

Best way to do is :

[self performSelector:@selector(YourFunctionName) 
           withObject:(can be Self or Object from other Classes) 
           afterDelay:(Time Of Delay)];

you can also pass nil as withObject parameter.

example :

[self performSelector:@selector(subscribe) withObject:self afterDelay:3.0 ];

TypeError: unsupported operand type(s) for -: 'str' and 'int'

For future reference Python is strongly typed. Unlike other dynamic languages, it will not automagically cast objects from one type or the other (say from str to int) so you must do this yourself. You'll like that in the long-run, trust me!

Java division by zero doesnt throw an ArithmeticException - why?

That's because you are dealing with floating point numbers. Division by zero returns Infinity, which is similar to NaN (not a number).

If you want to prevent this, you have to test tab[i] before using it. Then you can throw your own exception, if you really need it.

How to get an isoformat datetime string including the default timezone?

Nine years later. If you know your time zone. I like the T between date and time. And if you don't want microseconds.

Python <= 3.8

pip3 install pytz  # needed!

python3
>>> import datetime
>>> import pytz
>>> datetime.datetime.now(pytz.timezone('Europe/Berlin')).isoformat('T', 'seconds')
'2020-11-09T18:23:28+01:00'

Tested on Ubuntu 18.04 and Python 3.6.9.


Python >= 3.9

pip3 install tzdata  # only on Windows needed!

py -3
>>> import datetime
>>> import zoneinfo
>>> datetime.datetime.now(zoneinfo.ZoneInfo('Europe/Berlin')).isoformat('T', 'seconds')
'2020-11-09T18:39:36+01:00'

Tested on Windows 10 and Python 3.9.0.

sklearn error ValueError: Input contains NaN, infinity or a value too large for dtype('float64')

In most cases getting rid of infinite and null values solve this problem.

get rid of infinite values.

df.replace([np.inf, -np.inf], np.nan, inplace=True)

get rid of null values the way you like, specific value such as 999, mean, or create your own function to impute missing values

df.fillna(999, inplace=True)

ValueError: not enough values to unpack (expected 11, got 1)

For the line

line.split()

What are you splitting on? Looks like a CSV, so try

line.split(',')

Example:

"one,two,three".split()  # returns one element ["one,two,three"]
"one,two,three".split(',')  # returns three elements ["one", "two", "three"]

As @TigerhawkT3 mentions, it would be better to use the CSV module. Incredibly quick and easy method available here.

Refer to a cell in another worksheet by referencing the current worksheet's name?

Unless you want to go the VBA route to work out the Tab name, the Excel formula is fairly ugly based upon Mid functions, etc. But both these methods can be found here if you want to go that way.

Rather, the way I would do it is:

1) Make one cell on your sheet named, for example, Reference_Sheet and put in that cell the value "Jan Item" for example.

2) Now, use the Indirect function like:

=INDIRECT(Reference_Sheet&"!J3") 

3) Now, for each month's sheet, you just have to change that one Reference_Sheet cell.

Hope this gives you what you're looking for!

Assert that a WebElement is not present using Selenium WebDriver with java

Try this -

private boolean verifyElementAbsent(String locator) throws Exception {
    try {
        driver.findElement(By.xpath(locator));
        System.out.println("Element Present");
        return false;

    } catch (NoSuchElementException e) {
        System.out.println("Element absent");
        return true;
    }
}

Get Application Directory

I got this

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

from here:

How do I find a default constraint using INFORMATION_SCHEMA?

I don't think it's in the INFORMATION_SCHEMA - you'll probably have to use sysobjects or related deprecated tables/views.

You would think there would be a type for this in INFORMATION_SCHEMA.TABLE_CONSTRAINTS, but I don't see one.

Drawing Circle with OpenGL

We will find the value of X and Y from this image. We know, sin?=vertical/hypotenuse and cos?=base/hypotenuse from the image we can say base=X and Y=vertical. Now we can write X=hypotenuse*cos? and Y=hypotenuse*sin?. We will find the value of X and Y from this image. We know, sin?=vertical/hypotenuse and cos?=base/hypotenuse from the image we can say X=base and Y=vertical. Now we can write X=hypotenuse * cos? and Y=hypotenuse * sin?.

Now look at this code

void display(){
float x,y;
glColor3f(1, 1, 0);
for(double i =0; i <= 360;){
    glBegin(GL_TRIANGLES);
    x=5*cos(i);
    y=5*sin(i);
    glVertex2d(x, y);
    i=i+.5;
    x=5*cos(i);
    y=5*sin(i);
    glVertex2d(x, y);
    glVertex2d(0, 0);
    glEnd();
    i=i+.5;
}
glEnd();

glutSwapBuffers();
}

JavaScript: Create and save file

Tried this in the console, and it works.

var aFileParts = ['<a id="a"><b id="b">hey!</b></a>'];
var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // the blob
window.open(URL.createObjectURL(oMyBlob));

Show data on mouseover of circle

This concise example demonstrates common way how to create custom tooltip in d3.

_x000D_
_x000D_
var w = 500;_x000D_
var h = 150;_x000D_
_x000D_
var dataset = [5, 10, 15, 20, 25];_x000D_
_x000D_
// firstly we create div element that we can use as_x000D_
// tooltip container, it have absolute position and_x000D_
// visibility: hidden by default_x000D_
_x000D_
var tooltip = d3.select("body")_x000D_
  .append("div")_x000D_
  .attr('class', 'tooltip');_x000D_
_x000D_
var svg = d3.select("body")_x000D_
  .append("svg")_x000D_
  .attr("width", w)_x000D_
  .attr("height", h);_x000D_
_x000D_
// here we add some circles on the page_x000D_
_x000D_
var circles = svg.selectAll("circle")_x000D_
  .data(dataset)_x000D_
  .enter()_x000D_
  .append("circle");_x000D_
_x000D_
circles.attr("cx", function(d, i) {_x000D_
    return (i * 50) + 25;_x000D_
  })_x000D_
  .attr("cy", h / 2)_x000D_
  .attr("r", function(d) {_x000D_
    return d;_x000D_
  })_x000D_
  _x000D_
  // we define "mouseover" handler, here we change tooltip_x000D_
  // visibility to "visible" and add appropriate test_x000D_
  _x000D_
  .on("mouseover", function(d) {_x000D_
    return tooltip.style("visibility", "visible").text('radius = ' + d);_x000D_
  })_x000D_
  _x000D_
  // we move tooltip during of "mousemove"_x000D_
  _x000D_
  .on("mousemove", function() {_x000D_
    return tooltip.style("top", (event.pageY - 30) + "px")_x000D_
      .style("left", event.pageX + "px");_x000D_
  })_x000D_
  _x000D_
  // we hide our tooltip on "mouseout"_x000D_
  _x000D_
  .on("mouseout", function() {_x000D_
    return tooltip.style("visibility", "hidden");_x000D_
  });
_x000D_
.tooltip {_x000D_
    position: absolute;_x000D_
    z-index: 10;_x000D_
    visibility: hidden;_x000D_
    background-color: lightblue;_x000D_
    text-align: center;_x000D_
    padding: 4px;_x000D_
    border-radius: 4px;_x000D_
    font-weight: bold;_x000D_
    color: orange;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>
_x000D_
_x000D_
_x000D_

Why does this CSS margin-top style not work?

Use padding-top:50pxfor outer div. Something like this:

#outer {
    width:500px; 
    height:200px; 
    background:#FFCCCC;
    margin:50px auto 0 auto;
    display:table;}

Note: padding will increase the size of your div. In this case if the size of your div is important, I mean if it must have a specific height. decrease the height by 50px.:

#outer {
    width:500px; 
    height:150px; 
    background:#FFCCCC;
    margin:50px auto 0 auto;
    display:table;}

One liner for If string is not null or empty else

You could use the ternary operator:

return string.IsNullOrEmpty(strTestString) ? "0" : strTestString

FooTextBox.Text = string.IsNullOrEmpty(strFoo) ? "0" : strFoo;

How to bind list to dataGridView?

Using DataTable is valid as user927524 stated. You can also do it by adding rows manually, which will not require to add a specific wrapping class:

List<string> filenamesList = ...;
foreach(string filename in filenamesList)
      gvFilesOnServer.Rows.Add(new object[]{filename});

In any case, thanks user927524 for clearing this weird behavior!!

Stick button to right side of div

Another solution: change margins. Depending on the siblings of the button, display should be modified.

button {
    display:      block;
    margin-left:  auto;
    margin-right: 0;
}

get next and previous day with PHP

always make sure to have set your default timezone

date_default_timezone_set('Europe/Berlin');

create DateTime instance, holding the current datetime

$datetime = new DateTime();

create one day interval

$interval = new DateInterval('P1D');

modify the DateTime instance

$datetime->sub($interval);

display the result, or print_r($datetime); for more insight

echo $datetime->format('Y-m-d');

TIP:

If you don't want to change the default timezone, use the DateTimeZone class instead.

$myTimezone = new DateTimeZone('Europe/Berlin');
$datetime->setTimezone($myTimezone); 

or just include it inside the constructor in this form new DateTime("now", $myTimezone);

How do I show a console output/window in a forms application?

You can call AttachConsole using pinvoke to get a console window attached to a WinForms project: http://www.csharp411.com/console-output-from-winforms-application/

You may also want to consider Log4net ( http://logging.apache.org/log4net/index.html ) for configuring log output in different configurations.

vertical-align: middle doesn't work

Vertical align doesn't quite work the way you want it to. See: http://phrogz.net/css/vertical-align/index.html

This isn't pretty, but it WILL do what you want: Vertical align behaves as expected only when used in a table cell.

http://jsfiddle.net/e8ESb/6/

There are other alternatives: You can declare things as tables or table cells within CSS to make them behave as desired, for example. Margins and positioning can sometimes be played with to get the same effect. None of the solutions are terrible pretty, though.

How to create a folder with name as current date in batch (.bat) files

this worked better for me,

@echo off    
set temp=%DATE:/=%
set dirname="%temp:~4,4%%temp:~2,2%%temp:~0,2%"
mkdir %dirname%

How do I break out of a loop in Perl?

On a large iteration I like using interrupts. Just press Ctrl + C to quit:

my $exitflag = 0;
$SIG{INT} = sub { $exitflag=1 };

while(!$exitflag) {
    # Do your stuff
}

How to show text on image when hovering?

It's simple. Wrap the image and the "appear on hover" description in a div with the same dimensions of the image. Then, with some CSS, order the description to appear while hovering that div.

_x000D_
_x000D_
/* quick reset */_x000D_
* {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  border: 0;_x000D_
}_x000D_
_x000D_
/* relevant styles */_x000D_
.img__wrap {_x000D_
  position: relative;_x000D_
  height: 200px;_x000D_
  width: 257px;_x000D_
}_x000D_
_x000D_
.img__description {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  background: rgba(29, 106, 154, 0.72);_x000D_
  color: #fff;_x000D_
  visibility: hidden;_x000D_
  opacity: 0;_x000D_
_x000D_
  /* transition effect. not necessary */_x000D_
  transition: opacity .2s, visibility .2s;_x000D_
}_x000D_
_x000D_
.img__wrap:hover .img__description {_x000D_
  visibility: visible;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<div class="img__wrap">_x000D_
  <img class="img__img" src="http://placehold.it/257x200.jpg" />_x000D_
  <p class="img__description">This image looks super neat.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

A nice fiddle: https://jsfiddle.net/govdqd8y/

Ternary operator ?: vs if...else

Now I can't help you with that, I may be able to help with a secondary question beneath it, do I want to use it? If you just want to know of the speed, just ignore my comment.

All I can say is please be very smart about when to use the ternary ? : operator. It can be a blessing as much as a curse for readability.

Ask yourself if you find this easier to read before using it

int x = x == 1 ? x = 1 : x = 1;

if (x == 1)
{
   x = 1
}
else
{
   x = 2
}

if (x == 1)
    x = 1
else
    x = 1

Yes It looks stupid to make the code 100% bogus. But that little trick helped me analyse my readability of code. It's the readability of the operator you look at in this sample, and not the content.

It LOOKS clean, but so does the average toilet seat and doorknob

In my experience, which is limited, I have seen very little people actually being able to quickly extradite information required from a ternary operator, avoid unless 100% sure it's better. It's a pain to fix when it's bugged aswell I think

Input type DateTime - Value format?

This was a good waste of an hour of my time. For you eager beavers, the following format worked for me:

<input type="datetime-local" name="to" id="to" value="2014-12-08T15:43:00">

The spec was a little confusing to me, it said to use RFC 3339, but on my PHP server when I used the format DATE_RFC3339 it wasn't initializing my hmtl input :( PHP's constant for DATE_RFC3339 is "Y-m-d\TH:i:sP" at the time of writing, it makes sense that you should get rid of the timezone info (we're using datetime-LOCAL, folks). So the format that worked for me was:

"Y-m-d\TH:i:s"

I would've thought it more intuitive to be able to set the value of the datepicker as the datepicker displays the date, but I'm guessing the way it is displayed differs across browsers.

Best timing method in C?

If you don't want CPU time then I think what you're looking for is the timeval struct.

I use the below for calculating execution time:

int timeval_subtract(struct timeval *result,                                                                                                                                        
                     struct timeval end,                                                                                                                                                 
                     struct timeval start)                                                                                                                                               
{                                                                                                                                                                                   
        if (start.tv_usec < end.tv_usec) {                                                                                                                                          
                int nsec = (end.tv_usec - start.tv_usec) / 1000000 + 1;                                                                                                             
                end.tv_usec -= 1000000 * nsec;                                                                                                                                      
                end.tv_sec += nsec;                                                                                                                                                 
        }                                                                                                                                                                           
        if (start.tv_usec - end.tv_usec > 1000000) {                                                                                                                                
                int nsec = (end.tv_usec - start.tv_usec) / 1000000;                                                                                                                 
                end.tv_usec += 1000000 * nsec;                                                                                                                                      
                end.tv_sec -= nsec;                                                                                                                                                 
        }                                                                                                                                                                           

        result->tv_sec = end.tv_sec - start.tv_sec;                                                                                                                                 
        result->tv_usec = end.tv_usec - start.tv_usec;                                                                                                                              

        return end.tv_sec < start.tv_sec;                                                                                                                                           
}                                                                                                                                                                                   

void set_exec_time(int end)                                                                                                                                                         
{                                                                                                                                                                                   
        static struct timeval time_start;                                                                                                                                           
        struct timeval time_end;                                                                                                                                                    
        struct timeval time_diff;                                                                                                                                                   

        if (end) {                                                                                                                                                                  
                gettimeofday(&time_end, NULL);                                                                                                                                      
                if (timeval_subtract(&time_diff, time_end, time_start) == 0) {                                                                                                      
                        if (end == 1)                                                                                                                                               
                                printf("\nexec time: %1.2fs\n",                                                                                                                     
                                        time_diff.tv_sec + (time_diff.tv_usec / 1000000.0f));                                                                                       
                        else if (end == 2)                                                                                                                                          
                                printf("%1.2fs",                                                                                                                                    
                                        time_diff.tv_sec + (time_diff.tv_usec / 1000000.0f));                                                                                       
                }                                                                                                                                                                   
                return;                                                                                                                                                             
        }                                                                                                                                                                           
        gettimeofday(&time_start, NULL);                                                                                                                                            
}                                                                                                                                                                                   

void start_exec_timer()                                                                                                                                                             
{                                                                                                                                                                                   
        set_exec_time(0);                                                                                                                                                           
}                                                                                                                                                                                   

void print_exec_timer()                                                                                                                                                             
{                                                                                                                                                                                   
        set_exec_time(1);                                                                                                                                                           
}

Why does typeof array with objects return "object" and not "array"?

One of the weird behaviour and spec in Javascript is the typeof Array is Object.

You can check if the variable is an array in couple of ways:

var isArr = data instanceof Array;
var isArr = Array.isArray(data);

But the most reliable way is:

isArr = Object.prototype.toString.call(data) == '[object Array]';

Since you tagged your question with jQuery, you can use jQuery isArray function:

var isArr = $.isArray(data);

gitignore all files of extension in directory

UPDATE: Take a look at @Joey's answer: Git now supports the ** syntax in patterns. Both approaches should work fine.


The gitignore(5) man page states:

Patterns read from a .gitignore file in the same directory as the path, or in any parent directory, with patterns in the higher level files (up to the toplevel of the work tree) being overridden by those in lower level files down to the directory containing the file.

What this means is that the patterns in a .gitignore file in any given directory of your repo will affect that directory and all subdirectories.

The pattern you provided

/public/static/**/*.js

isn't quite right, firstly because (as you correctly noted) the ** syntax is not used by Git. Also, the leading / anchors that pattern to the start of the pathname. (So, /public/static/*.js will match /public/static/foo.js but not /public/static/foo/bar.js.) Removing the leading / won't work either, matching paths like public/static/foo.js and foo/public/static/bar.js. EDIT: Just removing the leading slash won't work either — because the pattern still contains a slash, it is treated by Git as a plain, non-recursive shell glob (thanks @Joey Hoer for pointing this out).

As @ptyx suggested, what you need to do is create the file <repo>/public/static/.gitignore and include just this pattern:

*.js

There is no leading /, so it will match at any part of the path, and that pattern will only ever be applied to files in the /public/static directory and its subdirectories.

Set Google Maps Container DIV width and height 100%

Very few people realize the power of css positioning. To set the map to occupy 100% height of it's parent container do following:

#map_canvas_container {position: relative;}

#map_canvas {position: absolute; top: 0; right: 0; bottom: 0; left: 0;}

If you have any non absolutely positioned elements inside #map_canvas_container they will set the height of it and the map will take the exact available space.

Force decimal point instead of comma in HTML5 number input (client-side)

With the step attribute specified to the precision of the decimals you want, and the lang attribute [which is set to a locale that formats decimals with period], your html5 numeric input will accept decimals. eg. to take values like 10.56; i mean 2 decimal place numbers, do this:

<input type="number" step="0.01" min="0" lang="en" value="1.99">

You can further specify the max attribute for the maximum allowable value.

Edit Add a lang attribute to the input element with a locale value that formats decimals with point instead of comma

Auto expand a textarea using jQuery

People seem to have very over worked solutions...

This is how I do it:

  $('textarea').keyup(function()
  {
    var 
    $this  = $(this),
    height = parseInt($this.css('line-height'),     10),
    padTop = parseInt($this.css('padding-top'),     10),
    padBot = parseInt($this.css('padding-bottom'),  10);

    $this.height(0);

    var 
    scroll = $this.prop('scrollHeight'),
    lines  = (scroll  - padTop - padBot) / height;

    $this.height(height * lines);
  });

This will work with long lines, as well as line breaks.. grows and shrinks..

Remove gutter space for a specific div only

Example 4 columns of span3. For other span widths use new width = old width + gutter size. Use media queries to make it responsive.

css:

    <style type="text/css">
    @media (min-width: 1200px) 
    {   
        .nogutter .span3
        {
            margin-left: 0px; width:300px;
        }   
    }
    @media (min-width: 980px) and (max-width: 1199px) 
    { 
        .nogutter .span3
        {
            margin-left: 0px; width:240px;
        }   
    }
    @media (min-width: 768px) and (max-width: 979px) 
    { 
        .nogutter .span3
        {   
            margin-left: 0px; width:186px;
        }   
    }
    </style>

html:

<div class="container">
<div class="row">
  <div class="span3" style="background-color:red;">...</div>
  <div class="span3" style="background-color:red;">...</div>
  <div class="span3" style="background-color:red;">...</div>
  <div class="span3" style="background-color:red;">...</div>
</div>
<br>
<div class="row nogutter">
  <div class="span3" style="background-color:red;">...</div>
  <div class="span3" style="background-color:red;">...</div>
  <div class="span3" style="background-color:red;">...</div>
  <div class="span3" style="background-color:red;">...</div>
</div> 
</div>

update: or split a span12 div in 100/numberofcolumns % width parts floating left:

<div class="row">
  <div class="span12">
    <div style="background-color:green;width:25%;float:left;">...</div>
  <div style="background-color:yellow;width:25%;float:left;">...</div>
  <div style="background-color:red;width:25%;float:left;">...</div>
  <div style="background-color:blue;width:25%;float:left;">...</div>
  </div>
</div>  

For both solutions see: http://bootply.com/61557

Setting maxlength of textbox with JavaScript or jQuery

set the attribute, not a property

$("#ms_num").attr("maxlength", 6);

Remove blank lines with grep

I prefer using egrep, though in my test with a genuine file with blank line your approach worked fine (though without quotation marks in my test). This worked too:

egrep -v "^(\r?\n)?$" filename.txt

Switching between GCC and Clang/LLVM using CMake

CMake honors the environment variables CC and CXX upon detecting the C and C++ compiler to use:

$ export CC=/usr/bin/clang
$ export CXX=/usr/bin/clang++
$ cmake ..
-- The C compiler identification is Clang
-- The CXX compiler identification is Clang

The compiler specific flags can be overridden by putting them into a make override file and pointing the CMAKE_USER_MAKE_RULES_OVERRIDE variable to it. Create a file ~/ClangOverrides.txt with the following contents:

SET (CMAKE_C_FLAGS_INIT                "-Wall -std=c99")
SET (CMAKE_C_FLAGS_DEBUG_INIT          "-g")
SET (CMAKE_C_FLAGS_MINSIZEREL_INIT     "-Os -DNDEBUG")
SET (CMAKE_C_FLAGS_RELEASE_INIT        "-O3 -DNDEBUG")
SET (CMAKE_C_FLAGS_RELWITHDEBINFO_INIT "-O2 -g")

SET (CMAKE_CXX_FLAGS_INIT                "-Wall")
SET (CMAKE_CXX_FLAGS_DEBUG_INIT          "-g")
SET (CMAKE_CXX_FLAGS_MINSIZEREL_INIT     "-Os -DNDEBUG")
SET (CMAKE_CXX_FLAGS_RELEASE_INIT        "-O3 -DNDEBUG")
SET (CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT "-O2 -g")

The suffix _INIT will make CMake initialize the corresponding *_FLAGS variable with the given value. Then invoke cmake in the following way:

$ cmake -DCMAKE_USER_MAKE_RULES_OVERRIDE=~/ClangOverrides.txt ..

Finally to force the use of the LLVM binutils, set the internal variable _CMAKE_TOOLCHAIN_PREFIX. This variable is honored by the CMakeFindBinUtils module:

$ cmake -D_CMAKE_TOOLCHAIN_PREFIX=llvm- ..

Putting this all together you can write a shell wrapper which sets up the environment variables CC and CXX and then invokes cmake with the mentioned variable overrides.

Also see this CMake FAQ on make override files.

difference between System.out.println() and System.err.println()

System.out's main purpose is giving standard output.

System.err's main purpose is giving standard error.


Look at these

http://www.devx.com/tips/Tip/14698

http://wiki.eclipse.org/FAQ_Where_does_System.out_and_System.err_output_go%3F

div inside table

While you can, as others have noted here, put a DIV inside a TD (not as a direct child of TABLE), I strongly advise against using a DIV as a child of a TD. Unless, of course, you're a fan of headaches.

There is little to be gained and a whole lot to be lost, as there are many cross-browser discrepancies regarding how widths, margins, borders, etc., are handled when you combine the two. I can't tell you how many times I've had to clean up that kind of markup for clients because they were having trouble getting their HTML to display correctly in this or that browser.

Then again, if you're not fussy about how things look, disregard this advice.

How does ifstream's eof() work?

-1 is get's way of saying you've reached the end of file. Compare it using the std::char_traits<char>::eof() (or std::istream::traits_type::eof()) - avoid -1, it's a magic number. (Although the other one is a bit verbose - you can always just call istream::eof)

The EOF flag is only set once a read tries to read past the end of the file. If I have a 3 byte file, and I only read 3 bytes, EOF is false, because I've not tried to read past the end of the file yet. While this seems confusing for files, which typically know their size, EOF is not known until a read is attempted on some devices, such as pipes and network sockets.

The second example works as inf >> foo will always return inf, with the side effect of attempt to read something and store it in foo. inf, in an if or while, will evaluate to true if the file is "good": no errors, no EOF. Thus, when a read fails, inf evaulates to false, and your loop properly aborts. However, take this common error:

while(!inf.eof())  // EOF is false here
{
    inf >> x;      // read fails, EOF becomes true, x is not set
    // use x       // we use x, despite our read failing.
}

However, this:

while(inf >> x)  // Attempt read into x, return false if it fails
{
    // will only be entered if read succeeded.
}

Which is what we want.

How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?

For the record, the spring.jpa.hibernate.ddl-auto property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto.

The values create, create-drop, validate, and update basically influence how the schema tool management will manipulate the database schema at startup.

For example, the update operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.

The update operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.

Typically in test case scenarios, you'll likely use create-drop so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.

In development, it's often common to see developers use update to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.

In production, it's often highly recommended you use none or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.

How to debug Javascript with IE 8

I discovered today that we can now debug Javascript With the developer tool bar plugins integreted in IE 8.

  • Click ? Tools on the toolbar, to the right of the tabs.
  • Select Developer Tools. The Developer Tools dialogue should open.
  • Click the Script tab in the dialogue.
  • Click the Start Debugging button.

You can use watch, breakpoint, see the call stack etc, similarly to debuggers in professional browsers.

You can also use the statement debugger; in your JavaScript code the set a breakpoint.

AutoComplete TextBox in WPF

Nimgoble's is the version I used in 2015. Thought I'd put it here as this question was top of the list in google for "wpf autocomplete textbox"

  1. Install nuget package for project in Visual Studio

  2. Add a reference to the library in the xaml:
    xmlns:behaviors="clr-namespace:WPFTextBoxAutoComplete;assembly=WPFTextBoxAutoComplete"

  3. Create a textbox and bind the AutoCompleteBehaviour to List<String> (TestItems):
    <TextBox Text="{Binding TestText, UpdateSourceTrigger=PropertyChanged}" behaviors:AutoCompleteBehavior.AutoCompleteItemsSource="{Binding TestItems}" />

IMHO this is much easier to get started and manage than the other options listed above.

How to output messages to the Eclipse console when developing for Android

System.out.println() also outputs to LogCat. The benefit of using good old System.out.println() is that you can print an object like System.out.println(object) to the console if you need to check if a variable is initialized or not.

Log.d, Log.v, Log.w etc methods only allow you to print strings to the console and not objects. To circumvent this (if you desire), you must use String.format.

Selecting multiple classes with jQuery

I use $('.myClass.myOtherClass').removeClass('theclass');

How to read Excel cell having Date with Apache POI?

If you know the cell number, then i would recommend using getDateCellValue() method Here's an example for the same that worked for me - java.util.Date date = row.getCell().getDateCellValue(); System.out.println(date);

Equivalent of jQuery .hide() to set visibility: hidden

You could make your own plugins.

jQuery.fn.visible = function() {
    return this.css('visibility', 'visible');
};

jQuery.fn.invisible = function() {
    return this.css('visibility', 'hidden');
};

jQuery.fn.visibilityToggle = function() {
    return this.css('visibility', function(i, visibility) {
        return (visibility == 'visible') ? 'hidden' : 'visible';
    });
};

If you want to overload the original jQuery toggle(), which I don't recommend...

!(function($) {
    var toggle = $.fn.toggle;
    $.fn.toggle = function() {
        var args = $.makeArray(arguments),
            lastArg = args.pop();

        if (lastArg == 'visibility') {
            return this.visibilityToggle();
        }

        return toggle.apply(this, arguments);
    };
})(jQuery);

jsFiddle.

Define preprocessor macro through CMake?

The other solution proposed on this page are useful some versions of Cmake < 3.3.2. Here the solution for the version I am using (i.e., 3.3.2). Check the version of your Cmake by using $ cmake --version and pick the solution that fits with your needs. The cmake documentation can be found on the official page.

With CMake version 3.3.2, in order to create

#define foo

I needed to use:

add_definitions(-Dfoo)   # <--------HERE THE NEW CMAKE LINE inside CMakeLists.txt
add_executable( ....)
target_link_libraries(....)

and, in order to have a preprocessor macro definition like this other one:

#define foo=5

the line is so modified:

add_definitions(-Dfoo=5)   # <--------HERE THE NEW CMAKE LINE inside CMakeLists.txt
add_executable( ....)
target_link_libraries(....)

The term 'ng' is not recognized as the name of a cmdlet

Solution Worked For me :

Add a path to your environment Variable

C:\Users\YourPcName\AppData\Roaming\npm

as well as your bin folder of the angular file [present their itself]

C:\Users\YoutPcName\AppData\Roaming\npm\node_modules\angular-cli\bin

and then run ng -v it will pop up angular cli gui in your Command prompt. Note After running npm i -g @angular/cli do restart your command prompt and check if it works otherwise clean cache and repeats the above steps.

There has been an error processing your request, Error log record number

You can see the error information from:

Magento/var/report

Most of the time it is cause by broken database connection especially at local server, when one forget to start XAMPP or WAMPP server.

Case insensitive access for generic dictionary

Its not very elegant but in case you cant change the creation of dictionary, and all you need is a dirty hack, how about this:

var item = MyDictionary.Where(x => x.Key.ToLower() == MyIndex.ToLower()).FirstOrDefault();
    if (item != null)
    {
        TheValue = item.Value;
    }

How to disable an input type=text?

If you know this when the page is rendered, which it sounds like you do because the database has a value, it's better to disable it when rendered instead of JavaScript. To do that, just add the readonly attribute (or disabled, if you want to remove it from the form submission as well) to the <input>, like this:

<input type="text" disabled="disabled" />
//or...
<input type="text" readonly="readonly" />

Auto line-wrapping in SVG text

This functionality can also be added using JavaScript. Carto.net has an example:

http://old.carto.net/papers/svg/textFlow/

Something else that also might be useful to are you are editable text areas:

http://old.carto.net/papers/svg/gui/textbox/

Swift - encode URL

let Url = URL(string: urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")

How to get the host name of the current machine as defined in the Ansible hosts file?

The necessary variable is inventory_hostname.

- name: Install this only for local dev machine
  pip: name=pyramid
  when: inventory_hostname == "local"

It is somewhat hidden in the documentation at the bottom of this section.

fastest way to export blobs from table into individual files

I tried using a CLR function and it was more than twice as fast as BCP. Here's my code.

Original Method:

SET @bcpCommand = 'bcp "SELECT blobcolumn FROM blobtable WHERE ID = ' + CAST(@FileID AS VARCHAR(20)) + '" queryout "' + @FileName + '" -T -c'
EXEC master..xp_cmdshell @bcpCommand

CLR Method:

declare @file varbinary(max) = (select blobcolumn from blobtable WHERE ID = @fileid)
declare @filepath nvarchar(4000) = N'c:\temp\' + @FileName
SELECT Master.dbo.WriteToFile(@file, @filepath, 0)

C# Code for the CLR function

using System;
using System.Data;
using System.Data.SqlTypes;
using System.IO;
using Microsoft.SqlServer.Server;

namespace BlobExport
{
    public class Functions
    {
      [SqlFunction]
      public static SqlString WriteToFile(SqlBytes binary, SqlString path, SqlBoolean append)
      {        
        try
        {
          if (!binary.IsNull && !path.IsNull && !append.IsNull)
          {         
            var dir = Path.GetDirectoryName(path.Value);           
            if (!Directory.Exists(dir))              
              Directory.CreateDirectory(dir);            
              using (var fs = new FileStream(path.Value, append ? FileMode.Append : FileMode.OpenOrCreate))
            {
                byte[] byteArr = binary.Value;
                for (int i = 0; i < byteArr.Length; i++)
                {
                    fs.WriteByte(byteArr[i]);
                };
            }
            return "SUCCESS";
          }
          else
             "NULL INPUT";
        }
        catch (Exception ex)
        {          
          return ex.Message;
        }
      }
    }
}

How can I pass a reference to a function, with parameters?

The following is equivalent to your second code block:

var f = function () {
        //Some logic here...
    };

var fr = f;

fr(pars);

If you want to actually pass a reference to a function to some other function, you can do something like this:

function fiz(x, y, z) {
    return x + y + z;
}

// elsewhere...

function foo(fn, p, q, r) {
    return function () {
        return fn(p, q, r);
    }
}

// finally...

f = foo(fiz, 1, 2, 3);
f(); // returns 6

You're almost certainly better off using a framework for this sort of thing, though.

Java Constructor Inheritance

David's answer is correct. I'd like to add that you might be getting a sign from God that your design is messed up, and that "Son" ought not to be a subclass of "Super", but that, instead, Super has some implementation detail best expressed by having the functionality that Son provides, as a strategy of sorts.

EDIT: Jon Skeet's answer is awesomest.

How do you remove an array element in a foreach loop?

Instead of doing foreach() loop on the array, it would be faster to use array_search() to find the proper key. On small arrays, I would go with foreach for better readibility, but for bigger arrays, or often executed code, this should be a bit more optimal:

$result=array_search($unwantedValue,$array,true);
if($result !== false) {
  unset($array[$result]);   
}

The strict comparsion operator !== is needed, because array_search() can return 0 as the index of the $unwantedValue.

Also, the above example will remove just the first value $unwantedValue, if the $unwantedValue can occur more then once in the $array, You should use array_keys(), to find all of them:

$result=array_keys($array,$unwantedValue,true)
foreach($result as $key) {
  unset($array[$key]);
}

Check http://php.net/manual/en/function.array-search.php for more information.

Getting the class of the element that fired an event using JQuery

This will contain the full class (which may be multiple space separated classes, if the element has more than one class). In your code it will contain either "konbo" or "kinta":

event.target.className

You can use jQuery to check for classes by name:

$(event.target).hasClass('konbo');

and to add or remove them with addClass and removeClass.

Perform .join on value in array of objects

lets say the objects array is referenced by the variable users

If ES6 can be used then the easiest solution will be:

users.map(user => user.name).join(', ');

If not, and lodash can be used so :

 _.map(users, function(user) {
     return user.name;
 }).join(', ');

How can I right-align text in a DataGridView column?

you can edit all the columns at once by using this simple code via Foreach loop

        foreach (DataGridViewColumn item in datagridview1.Columns)
        {
            item.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
        }

OracleCommand SQL Parameters Binding

Remove single quotes around @username, and with respect to oracle use : with parameter name instead of @, like:

OracleCommand oraCommand = new OracleCommand("SELECT fullname FROM sup_sys.user_profile
                           WHERE domain_user_name = :userName", db);
oraCommand.Parameters.Add(new OracleParameter("userName", domainUser));

Source: Using Parameters

Which is the default location for keystore/truststore of Java applications?

In Java, according to the JSSE Reference Guide, there is no default for the keystore, the default for the truststore is "jssecacerts, if it exists. Otherwise, cacerts".

A few applications use ~/.keystore as a default keystore, but this is not without problems (mainly because you might not want all the application run by the user to use that trust store).

I'd suggest using application-specific values that you bundle with your application instead, it would tend to be more applicable in general.

What is the difference between Left, Right, Outer and Inner Joins?

SQL JOINS difference:

Very simple to remember :

INNER JOIN only show records common to both tables.

OUTER JOIN all the content of the both tables are merged together either they are matched or not.

LEFT JOIN is same as LEFT OUTER JOIN - (Select records from the first (left-most) table with matching right table records.)

RIGHT JOIN is same as RIGHT OUTER JOIN - (Select records from the second (right-most) table with matching left table records.)

enter image description here

How to read the output from git diff?

@@ -1,2 +3,4 @@ part of the diff

This part took me a while to understand, so I've created a minimal example.

The format is basically the same the diff -u unified diff.

For instance:

diff -u <(seq 16) <(seq 16 | grep -Ev '^(2|3|14|15)$')

Here we removed lines 2, 3, 14 and 15. Output:

@@ -1,6 +1,4 @@
 1
-2
-3
 4
 5
 6
@@ -11,6 +9,4 @@
 11
 12
 13
-14
-15
 16

@@ -1,6 +1,4 @@ means:

  • -1,6 means that this piece of the first file starts at line 1 and shows a total of 6 lines. Therefore it shows lines 1 to 6.

    1
    2
    3
    4
    5
    6
    

    - means "old", as we usually invoke it as diff -u old new.

  • +1,4 means that this piece of the second file starts at line 1 and shows a total of 4 lines. Therefore it shows lines 1 to 4.

    + means "new".

    We only have 4 lines instead of 6 because 2 lines were removed! The new hunk is just:

    1
    4
    5
    6
    

@@ -11,6 +9,4 @@ for the second hunk is analogous:

  • on the old file, we have 6 lines, starting at line 11 of the old file:

    11
    12
    13
    14
    15
    16
    
  • on the new file, we have 4 lines, starting at line 9 of the new file:

    11
    12
    13
    16
    

    Note that line 11 is the 9th line of the new file because we have already removed 2 lines on the previous hunk: 2 and 3.

Hunk header

Depending on your git version and configuration, you can also get a code line next to the @@ line, e.g. the func1() { in:

@@ -4,7 +4,6 @@ func1() {

This can also be obtained with the -p flag of plain diff.

Example: old file:

func1() {
    1;
    2;
    3;
    4;
    5;
    6;
    7;
    8;
    9;
}

If we remove line 6, the diff shows:

@@ -4,7 +4,6 @@ func1() {
     3;
     4;
     5;
-    6;
     7;
     8;
     9;

Note that this is not the correct line for func1: it skipped lines 1 and 2.

This awesome feature often tells exactly to which function or class each hunk belongs, which is very useful to interpret the diff.

How the algorithm to choose the header works exactly is discussed at: Where does the excerpt in the git diff hunk header come from?

How to fix homebrew permissions?

I used these two commands and saved my problem

sudo chown -R $(whoami) /usr/local

sudo chown -R $(whoami) /usr/local/etc/bash_completion.d /usr/local/lib/python3.7/site-packages /usr/local/share/aclocal /usr/local/share/locale /usr/local/share/man/man7 /usr/local/share/man/man8 /usr/local/share/zsh /usr/local/share/zsh/site-functions /usr/local/var/homebrew/locks

How to set focus to a button widget programmatically?

Try this:

btn.requestFocusFromTouch();

Generate Controller and Model

Use:

make:model {{SingularName}}

e.g

make:model Video

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

GetDateTimeFormats can parse DateTime to different formats. Example to "yyyy-MM-dd" format.

SomeDate.Value.GetDateTimeFormats()[5]

GetDateTimeFormats

docker run <IMAGE> <MULTIPLE COMMANDS>

To run multiple commands in docker, use /bin/bash -c and semicolon ;

docker run image_name /bin/bash -c "cd /path/to/somewhere; python a.py"

In case we need command2 (python) will be executed if and only if command1 (cd) returned zero (no error) exit status, use && instead of ;

docker run image_name /bin/bash -c "cd /path/to/somewhere && python a.py"

Vertical Menu in Bootstrap

This doesn't quite yet look like what I want, but I accomplished something like this by stacking nav pills in the leftmost two spans. This is what my app's app/views/layouts/application.html.erb file looks like:

<!DOCTYPE html>
...
  <body>
    <!-- top navigation bar -->
    <div class="navbar navbar-fixed-top">
       ...
    </div>
    <div class="container-fluid">
      <!-- the navigation buttons bar on the left -->
      <div class="sidebar-nav span2"> <!-- we reserve 2 spans out of 12 for this -->
        <ul class="nav nav-pills nav-stacked">
          <li class="<%= current_page?(root_path) ? 'active' : 'inactive' %>">
            <%= link_to "Home", root_path %>
          </li>
          <li class="<%= current_page?(section_a_path) ? 'active' : 'inactive' %>">
            <%= link_to "Section A", section_a_path %>
          </li>
          <li class="<%= current_page?(section_b_path) ? 'active' : 'inactive' %>">
            <%= link_to "Section B", section_b_path %>
          </li>
        </ul>
      </div>
      <div class="container-fluid span10"> <!-- use the remaining 10 spans -->
        <%= flash_messages %>
        <%= yield :layout %> <!-- the content page sees a full 12 spans -->
      </div>
    </div> <!-- class="container-fluid" -->
    ...
  </body>
</html>

Now the stacked pills appear on the top left, below the navbar. When the user clicks on one of them, the corresponding page loads. From the point of view of application.html.erb, that page has the 10 rightmost spans available for it, but from the page's view, it has the full 12 spans available.

The button corresponding to the page currently being displayed is rendered as active, and the others as inactive. Specify the colours for active and inactive buttons in file app/assets/stylesheets/custom.css.scss (in this case, the colour for a disabled state is also defined):

@import "bootstrap";
...
$spray:       #81c9e2;
$grey_light:  #dddddd;
...
.nav-pills {
    .inactive > a, .inactive > a:hover {
        background-color: $spray;
    }
    .disabled > a, .disabled > a:hover {
        background-color: $grey_light;
    }
}

The active pill's colour is not defined, so it appears as the default blue.

File custom.css.scss is included because of the line *= require_tree . in file app/assets/stylesheets/application.css.

How to disable mouse right click on a web page?

Firstly, if you are doing this just to prevent people viewing the source of your page - it won't work, because they can always use a keyboard shortcut to view it.

Secondly, you will have to use JavaScript to accomplish this. If the user has JS disabled, you cannot prevent the right click.

That said, add this to your body tag to disable right clicks.

<body oncontextmenu="return false;">

Extract a substring from a string in Ruby using a regular expression

A simpler scan would be:

String1.scan(/<(\S+)>/).last

How do I create a circle or square with just CSS - with a hollow center?

Try This

_x000D_
_x000D_
div.circle {_x000D_
  -moz-border-radius: 50px/50px;_x000D_
  -webkit-border-radius: 50px 50px;_x000D_
  border-radius: 50px/50px;_x000D_
  border: solid 21px #f00;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
}_x000D_
_x000D_
div.square {_x000D_
  border: solid 21px #f0f;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
}
_x000D_
<div class="circle">_x000D_
  <img/>_x000D_
</div>_x000D_
 <hr/>_x000D_
<div class="square">_x000D_
  <img/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

More here

How to group by month from Date field using sql

Use the DATEPART function to extract the month from the date.

So you would do something like this:

SELECT DATEPART(month, Closing_Date) AS Closing_Month, COUNT(Status) AS TotalCount
FROM t
GROUP BY DATEPART(month, Closing_Date)

SQL Insert Query Using C#

private void button1_Click(object sender, EventArgs e)
    {
        String query = "INSERT INTO product (productid, productname,productdesc,productqty) VALUES (@txtitemid,@txtitemname,@txtitemdesc,@txtitemqty)";
        try
        {
            using (SqlCommand command = new SqlCommand(query, con))
            {

                command.Parameters.AddWithValue("@txtitemid", txtitemid.Text);
                command.Parameters.AddWithValue("@txtitemname", txtitemname.Text);
                command.Parameters.AddWithValue("@txtitemdesc", txtitemdesc.Text);
                command.Parameters.AddWithValue("@txtitemqty", txtitemqty.Text);


                con.Open();
                int result = command.ExecuteNonQuery();

                // Check Error
                if (result < 0)
                    MessageBox.Show("Error");

                MessageBox.Show("Record...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                con.Close();
                loader();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            con.Close();
        }
    }

Pure JavaScript Send POST Data Without a Form

The [new-ish at the time of writing in 2017] Fetch API is intended to make GET requests easy, but it is able to POST as well.

let data = {element: "barium"};

fetch("/post/data/here", {
  method: "POST", 
  body: JSON.stringify(data)
}).then(res => {
  console.log("Request complete! response:", res);
});

If you are as lazy as me (or just prefer a shortcut/helper):

window.post = function(url, data) {
  return fetch(url, {method: "POST", body: JSON.stringify(data)});
}

// ...

post("post/data/here", {element: "osmium"});

Best way to replace multiple characters in a string?

advanced way using regex

import re
text = "hello ,world!"
replaces = {"hello": "hi", "world":" 2020", "!":"."}
regex = re.sub("|".join(replaces.keys()), lambda match: replaces[match.string[match.start():match.end()]], text)
print(regex)

How to echo or print an array in PHP?

This will do

foreach($results['data'] as $result) {
    echo $result['type'], '<br>';
}

Getting value from appsettings.json in .net core

Its simple: In appsettings.json

  "MyValues": {
    "Value1": "Xyz"
  }

In .cs file:

static IConfiguration conf = (new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build());
        public static string myValue1= conf["MyValues:Value1"].ToString();

ValueError: math domain error

you are getting math domain error for either one of the reason : either you are trying to use a negative number inside log function or a zero value.

Round a double to 2 decimal places

Rounding a double is usually not what one wants. Instead, use String.format() to represent it in the desired format.

Convert list to dictionary using linq and not worrying about duplicates

You can create an extension method similar to ToDictionary() with the difference being that it allows duplicates. Something like:

    public static Dictionary<TKey, TElement> SafeToDictionary<TSource, TKey, TElement>(
        this IEnumerable<TSource> source, 
        Func<TSource, TKey> keySelector, 
        Func<TSource, TElement> elementSelector, 
        IEqualityComparer<TKey> comparer = null)
    {
        var dictionary = new Dictionary<TKey, TElement>(comparer);

        if (source == null)
        {
            return dictionary;
        }

        foreach (TSource element in source)
        {
            dictionary[keySelector(element)] = elementSelector(element);
        }

        return dictionary; 
    }

In this case, if there are duplicates, then the last value wins.

How to center a (background) image within a div?

This works for me:

.network-connections-icon {
  background-image: url(url);
  background-size: 100%;
  width: 56px;
  height: 56px;
  margin: 0 auto;
}

Why can't I use switch statement on a String?

If you have a place in your code where you can switch on a String, then it may be better to refactor the String to be an enumeration of the possible values, which you can switch on. Of course, you limit the potential values of Strings you can have to those in the enumeration, which may or may not be desired.

Of course your enumeration could have an entry for 'other', and a fromString(String) method, then you could have

ValueEnum enumval = ValueEnum.fromString(myString);
switch (enumval) {
   case MILK: lap(); break;
   case WATER: sip(); break;
   case BEER: quaff(); break;
   case OTHER: 
   default: dance(); break;
}

Efficiently getting all divisors of a given number

Here's my code:

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>

using namespace std;

#define pii pair<int, int>

#define MAX 46656
#define LMT 216
#define LEN 4830
#define RNG 100032

unsigned base[MAX / 64], segment[RNG / 64], primes[LEN];

#define sq(x) ((x)*(x))
#define mset(x,v) memset(x,v,sizeof(x))
#define chkC(x,n) (x[n>>6]&(1<<((n>>1)&31)))
#define setC(x,n) (x[n>>6]|=(1<<((n>>1)&31)))

// http://zobayer.blogspot.com/2009/09/segmented-sieve.html
void sieve()
{
    unsigned i, j, k;
    for (i = 3; i<LMT; i += 2)
        if (!chkC(base, i))
            for (j = i*i, k = i << 1; j<MAX; j += k)
                setC(base, j);
    primes[0] = 2;
    for (i = 3, j = 1; i<MAX; i += 2)
        if (!chkC(base, i))
            primes[j++] = i;
}


//http://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/
vector <pii> factors;
void primeFactors(int num)
{
    int expo = 0;   
    for (int i = 0; primes[i] <= sqrt(num); i++)
    {
        expo = 0;
        int prime = primes[i];
        while (num % prime == 0){
            expo++;
            num = num / prime;
        }
        if (expo>0)
            factors.push_back(make_pair(prime, expo));
    }

    if ( num >= 2)
        factors.push_back(make_pair(num, 1));

}

vector <int> divisors;
void setDivisors(int n, int i) {
    int j, x, k;
    for (j = i; j<factors.size(); j++) {
        x = factors[j].first * n;
        for (k = 0; k<factors[j].second; k++) {
            divisors.push_back(x);
            setDivisors(x, j + 1);
            x *= factors[j].first;
        }
    }
}

int main() {

    sieve();
    int n, x, i; 
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> x;
        primeFactors(x);
        setDivisors(1, 0);
        divisors.push_back(1);
        sort(divisors.begin(), divisors.end());
        cout << divisors.size() << "\n";
        for (int j = 0; j < divisors.size(); j++) {
            cout << divisors[j] << " "; 
        }
        cout << "\n";
        divisors.clear();
        factors.clear();
    }
}

The first part, sieve() is used to find the prime numbers and put them in primes[] array. Follow the link to find more about that code (bitwise sieve).

The second part primeFactors(x) takes an integer (x) as input and finds out its prime factors and corresponding exponent, and puts them in vector factors[]. For example, primeFactors(12) will populate factors[] in this way:

factors[0].first=2, factors[0].second=2
factors[1].first=3, factors[1].second=1

as 12 = 2^2 * 3^1

The third part setDivisors() recursively calls itself to calculate all the divisors of x, using the vector factors[] and puts them in vector divisors[].

It can calculate divisors of any number which fits in int. Also it is quite fast.

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

How to check the version of GitLab?

You have two choices (after logged in).

  1. Use API url https://gitlab.example.com/api/v4/version (you can use it from command line with private token), it returns {"version":"10.1.0","revision":"5a695c4"}
  2. Use HELP url in browser https://gitlab.example.com/help and you will see version of GitLab, ie GitLab Community Edition 10.1.0 5a695c4

Android: combining text & image on a Button or ImageButton

MaterialButton has support for setting an icon and aligning it to the text:

<com.google.android.material.button.MaterialButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="My button"
        app:icon="@drawable/your_icon"
        app:iconGravity="textStart"
        />

app:iconGravity can also be to start / end if you want to align the icon to the button instead of the text inside it.

How to sum a variable by group

library(plyr)
ddply(tbl, .(Category), summarise, sum = sum(Frequency))

Understanding esModuleInterop in tsconfig file

Problem statement

Problem occurs when we want to import CommonJS module into ES6 module codebase.

Before these flags we had to import CommonJS modules with star (* as something) import:

// node_modules/moment/index.js
exports = moment
// index.ts file in our app
import * as moment from 'moment'
moment(); // not compliant with es6 module spec

// transpiled js (simplified):
const moment = require("moment");
moment();

We can see that * was somehow equivalent to exports variable. It worked fine, but it wasn't compliant with es6 modules spec. In spec, the namespace record in star import (moment in our case) can be only a plain object, not callable (moment() is not allowed).

Solution

With flag esModuleInterop we can import CommonJS modules in compliance with es6 modules spec. Now our import code looks like this:

// index.ts file in our app
import moment from 'moment'
moment(); // compliant with es6 module spec

// transpiled js with esModuleInterop (simplified):
const moment = __importDefault(require('moment'));
moment.default();

It works and it's perfectly valid with es6 modules spec, because moment is not namespace from star import, it's default import.

But how does it work? As you can see, because we did a default import, we called the default property on a moment object. But we didn't declare a default property on the exports object in the moment library. The key is the __importDefault function. It assigns module (exports) to the default property for CommonJS modules:

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};

As you can see, we import es6 modules as they are, but CommonJS modules are wrapped into an object with the default key. This makes it possible to import defaults on CommonJS modules.

__importStar does the similar job - it returns untouched esModules, but translates CommonJS modules into modules with a default property:

// index.ts file in our app
import * as moment from 'moment'

// transpiled js with esModuleInterop (simplified):
const moment = __importStar(require("moment"));
// note that "moment" is now uncallable - ts will report error!
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};

Synthetic imports

And what about allowSyntheticDefaultImports - what is it for? Now the docs should be clear:

Allow default imports from modules with no default export. This does not affect code emit, just typechecking.

In moment typings we don't have specified default export, and we shouldn't have, because it's available only with flag esModuleInterop on. So allowSyntheticDefaultImports will not report an error if we want to import default from a third-party module which doesn't have a default export.

The required anti-forgery form field "__RequestVerificationToken" is not present Error in user Registration

In my case, I had this in my web.config:

<httpCookies requireSSL="true" />

But my project was set to not use SSL. Commenting out that line or setting up the project to always use SSL solved it.

How do I convert a TimeSpan to a formatted string?

According to the Microsoft documentation, the TimeSpan structure exposes Hours, Minutes, Seconds, and Milliseconds as integer members. Maybe you want something like:

dateDifference.Hours.ToString() + " hrs, " + dateDifference.Minutes.ToString() + " mins, " + dateDifference.Seconds.ToString() + " secs"

SQL - Update multiple records in one query

maybe for someone it will be useful

for Postgresql 9.5 works as a charm

INSERT INTO tabelname(id, col2, col3, col4)
VALUES
    (1, 1, 1, 'text for col4'),
    (DEFAULT,1,4,'another text for col4')
ON CONFLICT (id) DO UPDATE SET
    col2 = EXCLUDED.col2,
    col3 = EXCLUDED.col3,
    col4 = EXCLUDED.col4

this SQL updates existing record and inserts if new one (2 in 1)

What is the difference between precision and scale?

Precision 4, scale 2: 99.99

Precision 10, scale 0: 9999999999

Precision 8, scale 3: 99999.999

Precision 5, scale -3: 99999000

How do I return multiple values from a function?

I prefer to use tuples whenever a tuple feels "natural"; coordinates are a typical example, where the separate objects can stand on their own, e.g. in one-axis only scaling calculations, and the order is important. Note: if I can sort or shuffle the items without an adverse effect to the meaning of the group, then I probably shouldn't use a tuple.

I use dictionaries as a return value only when the grouped objects aren't always the same. Think optional email headers.

For the rest of the cases, where the grouped objects have inherent meaning inside the group or a fully-fledged object with its own methods is needed, I use a class.

HTTP headers in Websockets client API

Sending Authorization header is not possible.

Attaching a token query parameter is an option. However, in some circumstances, it may be undesirable to send your main login token in plain text as a query parameter because it is more opaque than using a header and will end up being logged whoknowswhere. If this raises security concerns for you, an alternative is to use a secondary JWT token just for the web socket stuff.

Create a REST endpoint for generating this JWT, which can of course only be accessed by users authenticated with your primary login token (transmitted via header). The web socket JWT can be configured differently than your login token, e.g. with a shorter timeout, so it's safer to send around as query param of your upgrade request.

Create a separate JwtAuthHandler for the same route you register the SockJS eventbusHandler on. Make sure your auth handler is registered first, so you can check the web socket token against your database (the JWT should be somehow linked to your user in the backend).

How to present popover properly in iOS 8

In iOS9 UIPopoverController is depreciated. So can use the below code for Objective-C version above iOS9.x,

- (IBAction)onclickPopover:(id)sender {
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
UIViewController *viewController = [sb instantiateViewControllerWithIdentifier:@"popover"];

viewController.modalPresentationStyle = UIModalPresentationPopover;
viewController.popoverPresentationController.sourceView = self.popOverBtn;
viewController.popoverPresentationController.sourceRect = self.popOverBtn.bounds;
viewController.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionAny;
[self presentViewController:viewController animated:YES completion:nil]; }

Semaphore vs. Monitors - what's the difference?

A semaphore is a signaling mechanism used to coordinate between threads. Example: One thread is downloading files from the internet and another thread is analyzing the files. This is a classic producer/consumer scenario. The producer calls signal() on the semaphore when a file is downloaded. The consumer calls wait() on the same semaphore in order to be blocked until the signal indicates a file is ready. If the semaphore is already signaled when the consumer calls wait, the call does not block. Multiple threads can wait on a semaphore, but each signal will only unblock a single thread.

A counting semaphore keeps track of the number of signals. E.g. if the producer signals three times in a row, wait() can be called three times without blocking. A binary semaphore does not count but just have the "waiting" and "signalled" states.

A mutex (mutual exclusion lock) is a lock which is owned by a single thread. Only the thread which have acquired the lock can realease it again. Other threads which try to acquire the lock will be blocked until the current owner thread releases it. A mutex lock does not in itself lock anything - it is really just a flag. But code can check for ownership of a mutex lock to ensure that only one thread at a time can access some object or resource.

A monitor is a higher-level construct which uses an underlying mutex lock to ensure thread-safe access to some object. Unfortunately the word "monitor" is used in a few different meanings depending on context and platform and context, but in Java for example, a monitor is a mutex lock which is implicitly associated with an object, and which can be invoked with the synchronized keyword. The synchronized keyword can be applied to a class, method or block and ensures only one thread can execute the code at a time.

Force table column widths to always be fixed regardless of contents

You can also work with "overflow: hidden" or "overflow-x: hidden" (for just the width). This requires a defined width (and/or height?) and maybe a "display: block" as well.

"Overflow:Hidden" hides the whole content, which does not fit into the defined box.

Example:

http://jsfiddle.net/NAJvp/

HTML:

<table border="1">
    <tr>
        <td><div>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</div></td>
        <td>bbb</td>
        <td>cccc</td>
    </tr>
</table>

CSS:

td div { width: 100px; overflow-y: hidden; }

EDIT: Shame on me, I've seen, you already use "overflow". I guess it doesn't work, because you don't set "display: block" to your element ...

Jquery DatePicker Set default date

First you need to get the current date

var currentDate = new Date();

Then you need to place it in the arguments of datepicker like given below

$("#datepicker").datepicker("setDate", currentDate);

Check the following jsfiddle.

Need help rounding to 2 decimal places

It is caused by a lack of precision with doubles / decimals (i.e. - the function will not always give the result you expect).

See the following link: MSDN on Math.Round

Here is the relevant quote:

Because of the loss of precision that can result from representing decimal values as floating-point numbers or performing arithmetic operations on floating-point values, in some cases the Round(Double, Int32, MidpointRounding) method may not appear to round midpoint values as specified by the mode parameter.This is illustrated in the following example, where 2.135 is rounded to 2.13 instead of 2.14.This occurs because internally the method multiplies value by 10digits, and the multiplication operation in this case suffers from a loss of precision.

add an element to int [] array in java

int[] oldArray = {1,2,3,4,5};

    //new value
    int newValue = 10;

    //define the new array
    int[] newArray = new int[oldArray.length + 1];

    //copy values into new array
    for(int i=0;i < oldArray.length;i++)
        newArray[i] = oldArray[i];
    //another solution is to use 
    //System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);

    //add new value to the new array
    newArray[newArray.length-1] = newValue;

    //copy the address to the old reference 
    //the old array values will be deleted by the Garbage Collector
    oldArray = newArray;

Adding maven nexus repo to my pom.xml

From the Apache Maven site

<project>
  ...
  <repositories>
    <repository>
      <id>my-internal-site</id>
      <url>http://myserver/repo</url>
    </repository>
  </repositories>
  ...
</project>

"The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml." - Apache Maven site - settings reference

<servers>
    <server>
        <id>server001</id>
        <username>my_login</username>
        <password>my_password</password>
        <privateKey>${user.home}/.ssh/id_dsa</privateKey>
        <passphrase>some_passphrase</passphrase>
        <filePermissions>664</filePermissions>
        <directoryPermissions>775</directoryPermissions>
        <configuration></configuration>
    </server>
</servers>

Replacing a character from a certain index

You can't replace a letter in a string. Convert the string to a list, replace the letter, and convert it back to a string.

>>> s = list("Hello world")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> s[int(len(s) / 2)] = '-'
>>> s
['H', 'e', 'l', 'l', 'o', '-', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello-World'

How to open the Google Play Store directly from my Android application?

public void launchPlayStore(Context context, String packageName) {
    Intent intent = null;
    try {
            intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setData(Uri.parse("market://details?id=" + packageName));
            context.startActivity(intent);
        } catch (android.content.ActivityNotFoundException anfe) {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + packageName)));
        }
    }

Flexbox: how to get divs to fill up 100% of the container width without wrapping?

You can use the shorthand flex property and set it to

flex: 0 0 100%;

That's flex-grow, flex-shrink, and flex-basis in one line. Flex shrink was described above, flex grow is the opposite, and flex basis is the size of the container.

How do I include a Perl module that's in a different directory?

EDIT: Putting the right solution first, originally from this question. It's the only one that searches relative to the module directory:

use FindBin;                 # locate this script
use lib "$FindBin::Bin/..";  # use the parent directory
use yourlib;

There's many other ways that search for libraries relative to the current directory. You can invoke perl with the -I argument, passing the directory of the other module:

perl -I.. yourscript.pl

You can include a line near the top of your perl script:

use lib '..';

You can modify the environment variable PERL5LIB before you run the script:

export PERL5LIB=$PERL5LIB:..

The push(@INC) strategy can also work, but it has to be wrapped in BEGIN{} to make sure that the push is run before the module search:

BEGIN {push @INC, '..'}
use yourlib;

GetFiles with multiple extensions

You can't do that, because GetFiles only accepts a single search pattern. Instead, you can call GetFiles with no pattern, and filter the results in code:

string[] extensions = new[] { ".jpg", ".tiff", ".bmp" };

FileInfo[] files =
    dinfo.GetFiles()
         .Where(f => extensions.Contains(f.Extension.ToLower()))
         .ToArray();

If you're working with .NET 4, you can use the EnumerateFiles method to avoid loading all FileInfo objects in memory at once:

string[] extensions = new[] { ".jpg", ".tiff", ".bmp" };

FileInfo[] files =
    dinfo.EnumerateFiles()
         .Where(f => extensions.Contains(f.Extension.ToLower()))
         .ToArray();

How to display a list of images in a ListView in Android?

We need to implement two layouts. One to hold listview and another to hold row item of listview. Implement your own custom adapter. Idea is to include one textview and one imageview.

public View getView(int position, View convertView, ViewGroup parent) {
 // TODO Auto-generated method stub
 LayoutInflater inflater = (LayoutInflater) context
 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 View single_row = inflater.inflate(R.layout.list_row, null,
 true);
 TextView textView = (TextView) single_row.findViewById(R.id.textView);
 ImageView imageView = (ImageView) single_row.findViewById(R.id.imageView);
 textView.setText(color_names[position]);
 imageView.setImageResource(image_id[position]);
 return single_row; 
 }

Next we implement functionality in main activity to include images and text data dynamically during runtime. You can pass dynamically created text array and image id array to the constructor of custom adapter.

Customlistadapter adapter = new Customlistadapter(this, image_id, text_name);

Sprintf equivalent in Java

Both solutions workto simulate printf, but in a different way. For instance, to convert a value to a hex string, you have the 2 following solutions:

  • with format(), closest to sprintf():

    final static String HexChars = "0123456789abcdef";
    
    public static String getHexQuad(long v) {
        String ret;
        if(v > 0xffff) ret = getHexQuad(v >> 16); else ret = "";
        ret += String.format("%c%c%c%c",
            HexChars.charAt((int) ((v >> 12) & 0x0f)),
            HexChars.charAt((int) ((v >>  8) & 0x0f)),
            HexChars.charAt((int) ((v >>  4) & 0x0f)),
            HexChars.charAt((int) ( v        & 0x0f)));
        return ret;
    }
    
  • with replace(char oldchar , char newchar), somewhat faster but pretty limited:

        ...
        ret += "ABCD".
            replace('A', HexChars.charAt((int) ((v >> 12) & 0x0f))).
            replace('B', HexChars.charAt((int) ((v >>  8) & 0x0f))).
            replace('C', HexChars.charAt((int) ((v >>  4) & 0x0f))).
            replace('D', HexChars.charAt((int) ( v        & 0x0f)));
        ...
    
  • There is a third solution consisting of just adding the char to ret one by one (char are numbers that add to each other!) such as in:

    ...
    ret += HexChars.charAt((int) ((v >> 12) & 0x0f)));
    ret += HexChars.charAt((int) ((v >>  8) & 0x0f)));
    ...
    

...but that'd be really ugly.

Insert image after each list item

The easier way to do it is just:

ul li:after {
    content: url('../images/small_triangle.png');
}

What's the difference between struct and class in .NET?

Besides the basic difference of access specifier, and few mentioned above I would like to add some of the major differences including few of the mentioned above with a code sample with output, which will give a more clear idea of the reference and value

Structs:

  • Are value types and do not require heap allocation.
  • Memory allocation is different and is stored in stack
  • Useful for small data structures
  • Affect performance, when we pass value to method, we pass the entire data structure and all is passed to the stack.
  • Constructor simply returns the struct value itself (typically in a temporary location on the stack), and this value is then copied as necessary
  • The variables each have their own copy of the data, and it is not possible for operations on one to affect the other.
  • Do not support user-specified inheritance, and they implicitly inherit from type object

Class:

  • Reference Type value
  • Stored in Heap
  • Store a reference to a dynamically allocated object
  • Constructors are invoked with the new operator, but that does not allocate memory on the heap
  • Multiple variables may have a reference to the same object
  • It is possible for operations on one variable to affect the object referenced by the other variable

Code Sample

    static void Main(string[] args)
    {
        //Struct
        myStruct objStruct = new myStruct();
        objStruct.x = 10;
        Console.WriteLine("Initial value of Struct Object is: " + objStruct.x);
        Console.WriteLine();
        methodStruct(objStruct);
        Console.WriteLine();
        Console.WriteLine("After Method call value of Struct Object is: " + objStruct.x);
        Console.WriteLine();

        //Class
        myClass objClass = new myClass(10);
        Console.WriteLine("Initial value of Class Object is: " + objClass.x);
        Console.WriteLine();
        methodClass(objClass);
        Console.WriteLine();
        Console.WriteLine("After Method call value of Class Object is: " + objClass.x);
        Console.Read();
    }
    static void methodStruct(myStruct newStruct)
    {
        newStruct.x = 20;
        Console.WriteLine("Inside Struct Method");
        Console.WriteLine("Inside Method value of Struct Object is: " + newStruct.x);
    }
    static void methodClass(myClass newClass)
    {
        newClass.x = 20;
        Console.WriteLine("Inside Class Method");
        Console.WriteLine("Inside Method value of Class Object is: " + newClass.x);
    }
    public struct myStruct
    {
        public int x;
        public myStruct(int xCons)
        {
            this.x = xCons;
        }
    }
    public class myClass
    {
        public int x;
        public myClass(int xCons)
        {
            this.x = xCons;
        }
    }

Output

Initial value of Struct Object is: 10

Inside Struct Method Inside Method value of Struct Object is: 20

After Method call value of Struct Object is: 10

Initial value of Class Object is: 10

Inside Class Method Inside Method value of Class Object is: 20

After Method call value of Class Object is: 20

Here you can clearly see the difference between call by value and call by reference.

__init__ and arguments in Python

Every method needs to accept one argument: The instance itself (or the class if it is a static method).

Read more about classes in Python.

How to compare Boolean?

From your comments, it seems like you're looking for "best practices" for the use of the Boolean wrapper class. But there really aren't any best practices, because it's a bad idea to use this class to begin with. The only reason to use the object wrapper is in cases where you absolutely must (such as when using Generics, i.e., storing a boolean in a HashMap<String, Boolean> or the like). Using the object wrapper has no upsides and a lot of downsides, most notably that it opens you up to NullPointerExceptions.

Does it matter if '!' is used instead of .equals() for Boolean?

Both techniques will be susceptible to a NullPointerException, so it doesn't matter in that regard. In the first scenario, the Boolean will be unboxed into its respective boolean value and compared as normal. In the second scenario, you are invoking a method from the Boolean class, which is the following:

public boolean equals(Object obj) {
    if (obj instanceof Boolean) {
        return value == ((Boolean)obj).booleanValue();
    }
    return false;
}

Either way, the results are the same.

Would it matter if .equals(false) was used to check for the value of the Boolean checker?

Per above, no.

Secondary question: Should Boolean be dealt differently than boolean?

If you absolutely must use the Boolean class, always check for null before performing any comparisons. e.g.,

Map<String, Boolean> map = new HashMap<String, Boolean>();
//...stuff to populate the Map
Boolean value = map.get("someKey");
if(value != null && value) {
    //do stuff
}

This will work because Java short-circuits conditional evaluations. You can also use the ternary operator.

boolean easyToUseValue = value != null ? value : false;

But seriously... just use the primitive type, unless you're forced not to.

Java Set retain order?

The Set interface itself does not stipulate any particular order. The SortedSet does however.

Running code in main thread from another thread

for Kotlin, you can use Anko corountines:

update

doAsync {
   ...
}

deprecated

async(UI) {
    // Code run on UI thread
    // Use ref() instead of this@MyActivity
}

Is there a function to split a string in PL/SQL?

You have to roll your own. E.g.,

/* from :http://www.builderau.com.au/architect/database/soa/Create-functions-to-join-and-split-strings-in-Oracle/0,339024547,339129882,00.htm

select split('foo,bar,zoo') from dual;
select * from table(split('foo,bar,zoo'));

pipelined function is SQL only (no PL/SQL !)
*/

create or replace type split_tbl as table of varchar2(32767);
/
show errors

create or replace function split
(
    p_list varchar2,
    p_del varchar2 := ','
) return split_tbl pipelined
is
    l_idx    pls_integer;
    l_list    varchar2(32767) := p_list;
    l_value    varchar2(32767);
begin
    loop
        l_idx := instr(l_list,p_del);
        if l_idx > 0 then
            pipe row(substr(l_list,1,l_idx-1));
            l_list := substr(l_list,l_idx+length(p_del));

        else
            pipe row(l_list);
            exit;
        end if;
    end loop;
    return;
end split;
/
show errors;

/* An own implementation. */

create or replace function split2(
  list in varchar2,
  delimiter in varchar2 default ','
) return split_tbl as
  splitted split_tbl := split_tbl();
  i pls_integer := 0;
  list_ varchar2(32767) := list;
begin
  loop
    i := instr(list_, delimiter);
    if i > 0 then
      splitted.extend(1);
      splitted(splitted.last) := substr(list_, 1, i - 1);
      list_ := substr(list_, i + length(delimiter));
    else
      splitted.extend(1);
      splitted(splitted.last) := list_;
      return splitted;
    end if;
  end loop;
end;
/
show errors

declare
  got split_tbl;

  procedure print(tbl in split_tbl) as
  begin
    for i in tbl.first .. tbl.last loop
      dbms_output.put_line(i || ' = ' || tbl(i));
    end loop;
  end;

begin
  got := split2('foo,bar,zoo');
  print(got);
  print(split2('1 2 3 4 5', ' '));
end;
/

How to register multiple implementations of the same interface in Asp.Net Core?

I didn't have time to read through them all but it seemed everyone was providing solutions to problems that shouldn't exist in the first place.

If you need all of the registered IService implementations then you need them all. But DO NOT inject them all with IEnumerable and then use logic to select one based on some type of key. Problem with doing that is you need a key and the logic should not need to change if the key changes ie; different implementation of IService so typeof doesn't work any more.

The Real Problem

There is business logic here that should be in an engine service. Something like IServiceDecisionEngine is needed. The implementation of the IServiceDecisionEngine gets ONLY the needed IService implementations from DI. Like

public class ServiceDecisionEngine<SomeData>: IServiceDecisionEngine<T> 
{
    public ServiceDecisionEngine(IService serviceA, IService serviceB) { }

    public IService ResolveService(SomeData dataNeededForLogic)
    {
        if (dataNeededForLogic.someValue == true) 
        { 
            return serviceA;
        } 
        return serviceB;
    }
}

Now in your DI, you can do .AddScoped<IServiceDecisionEngine<SomeData>, new ServiceDecisionEngine(new ServiceA(), new ServiceB()) and the managerService that needs an IService will get it by injecting and using IServiceDecisionEngine.

How to get the current working directory using python 3?

Using pathlib you can get the folder in which the current file is located. __file__ is the pathname of the file from which the module was loaded. Ref: docs

import pathlib

current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)

Doc ref: link

Angular2 *ngIf check object array length in template

You could use *ngIf="teamMembers != 0" to check whether data is present

How to implement and do OCR in a C# project?

Here's one: (check out http://hongouru.blogspot.ie/2011/09/c-ocr-optical-character-recognition.html or http://www.codeproject.com/Articles/41709/How-To-Use-Office-2007-OCR-Using-C for more info)

using MODI;
static void Main(string[] args)
{
    DocumentClass myDoc = new DocumentClass();
    myDoc.Create(@"theDocumentName.tiff"); //we work with the .tiff extension
    myDoc.OCR(MiLANGUAGES.miLANG_ENGLISH, true, true);

    foreach (Image anImage in myDoc.Images)
    {
        Console.WriteLine(anImage.Layout.Text); //here we cout to the console.
    }
}

Return datetime object of previous month

You could do it in two lines like this:

now = datetime.now()
last_month = datetime(now.year, now.month - 1, now.day)

remember the imports

from datetime import datetime

How to deal with "java.lang.OutOfMemoryError: Java heap space" error?

You could specify per project how much heap space your project wants

Following is for Eclipse Helios/Juno/Kepler:

Right mouse click on

 Run As - Run Configuration - Arguments - Vm Arguments, 

then add this

-Xmx2048m

Best practice for localization and globalization of strings and labels

jQuery.i18n is a lightweight jQuery plugin for enabling internationalization in your web pages. It allows you to package custom resource strings in ‘.properties’ files, just like in Java Resource Bundles. It loads and parses resource bundles (.properties) based on provided language or language reported by browser.

to know more about this take a look at the How to internationalize your pages using JQuery?

Add SUM of values of two LISTS into new LIST

Here is another way to do it. We make use of the internal __add__ function of python:

class SumList(object):
    def __init__(self, this_list):
        self.mylist = this_list

    def __add__(self, other):
        new_list = []
        zipped_list = zip(self.mylist, other.mylist)
        for item in zipped_list:
            new_list.append(item[0] + item[1])
        return SumList(new_list)

    def __repr__(self):
        return str(self.mylist)

list1 = SumList([1,2,3,4,5])
list2 = SumList([10,20,30,40,50])
sum_list1_list2 = list1 + list2
print(sum_list1_list2)

Output

[11, 22, 33, 44, 55]

jQuery detect if textarea is empty

I know you are long past getting a solution. So, this is for others that come along to see how other people are solving the same common problem-- like me.

The examples in the question and answers indicates the use of jQuery and I am using the .change listener/handler/whatever to see if my textarea changes. This should take care of manual text changes, automated text changes, etc. to trigger the

//pseudocode
$(document).ready(function () {
    $('#textarea').change(function () {
        if ($.trim($('#textarea').val()).length < 1) {

            $('#output').html('Someway your box is being reported as empty... sadness.');

        } else {

            $('#output').html('Your users managed to put something in the box!');
            //No guarantee it isn't mindless gibberish, sorry.

        }
    });
});

Seems to work on all the browsers I use. http://jsfiddle.net/Q3LW6/. Message shows when textarea loses focus.

Newer, more thorough example: https://jsfiddle.net/BradChesney79/tjj6338a/

Uses and reports .change(), .blur(), .keydown(), .keyup(), .mousedown(), .mouseup(), .click(), mouseleave(), and .setInterval().

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

The solution is running this command:

set OPENSSL_CONF=C:\OpenSSL-Win32\bin\openssl.cfg   

or

set OPENSSL_CONF=[path-to-OpenSSL-install-dir]\bin\openssl.cfg

in the command prompt before using openssl command.

Let openssl know for sure where to find its .cfg file.

Alternatively you could set the same variable OPENSSL_CONF in the Windows environment variables.

NOTE: This can happen when using the OpenSSL binary distribution from Shining Light Productions (a compiled + installer version of the official OpenSSL that is free to download & use). This distribution is "semi-officially" linked from OpenSSL's site as a "service primarily for operating systems where there are no pre-compiled OpenSSL packages".

Java: Reading a file into an array

Here is some example code to help you get started:

package com.acme;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileArrayProvider {

    public String[] readLines(String filename) throws IOException {
        FileReader fileReader = new FileReader(filename);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> lines = new ArrayList<String>();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            lines.add(line);
        }
        bufferedReader.close();
        return lines.toArray(new String[lines.size()]);
    }
}

And an example unit test:

package com.acme;

import java.io.IOException;

import org.junit.Test;

public class FileArrayProviderTest {

    @Test
    public void testFileArrayProvider() throws IOException {
        FileArrayProvider fap = new FileArrayProvider();
        String[] lines = fap
                .readLines("src/main/java/com/acme/FileArrayProvider.java");
        for (String line : lines) {
            System.out.println(line);
        }
    }
}

Hope this helps.

How can I set multiple CSS styles in JavaScript?

If you have the CSS values as string and there is no other CSS already set for the element (or you don't care about overwriting), make use of the cssText property:

document.getElementById("myElement").style.cssText = "display: block; position: absolute";

This is good in a sense as it avoids repainting the element every time you change a property (you change them all "at once" somehow).

On the other side, you would have to build the string first.

Is there a portable way to get the current username in Python?

You can probably use:

os.environ.get('USERNAME')

or

os.environ.get('USER')

But it's not going to be safe because environment variables can be changed.

How do I set the colour of a label (coloured text) in Java?

JLabel label = new JLabel ("Text Color: Red");
label.setForeground (Color.red);

this should work

Is there any advantage of using map over unordered_map in case of trivial keys?

I'd echo roughly the same point GMan made: depending on the type of use, std::map can be (and often is) faster than std::tr1::unordered_map (using the implementation included in VS 2008 SP1).

There are a few complicating factors to keep in mind. For example, in std::map, you're comparing keys, which means you only ever look at enough of the beginning of a key to distinguish between the right and left sub-branches of the tree. In my experience, nearly the only time you look at an entire key is if you're using something like int that you can compare in a single instruction. With a more typical key type like std::string, you often compare only a few characters or so.

A decent hash function, by contrast, always looks at the entire key. IOW, even if the table lookup is constant complexity, the hash itself has roughly linear complexity (though on the length of the key, not the number of items). With long strings as keys, an std::map might finish a search before an unordered_map would even start its search.

Second, while there are several methods of resizing hash tables, most of them are pretty slow -- to the point that unless lookups are considerably more frequent than insertions and deletions, std::map will often be faster than std::unordered_map.

Of course, as I mentioned in the comment on your previous question, you can also use a table of trees. This has both advantages and disadvantages. On one hand, it limits the worst case to that of a tree. It also allows fast insertion and deletion, because (at least when I've done it) I've used a fixed-size of table. Eliminating all table resizing allows you to keep your hash table a lot simpler and typically faster.

One other point: the requirements for hashing and tree-based maps are different. Hashing obviously requires a hash function, and an equality comparison, where ordered maps require a less-than comparison. Of course the hybrid I mentioned requires both. Of course, for the common case of using a string as the key, this isn't really a problem, but some types of keys suit ordering better than hashing (or vice versa).

Postgresql, update if row with some unique value exists, else insert

If INSERTS are rare, I would avoid doing a NOT EXISTS (...) since it emits a SELECT on all updates. Instead, take a look at wildpeaks answer: https://dba.stackexchange.com/questions/5815/how-can-i-insert-if-key-not-exist-with-postgresql

CREATE OR REPLACE FUNCTION upsert_tableName(arg1 type, arg2 type) RETURNS VOID AS $$ 
    DECLARE 
    BEGIN 
        UPDATE tableName SET col1 = value WHERE colX = arg1 and colY = arg2; 
        IF NOT FOUND THEN 
        INSERT INTO tableName values (value, arg1, arg2); 
        END IF; 
    END; 
    $$ LANGUAGE 'plpgsql'; 

This way Postgres will initially try to do a UPDATE. If no rows was affected, it will fall back to emitting an INSERT.

ps1 cannot be loaded because running scripts is disabled on this system

Another solution is Remove ng.ps1 from the directory C:\Users%username%\AppData\Roaming\npm\ and clearing the npm cache

Instantly detect client disconnection from server socket

This is in VB, but it seems to work well for me. It looks for a 0 byte return like the previous post.

Private Sub RecData(ByVal AR As IAsyncResult)
    Dim Socket As Socket = AR.AsyncState

    If Socket.Connected = False And Socket.Available = False Then
        Debug.Print("Detected Disconnected Socket - " + Socket.RemoteEndPoint.ToString)
        Exit Sub
    End If
    Dim BytesRead As Int32 = Socket.EndReceive(AR)
    If BytesRead = 0 Then
        Debug.Print("Detected Disconnected Socket - Bytes Read = 0 - " + Socket.RemoteEndPoint.ToString)
        UpdateText("Client " + Socket.RemoteEndPoint.ToString + " has disconnected from Server.")
        Socket.Close()
        Exit Sub
    End If
    Dim msg As String = System.Text.ASCIIEncoding.ASCII.GetString(ByteData)
    Erase ByteData
    ReDim ByteData(1024)
    ClientSocket.BeginReceive(ByteData, 0, ByteData.Length, SocketFlags.None, New AsyncCallback(AddressOf RecData), ClientSocket)
    UpdateText(msg)
End Sub

input() error - NameError: name '...' is not defined

Try using raw_input rather than input if you simply want to read strings.

print("Enter your name: ")
x = raw_input()
print("Hello, "+x)

Image contains the output screen

Importing files from different folder

In Python 3.4 and later, you can import from a source file directly (link to documentation). This is not the simplest solution, but I'm including this answer for completeness.

Here is an example. First, the file to be imported, named foo.py:

def announce():
    print("Imported!")

The code that imports the file above, inspired heavily by the example in the documentation:

import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

foo = module_from_file("foo", "/path/to/foo.py")

if __name__ == "__main__":
    print(foo)
    print(dir(foo))
    foo.announce()

The output:

<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!

Note that the variable name, the module name, and the filename need not match. This code still works:

import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

baz = module_from_file("bar", "/path/to/foo.py")

if __name__ == "__main__":
    print(baz)
    print(dir(baz))
    baz.announce()

The output:

<module 'bar' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!

Programmatically importing modules was introduced in Python 3.1 and gives you more control over how modules are imported. Refer to the documentation for more information.

In vb.net, how to get the column names from a datatable

' i modify the code for Datatable 

For Each c as DataColumn in dt.Columns
 For j=0 To _dataTable.Columns.Count-1
            xlWorksheet.Cells (i+1, j+1) = _dataTable.Columns(j).ColumnName
Next
Next

Hope this could be help!

ValueError: invalid literal for int () with base 10

This could also happen when you have to map space separated integers to a list but you enter the integers line by line using the .input(). Like for example I was solving this problem on HackerRank Bon-Appetit, and the got the following error while compiling enter image description here

So instead of giving input to the program line by line try to map the space separated integers into a list using the map() method.

What does .class mean in Java?

Class is a parameterizable class, hence you can use the syntax Class<T> where T is a type. By writing Class<?>, you're declaring a Class object which can be of any type (? is a wildcard). The Class type is a type that contains meta-information about a class.

It's always good practice to refer to a generic type by specifying his specific type, by using Class<?> you're respecting this practice (you're aware of Class to be parameterizable) but you're not restricting your parameter to have a specific type.

Reference about Generics and Wildcards: http://docs.oracle.com/javase/tutorial/java/generics/wildcards.html

Reference about Class object and reflection (the feature of Java language used to introspect itself): https://www.oracle.com/technetwork/articles/java/javareflection-1536171.html

Best way to track onchange as-you-type in input type="text"?

Javascript is unpredictable and funny here.

  • onchange occurs only when you blur the textbox
  • onkeyup & onkeypress doesn't always occur on text change
  • onkeydown occurs on text change (but cannot track cut & paste with mouse click)
  • onpaste & oncut occurs with keypress and even with the mouse right click.

So, to track the change in textbox, we need onkeydown, oncut and onpaste. In the callback of these event, if you check the value of the textbox then you don't get the updated value as the value is changed after the callback. So a solution for this is to set a timeout function with a timeout of 50 mili-seconds (or may be less) to track the change.

This is a dirty hack but this is the only way, as I researched.

Here is an example. http://jsfiddle.net/2BfGC/12/

Prevent textbox autofill with previously entered values

Autocomplete need to set off from textbox

<asp:TextBox ID="TextBox1" runat="server" autocomplete="off"></asp:TextBox>

Static image src in Vue.js template

If you want to bind a string to the src attribute, you should wrap it on single quotes:

<img v-bind:src="'/static/img/clear.gif'">
<!-- or shorthand -->
<img :src="'/static/img/clear.gif'">

IMO you do not need to bind a string, you could use the simple way:

<img src="/static/img/clear.gif">

Check an example about the image preload here: http://codepen.io/pespantelis/pen/RWVZxL

Sort ArrayList of custom Objects by property

I prefer this process:

public class SortUtil
{    
    public static <T> List<T> sort(List<T> list, String sortByProperty)
    {
            Collections.sort(list, new BeanComparator(sortByProperty));
            return list;
    }
}

List<T> sortedList = SortUtil<T>.sort(unsortedList, "startDate");

If you list of objects has a property called startDate, you call use this over and over. You can even chain them startDate.time.

This requires your object to be Comparable which means you need a compareTo, equals, and hashCode implementation.

Yes, it could be faster... But now you don't have to make a new Comparator for each type of sort. If you can save on dev time and give up on runtime, you might go with this one.

How to run VBScript from command line without Cscript/Wscript

You may follow the following steps:

  • Open your CMD(Command Prompt)
  • Type 'D:' and hit Enter. Example: C:\Users\[Your User Name]>D:
  • Type 'CD VBS' and hit Enter. Example: D:>CD VBS
  • Type 'Converter.vbs' or 'start Converter.vbs' and hit Enter. Example: D:\VBS>Converter.vbs Or D:\VBS>start Converter.vbs

Hiding and Showing TabPages in tabControl

TabPanel1.Visible = true; // Show Tabpage 1
TabPanel1.Visible = false; //Hide Tabpage 1

How to return a complex JSON response with Node.js?

[Edit] After reviewing the Mongoose documentation, it looks like you can send each query result as a separate chunk; the web server uses chunked transfer encoding by default so all you have to do is wrap an array around the items to make it a valid JSON object.

Roughly (untested):

app.get('/users/:email/messages/unread', function(req, res, next) {
  var firstItem=true, query=MessageInfo.find(/*...*/);
  res.writeHead(200, {'Content-Type': 'application/json'});
  query.each(function(docs) {
    // Start the JSON array or separate the next element.
    res.write(firstItem ? (firstItem=false,'[') : ',');
    res.write(JSON.stringify({ msgId: msg.fileName }));
  });
  res.end(']'); // End the JSON array and response.
});

Alternatively, as you mention, you can simply send the array contents as-is. In this case the response body will be buffered and sent immediately, which may consume a large amount of additional memory (above what is required to store the results themselves) for large result sets. For example:

// ...
var query = MessageInfo.find(/*...*/);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(query.map(function(x){ return x.fileName })));

Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'?

Disabling "Google App Engine Support" in pycharm preferences fixed this issue for me.

pycharm app engine preferences

Best way to remove an event handler in jQuery?

To remove ALL event-handlers, this is what worked for me:

To remove all event handlers mean to have the plain HTML structure without all the event handlers attached to the element and its child nodes. To do this, jQuery's clone() helped.

var original, clone;
// element with id my-div and its child nodes have some event-handlers
original = $('#my-div');
clone = original.clone();
//
original.replaceWith(clone);

With this, we'll have the clone in place of the original with no event-handlers on it.

Good Luck...

android: how to align image in the horizontal center of an imageview?

You can center the ImageView itself by using:

android:layout_centerVertical="true" or android:layout_centerHorizontal="true" For vertical or horizontal. Or to center inside the parent:

android:layout_centerInParent="true"

But it sounds like you are trying to center the actual source image inside the imageview itself, which I am not sure on.

How can I find and run the keytool

On cmd window (need to run as Administrator),

cd %JAVA_HOME% 

only works if you have set up your system environment variable JAVA_HOME . To set up your system variable for your path, you can do this

setx %JAVA_HOME% C:\Java\jdk1.8.0_121\

Then, you can type

cd c:\Java\jdk1.8.0_121\bin

or

cd %JAVA_HOME%\bin

Then, execute any commands provided by JAVA jdk's, such as

keytool -genkey -v -keystore myapp.keystore -alias myapp

You just have to answer the questions (equivalent to typing the values on cmd line) after hitting enter! The key would be generated

How to get the correct range to set the value to a cell?

Solution : SpreadsheetApp.getActiveSheet().getRange('F2').setValue('hello')

Explanation :

Setting value in a cell in spreadsheet to which script is attached

SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);

Setting value in a cell in sheet which is open currently and to which script is attached

SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(RANGE).setValue(VALUE);

Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet name known)

SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);

Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet position known)

SpreadsheetApp.openById(SHEET_ID).getSheets()[POSITION].getRange(RANGE).setValue(VALUE);

These are constants, you must define them yourself

SHEET_ID

SHEET_NAME

POSITION

VALUE

RANGE

By script attached to a sheet I mean that script is residing in the script editor of that sheet. Not attached means not residing in the script editor of that sheet. It can be in any other place.

How to make a flex item not fill the height of the flex container?

When you create a flex container various default flex rules come into play.

Two of these default rules are flex-direction: row and align-items: stretch. This means that flex items will automatically align in a single row, and each item will fill the height of the container.

If you don't want flex items to stretch – i.e., like you wrote:

make its height the minimum required for holding its content

... then simply override the default with align-items: flex-start.

_x000D_
_x000D_
#a {_x000D_
  display: flex;_x000D_
  align-items: flex-start; /* NEW */_x000D_
}_x000D_
#a > div {_x000D_
  background-color: red;_x000D_
  padding: 5px;_x000D_
  margin: 2px;_x000D_
}_x000D_
#b {_x000D_
  height: auto;_x000D_
}
_x000D_
<div id="a">_x000D_
  <div id="b">left</div>_x000D_
  <div>_x000D_
    right<br>right<br>right<br>right<br>right<br>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here's an illustration from the flexbox spec that highlights the five values for align-items and how they position flex items within the container. As mentioned before, stretch is the default value.

enter image description here Source: W3C

Checking character length in ruby

Instead of using a regular expression, just check if string.length > 25

jQuery remove special characters from string and more

this will remove all the special character

 str.replace(/[_\W]+/g, "");

this is really helpful and solve my issue. Please run the below code and ensure it works

_x000D_
_x000D_
var str="hello world !#to&you%*()";_x000D_
console.log(str.replace(/[_\W]+/g, ""));
_x000D_
_x000D_
_x000D_

Spring Boot @Value Properties

Make sure your application.properties file is under src/main/resources/application.properties. Is one way to go. Then add @PostConstruct as follows

Sample Application.properties

file.directory = somePlaceOverHere

Sample Java Class

@ComponentScan
public class PrintProperty {

  @Value("${file.directory}")
  private String fileDirectory;

  @PostConstruct
  public void print() {
    System.out.println(fileDirectory);
  }
}

Code above will print out "somePlaceOverhere"

How can I combine multiple nested Substitute functions in Excel?

Thanks for the idea of breaking down a formula Werner!

Using Alt+Enter allows one to put each bit of a complex substitute formula on separate lines: they become easier to follow and automatically line themselves up when Enter is pressed.

Just make sure you have enough end statements to match the number of substitute( lines either side of the cell reference.

As in this example:

=
substitute(
substitute(
substitute(
substitute(
B11
,"(","")
,")","")
,"[","")
,"]","")

becomes:

=
SUBSTITUTE(
SUBSTITUTE(
SUBSTITUTE(
SUBSTITUTE(B12,"(",""),")",""),"[",""),"]","")

which works fine as is, but one can always delete the extra paragraphs manually:

=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(B12,"(",""),")",""),"[",""),"]","")

Name > substitute()

[American Samoa] > American Samoa

How to force delete a file?

You have to close that application first. There is no way to delete it, if it's used by some application.

UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.

There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.

Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.

Fixing Segmentation faults in C++

I don't know of any methodology to use to fix things like this. I don't think it would be possible to come up with one either for the very issue at hand is that your program's behavior is undefined (I don't know of any case when SEGFAULT hasn't been caused by some sort of UB).

There are all kinds of "methodologies" to avoid the issue before it arises. One important one is RAII.

Besides that, you just have to throw your best psychic energies at it.

Sorting multiple keys with Unix sort

Take care though:

If you want to sort the file primarily by field 3, and secondarily by field 2 you want this:

sort -k 3,3 -k 2,2 < inputfile

Not this: sort -k 3 -k 2 < inputfile which sorts the file by the string from the beginning of field 3 to the end of line (which is potentially unique).

-k, --key=POS1[,POS2]     start a key at POS1 (origin 1), end it at POS2
                          (default end of line)

What exactly does the "u" do? "git push -u origin master" vs "git push origin master"

git push -u origin master

… is the same as:

git push origin master ; git branch --set-upstream master origin/master

Do the last statement, if you forget the -u!

Or you could force it:

git config branch.master.remote origin
git config branch.master.merge refs/heads/master

If you let the command do it for you, it will pick your mistakes like if you typed a non-existent branch or you didn't git remote add; though that might be what you want. :)

jQuery .find() on data from .ajax() call is returning "[object Object]" instead of div

do not forget to do it with parse html. like:

$.ajax({
    url: url, 
    cache: false,
    success: function(response) {
        var parsed = $.parseHTML(response);
        result = $(parsed).find("#result");
    }
});

has to work :)

How do I use $scope.$watch and $scope.$apply in AngularJS?

Just finish reading ALL the above, boring and sleepy (sorry but is true). Very technical, in-depth, detailed, and dry. Why am I writing? Because AngularJS is massive, lots of inter-connected concepts can turn anyone going nuts. I often asked myself, am I not smart enough to understand them? No! It's because so few can explain the tech in a for-dummie language w/o all the terminologies! Okay, let me try:

1) They are all event-driven things. (I hear the laugh, but read on)

If you don't know what event-driven is Then think you place a button on the page, hook it up w/ a function using "on-click", waiting for users to click on it to trigger the actions you plant inside the function. Or think of "trigger" of SQL Server / Oracle.

2) $watch is "on-click".

What's special about is it takes 2 functions as parameters, first one gives the value from the event, second one takes the value into consideration...

3) $digest is the boss who checks around tirelessly, bla-bla-bla but a good boss.

4) $apply gives you the way when you want to do it manually, like a fail-proof (in case on-click doesn't kick in, you force it to run.)

Now, let's make it visual. Picture this to make it even more easy to grab the idea:

In a restaurant,

- WAITERS

are supposed to take orders from customers, this is

$watch(
  function(){return orders;},
  function(){Kitchen make it;}
);

- MANAGER running around to make sure all waiters are awake, responsive to any sign of changes from customers. This is $digest()

- OWNER has the ultimate power to drive everyone upon request, this is $apply()

How to find substring from string?

If you are utilizing arrays too much then you should include cstring.h because it has too many functions including finding substrings.

Filter items which array contains any of given values

Whilst this an old question, I ran into this problem myself recently and some of the answers here are now deprecated (as the comments point out). So for the benefit of others who may have stumbled here:

A term query can be used to find the exact term specified in the reverse index:

{
  "query": {
   "term" : { "tags" : "a" }
} 

From the documenation https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-term-query.html

Alternatively you can use a terms query, which will match all documents with any of the items specified in the given array:

{
  "query": {
   "terms" : { "tags" : ["a", "c"]}
} 

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-query.html

One gotcha to be aware of (which caught me out) - how you define the document also makes a difference. If the field you're searching in has been indexed as a text type then Elasticsearch will perform a full text search (i.e using an analyzed string).

If you've indexed the field as a keyword then a keyword search using a 'non-analyzed' string is performed. This can have a massive practical impact as Analyzed strings are pre-processed (lowercased, punctuation dropped etc.) See (https://www.elastic.co/guide/en/elasticsearch/guide/master/term-vs-full-text.html)

To avoid these issues, the string field has split into two new types: text, which should be used for full-text search, and keyword, which should be used for keyword search. (https://www.elastic.co/blog/strings-are-dead-long-live-strings)

Is bool a native C type?

bool exists in the current C - C99, but not in C89/90.

In C99 the native type is actually called _Bool, while bool is a standard library macro defined in stdbool.h (which expectedly resolves to _Bool). Objects of type _Bool hold either 0 or 1, while true and false are also macros from stdbool.h.

Note, BTW, that this implies that C preprocessor will interpret #if true as #if 0 unless stdbool.h is included. Meanwhile, C++ preprocessor is required to natively recognize true as a language literal.

Importing variables from another file?

Import file1 inside file2:

To import all variables from file1 without flooding file2's namespace, use:

import file1

#now use file1.x1, file2.x2, ... to access those variables

To import all variables from file1 to file2's namespace( not recommended):

from file1 import *
#now use x1, x2..

From the docs:

While it is valid to use from module import * at module level it is usually a bad idea. For one, this loses an important property Python otherwise has — you can know where each toplevel name is defined by a simple “search” function in your favourite editor. You also open yourself to trouble in the future, if some module grows additional functions or classes.

Connecting to TCP Socket from browser using javascript

ws2s project is aimed at bring socket to browser-side js. It is a websocket server which transform websocket to socket.

ws2s schematic diagram

enter image description here

code sample:

var socket = new WS2S("wss://ws2s.feling.io/").newSocket()

socket.onReady = () => {
  socket.connect("feling.io", 80)
  socket.send("GET / HTTP/1.1\r\nHost: feling.io\r\nConnection: close\r\n\r\n")
}

socket.onRecv = (data) => {
  console.log('onRecv', data)
}

Replacing few values in a pandas dataframe column with another value

Replace

DataFrame object has powerful and flexible replace method:

DataFrame.replace(
        to_replace=None,
        value=None,
        inplace=False,
        limit=None,
        regex=False, 
        method='pad',
        axis=None)

Note, if you need to make changes in place, use inplace boolean argument for replace method:

Inplace

inplace: boolean, default False If True, in place. Note: this will modify any other views on this object (e.g. a column form a DataFrame). Returns the caller if this is True.

Snippet

df['BrandName'].replace(
    to_replace=['ABC', 'AB'],
    value='A',
    inplace=True
)

Editing in the Chrome debugger

you can edit the javascrpit files dynamically in the Chrome debugger, under the Sources tab, however your changes will be lost if you refresh the page, to pause page loading before doing your changes, you will need to set a break point then reload the page and edit your changes and finally unpause the debugger to see your changes take effect. Chrome debugger

Python matplotlib multiple bars

import matplotlib.pyplot as plt
from matplotlib.dates import date2num
import datetime

x = [
    datetime.datetime(2011, 1, 4, 0, 0),
    datetime.datetime(2011, 1, 5, 0, 0),
    datetime.datetime(2011, 1, 6, 0, 0)
]
x = date2num(x)

y = [4, 9, 2]
z = [1, 2, 3]
k = [11, 12, 13]

ax = plt.subplot(111)
ax.bar(x-0.2, y, width=0.2, color='b', align='center')
ax.bar(x, z, width=0.2, color='g', align='center')
ax.bar(x+0.2, k, width=0.2, color='r', align='center')
ax.xaxis_date()

plt.show()

enter image description here

I don't know what's the "y values are also overlapping" means, does the following code solve your problem?

ax = plt.subplot(111)
w = 0.3
ax.bar(x-w, y, width=w, color='b', align='center')
ax.bar(x, z, width=w, color='g', align='center')
ax.bar(x+w, k, width=w, color='r', align='center')
ax.xaxis_date()
ax.autoscale(tight=True)

plt.show()

enter image description here

img tag displays wrong orientation

An easy way to the fix the problem, sans coding, is to use Photoshop's Save for Web export function. In the dialog box one can chose to remove all or most of an image's EXIF data. I usually just keep copyright and contact info. Also, since images coming directly from a digital camera are greatly oversized for web display it is a good idea to downsize them via Save for the Web anyway. For those that are not Photoshop savvy, I have no doubt that there are online resources for resizing an image and stripping it of any unnecessary EXIF data.

How to save and load numpy.array() data properly?

np.fromfile() has a sep= keyword argument:

Separator between items if file is a text file. Empty (“”) separator means the file should be treated as binary. Spaces (” ”) in the separator match zero or more whitespace characters. A separator consisting only of spaces must match at least one whitespace.

The default value of sep="" means that np.fromfile() tries to read it as a binary file rather than a space-separated text file, so you get nonsense values back. If you use np.fromfile('markers.txt', sep=" ") you will get the result you are looking for.

However, as others have pointed out, np.loadtxt() is the preferred way to convert text files to numpy arrays, and unless the file needs to be human-readable it is usually better to use binary formats instead (e.g. np.load()/np.save()).

How to block until an event is fired in c#

A very easy kind of event you can wait for is the ManualResetEvent, and even better, the ManualResetEventSlim.

They have a WaitOne() method that does exactly that. You can wait forever, or set a timeout, or a "cancellation token" which is a way for you to decide to stop waiting for the event (if you want to cancel your work, or your app is asked to exit).

You fire them calling Set().

Here is the doc.

Change table header color using bootstrap

You could simply apply one of the bootstrap contextual background colors to the header row. In this case (blue background, white text): primary.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>_x000D_
_x000D_
<table class="table" >_x000D_
  <tr class="bg-primary">_x000D_
    <th>_x000D_
        Firstname_x000D_
    </th>_x000D_
    <th>_x000D_
        Surname_x000D_
    </th>_x000D_
    <th></th>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>John</td>_x000D_
    <td>Doe</td>_x000D_
  </tr>_x000D_
    <tr>_x000D_
      <td>Jane</td>_x000D_
      <td>Roe</td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

What is the meaning of "this" in Java?

If the instance variables are same as the variables that are declared in the constructor then we use "this" to assign data.

class Example{
     int assign;// instance variable

     Example(int assign){ // variable inside constructor
          this.assign=assign;
     }
}

Hope this helps.

Oracle SQL Developer - tables cannot be seen

I had this problem on my Mac. Fixed it by uninstalling it AND removing the /Users/aa77686/.sqldeveloper folder. Uninstalling without deleting that folder did not fix it.
Then redownloaded and reinstalled.
Started it up, added connections and it worked fine.
Quit it, restarted it several times and it shows the tables, etc. correctly each time so far.

How to parse a JSON Input stream

{
    InputStream is = HTTPClient.get(url);
    InputStreamReader reader = new InputStreamReader(is);
    JSONTokener tokenizer = new JSONTokener(reader);
    JSONObject jsonObject = new JSONObject(tokenizer);
}

Can you animate a height change on a UITableViewCell when selected?

I found a REALLY SIMPLE solution to this as a side-effect to a UITableView I was working on.....

Store the cell height in a variable that reports the original height normally via the tableView: heightForRowAtIndexPath:, then when you want to animate a height change, simply change the value of the variable and call this...

[tableView beginUpdates];
[tableView endUpdates];

You will find it doesn't do a full reload but is enough for the UITableView to know it has to redraw the cells, grabbing the new height value for the cell.... and guess what? It ANIMATES the change for you. Sweet.

I have a more detailed explanation and full code samples on my blog... Animate UITableView Cell Height Change

How do I git rm a file without deleting it from disk?

git rm --cached file

should do what you want.

You can read more details at git help rm

How to check if array element is null to avoid NullPointerException in Java

The given code works for me. Notice that someArray[i] is always null since you have not initialized the second dimension of the array.

Mobile Safari: Javascript focus() method on inputfield only works with click?

UPDATE

I also tried this, but to no avail:

$(document).ready(function() {
$('body :not(.wr-dropdown)').bind("click", function(e) {
    $('.test').focus();
})
$('.wr-dropdown').on('change', function(e) {
    if ($(".wr-dropdow option[value='/search']")) {
        setTimeout(function(e) {
            $('body :not(.wr-dropdown)').trigger("click");
        },3000)         
    } 
}); 

});

I am confused as to why you say this isn't working because your JSFiddle is working just fine, but here is my suggestion anyway...

Try this line of code in your SetTimeOut function on your click event:

document.myInput.focus();

myInput correlates to the name attribute of the input tag.

<input name="myInput">

And use this code to blur the field:

document.activeElement.blur();

How to make an ng-click event conditional?

We can add ng-click event conditionally without using disabled class.

HTML:

<div ng-repeat="object in objects">
<span ng-click="!object.status && disableIt(object)">{{object.value}}</span>
</div>

Setting onClickListener for the Drawable right of an EditText

This has been already answered but I tried a different way to make it simpler.

The idea is using putting an ImageButton on the right of EditText and having negative margin to it so that the EditText flows into the ImageButton making it look like the Button is in the EditText.

enter image description here

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <EditText
            android:id="@+id/editText"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:hint="Enter Pin"
            android:singleLine="true"
            android:textSize="25sp"
            android:paddingRight="60dp"
            />
        <ImageButton
            android:id="@+id/pastePin"
            android:layout_marginLeft="-60dp"
            style="?android:buttonBarButtonStyle"
            android:paddingBottom="5dp"
            android:src="@drawable/ic_action_paste"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

Also, as shown above, you can use a paddingRight of similar width in the EditText if you don't want the text in it to be flown over the ImageButton.

I guessed margin size with the help of android-studio's layout designer and it looks similar across all screen sizes. Or else you can calculate the width of the ImageButton and set the margin programatically.

Create Table from JSON Data with angularjs and ng-repeat

To create HTML table using JSON, we will use ngRepeat directive of AngularJS.

Example

HTML

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<table border="1">
<tr ng-repeat="x in names">
<td>{{x.Name}}</td>
<td>{{x.City}}</td>
<td>{{x.Country}}</td></tr>
</table>
</div>
</body>
</html>

JavaScript

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope) {
    $scope.names = [
      { "Name" : "Max Joe", "City" : "Lulea", "Country" : "Sweden" },
      { "Name" : "Manish", "City" : "Delhi", "Country" : "India" },
      { "Name" : "Koniglich", "City" : "Barcelona", "Country" : "Spain" },
      { "Name" : "Wolski", "City" : "Arhus", "Country" : "Denmark" }
    ];
});

In above example I have created table from json. I have taken reference from http://www.tutsway.com/create-html-table-using-json-in-angular-js.php

segmentation fault : 11

Run your program with valgrind of linked to efence. That will tell you where the pointer is being dereferenced and most likely fix your problem if you fix all the errors they tell you about.

MySQL: Set user variable from result of query

Use this way so that result will not be displayed while running stored procedure.

The query:

SELECT a.strUserID FROM tblUsers a WHERE a.lngUserID = lngUserID LIMIT 1 INTO @strUserID;

How to go back (ctrl+z) in vi/vim

I had the same problem right now and i solved it. You must not need it anymore so I write for others:

if you use gvim on windows, you just add this in your _vimrc: $VIMRUNTIME/mswin.vim behave mswin

else just use imap...

How can I use modulo operator (%) in JavaScript?

It's the remainder operator and is used to get the remainder after integer division. Lots of languages have it. For example:

10 % 3 // = 1 ; because 3 * 3 gets you 9, and 10 - 9 is 1.

Apparently it is not the same as the modulo operator entirely.

MySQL Workbench Dark Theme

Quoting Yoga...

For Mac users, the code_editor.xml file is in MBP HD/ Applications/MySQLWorkbench.app/Contents/Resources/data/

I just discovered by dumbfounded experimentation (i.e. first thing I tried, worked) that if I copy that file to...

/Users/your.username/Library/Application Support/MySQL/Workbench/code_editor.xml

...and then edit it there, it does indeed override. Just worked perfectly for me on Mac OS X Sierra and MySQL Workbench 6.3.

How to evaluate http response codes from bash/shell script?

Here comes the long-winded – yet easy to understand – script, inspired by the solution of nicerobot, that only requests the response headers and avoids using IFS as suggested here. It outputs a bounce message when it encounters a response >= 400. This echo can be replaced with a bounce-script.

# set the url to probe
url='http://localhost:8080'
# use curl to request headers (return sensitive default on timeout: "timeout 500"). Parse the result into an array (avoid settings IFS, instead use read)
read -ra result <<< $(curl -Is --connect-timeout 5 "${url}" || echo "timeout 500")
# status code is second element of array "result"
status=${result[1]}
# if status code is greater than or equal to 400, then output a bounce message (replace this with any bounce script you like)
[ $status -ge 400  ] && echo "bounce at $url with status $status"

How can I make content appear beneath a fixed DIV element?

#nav{
    position: -webkit-sticky; /* Safari */
    position: sticky;
    top: 0;
    margin: 0 auto;
    z-index: 9999;
    background-color: white;
}

How to convert a file to utf-8 in Python?

Thanks for the replies, it works!

And since the source files are in mixed formats, I added a list of source formats to be tried in sequence (sourceFormats), and on UnicodeDecodeError I try the next format:

from __future__ import with_statement

import os
import sys
import codecs
from chardet.universaldetector import UniversalDetector

targetFormat = 'utf-8'
outputDir = 'converted'
detector = UniversalDetector()

def get_encoding_type(current_file):
    detector.reset()
    for line in file(current_file):
        detector.feed(line)
        if detector.done: break
    detector.close()
    return detector.result['encoding']

def convertFileBestGuess(filename):
   sourceFormats = ['ascii', 'iso-8859-1']
   for format in sourceFormats:
     try:
        with codecs.open(fileName, 'rU', format) as sourceFile:
            writeConversion(sourceFile)
            print('Done.')
            return
      except UnicodeDecodeError:
        pass

def convertFileWithDetection(fileName):
    print("Converting '" + fileName + "'...")
    format=get_encoding_type(fileName)
    try:
        with codecs.open(fileName, 'rU', format) as sourceFile:
            writeConversion(sourceFile)
            print('Done.')
            return
    except UnicodeDecodeError:
        pass

    print("Error: failed to convert '" + fileName + "'.")


def writeConversion(file):
    with codecs.open(outputDir + '/' + fileName, 'w', targetFormat) as targetFile:
        for line in file:
            targetFile.write(line)

# Off topic: get the file list and call convertFile on each file
# ...

(EDIT by Rudro Badhon: this incorporates the original try multiple formats until you don't get an exception as well as an alternate approach that uses chardet.universaldetector)

Can you hide the controls of a YouTube embed without enabling autoplay?

Autoplay works only with /v/ instead of /embed/, so change the src to:

src="//www.youtube.com/v/qUJYqhKZrwA?autoplay=1&showinfo=0&controls=0"

Bootstrap 4 - Glyphicons migration?

Migrating from Glyphicons to Font Awesome is quite easy.

Include a reference to Font Awesome (either locally, or use the CDN).

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

Then run a search and replace where you search for glyphicon glyphicon- and replace it with fa fa-, and also change the enclosing element from <span to <i. Most of the CSS class names are the same. Some have changed though, so you have to manually fix those.

Return JSON response from Flask view

In Flask 1.1, if you return a dictionary and it will automatically be converted into JSON. So if make_summary() returns a dictionary, you can

from flask import Flask

app = Flask(__name__)

@app.route('/summary')
def summary():
    d = make_summary()
    return d

The SO that asks about including the status code was closed as a duplicate to this one. So to also answer that question, you can include the status code by returning a tuple of the form (dict, int). The dict is converted to JSON and the int will be the HTTP Status Code. Without any input, the Status is the default 200. So in the above example the code would be 200. In the example below it is changed to 201.

from flask import Flask

app = Flask(__name__)

@app.route('/summary')
def summary():
    d = make_summary()
    return d, 201  # 200 is the default

You can check the status code using

curl --request GET "http://127.0.0.1:5000/summary" -w "\ncode: %{http_code}\n\n"

Automatically start a Windows Service on install

Automatic startup means that the service is automatically started when Windows starts. As others have mentioned, to start it from the console you should use the ServiceController.