Programs & Examples On #Job queue

In system software, a job queue (sometimes batch queue), is a data structure maintained by job scheduler software containing jobs to run.

Firing events on CSS class changes in jQuery

if you know a what event changed the class in the first place you may use a slight delay on the same event and the check the for the class. example

//this is not the code you control
$('input').on('blur', function(){
    $(this).addClass('error');
    $(this).before("<div class='someClass'>Warning Error</div>");
});

//this is your code
$('input').on('blur', function(){
    var el= $(this);
    setTimeout(function(){
        if ($(el).hasClass('error')){ 
            $(el).removeClass('error');
            $(el).prev('.someClass').hide();
        }
    },1000);
});

http://jsfiddle.net/GuDCp/3/

if, elif, else statement issues in Bash

[ is a command (or a builtin in some shells). It must be separated by whitespace from the preceding statement:

elif [

Recommended way to get hostname in Java

If you're not against using an external dependency from maven central, I wrote gethostname4j to solve this problem for myself. It just uses JNA to call libc's gethostname function (or gets the ComputerName on Windows) and returns it to you as a string.

https://github.com/mattsheppard/gethostname4j

How can I match on an attribute that contains a certain string?

Be aware that bobince's answer might be overly complicated if you can assume that the class name you are interested in is not a substring of another possible class name. If this is true, you can simply use substring matching via the contains function. The following will match any element whose class contains the substring 'atag':

//*[contains(@class,'atag')]

If the assumption above does not hold, a substring match will match elements you don't intend. In this case, you have to find the word boundaries. By using the space delimiters to find the class name boundaries, bobince's second answer finds the exact matches:

//*[contains(concat(' ', normalize-space(@class), ' '), ' atag ')]

This will match atag and not matag.

How to increase request timeout in IIS?

I know the question was about ASP but maybe somebody will find this answer helpful.

If you have a server behind the IIS 7.5 (e.g. Tomcat). In my case I have a server farm with Tomcat server configured. In such case you can change the timeout using the IIS Manager:

  • go to Server Farms -> {Server Name} -> Proxy
  • change the value in the Time-out entry box
  • click Apply (top-right corner)

or you can change it in the cofig file:

  • open %WinDir%\System32\Inetsrv\Config\applicationHost.config
  • adjust the server webFarm configuration to be similar to the following

Example:

<webFarm name="${SERVER_NAME}" enabled="true"> 
  <server address="${SERVER_ADDRESS}" enabled="true">
    <applicationRequestRouting httpPort="${SERVER_PORT}" />
  </server>
  <applicationRequestRouting>
    <protocol timeout="${TIME}" />
  </applicationRequestRouting>
</webFarm>

The ${TIME} is in HH:mm:ss format (so if you want to set it to 90 seconds then put there 00:01:30)

In case of Tomcat (and probably other servlet containers) you have to remember to change the timeout in the %TOMCAT_DIR%\conf\server.xml (just search for connectionTimeout attribute in Connector tag, and remember that it is specified in milliseconds)

How do I find the location of my Python site-packages directory?

Let's say you have installed the package 'django'. import it and type in dir(django). It will show you, all the functions and attributes with that module. Type in the python interpreter -

>>> import django
>>> dir(django)
['VERSION', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'get_version']
>>> print django.__path__
['/Library/Python/2.6/site-packages/django']

You can do the same thing if you have installed mercurial.

This is for Snow Leopard. But I think it should work in general as well.

Does Visual Studio have code coverage for unit tests?

As already mentioned you can use Fine Code Coverage that visualize coverlet output. If you create a xunit test project (dotnet new xunit) you'll find coverlet reference already present in csproj file because Coverlet is the default coverage tool for every .NET Core and >= .NET 5 applications.

Microsoft has an example using ReportGenerator that converts coverage reports generated by coverlet, OpenCover, dotCover, Visual Studio, NCover, Cobertura, JaCoCo, Clover, gcov or lcov into human readable reports in various formats.

Example report:

enter image description here

While the article focuses on C# and xUnit as the test framework, both MSTest and NUnit would also work.

Guide:

https://docs.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage?tabs=windows#generate-reports

If you want code coverage in .xml files you can run any of these commands:

dotnet test --collect:"XPlat Code Coverage"

dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura

Using floats with sprintf() in embedded C

Don't do this; integers in C/C++ are always rounded down so there is no need to use the floor function.

char str[100]; 
int d1 = value;

Better to use

int d1 = (int)(floor(value));

Then you won't get rounding up of the integer part (68.9999999999999999 becomes 69.00..). 68.09999847 instead of 68.1 is difficult to avoid - any floating point format has limited precision.

How can I change the default width of a Twitter Bootstrap modal box?

Preserve the responsive design, set the width to what you desire.

.modal-content {
  margin-left: auto;
  margin-right: auto;
  max-width: 360px;
}

Keep it simple.

Meaning of 'const' last in a function declaration of a class?

when you use const in the method signature (like your said: const char* foo() const;) you are telling the compiler that memory pointed to by this can't be changed by this method (which is foo here).

How to convert a string into double and vice versa?

This is the easiest way I know of:

float myFloat = 5.3;
NSInteger myInt = (NSInteger)myFloat;

How to specify the current directory as path in VBA?

I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path

But the main issue was not here. The problem was with these 2 lines of code

strFile = Dir(strPath & "*.csv")

Which should have written as

strFile = Dir(strPath & "\*.csv")

and

With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _

Which should have written as

With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _

Enabling CORS in Cloud Functions for Firebase

For what it's worth I was having the same issue when passing app into onRequest. I realized the issue was a trailing slash on the request url for the firebase function. Express was looking for '/' but I didn't have the trailing slash on the function [project-id].cloudfunctions.net/[function-name]. The CORS error was a false negative. When I added the trailing slash, I got the response I was expecting.

How can I divide one column of a data frame through another?

Hadley Wickham

dplyr

packages is always a saver in case of data wrangling. To add the desired division as a third variable I would use mutate()

d <- mutate(d, new = min / count2.freq)

Getting random numbers in Java

int max = 50;
int min = 1;

1. Using Math.random()

double random = Math.random() * 49 + 1;
or
int random = (int )(Math.random() * 50 + 1);

This will give you value from 1 to 50 in case of int or 1.0 (inclusive) to 50.0 (exclusive) in case of double

Why?

random() method returns a random number between 0.0 and 0.9..., you multiply it by 50, so upper limit becomes 0.0 to 49.999... when you add 1, it becomes 1.0 to 50.999..., now when you truncate to int, you get 1 to 50. (thanks to @rup in comments). leepoint's awesome write-up on both the approaches.

2. Using Random class in Java.

Random rand = new Random(); 
int value = rand.nextInt(50); 

This will give value from 0 to 49.

For 1 to 50: rand.nextInt((max - min) + 1) + min;

Source of some Java Random awesomeness.

How to debug (only) JavaScript in Visual Studio?

For debugging JavaScript code in VS2015, there is no need for

  1. Enabling script debugging in IE Options -> Advanced tab
  2. Writing debugger statement in JavaScript code

Attaching IE didn't work, but here is a workaround.

Select IE

enter image description here

and press F5. This will attach both worker process and IE as shown here- enter image description here

If you are not interested in debugging server code, detach it from Processes window. enter image description here

You will still face the slowness when you press F5 and all your server code compiles and loads up in VS. Note that you can detach and attach again the IE instance launched from VS. JavaScript breakpoints are hit the same way they are in server side code.

Import Google Play Services library in Android Studio

I solved the problem by installing the google play services package in sdk manager.

After it, create a new application & in the build.gradle add this

compile 'com.google.android.gms:play-services:4.3.+'

Like this

dependencies {
    compile 'com.android.support:appcompat-v7:+'
    compile 'com.google.android.gms:play-services:4.3.+'
}

Binding an Image in WPF MVVM

Displaying an Image in WPF is much easier than that. Try this:

<Image Source="{Binding DisplayedImagePath}" HorizontalAlignment="Left" 
    Margin="0,0,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Bottom" 
    Grid.Row="8" Width="200"  Grid.ColumnSpan="2" />

And the property can just be a string:

public string DisplayedImage 
{
    get { return @"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"; }
}

Although you really should add your images to a folder named Images in the root of your project and set their Build Action to Resource in the Properties Window in Visual Studio... you could then access them using this format:

public string DisplayedImage 
{
    get { return "/AssemblyName;component/Images/ImageName.jpg"; }
}

UPDATE >>>

As a final tip... if you ever have a problem with a control not working as expected, simply type 'WPF', the name of that control and then the word 'class' into a search engine. In this case, you would have typed 'WPF Image Class'. The top result will always be MSDN and if you click on the link, you'll find out all about that control and most pages have code examples as well.


UPDATE 2 >>>

If you followed the examples from the link to MSDN and it's not working, then your problem is not the Image control. Using the string property that I suggested, try this:

<StackPanel>
    <Image Source="{Binding DisplayedImagePath}" />
    <TextBlock Text="{Binding DisplayedImagePath}" />
</StackPanel>

If you can't see the file path in the TextBlock, then you probably haven't set your DataContext to the instance of your view model. If you can see the text, then the problem is with your file path.


UPDATE 3 >>>

In .NET 4, the above Image.Source values would work. However, Microsoft made some horrible changes in .NET 4.5 that broke many different things and so in .NET 4.5, you'd need to use the full pack path like this:

<Image Source="pack://application:,,,/AssemblyName;component/Images/image_to_use.png">

For further information on pack URIs, please see the Pack URIs in WPF page on Microsoft Docs.

Model summary in pytorch

For visualization and summary of PyTorch models, tensorboardX can also can be utilized.

How can I check a C# variable is an empty string "" or null?

Since .NET 2.0 you can use:

// Indicates whether the specified string is null or an Empty string.
string.IsNullOrEmpty(string value);

Additionally, since .NET 4.0 there's a new method that goes a bit farther:

// Indicates whether a specified string is null, empty, or consists only of white-space characters.
string.IsNullOrWhiteSpace(string value);

Angular and Typescript: Can't find names - Error: cannot find name

The accepted answer doesn't provide a viable fix, and most of the other ones suggest the "triple-slashes" workaround which is not viable anymore, since the browser.d.ts has been removed by the Angular2 latest RC's and thus is not available anymore.

I strongly suggest to install the typings module as suggested by a couple solutions here, yet it's not necessary to do it manually or globally - there's an effective way to do that for your project only and within VS2015 interface. Here's what you need to do:

  • add typings in the project's package.json file.
  • add a script block in the package.json file to execute/update typings after each NPM action.
  • add a typings.json file in the project's root folder containing a reference to core-js (overall better than es6-shim atm).

That's it.

You can also take a look to this other SO thread and/or read this post on my blog for additional details.

How to define a two-dimensional array?

In case if you need a matrix with predefined numbers you can use the following code:

def matrix(rows, cols, start=0):
    return [[c + start + r * cols for c in range(cols)] for r in range(rows)]


assert matrix(2, 3, 1) == [[1, 2, 3], [4, 5, 6]]

Programmatically extract contents of InstallShield setup.exe

There's no supported way to do this, but won't you have to examine the files related to each installer to figure out how to actually install them after extracting them? Assuming you can spend the time to figure out which command-line applies, here are some candidate parameters that normally allow you to extract an installation.

MSI Based (may not result in a usable image for an InstallScript MSI installation):

  • setup.exe /a /s /v"/qn TARGETDIR=\"choose-a-location\""

    or, to also extract prerequisites (for versions where it works),

  • setup.exe /a"choose-another-location" /s /v"/qn TARGETDIR=\"choose-a-location\""

InstallScript based:

  • setup.exe /s /extract_all

Suite based (may not be obvious how to install the resulting files):

  • setup.exe /silent /stage_only ISRootStagePath="choose-a-location"

Failed to resolve: com.android.support:appcompat-v7:28.0

my problem was just network connection. using VPN solved the issue.

Python Pandas counting and summing specific conditions

You didn't mention the fancy indexing capabilities of dataframes, e.g.:

>>> df = pd.DataFrame({"class":[1,1,1,2,2], "value":[1,2,3,4,5]})
>>> df[df["class"]==1].sum()
class    3
value    6
dtype: int64
>>> df[df["class"]==1].sum()["value"]
6
>>> df[df["class"]==1].count()["value"]
3

You could replace df["class"]==1by another condition.

How to switch to new window in Selenium for Python?

We can handle the different windows by moving between named windows using the “switchTo” method:

driver.switch_to.window("windowName")

<a href="somewhere.html" target="windowName">Click here to open a new window</a>

Alternatively, you can pass a “window handle” to the “switchTo().window()” method. Knowing this, it’s possible to iterate over every open window like so:

for handle in driver.window_handles:
    driver.switch_to.window(handle)

IPython Notebook save location

If you're using IPython 4.x/Jupyter, run

$ jupyter notebook --generate-config

This will create a file jupyter_notebook_config.py in ~/.jupyter. This file already has a line starting with # c.NotebookApp.notebook_dir=u''.

All you need to do is to uncomment this line and change the value to your desired location, e.g., c.NotebookApp.notebook_dir=u'/home/alice/my_ipython_notebooks'

Cassandra cqlsh - connection refused

Look for native_transport_port in /etc/cassandra/cassandra.yaml The default is 9842.

native_transport_port: 9842

For connecting to localhost with cqlsh, this port worked for me.

cqlsh 127.0.0.1 9842

How to stop text from taking up more than 1 line?

Using ellipsis will add the ... at the last.

   <style type="text/css">
    div {
      white-space: nowrap;
      overflow: hidden;
text-overflow: ellipsis;
    }
    </style>

Pandas index column title or name

Use df.index.rename('foo', inplace=True) to set the index name.

Seems this api is available since pandas 0.13.

How to increment a JavaScript variable using a button press event

<script type="text/javascript">
var i=0;

function increase()
{
    i++;
    return false;
}</script><input type="button" onclick="increase();">

convert streamed buffers to utf8-string

var fs = require("fs");

function readFileLineByLine(filename, processline) {
    var stream = fs.createReadStream(filename);
    var s = "";
    stream.on("data", function(data) {
        s += data.toString('utf8');
        var lines = s.split("\n");
        for (var i = 0; i < lines.length - 1; i++)
            processline(lines[i]);
        s = lines[lines.length - 1];
    });

    stream.on("end",function() {
        var lines = s.split("\n");
        for (var i = 0; i < lines.length; i++)
            processline(lines[i]);
    });
}

var linenumber = 0;
readFileLineByLine(filename, function(line) {
    console.log(++linenumber + " -- " + line);
});

How to center an element horizontally and vertically

  • Approach 1 - transform translateX/translateY:

    Example Here / Full Screen Example

    In supported browsers (most of them), you can use top: 50%/left: 50% in combination with translateX(-50%) translateY(-50%) to dynamically vertically/horizontally center the element.

_x000D_
_x000D_
.container {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    left: 50%;_x000D_
    -moz-transform: translateX(-50%) translateY(-50%);_x000D_
    -webkit-transform: translateX(-50%) translateY(-50%);_x000D_
    transform: translateX(-50%) translateY(-50%);_x000D_
}
_x000D_
<div class="container">_x000D_
    <span>I'm vertically/horizontally centered!</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_


  • Approach 2 - Flexbox method:

    Example Here / Full Screen Example

    In supported browsers, set the display of the targeted element to flex and use align-items: center for vertical centering and justify-content: center for horizontal centering. Just don't forget to add vendor prefixes for additional browser support (see example).

_x000D_
_x000D_
html, body, .container {_x000D_
    height: 100%;_x000D_
}_x000D_
_x000D_
.container {_x000D_
    display: -webkit-flexbox;_x000D_
    display: -ms-flexbox;_x000D_
    display: -webkit-flex;_x000D_
    display: flex;_x000D_
    -webkit-flex-align: center;_x000D_
    -ms-flex-align: center;_x000D_
    -webkit-align-items: center;_x000D_
    align-items: center;_x000D_
    justify-content: center;_x000D_
}
_x000D_
<div class="container"> _x000D_
  <span>I'm vertically/horizontally centered!</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_


  • Approach 3 - table-cell/vertical-align: middle:

    Example Here / Full Screen Example

    In some cases, you will need to ensure that the html/body element's height is set to 100%.

    For vertical alignment, set the parent element's width/height to 100% and add display: table. Then for the child element, change the display to table-cell and add vertical-align: middle.

    For horizontal centering, you could either add text-align: center to center the text and any other inline children elements. Alternatively, you could use margin: 0 auto, assuming the element is block level.

_x000D_
_x000D_
html, body {_x000D_
    height: 100%;_x000D_
}_x000D_
.parent {_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    display: table;_x000D_
    text-align: center;_x000D_
}_x000D_
.parent > .child {_x000D_
    display: table-cell;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<section class="parent">_x000D_
    <div class="child">I'm vertically/horizontally centered!</div>_x000D_
</section>
_x000D_
_x000D_
_x000D_


  • Approach 4 - Absolutely positioned 50% from the top with displacement:

    Example Here / Full Screen Example

    This approach assumes that the text has a known height - in this instance, 18px. Just absolutely position the element 50% from the top, relative to the parent element. Use a negative margin-top value that is half of the element's known height, in this case - -9px.

_x000D_
_x000D_
html, body, .container {_x000D_
    height: 100%;_x000D_
}_x000D_
_x000D_
.container {_x000D_
    position: relative;_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
.container > p {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    margin-top: -9px;_x000D_
}
_x000D_
<div class="container">_x000D_
    <p>I'm vertically/horizontally centered!</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_


  • Approach 5 - The line-height method (Least flexible - not suggested):

    Example Here

    In some cases, the parent element will have a fixed height. For vertical centering, all you have to do is set a line-height value on the child element equal to the fixed height of the parent element.

    Though this solution will work in some cases, it's worth noting that it won't work when there are multiple lines of text - like this.

_x000D_
_x000D_
.parent {_x000D_
    height: 200px;_x000D_
    width: 400px;_x000D_
    background: lightgray;_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
.parent > .child {_x000D_
    line-height: 200px;_x000D_
}
_x000D_
<div class="parent">_x000D_
    <span class="child">I'm vertically/horizontally centered!</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Python List & for-each access (Find/Replace in built-in list)

Python is not Java, nor C/C++ -- you need to stop thinking that way to really utilize the power of Python.

Python does not have pass-by-value, nor pass-by-reference, but instead uses pass-by-name (or pass-by-object) -- in other words, nearly everything is bound to a name that you can then use (the two obvious exceptions being tuple- and list-indexing).

When you do spam = "green", you have bound the name spam to the string object "green"; if you then do eggs = spam you have not copied anything, you have not made reference pointers; you have simply bound another name, eggs, to the same object ("green" in this case). If you then bind spam to something else (spam = 3.14159) eggs will still be bound to "green".

When a for-loop executes, it takes the name you give it, and binds it in turn to each object in the iterable while running the loop; when you call a function, it takes the names in the function header and binds them to the arguments passed; reassigning a name is actually rebinding a name (it can take a while to absorb this -- it did for me, anyway).

With for-loops utilizing lists, there are two basic ways to assign back to the list:

for i, item in enumerate(some_list):
    some_list[i] = process(item)

or

new_list = []
for item in some_list:
    new_list.append(process(item))
some_list[:] = new_list

Notice the [:] on that last some_list -- it is causing a mutation of some_list's elements (setting the entire thing to new_list's elements) instead of rebinding the name some_list to new_list. Is this important? It depends! If you have other names besides some_list bound to the same list object, and you want them to see the updates, then you need to use the slicing method; if you don't, or if you do not want them to see the updates, then rebind -- some_list = new_list.

Finding first and last index of some value in a list in Python

Sequences have a method index(value) which returns index of first occurrence - in your case this would be verts.index(value).

You can run it on verts[::-1] to find out the last index. Here, this would be len(verts) - 1 - verts[::-1].index(value)

Adjust list style image position?

A possible solution to this question that wasn't mentioned yet is the following:

    li {
        position: relative;
        list-style-type: none;
    }

    li:before {
        content: "";
        position: absolute;
        top: 8px;
        left: -16px;
        width: 8px;
        height: 8px;
        background-image: url('your-bullet.png');
    }

You can now use the top/left of the li:before to position the new bullet. Note that the width and height of the li:before need to be the same dimensions as the background image you choose. This works in Internet Explorer 8 and up.

How to escape special characters in building a JSON string?

regarding AlexB's post:

 \'  Apostrophe or single quote
 \"  Double quote

escaping single quotes is only valid in single quoted json strings
escaping double quotes is only valid in double quoted json strings

example:

'Bart\'s car'       -> valid
'Bart says \"Hi\"'  -> invalid

Setting and getting localStorage with jQuery

You said you are attempting to get the text from a div and store it on local storage.

Please Note: Text and Html are different. In the question you mentioned text. html() will return Html content like <a>example</a>. if you want to get Text content then you have to use text() instead of html() then the result will be example instead of <a>example<a>. Anyway, I am using your terminology let it be Text.

Step 1: get the text from div.

what you did is not get the text from div but set the text to a div.

$('#test').html("Test"); 

is actually setting text to div and the output will be a jQuery object. That is why it sets it as [object Object].

To get the text you have to write like this
$('#test').html();

This will return a string not an object so the result will be Test in your case.

Step 2: set it to local storage.

Your approach is correct and you can write it as

localStorage.key=value

But the preferred approach is

localStorage.setItem(key,value); to set

localStorage.getItem(key); to get.

key and value must be strings.

so in your context code will become

$('#test').html("Test");
localStorage.content = $('#test').html();
$('#test').html(localStorage.content);

But I don't find any meaning in your code. Because you want to get the text from div and store it on local storage. And again you are reading the same from local storage and set to div. just like a=10; b=a; a=b;

If you are facing any other problems please update your question accordingly.

Using Mockito to stub and execute methods for testing

You've nearly got it. The problem is that the Class Under Test (CUT) is not built for unit testing - it has not really been TDD'd.

Think of it like this…

  • I need to test a function of a class - let's call it myFunction
  • That function makes a call to a function on another class/service/database
  • That function also calls another method on the CUT

In the unit test

  • Should create a concrete CUT or @Spy on it
  • You can @Mock all of the other class/service/database (i.e. external dependencies)
  • You could stub the other function called in the CUT but it is not really how unit testing should be done

In order to avoid executing code that you are not strictly testing, you could abstract that code away into something that can be @Mocked.

In this very simple example, a function that creates an object will be difficult to test

public void doSomethingCool(String foo) {
    MyObject obj = new MyObject(foo);

    // can't do much with obj in a unit test unless it is returned
}

But a function that uses a service to get MyObject is easy to test, as we have abstracted the difficult/impossible to test code into something that makes this method testable.

public void doSomethingCool(String foo) {
    MyObject obj = MyObjectService.getMeAnObject(foo);
}

as MyObjectService can be mocked and also verified that .getMeAnObject() is called with the foo variable.

View's SELECT contains a subquery in the FROM clause

As the more recent MySQL documentation on view restrictions says:

Before MySQL 5.7.7, subqueries cannot be used in the FROM clause of a view.

This means, that choosing a MySQL v5.7.7 or newer or upgrading the existing MySQL instance to such a version, would remove this restriction on views completely.

However, if you have a current production MySQL version that is earlier than v5.7.7, then the removal of this restriction on views should only be one of the criteria being assessed while making a decision as to upgrade or not. Using the workaround techniques described in the other answers may be a more viable solution - at least on the shorter run.

How do I spool to a CSV formatted file using SQLPLUS?

You could use csv hint. See the following example:

select /*csv*/ table_name, tablespace_name
from all_tables
where owner = 'SYS'
and tablespace_name is not null;

How can I convert a DateTime to the number of seconds since 1970?

If the rest of your system is OK with DateTimeOffset instead of DateTime, there's a really convenient feature:

long unixSeconds = DateTimeOffset.Now.ToUnixTimeSeconds();

Getting the filenames of all files in a folder

Create a File object, passing the directory path to the constructor. Use the listFiles() to retrieve an array of File objects for each file in the directory, and then call the getName() method to get the filename.

List<String> results = new ArrayList<String>();


File[] files = new File("/path/to/the/directory").listFiles();
//If this pathname does not denote a directory, then listFiles() returns null. 

for (File file : files) {
    if (file.isFile()) {
        results.add(file.getName());
    }
}

AngularJS ui-router login authentication

The solutions posted so far are needlessly complicated, in my opinion. There's a simpler way. The documentation of ui-router says listen to $locationChangeSuccess and use $urlRouter.sync() to check a state transition, halt it, or resume it. But even that actually doesn't work.

However, here are two simple alternatives. Pick one:

Solution 1: listening on $locationChangeSuccess

You can listen to $locationChangeSuccess and you can perform some logic, even asynchronous logic there. Based on that logic, you can let the function return undefined, which will cause the state transition to continue as normal, or you can do $state.go('logInPage'), if the user needs to be authenticated. Here's an example:

angular.module('App', ['ui.router'])

// In the run phase of your Angular application  
.run(function($rootScope, user, $state) {

  // Listen to '$locationChangeSuccess', not '$stateChangeStart'
  $rootScope.$on('$locationChangeSuccess', function() {
    user
      .logIn()
      .catch(function() {
        // log-in promise failed. Redirect to log-in page.
        $state.go('logInPage')
      })
  })
})

Keep in mind that this doesn't actually prevent the target state from loading, but it does redirect to the log-in page if the user is unauthorized. That's okay since real protection is on the server, anyway.

Solution 2: using state resolve

In this solution, you use ui-router resolve feature.

You basically reject the promise in resolve if the user is not authenticated and then redirect them to the log-in page.

Here's how it goes:

angular.module('App', ['ui.router'])

.config(
  function($stateProvider) {
    $stateProvider
      .state('logInPage', {
        url: '/logInPage',
        templateUrl: 'sections/logInPage.html',
        controller: 'logInPageCtrl',
      })
      .state('myProtectedContent', {
        url: '/myProtectedContent',
        templateUrl: 'sections/myProtectedContent.html',
        controller: 'myProtectedContentCtrl',
        resolve: { authenticate: authenticate }
      })
      .state('alsoProtectedContent', {
        url: '/alsoProtectedContent',
        templateUrl: 'sections/alsoProtectedContent.html',
        controller: 'alsoProtectedContentCtrl',
        resolve: { authenticate: authenticate }
      })

    function authenticate($q, user, $state, $timeout) {
      if (user.isAuthenticated()) {
        // Resolve the promise successfully
        return $q.when()
      } else {
        // The next bit of code is asynchronously tricky.

        $timeout(function() {
          // This code runs after the authentication promise has been rejected.
          // Go to the log-in page
          $state.go('logInPage')
        })

        // Reject the authentication promise to prevent the state from loading
        return $q.reject()
      }
    }
  }
)

Unlike the first solution, this solution actually prevents the target state from loading.

R: numeric 'envir' arg not of length one in predict()

There are several problems here:

  1. The newdata argument of predict() needs a predictor variable. You should thus pass it values for Coupon, instead of Total, which is the response variable in your model.

  2. The predictor variable needs to be passed in as a named column in a data frame, so that predict() knows what the numbers its been handed represent. (The need for this becomes clear when you consider more complicated models, having more than one predictor variable).

  3. For this to work, your original call should pass df in through the data argument, rather than using it directly in your formula. (This way, the name of the column in newdata will be able to match the name on the RHS of the formula).

With those changes incorporated, this will work:

model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")

Best way to concatenate List of String objects?

It seems to me that the StringBuilder will be quick and efficient.

The basic form would look something like this:

public static String concatStrings(List<String> strings)
{
    StringBuilder sb = new StringBuilder();
    for(String s: strings)
    {
        sb.append(s);
    }
    return sb.toString();       
}

If that's too simplistic (and it probably is), you can use a similar approach and add a separator like this:

    public static String concatStringsWSep(List<String> strings, String separator)
{
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < strings.size(); i++)
    {
        sb.append(strings.get(i));
        if(i < strings.size() - 1)
            sb.append(separator);
    }
    return sb.toString();               
}

I agree with the others who have responded to this question when they say that you should not rely on the toString() method of Java's ArrayList.

Why aren't programs written in Assembly more often?

ASM has poor legibility and isn't really maintainable compared to higher-level languages.

Also, there are many fewer ASM developers than for other more popular languages, such as C.

Furthermore, if you use a higher-level language and new ASM instructions become available (SSE for example), you just need to update your compiler and your old code can easily make use of the new instructions.

What if the next CPU has twice as many registers?

The converse of this question would be: What functionality do compilers provide?

I doubt you can/want to/should optimize your ASM better than gcc -O3 can.

How to get names of classes inside a jar file?

You can try this :

unzip -v /your/jar.jar

This will be helpful only if your jar is executable i.e. in manifest you have defined some class as main class

Create file path from variables

Yes there is such a built-in function: os.path.join.

>>> import os.path
>>> os.path.join('/my/root/directory', 'in', 'here')
'/my/root/directory/in/here'

How do we change the URL of a working GitLab install?

You did everything correctly!

You might also change the email configuration, depending on if the email server is also the same server. The email configuration is in gitlab.yml for the mails sent by GitLab and also the admin-email.

How to alert using jQuery

For each works with JQuery as in

$(<selector>).each(function() {
   //this points to item
   alert('<msg>');
});

JQuery also, for a popup, has in the UI library a dialog widget: http://jqueryui.com/demos/dialog/

Check it out, works really well.

HTH.

Generating sql insert into for Oracle

Use a SQL function (I'm the author):

Usage:

select fn_gen_inserts('select * from tablename', 'p_new_owner_name', 'p_new_table_name')
from dual;

where:

p_sql            – dynamic query which will be used to export metadata rows
p_new_owner_name – owner name which will be used for generated INSERT
p_new_table_name – table name which will be used for generated INSERT

p_sql in this sample is 'select * from tablename'

You can find original source code here:

Ashish Kumar's script generates individually usable insert statements instead of a SQL block, but supports fewer datatypes.

Checking if type == list in python

Python 3.7.7

import typing
if isinstance([1, 2, 3, 4, 5] , typing.List):
    print("It is a list")

Is there a way for non-root processes to bind to "privileged" ports on Linux?

At startup:

iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080

Then you can bind to the port you forward to.

TokenMismatchException in VerifyCsrfToken.php Line 67

Use like this

<form>
<input type="hidden" name="_token" value="<?= csrf_token(); ?>" />

Binary search (bisection) in Python

def binary_search_length_of_a_list(single_method_list):
    index = 0
    first = 0
    last = 1

    while True:
        mid = ((first + last) // 2)
        if not single_method_list.get(index):
            break
        index = mid + 1
        first = index
        last = index + 1
    return mid

PL/SQL ORA-01422: exact fetch returns more than requested number of rows

It can also be due to a duplicate entry in any of the tables that are used.

Heroku 'Permission denied (publickey) fatal: Could not read from remote repository' woes

Had a similar issue, and tried lots of things. Ultimately what worked for me, was to have Gnu on Windows installed (https://github.com/bmatzelle/gow/releases) , and ensure that it was using the ssh tool inside that directory and not the one with Git. Once installed test with (ensure if its in your environment PATH that it preceds Git\bin)

C:\Git\htest2>which ssh
C:\Program Files (x86)\Gow\bin\ssh.BAT

I used putty and pageant as described here:http://rubyonrailswin.wordpress.com/2010/03/08/getting-git-to-work-on-heroku-on-windows-using-putty-plink-pageant/

Once the keys had been sent to heroku (heroku keys:add c:\Users\Person.ssh\id_rsa.pub), use

ssh -v <username>@heroku.com 

and ensure that your stack is showing use of Putty - ie a working stack:

Looking up host "heroku.com"
Connecting to 50.19.85.132 port 22
Server version: SSH-2.0-Twisted
Using SSH protocol version 2
**We claim version: SSH-2.0-PuTTY_Release_0.62**
Using Diffie-Hellman with standard group "group1"
Doing Diffie-Hellman key exchange with hash SHA-1
Host key fingerprint is:
ssh-rsa 2048 8b:48:5e:67:0e:c9:16:47:32:f2:87:0c:1f:c8:60:ad
Initialised AES-256 SDCTR client->server encryption
Initialised HMAC-SHA1 client->server MAC algorithm
Initialised AES-256 SDCTR server->client encryption
Initialised HMAC-SHA1 server->client MAC algorithm
Pageant is running. Requesting keys.
Pageant has 1 SSH-2 keys
Using username "*--ommitted for security--*".
**Trying Pageant key #0**
Authenticating with public key "rsa-key-20140401" from agent
Sending Pageant's response
Access granted
Opened channel for session
Server refused to allocate pty
Server refused to start a shell/command
FATAL ERROR: Server refused to start a shell/command

One that was running previously and failed:

C:\Git\htest2>ssh -v <username>@[email protected]
OpenSSH_4.6p1, OpenSSL 0.9.8e 23 Feb 2007
debug1: Connecting to heroku.com [50.19.85.156] port 22.
debug1: Connection established.
debug1: identity file /c/Users/Person/.ssh/identity type -1
debug1: identity file /c/Users/Person/.ssh/id_rsa type 1
debug1: identity file /c/Users/Person/.ssh/id_dsa type -1
debug1: Remote protocol version 2.0, remote software version Twisted
debug1: no match: Twisted
debug1: Enabling compatibility mode for protocol 2.0
**debug1: Local version string SSH-2.0-OpenSSH_4.6**
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-cbc hmac-md5 none
debug1: kex: client->server aes128-cbc hmac-md5 none
debug1: sending SSH2_MSG_KEXDH_INIT
debug1: expecting SSH2_MSG_KEXDH_REPLY
debug1: Host 'heroku.com' is known and matches the RSA host key.
debug1: Found key in /c/Users/Person/.ssh/known_hosts:1
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /c/Users/Person/.ssh/identity
debug1: Offering public key: /c/Users/Person/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 277
debug1: Trying private key: /c/Users/Person/.ssh/id_dsa
debug1: No more authentication methods to try.
Permission denied (publickey).

How to retrieve element value of XML using Java?

If the XML is well formed then you can convert it to Document. By using the XPath you can get the XML Elements.

String xml = "<stackusers><name>Yash</name><age>30</age></stackusers>";

Form XML-String Create Document and find the elements using its XML-Path.

Document doc = getDocument(xml, true);

    public static Document getDocument(String xmlData, boolean isXMLData) throws Exception {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        dbFactory.setNamespaceAware(true);
        dbFactory.setIgnoringComments(true);
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc;
        if (isXMLData) {
            InputSource ips = new org.xml.sax.InputSource(new StringReader(xmlData));
            doc = dBuilder.parse(ips);
        } else {
            doc = dBuilder.parse( new File(xmlData) );
        }
        return doc;
    }

Use org.apache.xpath.XPathAPI to get Node or NodeList.

System.out.println("XPathAPI:"+getNodeValue(doc, "/stackusers/age/text()"));

NodeList nodeList = getNodeList(doc, "/stackusers");
System.out.println("XPathAPI NodeList:"+ getXmlContentAsString(nodeList));
System.out.println("XPathAPI NodeList:"+ getXmlContentAsString(nodeList.item(0)));

    public static String getNodeValue(Document doc, String xpathExpression) throws Exception {
        Node node = org.apache.xpath.XPathAPI.selectSingleNode(doc, xpathExpression);
        String nodeValue = node.getNodeValue();
        return nodeValue;
    }
    public static NodeList getNodeList(Document doc, String xpathExpression) throws Exception {
        NodeList result = org.apache.xpath.XPathAPI.selectNodeList(doc, xpathExpression);
        return result;
    }

Using javax.xml.xpath.XPathFactory

System.out.println("javax.xml.xpath.XPathFactory:"+getXPathFactoryValue(doc, "/stackusers/age"));

    static XPath xpath = javax.xml.xpath.XPathFactory.newInstance().newXPath();
    public static String getXPathFactoryValue(Document doc, String xpathExpression) throws XPathExpressionException, TransformerException, IOException {
        Node node = (Node) xpath.evaluate(xpathExpression, doc, XPathConstants.NODE);
        String nodeStr = getXmlContentAsString(node);
        return nodeStr;
    }

Using Document Element.

System.out.println("DocumentElementText:"+getDocumentElementText(doc, "age"));

    public static String getDocumentElementText(Document doc, String elementName) {
        return doc.getElementsByTagName(elementName).item(0).getTextContent();
    }

Get value in between two strings.

String nodeVlaue = org.apache.commons.lang.StringUtils.substringBetween(xml, "<age>", "</age>");
System.out.println("StringUtils.substringBetween():"+nodeVlaue);

Full Example:

public static void main(String[] args) throws Exception {
    String xml = "<stackusers><name>Yash</name><age>30</age></stackusers>";
    Document doc = getDocument(xml, true);
    
    String nodeVlaue = org.apache.commons.lang.StringUtils.substringBetween(xml, "<age>", "</age>");
    System.out.println("StringUtils.substringBetween():"+nodeVlaue);
    
    System.out.println("DocumentElementText:"+getDocumentElementText(doc, "age"));
    System.out.println("javax.xml.xpath.XPathFactory:"+getXPathFactoryValue(doc, "/stackusers/age"));
    
    System.out.println("XPathAPI:"+getNodeValue(doc, "/stackusers/age/text()"));
    NodeList nodeList = getNodeList(doc, "/stackusers");
    System.out.println("XPathAPI NodeList:"+ getXmlContentAsString(nodeList));
    System.out.println("XPathAPI NodeList:"+ getXmlContentAsString(nodeList.item(0)));
}
public static String getXmlContentAsString(Node node) throws TransformerException, IOException {
    StringBuilder stringBuilder = new StringBuilder();
    NodeList childNodes = node.getChildNodes();
    int length = childNodes.getLength();
    for (int i = 0; i < length; i++) {
        stringBuilder.append( toString(childNodes.item(i), true) );
    }
    return stringBuilder.toString();
}

OutPut:

StringUtils.substringBetween():30
DocumentElementText:30
javax.xml.xpath.XPathFactory:30
XPathAPI:30
XPathAPI NodeList:<stackusers>
   <name>Yash</name>
   <age>30</age>
</stackusers>
XPathAPI NodeList:<name>Yash</name><age>30</age>

Why must wait() always be in synchronized block

directly from this java oracle tutorial:

When a thread invokes d.wait, it must own the intrinsic lock for d — otherwise an error is thrown. Invoking wait inside a synchronized method is a simple way to acquire the intrinsic lock.

How to use View.OnTouchListener instead of onClick

The event when user releases his finger is MotionEvent.ACTION_UP. I'm not aware if there are any guidelines which prohibit using View.OnTouchListener instead of onClick(), most probably it depends of situation.

Here's a sample code:

imageButton.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_UP){

            // Do what you want
            return true;
        }
        return false;
    }
});

What is a reasonable code coverage % for unit tests (and why)?

I don't think there can be such a B/W rule.
Code should be reviewed, with particular attention to the critical details.
However, if it hasn't been tested, it has a bug!

Link to a section of a webpage

The fragment identifier (also known as: Fragment IDs, Anchor Identifiers, Named Anchors) introduced by a hash mark # is the optional last part of a URL for a document. It is typically used to identify a portion of that document.

<a href="http://www.someuri.com/page#fragment">Link to fragment identifier</a>

Syntax for URIs also allows an optional query part introduced by a question mark ?. In URIs with a query and a fragment the fragment follows the query.

<a href="http://www.someuri.com/page?query=1#fragment">Link to fragment with a query</a>

When a Web browser requests a resource from a Web server, the agent sends the URI to the server, but does not send the fragment. Instead, the agent waits for the server to send the resource, and then the agent (Web browser) processes the resource according to the document type and fragment value.

Named Anchors <a name="fragment"> are deprecated in XHTML 1.0, the ID attribute is the suggested replacement. <div id="fragment"></div>

Nesting optgroups in a dropdownlist/select

I know this was quite a while ago, however I have a little extra to add:

This is not possible in HTML5 or any previous specs, nor is it proposed in HTML5.1 yet. I have made a request to the public-html-comments mailing list, but we'll see if anything comes of it.

Regardless, whilst this is not possible using <select> yet, you can achieve a similar effect with the following HTML, plus some CSS for prettiness:

_x000D_
_x000D_
<ul>_x000D_
  <li>_x000D_
 <input type="radio" name="location" value="0" id="loc_0" />_x000D_
 <label for="loc_0">United States</label>_x000D_
 <ul>_x000D_
   <li>_x000D_
  Northeast_x000D_
        <ul>_x000D_
       <li>_x000D_
   <input type="radio" name="location" value="1" id="loc_1" />_x000D_
   <label for="loc_1">New Hampshire</label>_x000D_
    </li>_x000D_
          <li>_x000D_
   <input type="radio" name="location" value="2" id="loc_2" />_x000D_
   <label for="loc_2">Vermont</label>_x000D_
    </li>_x000D_
          <li>_x000D_
    <input type="radio" name="location" value="3" id="loc_3" />_x000D_
    <label for="loc_3">Maine</label>_x000D_
    </li>_x000D_
   </ul>_x000D_
    </li>_x000D_
       <li>_x000D_
     Southeast_x000D_
           <ul>_x000D_
    <li>_x000D_
    <input type="radio" name="location" value="4" id="loc_4" />_x000D_
    <label for="loc_4">Georgia</label>_x000D_
    </li>_x000D_
             <li>_x000D_
    <input type="radio" name="location" value="5" id="loc_5" />_x000D_
    <label for="loc_5">Alabama</label>_x000D_
    </li>_x000D_
     </ul>_x000D_
  </li>_x000D_
   </ul>_x000D_
    </li>_x000D_
    <li>_x000D_
    <input type="radio" name="location" value="6" id="loc_6" />_x000D_
    <label for="loc_6">Canada</label>_x000D_
       <ul>_x000D_
    <li>_x000D_
    <input type="radio" name="location" value="7" id="loc_7" />_x000D_
    <label for="loc_7">Ontario</label>_x000D_
    </li>_x000D_
          <li>_x000D_
     <input type="radio" name="location" value="8" id="loc_8" />_x000D_
        <label for="loc_8">Quebec</label>_x000D_
    </li>_x000D_
          <li>_x000D_
      <input type="radio" name="location" value="9" id="loc_9" />_x000D_
      <label for="loc_9">Manitoba</label>_x000D_
    </li>_x000D_
  </ul>_x000D_
  </li>_x000D_
  </ul>
_x000D_
_x000D_
_x000D_

As an extra added benefit, this also means you can allow selection of the <optgroups> themselves. This might be useful if you had, for example, nested categories where the categories go into heavy detail and you want to allow users to select higher up in the hierarchy.

This will all work without JavaScript, however you might wish to add some to hide the radio buttons and then change the background color of the selected item or something.

Bear in mind, this is far from a perfect solution, but if you absolutely need a nested select with reasonable cross-browser compatibility, this is probably as close as you're going to get.

can you host a private repository for your organization to use with npm?

I guess this thread needs an update. If you look at any of the npm registries which are available, they are extremely heavy and they need couchdb. Gemfurry and others need you to fork off from public repos. Some of the npm's like shadow-npm have no recent commits.

Then, we found Reggie. Its got a good commit activity, extremely easy to install and use and has pretty good community support. Its extremely light-weight and you don't have to deal with couchdb, etc.

Skip rows during csv import pandas

I got the same issue while running the skiprows while reading the csv file. I was doning skip_rows=1 this will not work

Simple example gives an idea how to use skiprows while reading csv file.

import pandas as pd

#skiprows=1 will skip first line and try to read from second line
df = pd.read_csv('my_csv_file.csv', skiprows=1)  ## pandas as pd

#print the data frame
df

Permission denied (publickey) when SSH Access to Amazon EC2 instance

I had same problem and its very strange. If you believe you are doing all good than follow this: Some times there is confusion about user for the EC2 instance!! Some times you get ec2-user, ubuntu, centos etc. So check your username for the machie!!

Login with root user ssh -i yourkey.pem (400 permission) root@<ip> It will throw error and will give you the available username. then login with that user.

Setting the character encoding in form submit for Internet Explorer

With decent browsers:

<form accept-charset="ISO-8859-1" .... >

With IE (any):

document.charset = 'ISO-8859-1'; // do this before submitting your non-utf8 <form>!

Remove a JSON attribute

Simple:

delete myObj.test.key1;

How to check for null in Twig?

     //test if varibale exist
     {% if var is defined %}
         //todo
     {% endif %}

     //test if variable is not null
     {% if var is not null %}
         //todo
     {% endif %}

<hr> tag in Twitter Bootstrap not functioning correctly?

You may want one of these, so to correspond to the Bootstrap layout:

<div class="col-xs-12">
    <hr >
</div>

<!-- or -->

<div class="col-xs-12">
    <hr style="border-style: dashed; border-top-width: 2px;">
</div>

<!-- or -->

<div class="col-xs-12">
    <hr class="col-xs-1" style="border-style: dashed; border-top-width: 2px;">
</div>

Without a DIV grid element included, layout may brake on different devices.

Local file access with JavaScript

UPDATE This feature is removed since Firefox 17 (see https://bugzilla.mozilla.org/show_bug.cgi?id=546848).


On Firefox you (the programmer) can do this from within a JavaScript file:

netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");

and you (the browser user) will be prompted to allow access. (for Firefox you just need to do this once every time the browser is started)

If the browser user is someone else, they have to grant permission.

get next sequence value from database using hibernate

I found the solution:

public class DefaultPostgresKeyServer
{
    private Session session;
    private Iterator<BigInteger> iter;
    private long batchSize;

    public DefaultPostgresKeyServer (Session sess, long batchFetchSize)
    {
        this.session=sess;
        batchSize = batchFetchSize;
        iter = Collections.<BigInteger>emptyList().iterator();
    }

        @SuppressWarnings("unchecked")
        public Long getNextKey()
        {
            if ( ! iter.hasNext() )
            {
                Query query = session.createSQLQuery( "SELECT nextval( 'mySchema.mySequence' ) FROM generate_series( 1, " + batchSize + " )" );

                iter = (Iterator<BigInteger>) query.list().iterator();
            }
            return iter.next().longValue() ;
        }

}

css transform, jagged edges in chrome

If you are using transition instead of transform, -webkit-backface-visibility: hidden; does not work. A jagged edge appears during animation for a transparent png file.

To solve it I used: outline: 1px solid transparent;

What does @media screen and (max-width: 1024px) mean in CSS?

That’s a media query. It prevents the CSS inside it from being run unless the browser passes the tests it contains.

The tests in this media query are:

  1. @media screen — The browser identifies itself as being in the “screen” category. This roughly means the browser considers itself desktop-class — as opposed to e.g. an older mobile phone browser (note that the iPhone, and other smartphone browsers, do identify themselves as being in the screen category), or a screenreader — and that it’s displaying the page on-screen, rather than printing it.

  2. max-width: 1024px — the width of the browser window (including the scroll bar) is 1024 pixels or less. (CSS pixels, not device pixels.)

That second test suggests this is intended to limit the CSS to the iPad, iPhone, and similar devices (because some older browsers don’t support max-width in media queries, and a lot of desktop browsers are run wider than 1024 pixels).

However, it will also apply to desktop browser windows less than 1024 pixels wide, in browsers that support the max-width media query.

Here’s the Media Queries spec, it’s pretty readable:

How to use pagination on HTML tables?

Use tr to <tr class="paginate">

//Pagination

<div id="page-nav"></div>

//Script

 <script>
        jQuery(function($) {
            // Grab whatever we need to paginate
            var pageParts = $(".paginate");
    
            // How many parts do we have?
            var numPages = 100;
            // How many parts do we want per page?
            var perPage = 10;
    
            // When the document loads we're on page 1
            // So to start with... hide everything else
            pageParts.slice(perPage).hide();
            // Apply simplePagination to our placeholder
            $("#page-nav").pagination({
                items: numPages,
                itemsOnPage: perPage,
                cssStyle: "light-theme",
                // We implement the actual pagination
                //   in this next function. It runs on
                //   the event that a user changes page
                onPageClick: function(pageNum) {
                    // Which page parts do we show?
                    var start = perPage * (pageNum - 1);
                    var end = start + perPage;
    
                    // First hide all page parts
                    // Then show those just for our page
                    pageParts.hide()
                        .slice(start, end).show();
                }
            });
        });
    </script>

Why rgb and not cmy?

There's a difference between additive colors (http://en.wikipedia.org/wiki/Additive_color) and subtractive colors (http://en.wikipedia.org/wiki/Subtractive_color).

With additive colors, the more you add, the brighter the colors become. This is because they are emitting light. This is why the day light is (more or less) white, since the Sun is emitting in almost all the visible wavelength spectrum.

On the other hand, with subtractive colors the more colors you mix, the darker the resulting color. This is because they are reflecting light. This is also why the black colors get hotter quickly, because it absorbs (almost) all light energy and reflects (almost) none.

Specifically to your question, it depends what medium you are working on. Traditionally, additive colors (RGB) are used because the canon for computer graphics was the computer monitor, and since it's emitting light, it makes sense to use the same structure for the graphic card (the colors are shown without conversions). However, if you are used to graphic arts and press, subtractive color model is used (CMYK). In programs such as Photoshop, you can choose to work in CMYK space although it doesn't matter what color model you use: the primary colors of one group are the secondary colors of the second one and viceversa.

P.D.: my father worked at graphic arts, this is why i know this... :-P

How can I run a PHP script in the background after a form is submitted?

If you can access the server over ssh and can run your own scripts you can make a simple fifo server using php (although you will have to recompile php with posix support for fork).

The server can be written in anything really, you probably can easily do it in python.

Or the simplest solution would be sending an HttpRequest and not reading the return data but the server might destroy the script before it finish processing.

Example server :

<?php
define('FIFO_PATH', '/home/user/input.queue');
define('FORK_COUNT', 10);

if(file_exists(FIFO_PATH)) {
    die(FIFO_PATH . ' exists, please delete it and try again.' . "\n");
}

if(!file_exists(FIFO_PATH) && !posix_mkfifo(FIFO_PATH, 0666)){
    die('Couldn\'t create the listening fifo.' . "\n");
}

$pids = array();
$fp = fopen(FIFO_PATH, 'r+');
for($i = 0; $i < FORK_COUNT; ++$i) {
    $pids[$i] = pcntl_fork();
    if(!$pids[$i]) {
        echo "process(" . posix_getpid() . ", id=$i)\n";
        while(true) {
            $line = chop(fgets($fp));
            if($line == 'quit' || $line === false) break;
            echo "processing (" . posix_getpid() . ", id=$i) :: $line\n";
        //  $data = json_decode($line);
        //  processData($data);
        }
        exit();
    }
}
fclose($fp);
foreach($pids as $pid){
    pcntl_waitpid($pid, $status);
}
unlink(FIFO_PATH);
?>

Example client :

<?php
define('FIFO_PATH', '/home/user/input.queue');
if(!file_exists(FIFO_PATH)) {
    die(FIFO_PATH . ' doesn\'t exist, please make sure the fifo server is running.' . "\n");
}

function postToQueue($data) {
    $fp = fopen(FIFO_PATH, 'w+');
    stream_set_blocking($fp, false); //don't block
    $data = json_encode($data) . "\n";
    if(fwrite($fp, $data) != strlen($data)) {
        echo "Couldn't the server might be dead or there's a bug somewhere\n";
    }
    fclose($fp);
}
$i = 1000;
while(--$i) {
    postToQueue(array('xx'=>21, 'yy' => array(1,2,3)));
}
?>

How do you debug React Native?

Instead of Cmd+M, for Android Emulator Press F10 in Windows. The emulator starts to show all the react-native debug options.

image

How to press back button in android programmatically?

you can simply use onBackPressed();

or if you are using fragment you can use getActivity().onBackPressed()

SQL Server : Transpose rows to columns

SQL Server has a PIVOT command that might be what you are looking for.

select * from Tag
pivot (MAX(Value) for TagID in ([A1],[A2],[A3],[A4])) as TagTime;

If the columns are not constant, you'll have to combine this with some dynamic SQL.

DECLARE @columns AS VARCHAR(MAX);
DECLARE @sql AS VARCHAR(MAX);

select @columns = substring((Select DISTINCT ',' + QUOTENAME(TagID) FROM Tag FOR XML PATH ('')),2, 1000);

SELECT @sql =

'SELECT *
FROM TAG
PIVOT 
(
  MAX(Value) 
  FOR TagID IN( ' + @columns + ' )) as TagTime;';

 execute(@sql);

null check in jsf expression language

Use empty (it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"

If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"

Update: as per the comments, the Map turns out to actually be a List (please work on your naming conventions). To check if a List contains an item the "normal" EL way, use JSTL fn:contains (although not explicitly documented, it works for List as well).

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"

declaring a priority_queue in c++ with a custom comparator

prefer struct, and it's what std::greater do

struct Compare {
  bool operator()(Node const&, Node &) {}
}

Remove a modified file from pull request

Removing a file from pull request but not from your local repository.

  1. Go to your branch from where you created the request use the following commands

git checkout -- c:\temp..... next git checkout origin/master -- c:\temp... u replace origin/master with any other branch. Next git commit -m c:\temp..... Next git push origin

Note : no single quote or double quotes for the filepath

Setting up and using Meld as your git difftool and mergetool

I follow this simple setup with meld. Meld is free and opensource diff tool. You will see nice side by side comparison of files and directory for any code changes.

  1. Install meld in your Linux using yum/apt.
  2. Add following line in your ~/.gitconfig file
[diff]
    tool = meld
  1. Go to your code repo and type following command to see difference between last committed changes and current working directory (Unstaged uncommited changes)

git difftool --dir-diff ./

  1. To see difference between last committed code and staged code, use following command

git difftool --cached --dir-diff ./

Regular Expression to match string starting with a specific word

If you want to match anything that starts with "stop" including "stop going", "stop" and "stopping" use:

^stop

If you want to match the word stop followed by anything as in "stop going", "stop this", but not "stopped" and not "stopping" use:

^stop\W

How to send string from one activity to another?

You can send data from one actvity to another with an Intent

Intent sendStuff = new Intent(this, TargetActivity.class);
sendStuff.putExtra(key, stringvalue);
startActivity(sendStuff);

You then can retrieve this information in the second activity by getting the intent and extracting the string extra. Do this in your onCreate() method.

Intent startingIntent = getIntent();
String whatYouSent = startingIntent.getStringExtra(key, value);

Then all you have to do is call setText on your TextView and use that string.

@import vs #import - iOS 7

History:

#include => #import => .pch => @import

[#include vs #import]
[.pch - Precompiled header]

Module - @import

Product Name == Product Module Name 

@import module declaration says to compiler to load a precompiled binary of framework which decrease a building time. Modular Framework contains .modulemap[About]

If module feature is enabled in Xcode project #include and #import directives are automatically converted to @import that brings all advantages

enter image description here

Is it better to return null or empty collection?

I like to give explain here, with suitable example.

Consider a case here..

int totalValue = MySession.ListCustomerAccounts()
                          .FindAll(ac => ac.AccountHead.AccountHeadID 
                                         == accountHead.AccountHeadID)
                          .Sum(account => account.AccountValue);

Here Consider the functions I am using ..

1. ListCustomerAccounts() // User Defined
2. FindAll()              // Pre-defined Library Function

I can easily use ListCustomerAccount and FindAll instead of.,

int totalValue = 0; 
List<CustomerAccounts> custAccounts = ListCustomerAccounts();
if(custAccounts !=null ){
  List<CustomerAccounts> custAccountsFiltered = 
        custAccounts.FindAll(ac => ac.AccountHead.AccountHeadID 
                                   == accountHead.AccountHeadID );
   if(custAccountsFiltered != null)
      totalValue = custAccountsFiltered.Sum(account => 
                                            account.AccountValue).ToString();
}

NOTE : Since AccountValue is not null, the Sum() function will not return null., Hence I can use it directly.

Convert a list to a dictionary in Python

Simple answer

Another option (courtesy of Alex Martelli - source):

dict(x[i:i+2] for i in range(0, len(x), 2))

Related note

If you have this:

a = ['bi','double','duo','two']

and you want this (each element of the list keying a given value (2 in this case)):

{'bi':2,'double':2,'duo':2,'two':2}

you can use:

>>> dict((k,2) for k in a)
{'double': 2, 'bi': 2, 'two': 2, 'duo': 2}

Sorting a vector of custom objects

In C++20 one can default operator<=> without a user-defined comparator. The compiler will take care of that.

#include <iostream>
#include <compare>
#include <vector>
#include <algorithm>

struct MyInt
{
    int value;
    MyInt(int val) : value(val) {}
    auto operator<=>(const MyInt& other) const = default;
};


int main()
{
    MyInt Five(5);
    MyInt Two(2);
    MyInt Six(6);
    
    std::vector V{Five, Two, Six};
    std::sort(V.begin(), V.end());
    
    for (const auto& element : V)
        std::cout << element.value << std::endl;
}

Output:

2
5
6

How can I compare a date and a datetime in Python?

Create and similar object for comparison works too ex:

from datetime import datetime, date

now = datetime.now()
today = date.today()

# compare now with today
two_month_earlier = date(now.year, now.month - 2, now.day)
if two_month_earlier > today:
    print(True)

two_month_earlier = datetime(now.year, now.month - 2, now.day)
if two_month_earlier > now:
   print("this will work with datetime too")

HttpGet with HTTPS : SSLPeerUnverifiedException

Note: Do not do this in production code, use http instead, or the actual self signed public key as suggested above.

On HttpClient 4.xx:

import static org.junit.Assert.assertEquals;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.Test;

public class HttpClientTrustingAllCertsTest {

    @Test
    public void shouldAcceptUnsafeCerts() throws Exception {
        DefaultHttpClient httpclient = httpClientTrustingAllSSLCerts();
        HttpGet httpGet = new HttpGet("https://host_with_self_signed_cert");
        HttpResponse response = httpclient.execute( httpGet );
        assertEquals("HTTP/1.1 200 OK", response.getStatusLine().toString());
    }

    private DefaultHttpClient httpClientTrustingAllSSLCerts() throws NoSuchAlgorithmException, KeyManagementException {
        DefaultHttpClient httpclient = new DefaultHttpClient();

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, getTrustingManager(), new java.security.SecureRandom());

        SSLSocketFactory socketFactory = new SSLSocketFactory(sc);
        Scheme sch = new Scheme("https", 443, socketFactory);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);
        return httpclient;
    }

    private TrustManager[] getTrustingManager() {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                // Do nothing
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                // Do nothing
            }

        } };
        return trustAllCerts;
    }
}

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

The module was expected to contain an assembly manifest

In my case, I was using InstallUtil.exe which was causing an error. To install the .Net Core service in window best way to use sc command.

More information here Exe installation throwing error The module was expected to contain an assembly manifest .Net Core

Get most recent file in a directory on Linux

This is a recursive version (i.e. it finds the most recently updated file in a certain directory or any of its subdirectory)

find $DIR -type f -printf "%T@ %p\n" | sort -n | cut -d' ' -f 2- | tail -n 1

Edit: use -f 2- instead of -f 2 as suggested by Kevin

How can I use PHP to dynamically publish an ical file to be read by Google Calendar?

This should be very simple if Google Calendar does not require the *.ics-extension (which will require some URL rewriting in the server).

$ical = "BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
BEGIN:VEVENT
UID:" . md5(uniqid(mt_rand(), true)) . "@yourhost.test
DTSTAMP:" . gmdate('Ymd').'T'. gmdate('His') . "Z
DTSTART:19970714T170000Z
DTEND:19970715T035959Z
SUMMARY:Bastille Day Party
END:VEVENT
END:VCALENDAR";

//set correct content-type-header
header('Content-type: text/calendar; charset=utf-8');
header('Content-Disposition: inline; filename=calendar.ics');
echo $ical;
exit;

That's essentially all you need to make a client think that you're serving a iCalendar file, even though there might be some issues regarding caching, text encoding and so on. But you can start experimenting with this simple code.

Using an if statement to check if a div is empty

You can use .is().

if( $('#leftmenu').is(':empty') ) {
    // ...

Or you could just test the length property to see if one was found.

if( $('#leftmenu:empty').length ) {
    // ...

Keep in mind that empty means no white space either. If there's a chance that there will be white space, then you can use $.trim() and check for the length of the content.

if( !$.trim( $('#leftmenu').html() ).length ) {
    // ...

single line comment in HTML

from http://htmlhelp.com/reference/wilbur/misc/comment.html

Since HTML is officially an SGML application, the comment syntax used in HTML documents is actually the SGML comment syntax. Unfortunately this syntax is a bit unclear at first.

The definition of an SGML comment is basically as follows:

A comment declaration starts with <!, followed by zero or more comments, followed by >. A comment starts and ends with "--", and does not contain any occurrence of "--".
This means that the following are all legal SGML comments:
  1. <!-- Hello -->
  2. <!-- Hello -- -- Hello-->
  3. <!---->
  4. <!------ Hello -->
  5. <!>
Note that an "empty" comment tag, with just "--" characters, should always have a multiple of four "-" characters to be legal. (And yes, <!> is also a legal comment - it's the empty comment).

Not all HTML parsers get this right. For example, "<!------> hello-->" is a legal comment, as you can verify with the rule above. It is a comment tag with two comments; the first is empty and the second one contains "> hello". If you try it in a browser, you will find that the text is displayed on screen.

There are two possible reasons for this:

  1. The browser sees the ">" character and thinks the comment ends there.
  2. The browser sees the "-->" text and thinks the comment ends there.
There is also the problem with the "--" sequence. Some people have a habit of using things like "<!-------------->" as separators in their source. Unfortunately, in most cases, the number of "-" characters is not a multiple of four. This means that a browser who tries to get it right will actually get it wrong here and actually hide the rest of the document.

For this reason, use the following simple rule to compose valid and accepted comments:

An HTML comment begins with "<!--", ends with "-->" and does not contain "--" or ">" anywhere in the comment.

How to set Google Chrome in WebDriver

It was giving Illegal Exception.

My workaround with code:

public void dofirst(){
    System.setProperty("webdriver.chrome.driver","D:\\Softwares\\selenium\\chromedriver_win32\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("http://www.facebook.com");
}

Error loading the SDK when Eclipse starts

The issue is still coming for API 23. To get rid from this we have to uninstall android Wear packages for both API 22 and API 23 also (till current update).

enter image description here

Check if number is decimal

is_numeric returns true for decimals and integers. So if your user lazily enters 1 instead of 1.00 it will still return true:

echo is_numeric(1); // true
echo is_numeric(1.00); // true

You may wish to convert the integer to a decimal with PHP, or let your database do it for you.

Javascript - Regex to validate date format

Format, days, months and year:

var regex = /^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/;

Typedef function pointer?

typedef is a language construct that associates a name to a type.
You use it the same way you would use the original type, for instance

  typedef int myinteger;
  typedef char *mystring;
  typedef void (*myfunc)();

using them like

  myinteger i;   // is equivalent to    int i;
  mystring s;    // is the same as      char *s;
  myfunc f;      // compile equally as  void (*f)();

As you can see, you could just replace the typedefed name with its definition given above.

The difficulty lies in the pointer to functions syntax and readability in C and C++, and the typedef can improve the readability of such declarations. However, the syntax is appropriate, since functions - unlike other simpler types - may have a return value and parameters, thus the sometimes lengthy and complex declaration of a pointer to function.

The readability may start to be really tricky with pointers to functions arrays, and some other even more indirect flavors.

To answer your three questions

  • Why is typedef used? To ease the reading of the code - especially for pointers to functions, or structure names.

  • The syntax looks odd (in the pointer to function declaration) That syntax is not obvious to read, at least when beginning. Using a typedef declaration instead eases the reading

  • Is a function pointer created to store the memory address of a function? Yes, a function pointer stores the address of a function. This has nothing to do with the typedef construct which only ease the writing/reading of a program ; the compiler just expands the typedef definition before compiling the actual code.

Example:

typedef int (*t_somefunc)(int,int);

int product(int u, int v) {
  return u*v;
}

t_somefunc afunc = &product;
...
int x2 = (*afunc)(123, 456); // call product() to calculate 123*456

jQuery - If element has class do this

First, you're missing some parentheses in your conditional:

if ($("#about").hasClass("opened")) {
  $("#about").animate({right: "-700px"}, 2000);
}

But you can also simplify this to:

$('#about.opened').animate(...);

If #about doesn't have the opened class, it won't animate.

If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)

Postgres could not connect to server

If you shut down your system without quitting psql, postgres would not have removed some files.

I didn't find the file postmaster.pid in the location usr/local/var/postgres

So I did the below:

brew services start postgresql

The above command should let you start postgres

How to embed a PDF viewer in a page?

You could consider using PDFObject by Philip Hutchison.

Alternatively, if you're looking for a non-Javascript solution, you could use markup like this:

<object data="myfile.pdf" type="application/pdf" width="100%" height="100%">
  <p>Alternative text - include a link <a href="myfile.pdf">to the PDF!</a></p>
</object>

Java creating .jar file

Sine you've mentioned you're using Eclipse... Eclipse can create the JARs for you, so long as you've run each class that has a main once. Right-click the project and click Export, then select "Runnable JAR file" under the Java folder. Select the class name in the launch configuration, choose a place to save the jar, and make a decision how to handle libraries if necessary. Click finish, wipe hands on pants.

How to convert a byte array to a hex string in Java?

If you're using the Spring Security framework, you can use:

import org.springframework.security.crypto.codec.Hex

final String testString = "Test String";
final byte[] byteArray = testString.getBytes();
System.out.println(Hex.encode(byteArray));

Accessing localhost:port from Android emulator

I had the same issue when I was trying to connect to my IIS .NET Webservice from the Android emulator.

  1. install npm install -g iisexpress-proxy
  2. iisexpress-proxy 53990 to 9000 to proxy IIS express port to 9000 and access port 9000 from emulator like "http://10.0.2.2:9000"

the reason seems to be by default, IIS Express doesn't allow connections from network https://forums.asp.net/t/2125232.aspx?Bad+Request+Invalid+Hostname+when+accessing+localhost+Web+API+or+Web+App+from+across+LAN

Crop image in PHP

If you are trying to generate thumbnails, you must first resize the image using imagecopyresampled();. You must resize the image so that the size of the smaller side of the image is equal to the corresponding side of the thumb.

For example, if your source image is 1280x800px and your thumb is 200x150px, you must resize your image to 240x150px and then crop it to 200x150px. This is so that the aspect ratio of the image won't change.

Here's a general formula for creating thumbnails:

$image = imagecreatefromjpeg($_GET['src']);
$filename = 'images/cropped_whatever.jpg';

$thumb_width = 200;
$thumb_height = 150;

$width = imagesx($image);
$height = imagesy($image);

$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;

if ( $original_aspect >= $thumb_aspect )
{
   // If image is wider than thumbnail (in aspect ratio sense)
   $new_height = $thumb_height;
   $new_width = $width / ($height / $thumb_height);
}
else
{
   // If the thumbnail is wider than the image
   $new_width = $thumb_width;
   $new_height = $height / ($width / $thumb_width);
}

$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );

// Resize and crop
imagecopyresampled($thumb,
                   $image,
                   0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
                   0 - ($new_height - $thumb_height) / 2, // Center the image vertically
                   0, 0,
                   $new_width, $new_height,
                   $width, $height);
imagejpeg($thumb, $filename, 80);

Haven't tested this but it should work.

EDIT

Now tested and working.

How to use moment.js library in angular 2 typescript app?

For ANGULAR CLI users

Using external libraries is in the documentation here:

https://github.com/angular/angular-cli/wiki/stories-third-party-lib

Simply install your library via

npm install lib-name --save

and import it in your code. If the library does not include typings, you can install them using:

npm install lib-name --save

npm install @types/lib-name --save-dev

Then open src/tsconfig.app.json and add it to the types array:

"types":[ "lib-name" ]

If the library you added typings for is only to be used on your e2e tests, instead use e2e/tsconfig.e2e.json. The same goes for unit tests and src/tsconfig.spec.json.

If the library doesn't have typings available at @types/, you can still use it by manually adding typings for it:

First, create a typings.d.ts file in your src/ folder.

This file will be automatically included as global type definition. Then, in src/typings.d.ts, add the following code:

declare module 'typeless-package';

Finally, in the component or file that uses the library, add the following code:

import * as typelessPackage from 'typeless-package'; typelessPackage.method();

Done. Note: you might need or find useful to define more typings for the library that you're trying to use.

How to Position a table HTML?

As BalausC mentioned in a comment, you are probably looking for CSS (Cascading Style Sheets) not HTML attributes.

To position an element, a <table> in your case you want to use either padding or margins.

the difference between margins and paddings can be seen as the "box model":

box model image

Image from HTML Dog article on margins and padding http://www.htmldog.com/guides/cssbeginner/margins/.

I highly recommend the article above if you need to learn how to use CSS.

To move the table down and right I would use margins like so:

table{
    margin:25px 0 0 25px;
}

This is in shorthand so the margins are as follows:

margin: top right bottom left;

Remove a HTML tag but keep the innerHtml

// For MSIE:
el.removeNode(false);

// Old js, w/o loops, using DocumentFragment:
function replaceWithContents (el) {
  if (el.parentElement) {
    if (el.childNodes.length) {
      var range = document.createRange();
      range.selectNodeContents(el);
      el.parentNode.replaceChild(range.extractContents(), el);
    } else {
      el.parentNode.removeChild(el);
    }
  }
}

// Modern es:
const replaceWithContents = (el) => {
  el.replaceWith(...el.childNodes);
};

// or just:
el.replaceWith(...el.childNodes);

// Today (2018) destructuring assignment works a little slower
// Modern es, using DocumentFragment.
// It may be faster than using ...rest
const replaceWithContents = (el) => {
  if (el.parentElement) {
    if (el.childNodes.length) {
      const range = document.createRange();
      range.selectNodeContents(el);
      el.replaceWith(range.extractContents());
    } else {
      el.remove();
    }
  }
};

How can I fix WebStorm warning "Unresolved function or method" for "require" (Firefox Add-on SDK)

Working with Intellj 2016, Angular2, and Typescript... the only thing that worked for me was to get the Typescript Definitions for NodeJS

Get node.d.ts from DefinitelyTyped on GitHub

Or just run:

npm install @types/node --save-dev

Then in tsconfig.json, include

"types": [
     "node"
  ]

matplotlib get ylim values

Just use axes.get_ylim(), it is very similar to set_ylim. From the docs:

get_ylim()

Get the y-axis range [bottom, top]

How to use Collections.sort() in Java?

Sort the unsorted hashmap in ascending order.

// Sorting the list based on values
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) 
{
                return o2.getValue().compareTo(o1.getValue());
        }
    });

    // Maintaining insertion order with the help of LinkedList
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Entry<String, Integer> entry : list) {
        sortedMap.put(entry.getKey(), entry.getValue());
    }

Is it possible to insert multiple rows at a time in an SQLite database?

INSERT INTO TABLE_NAME 
            (DATA1, 
             DATA2) 
VALUES      (VAL1, 
             VAL2), 
            (VAL1, 
             VAL2), 
            (VAL1, 
             VAL2), 
            (VAL1, 
             VAL2), 
            (VAL1, 
             VAL2), 
            (VAL1, 
             VAL2), 
            (VAL1, 
             VAL2), 
            (VAL1, 
             VAL2); 

How to pip or easy_install tkinter on Windows

Well I can see two solutions here:

1) Follow the Docs-Tkinter install for Python (for Windows):

Tkinter (and, since Python 3.1, ttk) are included with all standard Python distributions. It is important that you use a version of Python supporting Tk 8.5 or greater, and ttk. We recommend installing the "ActivePython" distribution from ActiveState, which includes everything you'll need.

In your web browser, go to Activestate.com, and follow along the links to download the Community Edition of ActivePython for Windows. Make sure you're downloading a 3.1 or newer version, not a 2.x version.

Run the installer, and follow along. You'll end up with a fresh install of ActivePython, located in, e.g. C:\python32. From a Windows command prompt, or the Start Menu's "Run..." command, you should then be able to run a Python shell via:

% C:\python32\python

This should give you the Python command prompt. From the prompt, enter these two commands:

>>> import tkinter
>>> tkinter._test()

This should pop up a small window; the first line at the top of the window should say "This is Tcl/Tk version 8.5"; make sure it is not 8.4!

2) Uninstall 64-bit Python and install 32 bit Python.

Regex match digits, comma and semicolon?

You current regex will only match 1 character. you need either * (includes empty string) or + (at least one) to match multiple characters and numbers have a shortcut : \d (need \\ in a string).

word.matches("^[\\d,;]+$") 

The Pattern documentation is pretty good : http://download.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html

Also you can try your regexps online at: http://www.regexplanet.com/simple/index.html

OWIN Startup Class Missing

In my case, I had renamed the project and changed it's folder structure. I found that updating the RootNameSpace and AssemblyName in the .csproj file where the error was being thrown resolved the error. If you have modified paths of your project I'd recommend checking this as well.

<RootNamespace>Company.Product.WebAPI</RootNamespace>
<AssemblyName>Company.Product.WebAPI</AssemblyName>

Is there a numpy builtin to reject outliers from a list

Building on Benjamin's, using pandas.Series, and replacing MAD with IQR:

def reject_outliers(sr, iq_range=0.5):
    pcnt = (1 - iq_range) / 2
    qlow, median, qhigh = sr.dropna().quantile([pcnt, 0.50, 1-pcnt])
    iqr = qhigh - qlow
    return sr[ (sr - median).abs() <= iqr]

For instance, if you set iq_range=0.6, the percentiles of the interquartile-range would become: 0.20 <--> 0.80, so more outliers will be included.

How do I make an http request using cookies on Android?

I do not work with google android but I think you'll find it's not that hard to get this working. If you read the relevant bit of the java tutorial you'll see that a registered cookiehandler gets callbacks from the HTTP code.

So if there is no default (have you checked if CookieHandler.getDefault() really is null?) then you can simply extend CookieHandler, implement put/get and make it work pretty much automatically. Be sure to consider concurrent access and the like if you go that route.

edit: Obviously you'd have to set an instance of your custom implementation as the default handler through CookieHandler.setDefault() to receive the callbacks. Forgot to mention that.

get current date with 'yyyy-MM-dd' format in Angular 4

app.component.html

<div>
     <h5 style="color:#ffffff;">{{myDate | date:'fullDate'}}</h5>
</div>

app.component.ts

export class AppComponent implements OnInit {
myDate = Date.now();    //date 

What is the correct syntax of ng-include?

For those trouble shooting, it is important to know that ng-include requires the url path to be from the app root directory and not from the same directory where the partial.html lives. (whereas partial.html is the view file that the inline ng-include markup tag can be found).

For example:

Correct: div ng-include src=" '/views/partials/tabSlides/add-more.html' ">

Incorrect: div ng-include src=" 'add-more.html' ">

add new element in laravel collection object

I have solved this if you are using array called for 2 tables. Example you have, $tableA['yellow'] and $tableA['blue'] . You are getting these 2 values and you want to add another element inside them to separate them by their type.

foreach ($tableA['yellow'] as $value) {
    $value->type = 'YELLOW';  //you are adding new element named 'type'
}

foreach ($tableA['blue'] as $value) {
    $value->type = 'BLUE';  //you are adding new element named 'type'
}

So, both of the tables value will have new element called type.

How to get the selected value from drop down list in jsp?

use jquery

$("#item").change(function({
    var x=$(this).val();
});

Your value will be in x variable, use this variable value in your jsp, like this {x} this statement will give the value

Why an interface can not implement another interface?

Interface is the class that contains an abstract method that cannot create any object.Since Interface cannot create the object and its not a pure class, Its no worth implementing it.

Roblox Admin Command Script

for i=1,#target do
    game.Players.target[i].Character:BreakJoints()
end

Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:

game.Players.target.1.Character:BreakJoints()

Which is completely incorrect.


c = game.Players:GetChildren()

Never use "Players:GetChildren()", it is not guaranteed to return only players.

Instead use:

c = Game.Players:GetPlayers()

if msg:lower()=="me" then
    table.insert(people, source)
    return people

Here you add the player's name in the list "people", where you in the other places adds the player object.


Fixed code:

local Admins = {"FakeNameHereSoNoStalkers"}

function Kill(Players)
    for i,Player in ipairs(Players) do
        if Player.Character then
            Player.Character:BreakJoints()
        end
    end
end

function IsAdmin(Player)
    for i,AdminName in ipairs(Admins) do
        if Player.Name:lower() == AdminName:lower() then return true end
    end
    return false
end

function GetPlayers(Player,Msg)
    local Targets = {}
    local Players = Game.Players:GetPlayers()

    if Msg:lower() == "me" then
        Targets = { Player }
    elseif Msg:lower() == "all" then
        Targets = Players
    elseif Msg:lower() == "others" then
        for i,Plr in ipairs(Players) do
            if Plr ~= Player then
                table.insert(Targets,Plr)
            end
        end
    else
        for i,Plr in ipairs(Players) do
            if Plr.Name:lower():sub(1,Msg:len()) == Msg then
                table.insert(Targets,Plr)
            end
        end
    end
    return Targets
end

Game.Players.PlayerAdded:connect(function(Player)
    if IsAdmin(Player) then
        Player.Chatted:connect(function(Msg)
            if Msg:lower():sub(1,6) == ":kill " then
                Kill(GetPlayers(Player,Msg:sub(7)))
            end
        end)
    end
end)

Add/remove HTML inside div using JavaScript

You can do something like this.

function addRow() {
  const div = document.createElement('div');

  div.className = 'row';

  div.innerHTML = `
    <input type="text" name="name" value="" />
    <input type="text" name="value" value="" />
    <label> 
      <input type="checkbox" name="check" value="1" /> Checked? 
    </label>
    <input type="button" value="-" onclick="removeRow(this)" />
  `;

  document.getElementById('content').appendChild(div);
}

function removeRow(input) {
  document.getElementById('content').removeChild(input.parentNode);
}

How to check if a string "StartsWith" another string?

Without a helper function, just using regex's .test method:

/^He/.test('Hello world')

To do this with a dynamic string rather than a hardcoded one (assuming that the string will not contain any regexp control characters):

new RegExp('^' + needle).test(haystack)

You should check out Is there a RegExp.escape function in Javascript? if the possibility exists that regexp control characters appear in the string.

How to get the caller's method name in the called method?

Shorter version:

import inspect

def f1(): f2()

def f2():
    print 'caller name:', inspect.stack()[1][3]

f1()

(with thanks to @Alex, and Stefaan Lippen)

How to get current user, and how to use User class in MVC5?

I feel your pain, I'm trying to do the same thing. In my case I just want to clear the user.

I've created a base controller class that all my controllers inherit from. In it I override OnAuthentication and set the filterContext.HttpContext.User to null

That's the best I've managed to far...

public abstract class ApplicationController : Controller   
{
    ...
    protected override void OnAuthentication(AuthenticationContext filterContext)
    {
        base.OnAuthentication(filterContext); 

        if ( ... )
        {
            // You may find that modifying the 
            // filterContext.HttpContext.User 
            // here works as desired. 
            // In my case I just set it to null
            filterContext.HttpContext.User = null;
        }
    }
    ...
}

Creating a file name as a timestamp in a batch job

1) You can download GNU coreutils which comes with GNU date

2) you can use VBScript, which makes date manipulation easier in Windows:

Set objFS = CreateObject("Scripting.FileSystemObject")
strFolder = "c:\test"
Set objFolder = objFS.GetFolder(strFolder)
current = Now
mth = Month(current)
d = Day(current)
yr = Year(current)
If Len(mth) <2 Then
    mth="0"&mth
End If
If Len(d) < 2 Then
    d = "0"&d
End If
timestamp=yr & "-" & mth &"-"& d
For Each strFile In objFolder.Files
    strFileName = strFile.Name
    If InStr(strFileName,"file_name_here") > 0 Then
        BaseName = objFS.GetBaseName(strFileName)
        Extension = objFS.GetExtensionName(strFileName)
        NewName = BaseName & "-" & timestamp & "." & Extension
        strFile.Name = NewName
    End If
Next

Run the script as:

c:\test> cscript /nologo myscript.vbs

Encoding as Base64 in Java

You can also convert using Base64 encoding. To do this, you can use the javax.xml.bind.DatatypeConverter#printBase64Binary method.

For example:

byte[] salt = new byte[] { 50, 111, 8, 53, 86, 35, -19, -47 };
System.out.println(DatatypeConverter.printBase64Binary(salt));

Converting .NET DateTime to JSON

If you pass a DateTime from a .Net code to a javascript code, C#:

DateTime net_datetime = DateTime.Now;

javascript treats it as a string, like "/Date(1245398693390)/":

You can convert it as fllowing:

// convert the string to date correctly
var d = eval(net_datetime.slice(1, -1))

or:

// convert the string to date correctly
var d = eval("/Date(1245398693390)/".slice(1, -1))

AccessDenied for ListObjects for S3 bucket when permissions are s3:*

I got the same error when using policy as below, although i have "s3:ListBucket" for s3:ListObjects operation.

{
"Version": "2012-10-17",
"Statement": [
    {
        "Action": [
            "s3:ListBucket",
            "s3:GetObject",
            "s3:GetObjectAcl"
        ],
        "Resource": [
            "arn:aws:s3:::<bucketname>/*",
            "arn:aws:s3:::*-bucket/*"
        ],
        "Effect": "Allow"
    }
  ]
 }

Then i fixed it by adding one line "arn:aws:s3:::bucketname"

{
"Version": "2012-10-17",
"Statement": [
    {
        "Action": [
            "s3:ListBucket",
            "s3:GetObject",
            "s3:GetObjectAcl"
        ],
        "Resource": [
             "arn:aws:s3:::<bucketname>",
            "arn:aws:s3:::<bucketname>/*",
            "arn:aws:s3:::*-bucket/*"
        ],
        "Effect": "Allow"
    }
 ]
}

Set formula to a range of cells

Use this

            Sub calc()


            Range("C1:C10").FormulaR1C1 = "=(R10C1+R10C2)"


            End Sub

Multiple Java versions running concurrently under Windows

I was appalled at the clumsiness of the CLASSPATH, JAVA_HOME, and PATH ideas, in Windows, to keep track of Java files. I got here, because of multiple JREs, and how to content with it. Without regurgitating information, from a guy much more clever than me, I would rather point to to his article on this issue, which for me, resolves it perfectly.

Article by: Ted Neward: Multiple Java Homes: Giving Java Apps Their Own JRE

With the exponential growth of Java as a server-side development language has come an equivablent exponential growth in Java development tools, environments, frameworks, and extensions. Unfortunately, not all of these tools play nicely together under the same Java VM installation. Some require a Servlet 2.1-compliant environment, some require 2.2. Some only run under JDK 1.2 or above, some under JDK 1.1 (and no higher). Some require the "com.sun.swing" packages from pre-Swing 1.0 days, others require the "javax.swing" package names.

Worse yet, this problem can be found even within the corporate enterprise, as systems developed using Java from just six months ago may suddenly "not work" due to the installation of some Java Extension required by a new (seemingly unrelated) application release. This can complicate deployment of Java applications across the corporation, and lead customers to wonder precisely why, five years after the start of the infamous "Installing-this-app-breaks-my-system" woes began with Microsoft's DLL schemes, we still haven't progressed much beyond that. (In fact, the new .NET initiative actually seeks to solve the infamous "DLL-Hell" problem just described.)

This paper describes how to configure a Java installation such that a given application receives its own, private, JRE, allowing multiple Java environments to coexist without driving customers (or system administrators) insane...

nginx upload client_max_body_size issue

From the documentation:

It is necessary to keep in mind that the browsers do not know how to correctly show this error.

I suspect this is what's happening, if you inspect the HTTP to-and-fro using tools such as Firebug or Live HTTP Headers (both Firefox extensions) you'll be able to see what's really going on.

Cannot create PoolableConnectionFactory

The problem could be due to too many users accessing the db at the same time. Either increase number of users that can concurrently access the db or kick out existing users (or apps). Use "Show processlist;" in the host DB to check connected users;

I came across another reason, catalina.policy file, could prohibit accessing specific IP/PORT

Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

Change the position attribute to fixed instead of absolute.

.htaccess, order allow, deny, deny from all: confused?

This is a quite confusing way of using Apache configuration directives.

Technically, the first bit is equivalent to

Allow From All

This is because Order Deny,Allow makes the Deny directive evaluated before the Allow Directives. In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.

Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.

The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.

Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.

It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.

The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):

#
# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
#
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>

which forbids access to any file beginning by ".ht".

The equivalent Apache 2.4 configuration should look like:

<Files ~ "^\.ht">
    Require all denied
</Files>

How to call a method after a delay in Android

You can make it much cleaner by using the newly introduced lambda expressions:

new Handler().postDelayed(() -> {/*your code here*/}, time);

Android: How to change CheckBox size?

UPDATE: this only works from API 17 onwards...


To add to the other brilliant answers already given, you can only make the checkbox as small as the text size allows.

As per my answer on this question: - how can we reduce the size of checkbox please give me an idea


CheckBox derives its height from the TEXT as well as the image.

Set these properties in your XML:

android:text=""
android:textSize="0sp"

Of course this only works if you want no text (worked for me).

Without these changes, the CheckBox was giving me a big margin around my image, as mentioned by Joe

Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

There is a javascript library DNS-JS.com that does just this.

DNS.Query("dns-js.com",
    DNS.QueryType.A,
    function(data) {
        console.log(data);
});

How to enable C++17 compiling in Visual Studio?

Visual Studio 2020 version

In tasks.json file, (after you build and debug with the g++-9)

Add -std=c++2a for 2020 features (c++1z for 2017 features). Add -fconcepts to use concept keyword

"args": [
   "-std=c++2a",
   "-fconcepts",
   "-g",
   "${file}",
   "-o",
   "${fileDirname}/${fileBasenameNoExtension}"
],

now compile and you can use the 2020 features.

Which version of Python do I have installed?

For me, opening CMD and running

py

will show something like

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.

Creating dummy variables in pandas for python

I created a dummy variable for every state using this code.

def create_dummy_column(series, f):
    return series.apply(f)

for el in df.area_title.unique():
    col_name = el.split()[0] + "_dummy"
    f = lambda x: int(x==el)
    df[col_name] = create_dummy_column(df.area_title, f)
df.head()

More generally, I would just use .apply and pass it an anonymous function with the inequality that defines your category.

(Thank you to @prpl.mnky.dshwshr for the .unique() insight)

How to change line-ending settings

For me what did the trick was running the command

git config auto.crlf false

inside the folder of the project, I wanted it specifically for one project.

That command changed the file in path {project_name}/.git/config (fyi .git is a hidden folder) by adding the lines

[auto]
    crlf = false

at the end of the file. I suppose changing the file does the same trick as well.

Calculating Covariance with Python and Numpy

When a and b are 1-dimensional sequences, numpy.cov(a,b)[0][1] is equivalent to your cov(a,b).

The 2x2 array returned by np.cov(a,b) has elements equal to

cov(a,a)  cov(a,b)

cov(a,b)  cov(b,b)

(where, again, cov is the function you defined above.)

Why is &#65279; appearing in my HTML?

Before clear space (trim)

Then replace with RegEx .replace("/\xEF\xBB\xBF/", "")

I'm working on Javascript, I did with JavaScript.

How can I get the image url in a Wordpress theme?

I strongly recommend the following:

<img src="<?php echo get_stylesheet_directory_uri(); ?>/img-folder/your_image.jpg">

It works for almost any file you want to add to your wordpress project, be it image or CSS.

Sorting a list using Lambda/Linq to objects

You could use reflection to access the property.

public List<Employee> Sort(List<Employee> list, String sortBy, String sortDirection)
{
   PropertyInfo property = list.GetType().GetGenericArguments()[0].
                                GetType().GetProperty(sortBy);

   if (sortDirection == "ASC")
   {
      return list.OrderBy(e => property.GetValue(e, null));
   }
   if (sortDirection == "DESC")
   {
      return list.OrderByDescending(e => property.GetValue(e, null));
   }
   else
   {
      throw new ArgumentOutOfRangeException();
   }
}

Notes

  1. Why do you pass the list by reference?
  2. You should use a enum for the sort direction.
  3. You could get a much cleaner solution if you would pass a lambda expression specifying the property to sort by instead of the property name as a string.
  4. In my example list == null will cause a NullReferenceException, you should catch this case.

Java character array initializer

You initialized and declared your String to "Hi there", initialized your char[] array with the correct size, and you began a loop over the length of the array which prints an empty string combined with a given element being looked at in the array. At which point did you factor in the functionality to put in the characters from the String into the array?

When you attempt to print each element in the array, you print an empty String, since you're adding 'nothing' to an empty String, and since there was no functionality to add in the characters from the input String to the array. You have everything around it correctly implemented, though. This is the code that should go after you initialize the array, but before the for-loop that iterates over the array to print out the elements.

for (int count = 0; count < ini.length(); count++) {
  array[count] = ini.charAt(count);
}

It would be more efficient to just combine the for-loops to print each character out right after you put it into the array.

for (int count = 0; count < ini.length(); count++) {
  array[count] = ini.charAt(count);
  System.out.println(array[count]);
}

At this point, you're probably wondering why even put it in a char[] when I can just print them using the reference to the String object ini itself.

String ini = "Hi there";

for (int count = 0; count < ini.length(); count++) {
   System.out.println(ini.charAt(count));
}

Definitely read about Java Strings. They're fascinating and work pretty well, in my opinion. Here's a decent link: https://www.javatpoint.com/java-string

String ini = "Hi there"; // stored in String constant pool

is stored differently in memory than

String ini = new String("Hi there"); // stored in heap memory and String constant pool

, which is stored differently than

char[] inichar = new char[]{"H", "i", " ", "t", "h", "e", "r", "e"};
String ini = new String(inichar); // converts from char array to string

.

Scroll to a specific Element Using html

Yes, you may use an anchor by specifying the id attribute of an element and then linking to it with a hash.

For example (taken from the W3 specification):

You may read more about this in <A href="#section2">Section Two</A>.
...later in the document
<H2 id="section2">Section Two</H2>
...later in the document
<P>Please refer to <A href="#section2">Section Two</A> above
for more details.

CSS Selector "(A or B) and C"?

Not yet, but there is the experimental :matches() pseudo-class function that does just that:

:matches(.a .b) .c {
  /* stuff goes here */
}

You can find more info on it here and here. Currently, most browsers support its initial version :any(), which works the same way, but will be replaced by :matches(). We just have to wait a little more before using this everywhere (I surely will).

Android Starting Service at Boot Time , How to restart service class after device Reboot?

Pls check JobScheduler for apis above 26

WakeLock was the best option for this but it is deprecated in api level 26 Pls check this link if you consider api levels above 26
https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html#startWakefulService(android.content.Context,%20android.content.Intent)

It says

As of Android O, background check restrictions make this class no longer generally useful. (It is generally not safe to start a service from the receipt of a broadcast, because you don't have any guarantees that your app is in the foreground at this point and thus allowed to do so.) Instead, developers should use android.app.job.JobScheduler to schedule a job, and this does not require that the app hold a wake lock while doing so (the system will take care of holding a wake lock for the job).

so as it says cosider JobScheduler
https://developer.android.com/reference/android/app/job/JobScheduler

if it is to do something than to start and to keep it you can receive the broadcast ACTION_BOOT_COMPLETED

If it isn't about foreground pls check if an Accessibility service could do

another option is to start an activity from broadcast receiver and finish it after starting the service within onCreate() , since newer android versions doesnot allows starting services from receivers

android listview get selected item

final ListView lv = (ListView) findViewById(R.id.ListView01);

lv.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
        String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));

      }                 
});

I hope this fixes your problem.

Is it possible to have a HTML SELECT/OPTION value as NULL using PHP?

Yes, it is possible. You have to do something like this:

if(isset($_POST['submit']))
{
  $type_id = ($_POST['type_id'] == '' ? "null" : "'".$_POST['type_id']."'");
  $sql = "INSERT INTO `table` (`type_id`) VALUES (".$type_id.")";
}

It checks if the $_POST['type_id'] variable has an empty value. If yes, it assign NULL as a string to it. If not, it assign the value with ' to it for the SQL notation

How can I change an element's class with JavaScript?

You can use node.className like so:

document.getElementById('foo').className = 'bar';

This should work in IE5.5 and up according to PPK.

Is it possible to run one logrotate check manually?

You may want to run it in verbose + force mode.

logrotate -vf /etc/logrotate.conf

Angular.js How to change an elements css class on click and to remove all others

HTML

<span ng-class="{'item-text-wrap':viewMore}" ng-click="viewMore= !viewMore"></span>

How can I uninstall npm modules in Node.js?

To uninstall the Node.js module:

npm uninstall <module_name>

This will remove the module from folder node_modules, but not from file package.json. So when we do npm install again it will download the module.

So to remove the module from file package.json, use:

npm uninstall <module_name> --save

This also deletes the dependency from file package.json.

And if you want to uninstall any globally module you can use:

npm -g uninstall <module_name> --save

This will delete the dependency globally.

Cannot read property 'style' of undefined -- Uncaught Type Error

It's currently working, I've just changed the operator > in order to work in the snippet, take a look:

_x000D_
_x000D_
window.onload = function() {_x000D_
_x000D_
  if (window.location.href.indexOf("test") <= -1) {_x000D_
    var search_span = document.getElementsByClassName("securitySearchQuery");_x000D_
    search_span[0].style.color = "blue";_x000D_
    search_span[0].style.fontWeight = "bold";_x000D_
    search_span[0].style.fontSize = "40px";_x000D_
_x000D_
  }_x000D_
_x000D_
}
_x000D_
<h1 class="keyword-title">Search results for<span class="securitySearchQuery"> "hi".</span></h1>
_x000D_
_x000D_
_x000D_

What exactly is nullptr?

Well, other languages have reserved words that are instances of types. Python, for instance:

>>> None = 5
  File "<stdin>", line 1
SyntaxError: assignment to None
>>> type(None)
<type 'NoneType'>

This is actually a fairly close comparison because None is typically used for something that hasn't been intialized, but at the same time comparisons such as None == 0 are false.

On the other hand, in plain C, NULL == 0 would return true IIRC because NULL is just a macro returning 0, which is always an invalid address (AFAIK).

How do you specify a different port number in SQL Management Studio?

You'll need the SQL Server Configuration Manager. Go to Sql Native Client Configuration, Select Client Protocols, Right Click on TCP/IP and set your default port there.

C++ delete vector, objects, free memory

Move semantics allows for a straightforward way to release memory, by simply applying the assignment (=) operator from an empty rvalue:

std::vector<uint32_t> vec(100, 0);
std::cout << vec.capacity(); // 100

vec = vector<uint32_t>();    // Same as "vector<uint32_t>().swap(vec)";    
std::cout << vec.capacity(); // 0

It is as much efficient as the "swap()"-based method described in other answers (indeed, both are conceptually doing the same thing). When it comes to readability, however, the assignment version makes a better job at expressing the programmer's intention while being more concise.

How to trigger event in JavaScript?

function fireMouseEvent(obj, evtName) {
    if (obj.dispatchEvent) {
        //var event = new Event(evtName);
        var event = document.createEvent("MouseEvents");
        event.initMouseEvent(evtName, true, true, window,
                0, 0, 0, 0, 0, false, false, false, false, 0, null);
        obj.dispatchEvent(event);
    } else if (obj.fireEvent) {
        event = document.createEventObject();
        event.button = 1;
        obj.fireEvent("on" + evtName, event);
        obj.fireEvent(evtName);
    } else {
        obj[evtName]();
    }
}

var obj = document.getElementById("......");
fireMouseEvent(obj, "click");

Java - get the current class name?

Reflection APIs

There are several Reflection APIs which return classes but these may only be accessed if a Class has already been obtained either directly or indirectly.

Class.getSuperclass()
     Returns the super class for the given class.

        Class c = javax.swing.JButton.class.getSuperclass();
        The super class of javax.swing.JButton is javax.swing.AbstractButton.

        Class.getClasses()

Returns all the public classes, interfaces, and enums that are members of the class including inherited members.

        Class<?>[] c = Character.class.getClasses();

Character contains two member classes Character.Subset and
Character.UnicodeBlock.

        Class.getDeclaredClasses()
         Returns all of the classes interfaces, and enums that are explicitly declared in this class.

        Class<?>[] c = Character.class.getDeclaredClasses();
     Character contains two public member classes Character.Subset and Character.UnicodeBlock and one private class

Character.CharacterCache.

        Class.getDeclaringClass()
        java.lang.reflect.Field.getDeclaringClass()
        java.lang.reflect.Method.getDeclaringClass()
        java.lang.reflect.Constructor.getDeclaringClass()
     Returns the Class in which these members were declared. Anonymous Class Declarations will not have a declaring class but will

have an enclosing class.

        import java.lang.reflect.Field;

            Field f = System.class.getField("out");
            Class c = f.getDeclaringClass();
            The field out is declared in System.
            public class MyClass {
                static Object o = new Object() {
                    public void m() {} 
                };
                static Class<c> = o.getClass().getEnclosingClass();
            }

     The declaring class of the anonymous class defined by o is null.

    Class.getEnclosingClass()
     Returns the immediately enclosing class of the class.

    Class c = Thread.State.class().getEnclosingClass();
     The enclosing class of the enum Thread.State is Thread.

    public class MyClass {
        static Object o = new Object() { 
            public void m() {} 
        };
        static Class<c> = o.getClass().getEnclosingClass();
    }
     The anonymous class defined by o is enclosed by MyClass.

Check if a string is null or empty in XSLT

If a node has no value available in the input xml like below xpath,

<node>
    <ErrorCode/>
</node>

string() function converts into empty value. So this works fine:

string(/Node/ErrorCode) =''

Regex: Remove lines containing "help", etc

Another way to do this in Notepad++ is all in the Find/Replace dialog and with regex:

  • Ctrl + h to bring up the find replace dialog.

  • In the Find what: text box include your regex: .*help.*\r?\n (where the \r is optional in case the file doesn't have Windows line endings).

  • Leave the Replace with: text box empty.

  • Make sure the Regular expression radio button in the Search Mode area is selected. Then click Replace All and voila! All lines containing your search term help have been removed.

How-To Line Replace in N++

'workbooks.worksheets.activate' works, but '.select' does not

You can't select a sheet in a non-active workbook.

You must first activate the workbook, then you can select the sheet.

workbooks("A").activate
workbooks("A").worksheets("B").select 

When you use Activate it automatically activates the workbook.

Note you can select >1 sheet in a workbook:

activeworkbook.sheets(array("sheet1","sheet3")).select

but only one sheet can be Active, and if you activate a sheet which is not part of a multi-sheet selection then those other sheets will become un-selected.

Fill Combobox from database

To use the Combobox in the way you intend, you could pass in an object to the cmbTripName.Items.Add method.

That object should have FleetID and FleetName properties:

while (drd.Read())
{
    cmbTripName.Items.Add(new Fleet(drd["FleetID"].ToString(), drd["FleetName"].ToString()));
}
cmbTripName.ValueMember = "FleetId";
cmbTripName.DisplayMember = "FleetName";

The Fleet Class:

class Fleet
{
     public Fleet(string fleetId, string fleetName)
     {
           FleetId = fleetId;
           FleetName = fleetName
     }
     public string FleetId {get;set;}
     public string FleetName {get;set;}
}

Or, You could probably do away with the need for a Fleet class completely by using an anonymous type...

while (drd.Read())
{
    cmbTripName.Items.Add(new {FleetId = drd["FleetID"].ToString(), FleetName = drd["FleetName"].ToString()});
}
cmbTripName.ValueMember = "FleetId";
cmbTripName.DisplayMember = "FleetName";

Easiest way to split a string on newlines in .NET?

Silly answer: write to a temporary file so you can use the venerable File.ReadLines

var s = "Hello\r\nWorld";
var path = Path.GetTempFileName();
using (var writer = new StreamWriter(path))
{
    writer.Write(s);
}
var lines = File.ReadLines(path);

Laravel 4 with Sentry 2 add user to a group on Registration

Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.

Do you have this:

use Cartalyst\Sentry\Sentry; 

In your code?

Ok, but if this line is working for you:

$user = $this->sentry->register(array(     'username' => e($data['username']),     'email' => e($data['email']),      'password' => e($data['password'])     )); 

So you already have it instantiated and you can surely do:

$adminGroup = $this->sentry->findGroupById(5); 

How to get current url in view in asp.net core 1.0

This was apparently always possible in .net core 1.0 with Microsoft.AspNetCore.Http.Extensions, which adds extension to HttpRequest to get full URL; GetEncodedUrl.

e.g. from razor view:

@using Microsoft.AspNetCore.Http.Extensions
...
<a href="@Context.Request.GetEncodedUrl()">Link to myself</a>

Since 2.0, also have relative path and query GetEncodedPathAndQuery.

npm install error from the terminal

This is all because you are not in the desired directory. You need to first get into the desired directory. Mine was angular-phonecat directory. So I typed in cd angular-phonecat and then npm install.

How to wait for the 'end' of 'resize' event and only then perform an action?

There is a much simpler method to execute a function at the end of the resize than calculate the delta time between two calls, simply do it like this :

var resizeId;
$(window).resize(function() {
    clearTimeout(resizeId);
    resizeId = setTimeout(resizedEnded, 500);
});

function resizedEnded(){
    ...
}

And the equivalent for Angular2 :

private resizeId;
@HostListener('window:resize', ['$event'])
onResized(event: Event) {
  clearTimeout(this.resizeId);
  this.resizeId = setTimeout(() => {
    // Your callback method here.
  }, 500);
}

For the angular method, use the () => { } notation in the setTimeout to preserve the scope, otherwise you will not be able to make any function calls or use this.

phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)

When you install the WAMPP in your machine by default the password of PhpMyAdmin is blank. so put root in user Section and left blank of password field. hope it works.

Happy Coding!!

How to pick an image from gallery (SD Card) for my app?

For some reasons, all of the answers in this thread, in onActivityResult() try to post-process the received Uri, like getting the real path of the image and then use BitmapFactory.decodeFile(path) to get the Bitmap.

This step is unnecessary. The ImageView class has a method called setImageURI(uri). Pass your uri to it and you should be done.

Uri imageUri = data.getData();
imageView.setImageURI(imageUri);

For a complete working example you could take a look here: http://androidbitmaps.blogspot.com/2015/04/loading-images-in-android-part-iii-pick.html

PS:
Getting the Bitmap in a separate variable would make sense in cases where the image to be loaded is too large to fit in memory, and a scale down operation is necessary to prevent OurOfMemoryError, like shown in the @siamii answer.

jQuery duplicate DIV into another DIV

You'll want to use the clone() method in order to get a deep copy of the element:

$(function(){
  var $button = $('.button').clone();
  $('.package').html($button);
});

Full demo: http://jsfiddle.net/3rXjx/

From the jQuery docs:

The .clone() method performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes. When used in conjunction with one of the insertion methods, .clone() is a convenient way to duplicate elements on a page.

Capitalize the first letter of string in AngularJs

This is another way:

{{some_str | limitTo:1 | uppercase}}{{some_str.substr(1) | lowercase }}

How to check if a float value is a whole number

We can use the modulo (%) operator. This tells us how many remainders we have when we divide x by y - expresses as x % y. Every whole number must divide by 1, so if there is a remainder, it must not be a whole number.

This function will return a boolean, True or False, depending on whether n is a whole number.

def is_whole(n):
    return n % 1 == 0

Display a table/list data dynamically in MVC3/Razor from a JsonResult?

As Mystere Man suggested, getting just a view first and then again making an ajax call again to get the json result is unnecessary in this case. that is 2 calls to the server. I think you can directly return an HTML table of Users in the first call.

We will do this in this way. We will have a strongly typed view which will return the markup of list of users to the browser and this data is being supplied by an action method which we will invoke from our browser using an http request.

Have a ViewModel for the User

public class UserViewModel
{
  public int UserID { set;get;}
  public string FirstName { set;get;}
   //add remaining properties as per your requirement

}

and in your controller have a method to get a list of Users

public class UserController : Controller
{

   [HttpGet]
   public ActionResult List()
   {
     List<UserViewModel> objList=UserService.GetUsers();  // this method should returns list of  Users
     return View("users",objList)        
   }
}

Assuming that UserService.GetUsers() method will return a List of UserViewModel object which represents the list of usres in your datasource (Tables)

and in your users.cshtml ( which is under Views/User folder),

 @model List<UserViewModel>

 <table>

 @foreach(UserViewModel objUser in Model)
 {
   <tr>
      <td>@objUser.UserId.ToString()</td>
      <td>@objUser.FirstName</td>
   </tr>
 }
 </table>

All Set now you can access the url like yourdomain/User/List and it will give you a list of users in an HTML table.

How to programmatically set the Image source

Try to assign the image that way instead:

imgFavorito.Source = new BitmapImage(new Uri(base.BaseUri, @"/Assets/favorited.png"));

Specify the from user when sending email using the mail command

I faced the same issue. But i solved the problem just be setting geko field in /ect/passwd field. Postfix by default send the mail from user login. Lets suppose you want to change from field to Alert. You just need to edit /ect/passwd file in any editor you like.

  1. vim /ect/passwd

root:x:0:0:Alerts:/root:/bin/bash

  1. Restart postfix.

Now check the result.

  1. echo "This is the main body of the mail" | mail -s "Subject of the Email" [email protected]

Now in recipient. From will be shown as Alerts as you have specified in geko field. Hope this solution works for you.

Oracle Insert via Select from multiple tables where one table may not have a row

A slightly simplified version of Oglester's solution (the sequence doesn't require a select from DUAL:

INSERT INTO account_type_standard   
  (account_type_Standard_id, tax_status_id, recipient_id) 
VALUES(   
  account_type_standard_seq.nextval,
  (SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?),
  (SELECT recipient_id FROM recipient WHERE recipient_code = ?)
)

Running a shell script through Cygwin on Windows

If you don't mind always including .sh on the script file name, then you can keep the same script for Cygwin and Unix (Macbook).

To illustrate:
1. Always include .sh to your script file name, e.g., test1.sh
2. test1.sh looks like the following as an example:
#!/bin/bash echo '$0 = ' $0 echo '$1 = ' $1 filepath=$1 3. On Windows with Cygwin, you type "test1.sh" to run
4. On a Unix, you also type "test1.sh" to run


Note: On Windows, you need to use the file explorer to do following once:
1. Open the file explorer
2. Right-click on a file with .sh extension, like test1.sh
3. Open with... -> Select sh.exe
After this, your Windows 10 remembers to execute all .sh files with sh.exe.

Note: Using this method, you do not need to prepend your script file name with bash to run

Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;

If you use 'com.google.android.gms:play-services' You can add what you really need to look at the following list:

Google+ com.google.android.gms:play-services-plus:10.0.1

Google Account Login com.google.android.gms:play-services-auth:10.0.1

Google Actions, Base Client Library com.google.android.gms:play-services-base:10.0.1

Google Address API com.google.android.gms:play-services-identity:10.0.1

Firebase App Indexing com.google.firebase:firebase-appindexing:10.0.1 Google Analytics com.google.android.gms:play-services-analytics:10.0.1

Google Awareness com.google.android.gms:play-services-awareness:10.0.1

Google Cast com.google.android.gms:play-services-cast:10.0.1

Google Cloud Messaging com.google.android.gms:play-services-gcm:10.0.1

Google Drive com.google.android.gms:play-services-drive:10.0.1

Google Fit com.google.android.gms:play-services-fitness:10.0.1

Google Location and Activity Recognition com.google.android.gms:play-services-location:10.0.1

Google Maps com.google.android.gms:play-services-maps:10.0.1

Google Mobile Ads com.google.android.gms:play-services-ads:10.0.1

Google Places com.google.android.gms:play-services-places:10.0.1

Mobile Vision com.google.android.gms:play-services-vision:10.0.1

Google Nearby com.google.android.gms:play-services-nearby:10.0.1

Google Panorama Viewer com.google.android.gms:play-services-panorama:10.0.1

Google Play Game services com.google.android.gms:play-services-games:10.0.1

SafetyNet com.google.android.gms:play-services-safetynet:10.0.1

Android Pay com.google.android.gms:play-services-wallet:10.0.1

Android Wear com.google.android.gms:play-services-wearable:10.0.1

python pandas extract year from datetime: df['year'] = df['date'].year is not working

This works:

df['date'].dt.year

Now:

df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month

gives this data frame:

        date  Count  year  month
0 2010-06-30    525  2010      6
1 2010-07-30    136  2010      7
2 2010-08-31    125  2010      8
3 2010-09-30     84  2010      9
4 2010-10-29   4469  2010     10

Cannot execute script: Insufficient memory to continue the execution of the program

If you need to connect to LocalDB during development, you can use:

sqlcmd -S "(localdb)\MSSQLLocalDB" -d dbname -i file.sql

how to get current datetime in SQL?

Complete answer:

1. Is there a function available in SQL?
Yes, the SQL 92 spec, Oct 97, pg. 171, section 6.16 specifies this functions:

CURRENT_TIME       Time of day at moment of evaluation
CURRENT_DATE       Date at moment of evaluation
CURRENT_TIMESTAMP  Date & Time at moment of evaluation

2. It is implementation depended so each database has its own function for this?
Each database has its own implementations, but they have to implement the three function above if they comply with the SQL 92 specification (but depends on the version of the spec)

3. What is the function available in MySQL?

NOW() returns 2009-08-05 15:13:00  
CURDATE() returns 2009-08-05  
CURTIME() returns 15:13:00  

What is the difference between a URI, a URL and a URN?

I found:


A uniform resource identifier(URI) represents something of a big picture. You can split URIs/ URIs can be classified as locators (uniform resource locators- URL), or as names (uniform resource name-URN), or either both. So basically, a URN functions like a person's name and the URL depicts that person's address. So long story short, a URN defines an item's identity, while the URL provides defines the method for finding it, finally encapsulating these two concepts is the URI

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

I found it to be extremely easy to do this with the npm request package (https://www.npmjs.com/package/request)

Then I based my solution on this post http://blog.javascripting.com/2015/01/17/dont-hassle-with-cors/

'use strict'

const express = require('express');
const request = require('request');

let proxyConfig = {
    url : {
        base: 'http://servertoreach.com?id=',
    }
}

/* setting up and configuring node express server for the application */
let server = express();
server.set('port', 3000);


/* methods forwarded to the servertoreach proxy  */
server.use('/somethingElse', function(req, res)
{
    let url = proxyConfig.url.base + req.query.id;
    req.pipe(request(url)).pipe(res);
});


/* start the server */
server.listen(server.get('port'), function() {
    console.log('express server with a proxy listening on port ' + server.get('port'));
});

Generic Property in C#

public class MyProp<T>
{
...
}

public class ClassThatUsesMyProp
{
public MyProp<String> SomeProperty { get; set; }
}

How to reload a page after the OK click on the Alert Page

Interesting that Firefox will stop further processing of JavaScript after the relocate function. Chrome and IE will continue to display any other alerts and then reload the page. Try it:

<script type="text/javascript">
    alert('foo');
    window.location.reload(true);
    alert('bar');
    window.location.reload(true);
    alert('foobar');
    window.location.reload(true);
</script>