Programs & Examples On #Webserver

A software application that services requests from clients using the Hypertext Transfer Protocol.

Running Node.js in apache?

The common method for doing what you're looking to do is to run them side by side, and either proxy requests from apache to node.js based on domain / url, or simply have your node.js content be pulled from the node.js port. This later method works very well for having things like socket.io powered widgets on your site and such.


If you're going to be doing all of your dynamic content generation in node however, you might as well just use node.js as your primary webserver too, it does a very good job at serving both static and dynamic http requests.

See:

http://expressjs.com/

https://github.com/joyent/node/wiki/modules

Configure nginx with multiple locations with different root folders on subdomain

A little more elaborate example.

Setup: You have a website at example.com and you have a web app at example.com/webapp

...
server {
  listen 443 ssl;
  server_name example.com;

  root   /usr/share/nginx/html/website_dir;
  index  index.html index.htm;
  try_files $uri $uri/ /index.html;

  location /webapp/ {
    alias  /usr/share/nginx/html/webapp_dir/;
    index  index.html index.htm;
    try_files $uri $uri/ /webapp/index.html;
  }
}
...

I've named webapp_dir and website_dir on purpose. If you have matching names and folders you can use the root directive.

This setup works and is tested with Docker.

NB!!! Be careful with the slashes. Put them exactly as in the example.

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

I solved this by setting a higher timeout value for the proxy:

location / {
    proxy_read_timeout 300s;
    proxy_connect_timeout 75s;
    proxy_pass http://localhost:3000;
}

Documentation: https://nginx.org/en/docs/http/ngx_http_proxy_module.html

Apache Server (xampp) doesn't run on Windows 10 (Port 80)

In my case I need both XAMPP for Apache development & IIS Express for .Net 2013 development; so I do the following:

  1. In Command Prompt typed services.msc, this loads "Windows Services" where I located "World Wide Web Publishing Service" and stop it. World Wide Web Publishing Service STOP

  2. The I start XAMPP Control Panel click on "Config", then choose "Apache httpd.conf". Search for "80" then change that to "8080" in both "Listen 80" and "ServerName localhost:80". Save the file from "Save As" & choose "All files" to not save it as text from "Save As Type" & the "Encoding" should be "UTF-8". Apache httpd.conf

  3. Quit XAMPP Control Panel, then start it again and from "Action" start Apache & MySQL. Now you will see the port changed. As you know now you have to get to your Apache server by using "localhost:8080" instead of "localhost". Also you have both Apache & IIS Express running in the same Windows 10 PC.

I read a post some where were the writer suggested to use port "9080" but it did not work for me.

The program can't start because MSVCR110.dll is missing from your computer

Weird, just had simmilar issue, went here http://www.microsoft.com/en-us/download/confirmation.aspx?id=30679 downloaded and installed vcredist_x86 (i'm using 32bit apache) and it works like a charm.

Android - How to download a file from a webserver

Simple kotlin version

fun download(link: String, path: String) {
    URL(link).openStream().use { input ->
        FileOutputStream(File(path)).use { output ->
            input.copyTo(output)
        }
    }
}

EDIT

or as extension

fun String.saveTo(path: String) {
    URL(this).openStream().use { input ->
        FileOutputStream(File(path)).use { output ->
            input.copyTo(output)
        }
    }
}

// ...

"http://example.site/document".saveTo("some/path/file")

How to redirect user's browser URL to a different page in Nodejs?

For those who (unlike OP) are using the express lib:

http.get('*',function(req,res){  
    res.redirect('http://exmple.com'+req.url)
})

What is .htaccess file?

You are allow to use php_value to change php setting in .htaccess file. Same like how php.ini did.

Example:

php_value date.timezone Asia/Kuala_Lumpur

For other php setting, please read http://www.php.net/manual/en/ini.list.php

What is the difference between HTTP 1.1 and HTTP 2.0?

HTTP 2.0 is a binary protocol that multiplexes numerous streams going over a single (normally TLS-encrypted) TCP connection.

The contents of each stream are HTTP 1.1 requests and responses, just encoded and packed up differently. HTTP2 adds a number of features to manage the streams, but leaves old semantics untouched.

How to check if memcache or memcached is installed for PHP?

Note that all of the class_exists, extensions_loaded, and function_exists only check the link between PHP and the memcache package.

To actually check whether memcache is installed you must either:

  • know the OS platform and use shell commands to check whether memcache package is installed
  • or test whether memcache connection can be established on the expected port

EDIT 2: OK, actually here's an easier complete solution:

if (class_exists('Memcache')) {
    $memcache = new Memcache;
    $isMemcacheAvailable = @$memcache->connect('localhost');
}
if ($isMemcacheAvailable) {
    //...
}

Outdated code below


EDIT: Actually you must force PHP to throw error on warnings first. Have a look at this SO question answer.

You can then test the connection via:

try {
    $memcache->connect('localhost');
} catch (Exception $e) {
    // well it's not here
}

Using variables in Nginx location rules

You can't. Nginx doesn't really support variables in config files, and its developers mock everyone who ask for this feature to be added:

"[Variables] are rather costly compared to plain static configuration. [A] macro expansion and "include" directives should be used [with] e.g. sed + make or any other common template mechanism." http://nginx.org/en/docs/faq/variables_in_config.html

You should either write or download a little tool that will allow you to generate config files from placeholder config files.

Update The code below still works, but I've wrapped it all up into a small PHP program/library called Configurator also on Packagist, which allows easy generation of nginx/php-fpm etc config files, from templates and various forms of config data.

e.g. my nginx source config file looks like this:

location  / {
    try_files $uri /routing.php?$args;
    fastcgi_pass   unix:%phpfpm.socket%/php-fpm-www.sock;
    include       %mysite.root.directory%/conf/fastcgi.conf;
}

And then I have a config file with the variables defined:

phpfpm.socket=/var/run/php-fpm.socket
mysite.root.directory=/home/mysite

And then I generate the actual config file using that. It looks like you're a Python guy, so a PHP based example may not help you, but for anyone else who does use PHP:

<?php

require_once('path.php');

$filesToGenerate = array(
    'conf/nginx.conf' => 'autogen/nginx.conf',
    'conf/mysite.nginx.conf' => 'autogen/mysite.nginx.conf',
    'conf/mysite.php-fpm.conf' => 'autogen/mysite.php-fpm.conf',
    'conf/my.cnf' => 'autogen/my.cnf',
);

$environment = 'amazonec2';

if ($argc >= 2){
    $environmentRequired = $argv[1];

    $allowedVars = array(
        'amazonec2',
        'macports',
    );

    if (in_array($environmentRequired, $allowedVars) == true){
        $environment = $environmentRequired;
    }
}
else{
    echo "Defaulting to [".$environment."] environment";
}

$config = getConfigForEnvironment($environment);

foreach($filesToGenerate as $inputFilename => $outputFilename){
    generateConfigFile(PATH_TO_ROOT.$inputFilename, PATH_TO_ROOT.$outputFilename, $config);
}


function    getConfigForEnvironment($environment){
    $config = parse_ini_file(PATH_TO_ROOT."conf/deployConfig.ini", TRUE);
    $configWithMarkers = array();
    foreach($config[$environment] as $key => $value){
        $configWithMarkers['%'.$key.'%'] = $value;
    }

    return  $configWithMarkers;
}


function    generateConfigFile($inputFilename, $outputFilename, $config){

    $lines = file($inputFilename);

    if($lines === FALSE){
        echo "Failed to read [".$inputFilename."] for reading.";
        exit(-1);
    }

    $fileHandle = fopen($outputFilename, "w");

    if($fileHandle === FALSE){
        echo "Failed to read [".$outputFilename."] for writing.";
        exit(-1);
    }

    $search = array_keys($config);
    $replace = array_values($config);

    foreach($lines as $line){
        $line = str_replace($search, $replace, $line);
        fwrite($fileHandle, $line);
    }

    fclose($fileHandle);
}

?>

And then deployConfig.ini looks something like:

[global]

;global variables go here.

[amazonec2]
nginx.log.directory = /var/log/nginx
nginx.root.directory = /usr/share/nginx
nginx.conf.directory = /etc/nginx
nginx.run.directory  = /var/run
nginx.user           = nginx

[macports]
nginx.log.directory = /opt/local/var/log/nginx
nginx.root.directory = /opt/local/share/nginx
nginx.conf.directory = /opt/local/etc/nginx
nginx.run.directory  = /opt/local/var/run
nginx.user           = _www

Tomcat is web server or application server?

Tomcat is a web server (can handle HTTP requests/responses) and web container (implements Java Servlet API, also called servletcontainer) in one. Some may call it an application server, but it is definitely not an fullfledged Java EE application server (it does not implement the whole Java EE API).

See also:

Nginx location "not equal to" regex

According to nginx documentation

there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else

So you could define something like

location ~ (dir1|file2\.php) { 
    # empty
}

location / {
    rewrite ^/(.*) http://example.com/$1 permanent; 
}

How do I run a Python script on my web server?

Very simply, you can rename your Python script to "pythonscript.cgi". Post that in your cgi-bin directory, add the appropriate permissions and browse to it.

This is a great link you can start with.

Here's another good one.

Hope that helps.


EDIT (09/12/2015): The second link has long been removed. Replaced it with one that provides information referenced from the original.

How to open a web server port on EC2 instance

Follow the steps that are described on this answer just instead of using the drop down, type the port (8787) in "port range" an then "Add rule".

Go to the "Network & Security" -> Security Group settings in the left hand navigation

enter image description here Find the Security Group that your instance is apart of Click on Inbound Rules enter image description here Use the drop down and add HTTP (port 80) enter image description here Click Apply and enjoy

ssl_error_rx_record_too_long and Apache SSL

In my case I had to change the <VirtualHost *> back to <VirtualHost *:80> (which is the default on Ubuntu). Otherwise, the port 443 wasn't using SSL and was sending plain HTML back to the browser.

You can check whether this is your case quite easily: just connect to your server http://www.example.com:443. If you see plain HTML, your Apache is not using SSL on port 443 at all, most probably due to a VirtualHost misconfiguration.

Cheers!

apache not accepting incoming connections from outside of localhost

this would work: -- for REDHAT use : cat "/etc/sysconfig/iptables"

iptables -I  RH-Firewall-1-INPUT -s 192.168.1.3  -p tcp -m tcp --dport 80 -j ACCEPT

followed by

sudo /etc/init.d/iptables save

What is the difference between application server and web server?

Drawing my conclusion from posts of awesome SO evangelists above, I conclude that both are software that resides on actual metal servers(physical servers). Both work hand in hand to get service to the end-user. Then, depending on the setup, we can choose what to call it, which means how to describe it depends on the actual setup in use. If they both reside on the same bare metal(physical server), we call it web and application server...simple! If on separate machines, obviously, we have two distinct bare metals(physical servers) at our hands. Then we can label these servers according to their function: one web server and the other application server.

Web Server vs App Server

How to set the allowed url length for a nginx request (error code: 414, uri too large)

For anyone having issues with this on https://forge.laravel.com, I managed to get this to work using a compilation of SO answers;

You will need the sudo password.

sudo nano /etc/nginx/conf.d/uploads.conf

Replace contents with the following;

fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;

client_max_body_size 24M;
client_body_buffer_size 128k;

client_header_buffer_size 5120k;
large_client_header_buffers 16 5120k;

Using node.js as a simple web server

I think the part you're missing right now is that you're sending:

Content-Type: text/plain

If you want a web browser to render the HTML, you should change this to:

Content-Type: text/html

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

Following @Michelle Tilley solution, apparently it didn't work for me at first. Not sure why, maybe I am using chrome and different version of node. After did some minor tweaks, it is working for me now.

app.all('*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

In case someone facing similar issue as mine, this might be helpful.

XAMPP Object not found error

well, i had a similar problem, so when i entered, lets say: localhost/test.php I would got Object not found warning! I solved my problem when i realized that windows changed my test.php into this test.php.txt. I changed my extension and voila! problem solved I could finaly acceses localhost/test.php.

how to configuring a xampp web server for different root directory

  • Go to C:\xampp\apache\conf\httpd.conf
  • Open httpd.conf
  • Find tag : DocumentRoot "C:/xampp/htdocs"
  • Edit tag to : DocumentRoot "C:/xampp/htdocs/myproject/web"
  • Now find tag and change it to < Directory "C:/xampp/htdocs/myproject/web" >

  • Restart Your Apache

Amazon AWS Filezilla transfer permission denied

In my case the /var/www/html in not a directory but a symbolic link to the /var/app/current, so you should change the real directoy ie /var/app/current:

sudo chown -R ec2-user /var/app/current
sudo chmod -R 755 /var/app/current

I hope this save some of your times :)

How do I POST form data with UTF-8 encoding by using curl?

You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.

You should use this request:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod

How to create an HTTPS server in Node.js?

I found following example.

https://web.archive.org/web/20120203022122/http://www.silassewell.com/blog/2010/06/03/node-js-https-ssl-server-example/

This works for node v0.1.94 - v0.3.1. server.setSecure() is removed in newer versions of node.

Directly from that source:

const crypto = require('crypto'),
  fs = require("fs"),
  http = require("http");

var privateKey = fs.readFileSync('privatekey.pem').toString();
var certificate = fs.readFileSync('certificate.pem').toString();

var credentials = crypto.createCredentials({key: privateKey, cert: certificate});

var handler = function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
};

var server = http.createServer();
server.setSecure(credentials);
server.addListener("request", handler);
server.listen(8000);

How can I create a simple index.html file which lists all files/directories?

If you have a staging server that has directory listing enabled, then you can copy the index.html to the production server.

For example:

wget https://staging/dir/index.html

# do any additional processing on index.html

scp index.html prod/dir

Asp.net - <customErrors mode="Off"/> error when trying to access working webpage

Sometime in the future Comment out the following code in web.config

 <!--<system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>-->

update the to the following code.

<system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
    <customErrors mode="Off"/>
    <trust level="Full"/>
  </system.web>

Difference between the Apache HTTP Server and Apache Tomcat?

Well, Apache is HTTP webserver, where as Tomcat is also webserver for Servlets and JSP. Moreover Apache is preferred over Apache Tomcat in real time

What's the difference between a proxy server and a reverse proxy server?

My understanding from an Apache perspective is that proxy means that if site x proxies for site y, then requests for x return y.

The reverse proxy means that the response from y is adjusted so that all references to y become x.

So that the user cannot tell that a proxy is involved...

Is it possible to get a list of files under a directory of a website? How?

Any crawler or spider will read your index.htm or equivalent, that is exposed to the web, they will read the source code for that page, and find everything that is associated to that webpage and contains subdirectories. If they find a "contact us" button, there may be is included the path to the webpage or php that deal with the contact-us action, so they now have one more subdirectory/folder name to crawl and dig more. But even so, if that folder has a index.htm or equivalent file, it will not list all the files in such folder.

If by mistake, the programmer never included an index.htm file in such folder, then all the files will be listed on your computer screen, and also for the crawler/spider to keep digging. But, if you created a folder www.yoursite.com/nombresinistro75crazyragazzo19/ and put several files in there, and never published any button or never exposed that folder address anywhere in the net, keeping only in your head, chances are that nobody ever will find that path, with crawler or spider, for more sophisticated it can be.

Except, of course, if they can enter your FTP or access your site control panel.

How to automatically redirect HTTP to HTTPS on Apache servers?

Server version: Apache/2.4.29 (Ubuntu)

After long search on the web and in the official documentation of apache, the only solution that worked for me came from /usr/share/doc/apache2/README.Debian.gz

To enable SSL, type (as user root):

    a2ensite default-ssl
    a2enmod ssl

In the file /etc/apache2/sites-available/000-default.conf add the

Redirect "/" "https://sub.domain.com/"

<VirtualHost *:80>

    #ServerName www.example.com
    DocumentRoot /var/www/owncloud
    Redirect "/" "https://sub.domain.com/"

That's it.


P.S: If you want to read the manual without extracting:

gunzip -cd /usr/share/doc/apache2/README.Debian.gz

Deploy a project using Git push

The way I do it is I have a bare Git repository on my deployment server where I push changes. Then I log in to the deployment server, change to the actual web server docs directory, and do a git pull. I don't use any hooks to try to do this automatically, that seems like more trouble than it's worth.

Difference between web server, web container and application server

Web container also known as a Servlet container is the component of a web server that interacts with Java servlets. A web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights.

Minimal web server using netcat

while true; do (echo -e 'HTTP/1.1 200 OK\r\nConnection: close\r\n';) | timeout 1  nc -lp 8080 ; done

Closes connection after 1 sec, so curl doesn't hang on it.

Reload nginx configuration

If your system has systemctl

sudo systemctl reload nginx

If your system supports service (using debian/ubuntu) try this

sudo service nginx reload

If not (using centos/fedora/etc) you can try the init script

sudo /etc/init.d/nginx reload

Best lightweight web server (only static content) for Windows

Have a look at Cassini. This is basically what Visual Studio uses for its built-in debug web server. I've used it with Umbraco and it seems quite good.

How to return only the Date from a SQL Server DateTime datatype

DATEADD and DATEDIFF are better than CONVERTing to varchar. Both queries have the same execution plan, but execution plans are primarly about data access strategies and do not always reveal implicit costs involved in the CPU time taken to perform all the pieces. If both queries are run against a table with millions of rows, the CPU time using DateDiff can be close to 1/3rd of the Convert CPU time!

To see execution plans for queries:

set showplan_text on
GO 

Both DATEADD and DATEDIFF will execute a CONVERT_IMPLICIT.

Although the CONVERT solution is simpler and easier to read for some, it is slower. There is no need to cast back to datetime (this is implicitly done by the server). There is also no real need in the DateDiff method for DateAdd afterward as the integer result will also be implicitly converted back to datetime.


SELECT CONVERT(varchar, MyDate, 101) FROM DatesTable

  |--Compute Scalar(DEFINE:([Expr1004]=CONVERT(varchar(30),[TEST].[dbo].[DatesTable].[MyDate],101)))
       |--Table Scan(OBJECT:([TEST].[dbo].[DatesTable]))

SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, MyDate)) FROM DatesTable

  |--Compute Scalar(DEFINE:([Expr1004]=dateadd(day,(0),CONVERT_IMPLICIT(datetime,datediff(day,'1900-01-01 00:00:00.000',CONVERT_IMPLICIT(datetime,[TEST].[dbo].[DatesTable].[MyDate],0)),0))))
       |--Table Scan(OBJECT:([TEST].[dbo].[DatesTable]))

Using FLOOR() as @digi suggested has performance closer to DateDiff, but is not recommended as casting the datetime data type to float and back does not always yield the original value.

Remember guys: Don't believe anyone. Look at the performance statistics, and test it yourself!

Be careful when you're testing your results. Selecting many rows to the client will hide the performance difference becauses it takes longer to send the rows over the network than it does to perform the calculations. So make sure that the work for all the rows is done by the server but there is no rowset sent to the client.

There seems to be confusion for some people about when cache optimization affects queries. Running two queries in the same batch or in separate batches has no effect on caching. So you can either expire the cache manually or simply run the queries back and forth multiple times. Any optimization for query #2 would also affect any subsequent queries, so throw out execution #1 if you like.

Here is full test script and performance results that prove DateDiff is substantially faster than converting to varchar.

how to modify an existing check constraint?

You have to drop it and recreate it, but you don't have to incur the cost of revalidating the data if you don't want to.

alter table t drop constraint ck ;
alter table t add constraint ck check (n < 0) enable novalidate;

The enable novalidate clause will force inserts or updates to have the constraint enforced, but won't force a full table scan against the table to verify all rows comply.

How can I pass a member function where a free function is expected?

I asked a similar question (C++ openframeworks passing void from other classes) but the answer I found was clearer so here the explanation for future records:

it’s easier to use std::function as in:

 void draw(int grid, std::function<void()> element)

and then call as:

 grid.draw(12, std::bind(&BarrettaClass::draw, a, std::placeholders::_1));

or even easier:

  grid.draw(12, [&]{a.draw()});

where you create a lambda that calls the object capturing it by reference

Rethrowing exceptions in Java without losing the stack trace

something like this

try 
{
  ...
}
catch (FooException e) 
{
  throw e;
}
catch (Exception e)
{
  ...
}

Py_Initialize fails - unable to load the file system codec

The core reason is quite simple: Python does not find its modules directory, so it can of course not load encodings, too

Python doc on embedding says "Py_Initialize() calculates the module search path based upon its best guess" ... "In particular, it looks for a directory named lib/pythonX.Y"

Yet, if the modules are installed in (just) lib - relative to the python binary - above guess is wrong.

Although docs says that PYTHONHOME and PYTHONPATH are regarded, we observed that this was not the case; their actual presence or content was completely irrelevant.

The only thing that had an effect was a call to Py_SetPath() with e.g. [path-to]\lib as argument before Py_Initialize().

Sure this is only an option for an embedding scenario where one has direct access and control over the code; with a ready-made solution, special steps may be necessary to solve the issue.

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

There is now a headless version of opencv-python which removes the graphical dependencies (like libSM). You can see the normal / headless version on the releases page (and the GitHub issue leading to this); just add -headless when installing, e.g.,

pip install opencv-python-headless
# also contrib, if needed
pip install opencv-contrib-python-headless

Laravel 4: how to "order by" using Eloquent ORM

If you are using the Eloquent ORM you should consider using scopes. This would keep your logic in the model where it belongs.

So, in the model you would have:

public function scopeIdDescending($query)
{
        return $query->orderBy('id','DESC');
}   

And outside the model you would have:

$posts = Post::idDescending()->get();

More info: http://laravel.com/docs/eloquent#query-scopes

TSQL How do you output PRINT in a user defined function?

You can try returning the variable you wish to inspect. E.g. I have this function:

--Contencates seperate date and time strings and converts to a datetime. Date should be in format 25.03.2012. Time as 9:18:25.
ALTER FUNCTION [dbo].[ufn_GetDateTime] (@date nvarchar(11), @time nvarchar(11))
RETURNS datetime
AS
BEGIN

        --select dbo.ufn_GetDateTime('25.03.2012.', '9:18:25')

    declare @datetime datetime

    declare @day_part nvarchar(3)
    declare @month_part nvarchar(3)
    declare @year_part nvarchar(5)

    declare @point_ix int

    set @point_ix = charindex('.', @date)
    set @day_part = substring(@date, 0, @point_ix)

    set @date = substring(@date, @point_ix, len(@date) - @point_ix)
    set @point_ix = charindex('.', @date)

    set @month_part = substring(@date, 0, @point_ix)

    set @date = substring(@date, @point_ix, len(@date) - @point_ix)
    set @point_ix = charindex('.', @date)

    set @year_part = substring(@date, 0, @point_ix)

    set @datetime = @month_part + @day_part  + @year_part + ' ' + @time

    return @datetime
END

When I run it.. I get: Msg 241, Level 16, State 1, Line 1 Conversion failed when converting date and/or time from character string.

Arghh!!

So, what do I do?

ALTER FUNCTION [dbo].[ufn_GetDateTime] (@date nvarchar(11), @time nvarchar(11))
RETURNS nvarchar(22)
AS
BEGIN

        --select dbo.ufn_GetDateTime('25.03.2012.', '9:18:25')

    declare @day_part nvarchar(3)
    declare @point_ix int

    set @point_ix = charindex('.', @date)
    set @day_part = substring(@date, 0, @point_ix)

    return @day_part
END

And I get '25'. So, I am off by one and so I change to..

set @day_part = substring(@date, 0, @point_ix + 1)

Voila! Now it works :)

Why is the time complexity of both DFS and BFS O( V + E )

It's O(V+E) because each visit to v of V must visit each e of E where |e| <= V-1. Since there are V visits to v of V then that is O(V). Now you have to add V * |e| = E => O(E). So total time complexity is O(V + E).

Git - What is the difference between push.default "matching" and "simple"

Git v2.0 Release Notes

Backward compatibility notes

When git push [$there] does not say what to push, we have used the traditional "matching" semantics so far (all your branches were sent to the remote as long as there already are branches of the same name over there). In Git 2.0, the default is now the "simple" semantics, which pushes:

  • only the current branch to the branch with the same name, and only when the current branch is set to integrate with that remote branch, if you are pushing to the same remote as you fetch from; or

  • only the current branch to the branch with the same name, if you are pushing to a remote that is not where you usually fetch from.

You can use the configuration variable "push.default" to change this. If you are an old-timer who wants to keep using the "matching" semantics, you can set the variable to "matching", for example. Read the documentation for other possibilities.

When git add -u and git add -A are run inside a subdirectory without specifying which paths to add on the command line, they operate on the entire tree for consistency with git commit -a and other commands (these commands used to operate only on the current subdirectory). Say git add -u . or git add -A . if you want to limit the operation to the current directory.

git add <path> is the same as git add -A <path> now, so that git add dir/ will notice paths you removed from the directory and record the removal. In older versions of Git, git add <path> used to ignore removals. You can say git add --ignore-removal <path> to add only added or modified paths in <path>, if you really want to.

Plot Normal distribution with Matplotlib

Assuming you're getting norm from scipy.stats, you probably just need to sort your list:

import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt

h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]
h.sort()
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
plt.plot(h, pdf) # including h here is crucial

And so I get: enter image description here

MVC ajax json post to controller action method

Below is how I got this working.

The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.

[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]

[HttpPost]  
  public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)  
  {            
     var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
     return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
  }

The JQuery script used to call this action method:

var requestData = {
         InvoiceNumber: $.trim(this.value),
         SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
      };


      $.ajax({
         url: '/en/myController/GetDataForInvoiceNumber',
         type: 'POST',
         data: JSON.stringify(requestData),
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         error: function (xhr) {
            alert('Error: ' + xhr.statusText);
         },
         success: function (result) {
            CheckIfInvoiceFound(result);
         },
         async: true,
         processData: false
      });

How can I have linebreaks in my long LaTeX equations?

If it is inline equation, then use \allowbreak. Use it like:

$x_1,x_2,x_3,\allowbreak x_4,x_5$.

Latex will break equation in this place only if necessary.

how to get docker-compose to use the latest image from repository

If the docker compose configuration is in a file, simply run:

docker-compose -f appName.yml down && docker-compose -f appName.yml pull && docker-compose -f appName.yml up -d

Convert IQueryable<> type object to List<T> type?

The List class's constructor can convert an IQueryable for you:

public static List<TResult> ToList<TResult>(this IQueryable source)
{
    return new List<TResult>(source);
}

or you can just convert it without the extension method, of course:

var list = new List<T>(queryable);

How to enable scrolling of content inside a modal?

Actually for Bootstrap 3 you also need to override the .modal-open class on body.

    body.modal-open, 
    .modal-open 
    .navbar-fixed-top, 
    .modal-open 
    .navbar-fixed-bottom {
     margin-right: 15px; /*<-- to margin-right: 0px;*/
    }

Update div with jQuery ajax response html

You are setting the html of #showresults of whatever data is, and then replacing it with itself, which doesn't make much sense ?
I'm guessing you where really trying to find #showresults in the returned data, and then update the #showresults element in the DOM with the html from the one from the ajax call :

$('#submitform').click(function () {
    $.ajax({
        url: "getinfo.asp",
        data: {
            txtsearch: $('#appendedInputButton').val()
        },
        type: "GET",
        dataType: "html",
        success: function (data) {
            var result = $('<div />').append(data).find('#showresults').html();
            $('#showresults').html(result);
        },
        error: function (xhr, status) {
            alert("Sorry, there was a problem!");
        },
        complete: function (xhr, status) {
            //$('#showresults').slideDown('slow')
        }
    });
});

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

how to call a onclick function in <a> tag?

Fun! There are a few things to tease out here:

  • $leadID seems to be a php string. Make sure it gets printed in the right place. Also be aware of all the risks involved in passing your own strings around, like cross-site scripting and SQL injection vulnerabilities. There’s really no excuse for having Internet-facing production code not running on a solid framework.
  • Strings in Javascript (like in PHP and usually HTML) need to be enclosed in " or ' characters. Since you’re already inside both " and ', you’ll want to escape whichever you choose. \' to escape the PHP quotes, or &apos; to escape the HTML quotes.
  • <a /> elements are commonly used for “hyper”links, and almost always with a href attribute to indicate their destination, like this: <a href="http://www.google.com">Google homepage</a>.
  • You’re trying to double up on watching when the user clicks. Why? Because a standard click both activates the link (causing the browser to navigate to whatever URL, even that executes Javascript), and “triggers” the onclick event. Tip: Add a return false; to a Javascript event to suppress default behavior.
  • Within Javascript, onclick doesn’t mean anything on its own. That’s because onclick is a property, and not a variable. There has to be a reference to some object, so it knows whose onclick we’re talking about! One such object is window. You could write <a href="javascript:window.onclick = location.reload;">Activate me to reload when anything is clicked</a>.
  • Within HTML, onclick can mean something on its own, as long as its part of an HTML tag: <a href="#" onclick="location.reload(); return false;">. I bet you had this in mind.
  • Big difference between those two kinds of = assignments. The Javascript = expects something that hasn’t been run yet. You can wrap things in a function block to signal code that should be run later, if you want to specify some arguments now (like I didn’t above with reload): <a href="javascript:window.onclick = function () { window.open( ... ) };"> ....
  • Did you know you don’t even need to use Javascript to signal the browser to open a link in a new window? There’s a special target attribute for that: <a href="http://www.google.com" target="_blank">Google homepage</a>.

Hope those are useful.

Plot data in descending order as appears in data frame

You want reorder(). Here is an example with dummy data

set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))

require("ggplot2")

p1 <- ggplot(df, aes(x = Category, y = Count)) +
         geom_bar(stat = "identity")

p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
         geom_bar(stat = "identity")

require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))

Giving:

enter image description here

Use reorder(Category, Count) to have Category ordered from low-high.

Doing a cleanup action just before Node.js exits

The script below allows having a single handler for all exit conditions. It uses an app specific callback function to perform custom cleanup code.

cleanup.js

// Object to capture process exits and call app specific cleanup function

function noOp() {};

exports.Cleanup = function Cleanup(callback) {

  // attach user callback to the process event emitter
  // if no callback, it will still exit gracefully on Ctrl-C
  callback = callback || noOp;
  process.on('cleanup',callback);

  // do app specific cleaning before exiting
  process.on('exit', function () {
    process.emit('cleanup');
  });

  // catch ctrl+c event and exit normally
  process.on('SIGINT', function () {
    console.log('Ctrl-C...');
    process.exit(2);
  });

  //catch uncaught exceptions, trace, then exit normally
  process.on('uncaughtException', function(e) {
    console.log('Uncaught Exception...');
    console.log(e.stack);
    process.exit(99);
  });
};

This code intercepts uncaught exceptions, Ctrl+C and normal exit events. It then calls a single optional user cleanup callback function before exiting, handling all exit conditions with a single object.

The module simply extends the process object instead of defining another event emitter. Without an app specific callback the cleanup defaults to a no op function. This was sufficient for my use where child processes were left running when exiting by Ctrl+C.

You can easily add other exit events such as SIGHUP as desired. Note: per NodeJS manual, SIGKILL cannot have a listener. The test code below demonstrates various ways of using cleanup.js

// test cleanup.js on version 0.10.21

// loads module and registers app specific cleanup callback...
var cleanup = require('./cleanup').Cleanup(myCleanup);
//var cleanup = require('./cleanup').Cleanup(); // will call noOp

// defines app specific callback...
function myCleanup() {
  console.log('App specific cleanup code...');
};

// All of the following code is only needed for test demo

// Prevents the program from closing instantly
process.stdin.resume();

// Emits an uncaught exception when called because module does not exist
function error() {
  console.log('error');
  var x = require('');
};

// Try each of the following one at a time:

// Uncomment the next line to test exiting on an uncaught exception
//setTimeout(error,2000);

// Uncomment the next line to test exiting normally
//setTimeout(function(){process.exit(3)}, 2000);

// Type Ctrl-C to test forced exit 

Vagrant shared and synced folders

shared folders VS synced folders

Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf between host and guest (there is known performance issues if there are large numbers of files/directories).

Vagrantfile directory mounted as /vagrant in guest

Vagrant is mounting the current working directory (where Vagrantfile resides) as /vagrant in the guest, this is the default behaviour.

See docs

NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.

You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true in your Vagrantfile.

Why synced folder is not working

Based on the output /tmp on host was NOT mounted during up time.

Use VAGRANT_INFO=debug vagrant up or VAGRANT_INFO=debug vagrant reload to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp on host should be drwxrwxrwt).

I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)

config.vm.synced_folder "/tmp", "/tmp/src"

output

$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src

Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw).

Are there any log file about Windows Services Status?

Under Windows 7, open the Event Viewer. You can do this the way Gishu suggested for XP, typing eventvwr from the command line, or by opening the Control Panel, selecting System and Security, then Administrative Tools and finally Event Viewer. It may require UAC approval or an admin password.

In the left pane, expand Windows Logs and then System. You can filter the logs with Filter Current Log... from the Actions pane on the right and selecting "Service Control Manager." Or, depending on why you want this information, you might just need to look through the Error entries.

enter image description here

The actual log entry pane (not shown) is pretty user-friendly and self-explanatory. You'll be looking for messages like the following:

"The Praxco Assistant service entered the stopped state."
"The Windows Image Acquisition (WIA) service entered the running state."
"The MySQL service terminated unexpectedly. It has done this 3 time(s)."

How to open the terminal in Atom?

  1. Open your Atom IDE
  2. press ctrl+shift+P and search for "platformio-ide-terminal" package
  3. press install
  4. once installed press ctrl+~ (tilde above tab key in a standard keyboard)
  5. terminal opens enjoy!!!

How to use JUnit to test asynchronous processes

One method I've found pretty useful for testing asynchronous methods is injecting an Executor instance in the object-to-test's constructor. In production, the executor instance is configured to run asynchronously while in test it can be mocked to run synchronously.

So suppose I'm trying to test the asynchronous method Foo#doAsync(Callback c),

class Foo {
  private final Executor executor;
  public Foo(Executor executor) {
    this.executor = executor;
  }

  public void doAsync(Callback c) {
    executor.execute(new Runnable() {
      @Override public void run() {
        // Do stuff here
        c.onComplete(data);
      }
    });
  }
}

In production, I would construct Foo with an Executors.newSingleThreadExecutor() Executor instance while in test I would probably construct it with a synchronous executor that does the following --

class SynchronousExecutor implements Executor {
  @Override public void execute(Runnable r) {
    r.run();
  }
}

Now my JUnit test of the asynchronous method is pretty clean --

@Test public void testDoAsync() {
  Executor executor = new SynchronousExecutor();
  Foo objectToTest = new Foo(executor);

  Callback callback = mock(Callback.class);
  objectToTest.doAsync(callback);

  // Verify that Callback#onComplete was called using Mockito.
  verify(callback).onComplete(any(Data.class));

  // Assert that we got back the data that we expected.
  assertEquals(expectedData, callback.getData());
}

How do JavaScript closures work?

Every function in JavaScript maintains a link to its outer lexical environment. A lexical environment is a map of all the names (eg. variables, parameters) within a scope, with their values.

So, whenever you see the function keyword, code inside that function has access to variables declared outside the function.

_x000D_
_x000D_
function foo(x) {_x000D_
  var tmp = 3;_x000D_
_x000D_
  function bar(y) {_x000D_
    console.log(x + y + (++tmp)); // will log 16_x000D_
  }_x000D_
_x000D_
  bar(10);_x000D_
}_x000D_
_x000D_
foo(2);
_x000D_
_x000D_
_x000D_

This will log 16 because function bar closes over the parameter x and the variable tmp, both of which exist in the lexical environment of outer function foo.

Function bar, together with its link with the lexical environment of function foo is a closure.

A function doesn't have to return in order to create a closure. Simply by virtue of its declaration, every function closes over its enclosing lexical environment, forming a closure.

_x000D_
_x000D_
function foo(x) {_x000D_
  var tmp = 3;_x000D_
_x000D_
  return function (y) {_x000D_
    console.log(x + y + (++tmp)); // will also log 16_x000D_
  }_x000D_
}_x000D_
_x000D_
var bar = foo(2);_x000D_
bar(10); // 16_x000D_
bar(10); // 17
_x000D_
_x000D_
_x000D_

The above function will also log 16, because the code inside bar can still refer to argument x and variable tmp, even though they are no longer directly in scope.

However, since tmp is still hanging around inside bar's closure, it is available to be incremented. It will be incremented each time you call bar.

The simplest example of a closure is this:

_x000D_
_x000D_
var a = 10;_x000D_
_x000D_
function test() {_x000D_
  console.log(a); // will output 10_x000D_
  console.log(b); // will output 6_x000D_
}_x000D_
var b = 6;_x000D_
test();
_x000D_
_x000D_
_x000D_

When a JavaScript function is invoked, a new execution context ec is created. Together with the function arguments and the target object, this execution context also receives a link to the lexical environment of the calling execution context, meaning the variables declared in the outer lexical environment (in the above example, both a and b) are available from ec.

Every function creates a closure because every function has a link to its outer lexical environment.

Note that variables themselves are visible from within a closure, not copies.

Gradle sync failed: failed to find Build Tools revision 24.0.0 rc1

I ran into a same problem. I was running portable version of android studio so downloaded a package from https://developer.android.com/studio/#downloads and installed it, and like that, done!

Change the maximum upload file size

To locate the ini file, first run

php -i | grep -i "loaded configuration file"

Then open the file and change

upload_max_filesize = 2M
post_max_size = 2M

replacing the 2M with the size you want, for instance 100M.

I've got a blog post about with a little more info too http://www.seanbehan.com/how-to-increase-or-change-the-file-upload-size-in-the-php-ini-file-for-wordpress

How do I sum values in a column that match a given condition using pandas?

You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df. Then you can try :

df[df['a']==1]['b'].sum()

or you can also try :

sum(df[df['a']==1]['b'])

Another way could be to use the numpy library of python :

import numpy as np
print(np.where(df['a']==1, df['b'],0).sum())

numpy division with RuntimeWarning: invalid value encountered in double_scalars

You can't solve it. Simply answer1.sum()==0, and you can't perform a division by zero.

This happens because answer1 is the exponential of 2 very large, negative numbers, so that the result is rounded to zero.

nan is returned in this case because of the division by zero.

Now to solve your problem you could:

  • go for a library for high-precision mathematics, like mpmath. But that's less fun.
  • as an alternative to a bigger weapon, do some math manipulation, as detailed below.
  • go for a tailored scipy/numpy function that does exactly what you want! Check out @Warren Weckesser answer.

Here I explain how to do some math manipulation that helps on this problem. We have that for the numerator:

exp(-x)+exp(-y) = exp(log(exp(-x)+exp(-y)))
                = exp(log(exp(-x)*[1+exp(-y+x)]))
                = exp(log(exp(-x) + log(1+exp(-y+x)))
                = exp(-x + log(1+exp(-y+x)))

where above x=3* 1089 and y=3* 1093. Now, the argument of this exponential is

-x + log(1+exp(-y+x)) = -x + 6.1441934777474324e-06

For the denominator you could proceed similarly but obtain that log(1+exp(-z+k)) is already rounded to 0, so that the argument of the exponential function at the denominator is simply rounded to -z=-3000. You then have that your result is

exp(-x + log(1+exp(-y+x)))/exp(-z) = exp(-x+z+log(1+exp(-y+x)) 
                                   = exp(-266.99999385580668)

which is already extremely close to the result that you would get if you were to keep only the 2 leading terms (i.e. the first number 1089 in the numerator and the first number 1000 at the denominator):

exp(3*(1089-1000))=exp(-267)

For the sake of it, let's see how close we are from the solution of Wolfram alpha (link):

Log[(exp[-3*1089]+exp[-3*1093])/([exp[-3*1000]+exp[-3*4443])] -> -266.999993855806522267194565420933791813296828742310997510523

The difference between this number and the exponent above is +1.7053025658242404e-13, so the approximation we made at the denominator was fine.

The final result is

'exp(-266.99999385580668) = 1.1050349147204485e-116

From wolfram alpha is (link)

1.105034914720621496.. × 10^-116 # Wolfram alpha.

and again, it is safe to use numpy here too.

make a phone call click on a button

I've just solved the problem on an Android 4.0.2 device (GN) and the only version working for this device/version was similar to the first 5-starred with CALL_PHONE permission and the answer:

Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:123456789"));
startActivity(callIntent);

With any other solution i got the ActivityNotFoundException on this device/version. How about the older versions? Would someone give feedback?

What is the difference between SQL, PL-SQL and T-SQL?

  • SQL a language for talking to the database. It lets you select data, mutate and create database objects (like tables, views, etc.), change database settings.
  • PL-SQL a procedural programming language (with embedded SQL)
  • T-SQL (procedural) extensions for SQL used by SQL Server

How to convert an integer to a character array using C

The easy way is by using sprintf. I know others have suggested itoa, but a) it isn't part of the standard library, and b) sprintf gives you formatting options that itoa doesn't.

Spring Boot @autowired does not work, classes in different package

package com.test.springboot;
        @SpringBootApplication
    @ComponentScan(basePackages = "com.test.springboot")
    public class SpringBoot1Application {

        public static void main(String[] args) {
            ApplicationContext context=  SpringApplication.run(SpringBoot1Application.class, args);

=====================================================================

package com.test.springboot;
    @Controller
    public class StudentController {
        @Autowired
        private StudentDao studentDao;

        @RequestMapping("/")
        public String homePage() {
            return "home";
        }

Redeploy alternatives to JRebel

I have been working on an open source project that allows you to hot replace classes over and above what hot swap allows: https://github.com/fakereplace/fakereplace

It may or may not work for you, but any feedback is appreciated

how to add button click event in android studio

in Activity java class you would need a method first to find the view of the button as :

btnSum =(Button)findViewById(R.id.button);

after this set on click listener

btnSum.setOnClickListener(new View.OnClickListener() {

and override onClick method for your functionality .I have found a fully working example here : http://javainhouse.blogspot.in/2016/01/button-example-android-studio.html

Peak detection in a 2D array

I am not sure this answers the question, but it seems like you can just look for the n highest peaks that don't have neighbors.

Here is the gist. Note that it's in Ruby, but the idea should be clear.

require 'pp'

NUM_PEAKS = 5
NEIGHBOR_DISTANCE = 1

data = [[1,2,3,4,5],
        [2,6,4,4,6],
        [3,6,7,4,3],
       ]

def tuples(matrix)
  tuples = []
  matrix.each_with_index { |row, ri|
    row.each_with_index { |value, ci|
      tuples << [value, ri, ci]
    }
  }
  tuples
end

def neighbor?(t1, t2, distance = 1)
  [1,2].each { |axis|
    return false if (t1[axis] - t2[axis]).abs > distance
  }
  true
end

# convert the matrix into a sorted list of tuples (value, row, col), highest peaks first
sorted = tuples(data).sort_by { |tuple| tuple.first }.reverse

# the list of peaks that don't have neighbors
non_neighboring_peaks = []

sorted.each { |candidate|
  # always take the highest peak
  if non_neighboring_peaks.empty?
    non_neighboring_peaks << candidate
    puts "took the first peak: #{candidate}"
  else
    # check that this candidate doesn't have any accepted neighbors
    is_ok = true
    non_neighboring_peaks.each { |accepted|
      if neighbor?(candidate, accepted, NEIGHBOR_DISTANCE)
        is_ok = false
        break
      end
    }
    if is_ok
      non_neighboring_peaks << candidate
      puts "took #{candidate}"
    else
      puts "denied #{candidate}"
    end
  end
}

pp non_neighboring_peaks

Bootstrap: wider input field

I made a wider input field by using either span4 or span6 as class.

<input type="text" class="span6 input-large search-query">

This way you don't need the additional custom css, mentioned earlier.

How to sort an ArrayList?

The following line should do the thick

testList.sort(Collections.reverseOrder());

Python dictionary get multiple values

As I see no similar answer here - it is worth pointing out that with the usage of a (list / generator) comprehension, you can unpack those multiple values and assign them to multiple variables in a single line of code:

first_val, second_val = (myDict.get(key) for key in [first_key, second_key])

How to get HTTP Response Code using Selenium WebDriver

For those people using Python, you might consider Selenium Wire, a library for inspecting requests made by the browser during a test.

You get access to requests via the driver.requests attribute:

from seleniumwire import webdriver  # Import from seleniumwire

# Create a new instance of the Firefox driver
driver = webdriver.Firefox()

# Go to the Google home page
driver.get('https://www.google.com')

# Access requests via the `requests` attribute
for request in driver.requests:
    if request.response:
        print(
            request.url,
            request.response.status_code,
            request.response.headers['Content-Type']
        )

Prints:

https://www.google.com/ 200 text/html; charset=UTF-8
https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png 200 image/png
https://consent.google.com/status?continue=https://www.google.com&pc=s&timestamp=1531511954&gl=GB 204 text/html; charset=utf-8
https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png 200 image/png
https://ssl.gstatic.com/gb/images/i2_2ec824b0.png 200 image/png
https://www.google.com/gen_204?s=webaft&t=aft&atyp=csi&ei=kgRJW7DBONKTlwTK77wQ&rt=wsrt.366,aft.58,prt.58 204 text/html; charset=UTF-8
...

The library gives you the ability to access headers, status code, body content, as well as the ability to modify headers and rewrite URLs.

Rails ActiveRecord date between

You could use below gem to find the records between dates,

This gem quite easy to use and more clear By star am using this gem and the API more clear and documentation also well explained.

Post.between_times(Time.zone.now - 3.hours,  # all posts in last 3 hours
                  Time.zone.now)

Here you could pass our field also Post.by_month("January", field: :updated_at)

Please see the documentation and try it.

Cannot import scipy.misc.imread

If you have Pillow installed with scipy and it is still giving you error then check your scipy version because it has been removed from scipy since 1.3.0rc1.

rather install scipy 1.1.0 by :

pip install scipy==1.1.0

check https://github.com/scipy/scipy/issues/6212


The method imread in scipy.misc requires the forked package of PIL named Pillow. If you are having problem installing the right version of PIL try using imread in other packages:

from matplotlib.pyplot import imread
im = imread(image.png)

To read jpg images without PIL use:

import cv2 as cv
im = cv.imread(image.jpg)

You can try from scipy.misc.pilutil import imread instead of from scipy.misc import imread

Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.

Error java.lang.OutOfMemoryError: GC overhead limit exceeded

The following worked for me. Just add the following snippet:

android {
        compileSdkVersion 25
        buildToolsVersion '25.0.1'

defaultConfig {
        applicationId "yourpackage"
        minSdkVersion 10
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
dexOptions {
        javaMaxHeapSize "4g"
    }
}

Best way to parse command-line parameters?

I have never liked ruby like option parsers. Most developers that used them never write a proper man page for their scripts and end up with pages long options not organized in a proper way because of their parser.

I have always preferred Perl's way of doing things with Perl's Getopt::Long.

I am working on a scala implementation of it. The early API looks something like this:

def print_version() = () => println("version is 0.2")

def main(args: Array[String]) {
  val (options, remaining) = OptionParser.getOptions(args,
    Map(
      "-f|--flag"       -> 'flag,
      "-s|--string=s"   -> 'string,
      "-i|--int=i"      -> 'int,
      "-f|--float=f"    -> 'double,
      "-p|-procedure=p" -> { () => println("higher order function" }
      "-h=p"            -> { () => print_synopsis() }
      "--help|--man=p"  -> { () => launch_manpage() },
      "--version=p"     -> print_version,
    ))

So calling script like this:

$ script hello -f --string=mystring -i 7 --float 3.14 --p --version world -- --nothing

Would print:

higher order function
version is 0.2

And return:

remaining = Array("hello", "world", "--nothing")

options = Map('flag   -> true,
              'string -> "mystring",
              'int    -> 7,
              'double -> 3.14)

The project is hosted in github scala-getoptions.

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

The solution is to put the scripts in an outside js file (lets called 'yourDynamic.js') and re-register de file everytime you refresh the updatepanel.

I use this in the updatepanel_prerender event:

ScriptManager.RegisterClientScriptBlock(UpdatePanel1, UpdatePanel1.GetType(), "UpdatePanel1_PreRender", _
                   "<script type='text/javascript' id='UpdatePanel1_PreRender'>" & _
                   "include('yourDynamic.js');" & _
                   "removeDuplicatedScript('UpdatePanel1_PreRender');</script>" _
                   , False)

In the page or in some other include you will need this javascript:

// Include a javascript file inside another one.
function include(filename)
{
    var head = document.getElementsByTagName('head')[0];

    var scripts = document.getElementsByTagName('script');
    for(var x=0;x<scripts.length;>    {
        if (scripts[x].getAttribute('src'))
        {
            if(scripts[x].getAttribute('src').indexOf(filename) != -1)
            {
                head.removeChild(scripts[x]);
                break;
            }
        }
    }

    script = document.createElement('script');
    script.src = filename;
    script.type = 'text/javascript';
    head.appendChild(script)
}

// Removes duplicated scripts.
function removeDuplicatedScript(id)
{
    var count = 0;
    var head = document.getElementsByTagName('head')[0];

    var scripts = document.getElementsByTagName('script');
    var firstScript;
    for(var x=0;x<scripts.length;>    {
        if (scripts[x].getAttribute('id'))
        {
            if(scripts[x].getAttribute('id').indexOf(id) != -1)
            {
                if (count == 0)
                {
                    firstScript = scripts[x];
                    count++;
                }
                else
                {
                    head.removeChild(firstScript);
                    firstScript = scripts[x];
                    count = 1;
                }
            }
        }
    }
    clearAjaxNetJunk();
}
// Evoids the update panel auto generated scripts to grow to inifity. X-(
function clearAjaxNetJunk()
{
    var knowJunk = 'Sys.Application.add_init(function() {';
    var count = 0;
    var head = document.getElementsByTagName('head')[0];

    var scripts = document.getElementsByTagName('script');
    var firstScript;
    for(var x=0;x<scripts.length;>    {
        if (scripts[x].textContent)
        {
            if(scripts[x].textContent.indexOf(knowJunk) != -1)
            {
                if (count == 0)
                {
                    firstScript = scripts[x];
                    count++;
                }
                else
                {
                    head.removeChild(firstScript);
                    firstScript = scripts[x];
                    count = 1;
                }
            }
        }
    }
}

Pretty cool, ah...jejeje This part of what i posted some time ago here.

Hope this help... :)

How to properly override clone method?

Just because java's implementation of Cloneable is broken it doesn't mean you can't create one of your own.

If OP real purpose was to create a deep clone, i think that it is possible to create an interface like this:

public interface Cloneable<T> {
    public T getClone();
}

then use the prototype constructor mentioned before to implement it:

public class AClass implements Cloneable<AClass> {
    private int value;
    public AClass(int value) {
        this.vaue = value;
    }

    protected AClass(AClass p) {
        this(p.getValue());
    }

    public int getValue() {
        return value;
    }

    public AClass getClone() {
         return new AClass(this);
    }
}

and another class with an AClass object field:

public class BClass implements Cloneable<BClass> {
    private int value;
    private AClass a;

    public BClass(int value, AClass a) {
         this.value = value;
         this.a = a;
    }

    protected BClass(BClass p) {
        this(p.getValue(), p.getA().getClone());
    }

    public int getValue() {
        return value;
    }

    public AClass getA() {
        return a;
    }

    public BClass getClone() {
         return new BClass(this);
    }
}

In this way you can easely deep clone an object of class BClass without need for @SuppressWarnings or other gimmicky code.

How to check if a stored procedure exists before creating it

You can run procedural code anywhere you are able to run a query.

Just copy everything after AS:

BEGIN
    DECLARE @myvar INT
    SELECT  *
    FROM    mytable
    WHERE   @myvar ...
END

This code does exactly same things a stored proc would do, but is not stored on the database side.

That's much like what is called anonymous procedure in PL/SQL.

Update:

Your question title is a little bit confusing.

If you only need to create a procedure if it not exists, then your code is just fine.

Here's what SSMS outputs in the create script:

IF EXISTS ( SELECT  *
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'myproc')
                    AND type IN ( N'P', N'PC' ) ) 
DROP …
CREATE …

Update:

Example of how to do it when including the schema:

IF EXISTS ( SELECT * 
            FROM   sysobjects 
            WHERE  id = object_id(N'[dbo].[MyProc]') 
                   and OBJECTPROPERTY(id, N'IsProcedure') = 1 )
BEGIN
    DROP PROCEDURE [dbo].[MyProc]
END

In the example above, dbo is the schema.

Update:

In SQL Server 2016+, you can just do

CREATE OR ALTER PROCEDURE dbo.MyProc

Fatal error: [] operator not supported for strings

Such behavior is described in Migrating from PHP 7.0.x to PHP 7.1.x/

The empty index operator is not supported for strings anymore Applying the empty index operator to a string (e.g. $str[] = $x) throws a fatal error instead of converting silently to array.

In my case it was a mere initialization. I fixed it by replacing $foo='' with $foo=[].

$foo='';
$foo[]='test';
print_r($foo);

Initialize a long in Java

  1. You need to add the L character to the end of the number to make Java recognize it as a long.

    long i = 12345678910L;
    
  2. Yes.

See Primitive Data Types which says "An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int."

Pass Array Parameter in SqlCommand

If you are using MS SQL Server 2008 and above you can use table-valued parameters like described here http://www.sommarskog.se/arrays-in-sql-2008.html.

1. Create a table type for each parameter type you will be using

The following command creates a table type for integers:

create type int32_id_list as table (id int not null primary key)

2. Implement helper methods

public static SqlCommand AddParameter<T>(this SqlCommand command, string name, IEnumerable<T> ids)
{
  var parameter = command.CreateParameter();      

  parameter.ParameterName = name;
  parameter.TypeName = typeof(T).Name.ToLowerInvariant() + "_id_list";
  parameter.SqlDbType = SqlDbType.Structured;
  parameter.Direction = ParameterDirection.Input;

  parameter.Value = CreateIdList(ids);

  command.Parameters.Add(parameter);
  return command;
}

private static DataTable CreateIdList<T>(IEnumerable<T> ids)
{
  var table = new DataTable();
  table.Columns.Add("id", typeof (T));

  foreach (var id in ids)
  {
    table.Rows.Add(id);
  }

  return table;
}

3. Use it like this

cmd.CommandText = "select * from TableA where Age in (select id from @age)"; 
cmd.AddParameter("@age", new [] {1,2,3,4,5});

ASP.NET Web API application gives 404 when deployed at IIS 7

For me I received a 404 error on my websites NOT using IIS Express (using Local IIS) while running an application that WAS using IIS Express. If I would close the browser that was used to run IIS Express, then the 404 would go away. For me I had my IIS Express project calling into Local IIS services, so I converted the IIS Express project to use Local IIS and then everything worked. It seems that you can't run both a non-IIS Express and Local IIS website at the same time for some reason.

How to change a particular element of a C++ STL vector

Even though @JamesMcNellis answer is a valid one I would like to explain something about error handling and also the fact that there is another way of doing what you want.

You have four ways of accessing a specific item in a vector:

  • Using the [] operator
  • Using the member function at(...)
  • Using an iterator in combination with a given offset
  • Using std::for_each from the algorithm header of the standard C++ library. This is another way which I can recommend (it uses internally an iterator). You can read more about it for example here.

In the following examples I will be using the following vector as a lab rat and explaining the first three methods:

static const int arr[] = {1, 2, 3, 4};
std::vector<int> v(arr, arr+sizeof(arr)/sizeof(arr[0]));

This creates a vector as seen below:

1 2 3 4

First let's look at the [] way of doing things. It works in pretty much the same way as you expect when working with a normal array. You give an index and possibly you access the item you want. I say possibly because the [] operator doesn't check whether the vector actually has that many items. This leads to a silent invalid memory access. Example:

v[10] = 9;

This may or may not lead to an instant crash. Worst case is of course is if it doesn't and you actually get what seems to be a valid value. Similar to arrays this may lead to wasted time in trying to find the reason why for example 1000 lines of code later you get a value of 100 instead of 234, which is somewhat connected to that very location where you retrieve an item from you vector.

A much better way is to use at(...). This will automatically check for out of bounds behaviour and break throwing an std::out_of_range. So in the case when we have

v.at(10) = 9;

We will get:

terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 10) >= this->size() (which is 4)

The third way is similar to the [] operator in the sense you can screw things up. A vector just like an array is a sequence of continuous memory blocks containing data of the same type. This means that you can use your starting address by assigning it to an iterator and then just add an offset to this iterator. The offset simply stands for how many items after the first item you want to traverse:

std::vector<int>::iterator it = v.begin(); // First element of your vector
*(it+0) = 9;  // offest = 0 basically means accessing v.begin()
// Now we have 9 2 3 4 instead of 1 2 3 4
*(it+1) = -1; // offset = 1 means first item of v plus an additional one
// Now we have 9 -1 3 4 instead of 9 2 3 4
// ...

As you can see we can also do

*(it+10) = 9;

which is again an invalid memory access. This is basically the same as using at(0 + offset) but without the out of bounds error checking.

I would advice using at(...) whenever possible not only because it's more readable compared to the iterator access but because of the error checking for invalid index that I have mentioned above for both the iterator with offset combination and the [] operator.

How do I `jsonify` a list in Flask?

josonify works..but if you intend to just pass an array without the 'results' key, you can use json library from python. The following conversion works for me..

 import json

 @app.route('/test/json')
 def test_json():
 list = [
        {'a': 1, 'b': 2},
        {'a': 5, 'b': 10}
       ]
 return json.dumps(list))

Java program to find the largest & smallest number in n numbers without using arrays

Try this :

int smallest = Integer.MAX_VALUE;
for(int i=0;i<n;i++)
{
   num=input.nextInt();
   if(num>large)
   {
       large=num;
   }
   if(num<smallest){
       smallest=num;
   }

How do I use InputFilter to limit characters in an EditText in Android?

It's Right, the best way to go about it to fix it in the XML Layout itself using:

<EditText
android:inputType="text"
android:digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" />

as rightly pointed by Florian Fröhlich, it works well for text views even.

<TextView
android:inputType="text"
android:digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" />

Just a word of caution, the characters mentioned in the android:digits will only be displayed, so just be careful not to miss any set of characters out :)

Convert time.Time to string

package main                                                                                                                                                           

import (
    "fmt"
    "time"
)

// @link https://golang.org/pkg/time/

func main() {

    //caution : format string is `2006-01-02 15:04:05.000000000`
    current := time.Now()

    fmt.Println("origin : ", current.String())
    // origin :  2016-09-02 15:53:07.159994437 +0800 CST

    fmt.Println("mm-dd-yyyy : ", current.Format("01-02-2006"))
    // mm-dd-yyyy :  09-02-2016

    fmt.Println("yyyy-mm-dd : ", current.Format("2006-01-02"))
    // yyyy-mm-dd :  2016-09-02

    // separated by .
    fmt.Println("yyyy.mm.dd : ", current.Format("2006.01.02"))
    // yyyy.mm.dd :  2016.09.02

    fmt.Println("yyyy-mm-dd HH:mm:ss : ", current.Format("2006-01-02 15:04:05"))
    // yyyy-mm-dd HH:mm:ss :  2016-09-02 15:53:07

    // StampMicro
    fmt.Println("yyyy-mm-dd HH:mm:ss: ", current.Format("2006-01-02 15:04:05.000000"))
    // yyyy-mm-dd HH:mm:ss:  2016-09-02 15:53:07.159994

    //StampNano
    fmt.Println("yyyy-mm-dd HH:mm:ss: ", current.Format("2006-01-02 15:04:05.000000000"))
    // yyyy-mm-dd HH:mm:ss:  2016-09-02 15:53:07.159994437
}    

Python Pandas Counting the Occurrences of a Specific value

for finding a specific value of a column you can use the code below

irrespective of the preference you can use the any of the method you like

df.col_name.value_counts().Value_you_are_looking_for

take example of the titanic dataset

df.Sex.value_counts().male

this gives a count of all male on the ship Although if you want to count a numerical data then you cannot use the above method because value_counts() is used only with series type of data hence fails So for that you can use the second method example

the second method is

#this is an example method of counting on a data frame
df[(df['Survived']==1)&(df['Sex']=='male')].counts()

this is not that efficient as value_counts() but surely will help if you want to count values of a data frame hope this helps

Response.Redirect to new window

I just found the answer and it works :)

You need to add the following to your server side link/button:

OnClientClick="aspnetForm.target ='_blank';"

My entire button code looks something like:

<asp:LinkButton ID="myButton" runat="server" Text="Click Me!" 
                OnClick="myButton_Click" 
                OnClientClick="aspnetForm.target ='_blank';"/>

In the server side OnClick I do a Response.Redirect("MyPage.aspx"); and the page is opened in a new window.

The other part you need to add is to fix the form's target otherwise every link will open in a new window. To do so add the following in the header of your POPUP window.

<script type="text/javascript">
    function fixform() {
        if (opener.document.getElementById("aspnetForm").target != "_blank") return;
        opener.document.getElementById("aspnetForm").target = "";
        opener.document.getElementById("aspnetForm").action = opener.location.href;
    }
</script>

and

<body onload="fixform()">

C# Public Enums in Classes

Currently, your enum is nested inside of your Card class. All you have to do is move the definition of the enum out of the class:

// A better name which follows conventions instead of card_suits is
public enum CardSuit
{
    Clubs,
    Hearts,
    Spades,
    Diamonds
}

public class Card
{
}

To Specify:

The name change from card_suits to CardSuit was suggested because Microsoft guidelines suggest Pascal Case for Enumerations and the singular form is more descriptive in this case (as a plural would suggest that you're storing multiple enumeration values by ORing them together).

difference between css height : 100% vs height : auto

height: 100% gives the element 100% height of its parent container.

height: auto means the element height will depend upon the height of its children.

Consider these examples:

height: 100%

<div style="height: 50px">
    <div id="innerDiv" style="height: 100%">
    </div>
</div>

#innerDiv is going to have height: 50px

height: auto

<div style="height: 50px">
    <div id="innerDiv" style="height: auto">
          <div id="evenInner" style="height: 10px">
          </div>
    </div>
</div>

#innerDiv is going to have height: 10px

Android EditText view Floating Hint in Material Design

Use the TextInputLayout provided by the Material Components Library:

    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Label">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </com.google.android.material.textfield.TextInputLayout>

enter image description here

adding onclick event to dynamically added button?

but.onclick = function() { yourjavascriptfunction();};

or

but.onclick = function() { functionwithparam(param);};

Flexbox: 4 items per row

Flex wrap + negative margin

Why flex vs. display: inline-block?

Why negative margin?

Either you use SCSS or CSS-in-JS for the edge cases (i.e. first element in column), or you set a default margin and get rid of the outer margin later.

Implementation

https://codepen.io/zurfyx/pen/BaBWpja

<div class="outerContainer">
    <div class="container">
        <div class="elementContainer">
            <div class="element">
            </div>
        </div>
        ...
    </div>
</div>
:root {
  --columns: 2;
  --betweenColumns: 20px; /* This value is doubled when no margin collapsing */
}

.outerContainer {
    overflow: hidden; /* Hide the negative margin */
}

.container {
    background-color: grey;
    display: flex;
    flex-wrap: wrap;
    margin: calc(-1 * var(--betweenColumns));
}

.elementContainer {
    display: flex; /* To prevent margin collapsing */
    width: calc(1/var(--columns) * 100% - 2 * var(--betweenColumns));
    margin: var(--betweenColumns);
}

.element {
    display: flex;
    border: 1px solid red;
    background-color: yellow;
    width: 100%;
    height: 42px;
}

How do I declare an array with a custom class?

You have to provide a default constructor. While you're at it, fix your other constructor, too:

class Name
{
public:
  Name() { }
  Name(string const & f, string const & l) : first(f), last(l) { }
  //...
};

Alternatively, you have to provide the initializers:

Name arr[3] { { "John", "Doe" }, { "Jane", "Smith" }, { "", "" } };

The latter is conceptually preferable, because there's no reason that your class should have a notion of a "default" state. In that case, you simply have to provide an appropriate initializer for every element of the array.

Objects in C++ can never be in an ill-defined state; if you think about this, everything should become very clear.


An alternative is to use a dynamic container, though this is different from what you asked for:

std::vector<Name> arr;
arr.reserve(3);  // morally "an uninitialized array", though it really isn't

arr.emplace_back("John", "Doe");
arr.emplace_back("Jane", "Smith");
arr.emplace_back("", "");

std::vector<Name> brr { { "ab", "cd" }, { "de", "fg" } }; // yet another way

Getting 400 bad request error in Jquery Ajax POST

In case anyone else runs into this. I have a web site that was working fine on the desktop browser but I was getting 400 errors with Android devices.

It turned out to be the anti forgery token.

$.ajax({
        url: "/Cart/AddProduct/",
        data: {
            __RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
            productId: $(this).data("productcode")
        },

The problem was that the .Net controller wasn't set up correctly.

I needed to add the attributes to the controller:

    [AllowAnonymous]
    [IgnoreAntiforgeryToken]
    [DisableCors]
    [HttpPost]
    public async Task<JsonResult> AddProduct(int productId)
    {

The code needs review but for now at least I know what was causing it. 400 error not helpful at all.

In-memory size of a Python structure

I've been happily using pympler for such tasks. It's compatible with many versions of Python -- the asizeof module in particular goes back to 2.2!

For example, using hughdbrown's example but with from pympler import asizeof at the start and print asizeof.asizeof(v) at the end, I see (system Python 2.5 on MacOSX 10.5):

$ python pymp.py 
set 120
unicode 32
tuple 32
int 16
decimal 152
float 16
list 40
object 0
dict 144
str 32

Clearly there is some approximation here, but I've found it very useful for footprint analysis and tuning.

How to use log levels in java

Here is a good introduction to logging in Java: http://www.javapractices.com/topic/TopicAction.do?Id=143

Java comes with a logging API since it's 1.4.2 version: http://download.oracle.com/javase/1.4.2/docs/guide/util/logging/overview.html

You can also use other logging frameworks like Apache Log4j which is the most popular one: http://logging.apache.org/log4j

I suggest you to use a logging abstraction framework which allows you to change your logging framework without re-factoring you code. So you can starts by using Jul (Java Util Logging) then swith to Log4j without changing you code. The most popular logging facade is slf4j: http://www.slf4j.org/

Regards,

Metadata file '.dll' could not be found

For me it was an unused import "using ApsNetCore" on a Controller. Removed it, clean, rebuild it and it worked.

How the int.TryParse actually works

Check this simple program to understand int.TryParse

 class Program
 {
    static void Main()
    {
        string str = "7788";
        int num1;
        bool n = int.TryParse(str, out num1);
        Console.WriteLine(num1);
        Console.ReadLine();
    }
}

Output is : 7788

List of foreign keys and the tables they reference in Oracle DB

Its a bit late to anwser, but I hope my answer been useful for someone, who needs to select Composite foreign keys.

SELECT
    "C"."CONSTRAINT_NAME",
    "C"."OWNER" AS "SCHEMA_NAME",
    "C"."TABLE_NAME",
    "COL"."COLUMN_NAME",
    "REF_COL"."OWNER" AS "REF_SCHEMA_NAME",
    "REF_COL"."TABLE_NAME" AS "REF_TABLE_NAME",
    "REF_COL"."COLUMN_NAME" AS "REF_COLUMN_NAME"
FROM
    "USER_CONSTRAINTS" "C"
INNER JOIN "USER_CONS_COLUMNS" "COL" ON "COL"."OWNER" = "C"."OWNER"
 AND "COL"."CONSTRAINT_NAME" = "C"."CONSTRAINT_NAME"
INNER JOIN "USER_CONS_COLUMNS" "REF_COL" ON "REF_COL"."OWNER" = "C"."R_OWNER"
 AND "REF_COL"."CONSTRAINT_NAME" = "C"."R_CONSTRAINT_NAME"
 AND "REF_COL"."POSITION" = "COL"."POSITION"
WHERE "C"."TABLE_NAME" = 'TableName' AND "C"."CONSTRAINT_TYPE" = 'R'

CSS Margin: 0 is not setting to 0

I just started learning CSS today and encountered the same problem and I think You don't need to reset style of all HTML tags. You need to reset default margin of top HTML You used, which is paragraph tag. And I know this is old question, but maybe my solution below will help somebody.

Try this:

body{   
    margin: 0; 
    background:#F0F0F0;
}
p{
    margin: 0;
}

jquery remove "selected" attribute of option?

Another alternative:

$('option:selected', $('#mySelectParent')).removeAttr("selected");

Hope it helps

Exception Error c0000005 in VC++

Exception code c0000005 is the code for an access violation. That means that your program is accessing (either reading or writing) a memory address to which it does not have rights. Most commonly this is caused by:

  • Accessing a stale pointer. That is accessing memory that has already been deallocated. Note that such stale pointer accesses do not always result in access violations. Only if the memory manager has returned the memory to the system do you get an access violation.
  • Reading off the end of an array. This is when you have an array of length N and you access elements with index >=N.

To solve the problem you'll need to do some debugging. If you are not in a position to get the fault to occur under your debugger on your development machine you should get a crash dump file and load it into your debugger. This will allow you to see where in the code the problem occurred and hopefully lead you to the solution. You'll need to have the debugging symbols associated with the executable in order to see meaningful stack traces.

An existing connection was forcibly closed by the remote host

I had this issue when i tried to connect to postgresql while i'm using microsoft sutdio for mssql :)

Eclipse - debugger doesn't stop at breakpoint

For JDK7, run->Debug Configurations, check "Keep JUnit running after a test run when debugging".

Parameter "stratify" from method "train_test_split" (scikit Learn)

In this context, stratification means that the train_test_split method returns training and test subsets that have the same proportions of class labels as the input dataset.

Convert a Unicode string to a string in Python (containing extra symbols)

You can use encode to ASCII if you don't need to translate the non-ASCII characters:

>>> a=u"aaaàçççñññ"
>>> type(a)
<type 'unicode'>
>>> a.encode('ascii','ignore')
'aaa'
>>> a.encode('ascii','replace')
'aaa???????'
>>>

How to change a dataframe column from String type to Double type in PySpark?

the solution was simple -

toDoublefunc = UserDefinedFunction(lambda x: float(x),DoubleType())
changedTypedf = joindf.withColumn("label",toDoublefunc(joindf['show']))

pinpointing "conditional jump or move depends on uninitialized value(s)" valgrind message

Use the valgrind option --track-origins=yes to have it track the origin of uninitialized values. This will make it slower and take more memory, but can be very helpful if you need to track down the origin of an uninitialized value.

Update: Regarding the point at which the uninitialized value is reported, the valgrind manual states:

It is important to understand that your program can copy around junk (uninitialised) data as much as it likes. Memcheck observes this and keeps track of the data, but does not complain. A complaint is issued only when your program attempts to make use of uninitialised data in a way that might affect your program's externally-visible behaviour.

From the Valgrind FAQ:

As for eager reporting of copies of uninitialised memory values, this has been suggested multiple times. Unfortunately, almost all programs legitimately copy uninitialised memory values around (because compilers pad structs to preserve alignment) and eager checking leads to hundreds of false positives. Therefore Memcheck does not support eager checking at this time.

How to change the remote a branch is tracking?

With an up to date git (2.5.5) the command is the following :

git branch --set-upstream-to=origin/branch

This will update the remote tracked branch for your current local branch

nginx: connect() failed (111: Connection refused) while connecting to upstream

I don't think that solution would work anyways because you will see some error message in your error log file.

The solution was a lot easier than what I thought.

simply, open the following path to your php5-fpm

sudo nano /etc/php5/fpm/pool.d/www.conf

or if you're the admin 'root'

nano /etc/php5/fpm/pool.d/www.conf

Then find this line and uncomment it:

listen.allowed_clients = 127.0.0.1

This solution will make you be able to use listen = 127.0.0.1:9000 in your vhost blocks

like this: fastcgi_pass 127.0.0.1:9000;

after you make the modifications, all you need is to restart or reload both Nginx and Php5-fpm

Php5-fpm

sudo service php5-fpm restart

or

sudo service php5-fpm reload

Nginx

sudo service nginx restart

or

sudo service nginx reload

From the comments:

Also comment

;listen = /var/run/php5-fpm.sock 

and add

listen = 9000

Making a flex item float right

You can't use float inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle.

So if you want to position child element to right of parent element you can use margin-left: auto but now child element will also push other div to the right as you can see here Fiddle.

What you can do now is change order of elements and set order: 2 on child element so it doesn't affect second div

_x000D_
_x000D_
.parent {_x000D_
  display: flex;_x000D_
}_x000D_
.child {_x000D_
  margin-left: auto;_x000D_
  order: 2;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <div class="child">Ignore parent?</div>_x000D_
  <div>another child</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

how to add new <li> to <ul> onclick with javascript

There is nothing much to add to your code except appending the li tag to the ul

ul.appendChild(li)

and there you go just add this to your function and then it should work.

uncaught syntaxerror unexpected token U JSON

The parameter for the JSON.parse may be returning nothing (i.e. the value given for the JSON.parse is undefined)!

It happened to me while I was parsing the Compiled solidity code from an xyz.sol file.

import web3 from './web3';
import xyz from './build/xyz.json';

const i = new web3.eth.Contract(
  JSON.parse(xyz.interface),
  '0x99Fd6eFd4257645a34093E657f69150FEFf7CdF5'
);

export default i;

which was misspelled as

JSON.parse(xyz.intereface)

which was returning nothing!

Finding smallest value in an array most efficiently

The stl contains a bunch of methods that should be used dependent to the problem.

std::find
std::find_if
std::count
std::find
std::binary_search
std::equal_range
std::lower_bound
std::upper_bound

Now it contains on your data what algorithm to use. This Artikel contains a perfect table to help choosing the right algorithm.


In the special case where min max should be determined and you are using std::vector or ???* array

std::min_element
std::max_element

can be used.

What should I set JAVA_HOME environment variable on macOS X 10.6?

Nowadays Java seems to be installed in /Library/Java/JavaVirtualMachines

Warning message: In `...` : invalid factor level, NA generated

The warning message is because your "Type" variable was made a factor and "lunch" was not a defined level. Use the stringsAsFactors = FALSE flag when making your data frame to force "Type" to be a character.

> fixed <- data.frame("Type" = character(3), "Amount" = numeric(3))
> str(fixed)
'data.frame':   3 obs. of  2 variables:
 $ Type  : Factor w/ 1 level "": NA 1 1
 $ Amount: chr  "100" "0" "0"
> 
> fixed <- data.frame("Type" = character(3), "Amount" = numeric(3),stringsAsFactors=FALSE)
> fixed[1, ] <- c("lunch", 100)
> str(fixed)
'data.frame':   3 obs. of  2 variables:
 $ Type  : chr  "lunch" "" ""
 $ Amount: chr  "100" "0" "0"

Convert RGB values to Integer

I think the code is something like:

int rgb = red;
rgb = (rgb << 8) + green;
rgb = (rgb << 8) + blue;

Also, I believe you can get the individual values using:

int red = (rgb >> 16) & 0xFF;
int green = (rgb >> 8) & 0xFF;
int blue = rgb & 0xFF;

why $(window).load() is not working in jQuery?

You're using jQuery version 3.1.0 and the load event is deprecated for use since jQuery version 1.8. The load event is removed from jQuery 3.0. Instead you can use on method and bind the JavaScript load event:

 $(window).on('load', function () {
      alert("Window Loaded");
 });

Android : How to read file in bytes?

A simple InputStream will do

byte[] fileToBytes(File file){
    byte[] bytes = new byte[0];
    try(FileInputStream inputStream = new FileInputStream(file)) {
        bytes = new byte[inputStream.available()];
        //noinspection ResultOfMethodCallIgnored
        inputStream.read(bytes);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bytes;
}

Access-Control-Allow-Origin error sending a jQuery Post to Google API's

If you have this error trying to consume a service that you can't add the header Access-Control-Allow-Origin * in that application, but you can put in front of the server a reverse proxy, the error can avoided with a header rewrite.

Assuming the application is running on the port 8080 (public domain at www.mydomain.com), and you put the reverse proxy in the same host at port 80, this is the configuration for Nginx reverse proxy:

server {
    listen      80;
    server_name www.mydomain.com;
    access_log  /var/log/nginx/www.mydomain.com.access.log;
    error_log   /var/log/nginx/www.mydomain.com.error.log;

    location / {
        proxy_pass   http://127.0.0.1:8080;
        add_header   Access-Control-Allow-Origin *;
    }   
}

Is it possible to write to the console in colour in .NET?

Yes, it is possible as follows. These colours can be used in a console application to view some errors in red, etc.

Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;//after this line every text will be white on blue background
Console.WriteLine("White on blue.");
Console.WriteLine("Another line.");
Console.ResetColor();//reset to the defoult colour

Load Image from javascript

<span>
    <img id="my_image" src="#" />
</span>

<span class="spanloader">

    <span>set Loading Image Image</span>


</span>

<input type="button" id="btnnext" value="Next" />


<script type="text/javascript">

    $('#btnnext').click(function () {
        $(".spanloader").hide();
        $("#my_image").attr("src", "1.jpg");
    });

</script>

FutureWarning: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison

Eric's answer helpfully explains that the trouble comes from comparing a Pandas Series (containing a NumPy array) to a Python string. Unfortunately, his two workarounds both just suppress the warning.

To write code that doesn't cause the warning in the first place, explicitly compare your string to each element of the Series and get a separate bool for each. For example, you could use map and an anonymous function.

myRows = df[df['Unnamed: 5'].map( lambda x: x == 'Peter' )].index.tolist()

How to redirect a url in NGINX

This is the top hit on Google for "nginx redirect". If you got here just wanting to redirect a single location:

location = /content/unique-page-name {
  return 301 /new-name/unique-page-name;
}

Find Oracle JDBC driver in Maven repository

Try with:

<repositories>
    <!-- Repository for ORACLE ojdbc6. -->
    <repository>
        <id>codelds</id>
        <url>https://code.lds.org/nexus/content/groups/main-repo</url>
    </repository>
</repositories>
<dependencies> 
    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc6</artifactId>
        <version>11.2.0.3</version>
    </dependency>
</dependencies> 

How do I use itertools.groupby()?

This basic implementation helped me understand this function. Hope it helps others as well:

arr = [(1, "A"), (1, "B"), (1, "C"), (2, "D"), (2, "E"), (3, "F")]

for k,g in groupby(arr, lambda x: x[0]):
    print("--", k, "--")
    for tup in g:
        print(tup[1])  # tup[0] == k
-- 1 --
A
B
C
-- 2 --
D
E
-- 3 --
F

window.open with headers

Can I control the HTTP headers sent by window.open (cross browser)?

No

If not, can I somehow window.open a page that then issues my request with custom headers inside its popped-up window?

  • You can request a URL that triggers a server side program which makes the request with arbitrary headers and then returns the response
  • You can run JavaScript (probably saying goodbye to Progressive Enhancement) that uses XHR to make the request with arbitrary headers (assuming the URL fits within the Same Origin Policy) and then process the result in JS.

I need some cunning hacks...

It might help if you described the problem instead of asking if possible solutions would work.

MySQL: How to add one day to datetime field in query

Have a go with this, as this is how I would do it :)

SELECT * 
FROM fab_scheduler
WHERE custid = '123456'
AND CURDATE() = DATE(DATE_ADD(eventdate, INTERVAL 1 DAY))

Adding a Scrollable JTextArea (Java)

A scroll pane is a container which contains another component. You can't add your text area to two different scroll panes. The scroll pane takes care of the horizontal and vertical scroll bars.

And if you never add the scroll pane to the frame, it will never be visible.

Read the swing tutorial about scroll panes.

How to do a for loop in windows command line?

You might also consider adding ".

For example for %i in (*.wav) do opusenc "%~ni.wav" "%~ni.opus" is very good idea.

Client on Node.js: Uncaught ReferenceError: require is not defined

Replace all require statements with import statements. Example:

// Before:
const Web3 = require('web3');

// After:
import Web3 from 'web3';

It worked for me.

bash "if [ false ];" returns true instead of false -- why?

as noted by @tripleee, this is tangential, at best.

still, in case you arrived here searching for something like that (as i did), here is my solution

having to deal with user acessible configuration files, i use this function :

function isTrue() {
    if [[ "${@^^}" =~ ^(TRUE|OUI|Y|O$|ON$|[1-9]) ]]; then return 0;fi
    return 1
    }

wich can be used like that

if isTrue "$whatever"; then..

You can alter the "truth list" in the regexp, the one in this sample is french compatible and considers strings like "Yeah, yup, on,1, Oui,y,true to be "True".

note that the '^^' provides case insensivity

Java Desktop application: SWT vs. Swing

SWT was created as a response to the sluggishness of Swing around the turn of the century. Now that the differences in performance are becoming negligable, I think Swing is a better option for your standard applications. SWT/Eclipse has a nice framework which helps with a lot of boiler plate code.

How can I quantify difference between two images?

I have been having a lot of luck with jpg images taken with the same camera on a tripod by (1) simplifying greatly (like going from 3000 pixels wide to 100 pixels wide or even fewer) (2) flattening each jpg array into a single vector (3) pairwise correlating sequential images with a simple correlate algorithm to get correlation coefficient (4) squaring correlation coefficient to get r-square (i.e fraction of variability in one image explained by variation in the next) (5) generally in my application if r-square < 0.9, I say the two images are different and something happened in between.

This is robust and fast in my implementation (Mathematica 7)

It's worth playing around with the part of the image you are interested in and focussing on that by cropping all images to that little area, otherwise a distant-from-the-camera but important change will be missed.

I don't know how to use Python, but am sure it does correlations, too, no?

How do I remove accents from characters in a PHP string?

When using iconv, the parameter locale must be set:

function test_enc($text = 'ešcržýáíé EŠCRŽÝÁÍÉ fóø bår FÓØ BÅR æ')
{
    echo '<tt>';
    echo iconv('utf8', 'ascii//TRANSLIT', $text);
    echo '</tt><br/>';
} 

test_enc();
setlocale(LC_ALL, 'cs_CZ.utf8');
test_enc();
setlocale(LC_ALL, 'en_US.utf8');
test_enc();

Yields into:

????????? ????????? f?? b?r F?? B?R ae
escrzyaie ESCRZYAIE fo? bar FO? BAR ae
escrzyaie ESCRZYAIE fo? bar FO? BAR ae

Another locales then cs_CZ and en_US I haven't installed and I can't test it.

In C# I see solution using translation to unicode normalized form - accents are splitted out and then filtered via nonspacing unicode category.

Spring cron expression for every day 1:01:am

Try with:

@Scheduled(cron = "0 1 1 * * ?")

Below you can find the example patterns from the spring forum:

* "0 0 * * * *" = the top of every hour of every day.
* "*/10 * * * * *" = every ten seconds.
* "0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.
* "0 0 8,10 * * *" = 8 and 10 o'clock of every day.
* "0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30 and 10 o'clock every day.
* "0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays
* "0 0 0 25 12 ?" = every Christmas Day at midnight

Cron expression is represented by six fields:

second, minute, hour, day of month, month, day(s) of week

(*) means match any

*/X means "every X"

? ("no specific value") - useful when you need to specify something in one of the two fields in which the character is allowed, but not the other. For example, if I want my trigger to fire on a particular day of the month (say, the 10th), but I don't care what day of the week that happens to be, I would put "10" in the day-of-month field and "?" in the day-of-week field.

PS: In order to make it work, remember to enable it in your application context: https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html#scheduling-annotation-support

How to uncommit my last commit in Git

To keep the changes from the commit you want to undo

git reset --soft HEAD^

To destroy the changes from the commit you want to undo

git reset --hard HEAD^

You can also say

git reset --soft HEAD~2

to go back 2 commits.

Edit: As charsi mentioned, if you are on Windows you will need to put HEAD or commit hash in quotes.

git reset --soft "HEAD^"
git reset --soft "asdf"

How I can filter a Datatable?

use it:

.CopyToDataTable()

example:

string _sqlWhere = "Nachname = 'test'";
string _sqlOrder = "Nachname DESC";

DataTable _newDataTable = yurDateTable.Select(_sqlWhere, _sqlOrder).CopyToDataTable();

Capturing multiple line output into a Bash variable

Actually, RESULT contains what you want — to demonstrate:

echo "$RESULT"

What you show is what you get from:

echo $RESULT

As noted in the comments, the difference is that (1) the double-quoted version of the variable (echo "$RESULT") preserves internal spacing of the value exactly as it is represented in the variable — newlines, tabs, multiple blanks and all — whereas (2) the unquoted version (echo $RESULT) replaces each sequence of one or more blanks, tabs and newlines with a single space. Thus (1) preserves the shape of the input variable, whereas (2) creates a potentially very long single line of output with 'words' separated by single spaces (where a 'word' is a sequence of non-whitespace characters; there needn't be any alphanumerics in any of the words).

Difference between View and Request scope in managed beans

A @ViewScoped bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null or void (and thus navigates back to the same view). Once you refresh the page, or return a non-null string (even an empty string!) navigation outcome, then the view scope will end.

A @RequestScoped bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.

A @ViewScoped bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped bean. Every view has its own unique @ViewScoped bean.

See also:

Is it safe to use Project Lombok?

My take on Lombok is that it merely provides shortcuts for writing bolilerplate Java code.
When it comes to using shortcuts for writing bolilerplate Java code, I would rely on such features provided by IDE -- like in Eclipse, we can go to menu Source > Generate Getters and Setters for generating getters and setters.
I would not rely on a library like Lombok for this:

  1. It pollutes your code with an indirection layer of alternative syntax (read @Getter, @Setter, etc. annotations). Rather than learning an alternative syntax for Java, I would switch to any other language that natively provides Lombok like syntax.
  2. Lombok requires the use of a Lombok supported IDE to work with your code. This dependency introduces a considerable risk for any non-trivial project. Does the open source Lombok project have enough resources to keep providing support for different versions of a wide range of Java IDE's available?
  3. Does the open source Lombok project have enough resources to keep providing support for newer versions of Java that will be coming in future?
  4. I also feel nervous that Lombok may introduce compatibility issues with widely used frameworks/libraries (like Spring, Hibernate, Jackson, JUnit, Mockito) that work with your byte code at runtime.

All in all I would not prefer to "spice up" my Java with Lombok.

Laravel PHP Command Not Found

If you have Composer installed globally, you can install the Laravel installer tool using command below:

composer global require "laravel/installer=~1.1"

In angular $http service, How can I catch the "status" of error?

The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. Have a look at the docs https://docs.angularjs.org/api/ng/service/$http

Now the right way to use is:

// Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
});

The response object has these properties:

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.

A response status code between 200 and 299 is considered a success status and will result in the success callback being called.

$.widget is not a function

I got this error recently by introducing an old plugin to wordpress. It loaded an older version of jquery, which happened to be placed before the jquery mouse file. There was no jquery widget file loaded with the second version, which caused the error.

No error for using the extra jquery library -- that's a problem especially if a silent fail might have happened, causing a not so silent fail later on.

A potential way around it for wordpress might be to be explicit about the dependencies that way the jquery mouse would follow the widget which would follow the correct core leaving the other jquery to be loaded afterwards. Still might cause a production error later if you don't catch that and change the default function for jquery for the second version in all the files associated with it.

Spring Bean Scopes

In Spring, bean scope is used to decide which type of bean instance should be returned from Spring container back to the caller.

5 types of bean scopes are supported :

  1. Singleton : It returns a single bean instance per Spring IoC container.This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object.If no bean scope is specified in bean configuration file, default to singleton. enter image description here

  2. Prototype : It returns a new bean instance each time when requested. It does not store any cache version like singleton. enter image description here

  3. Request : It returns a single bean instance per HTTP request.

    enter image description here

  4. Session : It returns a single bean instance per HTTP session (User level session).

  5. GlobalSession : It returns a single bean instance per global HTTP session. It is only valid in the context of a web-aware Spring ApplicationContext (Application level session).

In most cases, you may only deal with the Spring’s core scope – singleton and prototype, and the default scope is singleton.

How to connect to local instance of SQL Server 2008 Express

Haha, oh boy, I figured it out. Somehow, someway, I did not install the Database Engine when I installed SQL Server 2008. I have no idea how I missed that, but that's what happened.

Insertion Sort vs. Selection Sort

The inner loop of the insertion sort goes through already sorted elements (contrary to the selection sort). This allows it to abort the inner loop when the right position is found. Which means, that:

  1. The inner loop will go through only half of its elements in an average case.
  2. The inner loop will be aborted even sooner if the array is almost sorted.
  3. The inner loop will abort immediately if the array is already sorted, making the complexity of the insertion sort linear in this case.

The selection sort will have to always go through all inner loop elements. That’s why the insertion sort is mostly preferred to the selection sort. But, on the other hand, the selection sort does much less element swaps, which might be more important in some cases.

Upload failed You need to use a different version code for your APK because you already have one with version code 2

This seems because you have already uploaded APK file of version 3 to Google Play Store. And again you are uploading apk with same version. So this issue has been occurred.

So for solution you need to change your version name and version code (increment with 1)and run application once and after export it upload to Google Play.

Creating a recursive method for Palindrome

Here is the code for palindrome check without creating many strings

public static boolean isPalindrome(String str){
    return isPalindrome(str,0,str.length()-1);
}

public static boolean isPalindrome(String str, int start, int end){
    if(start >= end)
        return true;
    else
        return (str.charAt(start) == str.charAt(end)) && isPalindrome(str, start+1, end-1);
}

Applying Comic Sans Ms font style

The httpd dæmon on OpenBSD uses the following stylesheet for all of its error messages, which presumably covers all the Comic Sans variations on non-Windows systems:

http://openbsd.su/src/usr.sbin/httpd/server_http.c#server_abort_http

810    style = "body { background-color: white; color: black; font-family: "
811        "'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', sans-serif; }\n"
812        "hr { border: 0; border-bottom: 1px dashed; }\n";

E.g., try this:

font-family: 'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', sans-serif;

What does the NS prefix mean?

NeXTSTEP or NeXTSTEP/Sun depending on who you are asking.

Sun had a fairly large investment in OpenStep for a while. Before Sun entered the picture most things in the foundation, even though it wasn't known as the foundation back then, was prefixed NX, for NeXT, and sometime just before Sun entered the picture everything was renamed to NS. The S most likely did not stand for Sun then but after Sun stepped in the general consensus was that it stood for Sun to honor their involvement.

I actually had a reference for this but I can't find it right now. I will update the post if/when I find it again.

How to remove stop words using nltk or python

In case your data are stored as a Pandas DataFrame, you can use remove_stopwords from textero that use the NLTK stopwords list by default.

import pandas as pd
import texthero as hero
df['text_without_stopwords'] = hero.remove_stopwords(df['text'])

Laravel - Return json along with http status code

This is how I do it in Laravel 5

return Response::json(['hello' => $value],201);

Or using a helper function:

return response()->json(['hello' => $value], 201); 

How to add plus one (+1) to a SQL Server column in a SQL Query

"UPDATE TableName SET TableField = TableField + 1 WHERE SomeFilterField = @ParameterID"

How to get body of a POST in php?

If you have the pecl/http extension installed, you can also use this:

$request = new http\Env\Request();
$request->getBody();

How do you get a list of the names of all files present in a directory in Node.js?

Get files in all subdirs

const fs=require('fs');

function getFiles (dir, files_){
    files_ = files_ || [];
    var files = fs.readdirSync(dir);
    for (var i in files){
        var name = dir + '/' + files[i];
        if (fs.statSync(name).isDirectory()){
            getFiles(name, files_);
        } else {
            files_.push(name);
        }
    }
    return files_;
}

console.log(getFiles('path/to/dir'))

Type datetime for input parameter in procedure

You should use the ISO-8601 format for string representations of dates - anything else is dependent on the SQL Server language and dateformat settings.

The ISO-8601 format for a DATETIME when using only the date is: YYYYMMDD (no dashes or antyhing!)

For a DATETIME with the time portion, it's YYYY-MM-DDTHH:MM:SS (with dashes, and a T in the middle to separate date and time portions).

If you want to convert a string to a DATE for SQL Server 2008 or newer, you can use YYYY-MM-DD (with the dashes) to achieve the same result. And don't ask me why this is so inconsistent and confusing - it just is, and you'll have to work with that for now.

So in your case, you should try:

declare @a datetime
declare @b datetime 

set @a = '2012-04-06T12:23:45'   -- 6th of April, 2012
set @b = '2012-08-06T21:10:12'   -- 6th of August, 2012

exec LogProcedure 'AccountLog', N'test', @a, @b

Furthermore - your stored proc has problem, since you're concatenating together datetime and string into a string, but you're not converting the datetime to string first, and also, you're forgetting the close quotes in your statement after both dates.

So change this line here to this:

IF @DateFirst <> '' and @DateLast <> ''
   SET @FinalSQL  = @FinalSQL + '  OR CONVERT(Date, DateLog) >= ''' + 
                    CONVERT(VARCHAR(50), @DateFirst, 126) +   -- convert @DateFirst to string for concatenation!
                    ''' AND CONVERT(Date, DateLog) <=''' +  -- you need closing quotes after @DateFirst!
                    CONVERT(VARCHAR(50), @DateLast, 126) + ''''      -- convert @DateLast to string and also: closing tags after that missing!

With these settings, and once you've fixed your stored procedure which contains problems right now, it will work.

How to do multiple arguments to map function where one remains the same in python?

To pass multiple arguments to a map function.

def q(x,y):
    return x*y

print map (q,range(0,10),range(10,20))

Here q is function with multiple argument that map() calls. Make sure, the length of both the ranges i.e.

len (range(a,a')) and len (range(b,b')) are equal.

Converting a PDF to PNG

I'll add my solution, even thought his thread is old. Maybe this will help someone anyway.

First, I need to generate the PDF. I use XeLaTeX for that:

xelatex test.tex

Now, ImageMagick and GraphicMagic both parse parameters from left to right, so the leftmost parameter, will be executed first. I ended up using this sequence for optimal processing:

gm convert -trim -transparent white -background transparent -density 1200x1200 -resize 25% test.pdf test.png

It gives nice graphics on transparent background, trimmed to what is actually on the page. The -density and -resize parameters, give a better granularity, and increase overall resolution.

I suggest checking if the density can be decreased for you. It'll cut down converting time.

How do I find the current machine's full hostname in C (hostname and domain information)?

To get a fully qualified name for a machine, we must first get the local hostname, and then lookup the canonical name.

The easiest way to do this is by first getting the local hostname using uname() or gethostname() and then performing a lookup with gethostbyname() and looking at the h_name member of the struct it returns. If you are using ANSI c, you must use uname() instead of gethostname().

Example:

char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);
printf("Hostname: %s\n", hostname);
struct hostent* h;
h = gethostbyname(hostname);
printf("h_name: %s\n", h->h_name);

Unfortunately, gethostbyname() is deprecated in the current POSIX specification, as it doesn't play well with IPv6. A more modern version of this code would use getaddrinfo().

Example:

struct addrinfo hints, *info, *p;
int gai_result;

char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);

memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; /*either IPV4 or IPV6*/
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_CANONNAME;

if ((gai_result = getaddrinfo(hostname, "http", &hints, &info)) != 0) {
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai_result));
    exit(1);
}

for(p = info; p != NULL; p = p->ai_next) {
    printf("hostname: %s\n", p->ai_canonname);
}

freeaddrinfo(info);

Of course, this will only work if the machine has a FQDN to give - if not, the result of the getaddrinfo() ends up being the same as the unqualified hostname.

Programmatically Creating UILabel

UILabel *lbl1 = [[UILabel alloc] init];
/*important--------- */lbl1.textColor = [UIColor blackColor];
[lbl1 setFrame:position];
lbl1.backgroundColor=[UIColor clearColor];
lbl1.textColor=[UIColor whiteColor];
lbl1.userInteractionEnabled=NO;
lbl1.text= @"TEST";
[self.view addSubview:lbl1];

Send parameter to Bootstrap modal window?

I have found this better way , no need to remove data , just call the source of the remote content each time

$(document).ready(function() {
    $('.class').click(function() {
        var id = this.id;
        //alert(id);checking that have correct id
        $("#iframe").attr("src","url?id=" + id);
        $('#Modal').modal({ 
            show: true 
        });
    });
});

How do I make a branch point at a specific commit?

git branch -f <branchname> <commit>

I go with Mark Longair's solution and comments and recommend anyone reads those before acting, but I'd suggest the emphasis should be on

git branch -f <branchname> <commit>

Here is a scenario where I have needed to do this.

Scenario

Develop on the wrong branch and hence need to reset it.

Start Okay

Cleanly develop and release some software.

So far so good

Develop on wrong branch

Mistake: Accidentally stay on the release branch while developing further.

After a mistake

Realize the mistake

"OH NO! I accidentally developed on the release branch." The workspace is maybe cluttered with half changed files that represent work-in-progress and we really don't want to touch and mess with. We'd just like git to flip a few pointers to keep track of the current state and put that release branch back how it should be.

Create a branch for the development that is up to date holding the work committed so far and switch to it.

git branch development
git checkout development 

Changed to another branch

Correct the branch

Now we are in the problem situation and need its solution! Rectify the mistake (of taking the release branch forward with the development) and put the release branch back how it should be.

Correct the release branch to point back to the last real release.

git branch -f release release2

The release branch is now correct again, like this ...

Corrected

What if I pushed the mistake to a remote?

git push -f <remote> <branch> is well described in another thread, though the word "overwrite" in the title is misleading. Force "git push" to overwrite remote files

RichTextBox (WPF) does not have string property "Text"

Using two extension methods, this becomes very easy:

public static class Ext
{
    public static void SetText(this RichTextBox richTextBox, string text)
    {
        richTextBox.Document.Blocks.Clear();
        richTextBox.Document.Blocks.Add(new Paragraph(new Run(text)));
    }

    public static string GetText(this RichTextBox richTextBox)
    {
        return new TextRange(richTextBox.Document.ContentStart,
            richTextBox.Document.ContentEnd).Text;
    }
}

How do I check OS with a preprocessor directive?

On MinGW, the _WIN32 define check isn't working. Here's a solution:

#if defined(_WIN32) || defined(__CYGWIN__)
    // Windows (x86 or x64)
    // ...
#elif defined(__linux__)
    // Linux
    // ...
#elif defined(__APPLE__) && defined(__MACH__)
    // Mac OS
    // ...
#elif defined(unix) || defined(__unix__) || defined(__unix)
    // Unix like OS
    // ...
#else
    #error Unknown environment!
#endif

For more information please look: https://sourceforge.net/p/predef/wiki/OperatingSystems/

How to write inline if statement for print?

You always need an else in an inline if:

a = 1 if b else 0

But an easier way to do it would be a = int(b).

What's wrong with using == to compare floats in Java?

As of today, the quick & easy way to do it is:

if (Float.compare(sectionID, currentSectionID) == 0) {...}

However, the docs do not clearly specify the value of the margin difference (an epsilon from @Victor 's answer) that is always present in calculations on floats, but it should be something reasonable as it is a part of the standard language library.

Yet if a higher or customized precision is needed, then

float epsilon = Float.MIN_NORMAL;  
if(Math.abs(sectionID - currentSectionID) < epsilon){...}

is another solution option.

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

What worked for me is that i hadn't set the local_listener, to see if the local listener is set login to sqlplus / as sysdba, make sure the database is open and run the following command show parameter local_listener, if the value is empty, then you will have to set the local_listener with the following SQL command ALTER SYSTEM SET LOCAL_LISTENER='<LISTENER_NAME_GOES_HERE>'

How do you plot bar charts in gnuplot?

plot "data.dat" using 2: xtic(1) with histogram

Here data.dat contains data of the form

title 1
title2 3
"long title" 5

How can I print a circular structure in a JSON-like format?

I know this question is old and has lots of great answers but I post this answer because of it's new flavor (es5+)

_x000D_
_x000D_
Object.defineProperties(JSON, {_x000D_
  refStringify: {_x000D_
    value: function(obj) {_x000D_
_x000D_
      let objMap = new Map();_x000D_
      let stringified = JSON.stringify(obj,_x000D_
        function(key, value) {_x000D_
_x000D_
          // only for objects_x000D_
          if (typeof value == 'object') {_x000D_
            // If has the value then return a reference to it_x000D_
            if (objMap.has(value))_x000D_
              return objMap.get(value);_x000D_
_x000D_
            objMap.set(value, `ref${objMap.size + 1}`);_x000D_
          }_x000D_
          return value;_x000D_
        });_x000D_
      return stringified;_x000D_
    }_x000D_
  },_x000D_
  refParse: {_x000D_
    value: function(str) {_x000D_
_x000D_
      let parsed = JSON.parse(str);_x000D_
      let objMap = _createObjectMap(parsed);_x000D_
      objMap.forEach((value, key) => _replaceKeyWithObject(value, key));_x000D_
      return parsed;_x000D_
    }_x000D_
  },_x000D_
});_x000D_
_x000D_
// *************************** Example_x000D_
let a = {_x000D_
  b: 32,_x000D_
  c: {_x000D_
    get a() {_x000D_
        return a;_x000D_
      },_x000D_
      get c() {_x000D_
        return a.c;_x000D_
      }_x000D_
  }_x000D_
};_x000D_
let stringified = JSON.refStringify(a);_x000D_
let parsed = JSON.refParse(stringified, 2);_x000D_
console.log(parsed, JSON.refStringify(parsed));_x000D_
// *************************** /Example_x000D_
_x000D_
// *************************** Helper_x000D_
function _createObjectMap(obj) {_x000D_
_x000D_
  let objMap = new Map();_x000D_
  JSON.stringify(obj, (key, value) => {_x000D_
    if (typeof value == 'object') {_x000D_
      if (objMap.has(value))_x000D_
        return objMap.get(value);_x000D_
      objMap.set(value, `ref${objMap.size + 1}`);_x000D_
_x000D_
    }_x000D_
    return value;_x000D_
  });_x000D_
  return objMap;_x000D_
}_x000D_
_x000D_
function _replaceKeyWithObject(key, obj, replaceWithObject = obj) {_x000D_
_x000D_
  Object.keys(obj).forEach(k => {_x000D_
_x000D_
    let val = obj[k];_x000D_
    if (val == key)_x000D_
      return (obj[k] = replaceWithObject);_x000D_
    if (typeof val == 'object' && val != replaceWithObject)_x000D_
      _replaceKeyWithObject(key, val, replaceWithObject);_x000D_
  });_x000D_
}
_x000D_
_x000D_
_x000D_

Import CSV file into SQL Server

Firs you need to import CSV file into Data Table

Then you can insert bulk rows using SQLBulkCopy

using System;
using System.Data;
using System.Data.SqlClient;

namespace SqlBulkInsertExample
{
    class Program
    {
      static void Main(string[] args)
        {
            DataTable prodSalesData = new DataTable("ProductSalesData");

            // Create Column 1: SaleDate
            DataColumn dateColumn = new DataColumn();
            dateColumn.DataType = Type.GetType("System.DateTime");
            dateColumn.ColumnName = "SaleDate";

            // Create Column 2: ProductName
            DataColumn productNameColumn = new DataColumn();
            productNameColumn.ColumnName = "ProductName";

            // Create Column 3: TotalSales
            DataColumn totalSalesColumn = new DataColumn();
            totalSalesColumn.DataType = Type.GetType("System.Int32");
            totalSalesColumn.ColumnName = "TotalSales";

            // Add the columns to the ProductSalesData DataTable
            prodSalesData.Columns.Add(dateColumn);
            prodSalesData.Columns.Add(productNameColumn);
            prodSalesData.Columns.Add(totalSalesColumn);

            // Let's populate the datatable with our stats.
            // You can add as many rows as you want here!

            // Create a new row
            DataRow dailyProductSalesRow = prodSalesData.NewRow();
            dailyProductSalesRow["SaleDate"] = DateTime.Now.Date;
            dailyProductSalesRow["ProductName"] = "Nike";
            dailyProductSalesRow["TotalSales"] = 10;

            // Add the row to the ProductSalesData DataTable
            prodSalesData.Rows.Add(dailyProductSalesRow);

            // Copy the DataTable to SQL Server using SqlBulkCopy
            using (SqlConnection dbConnection = new SqlConnection("Data Source=ProductHost;Initial Catalog=dbProduct;Integrated Security=SSPI;Connection Timeout=60;Min Pool Size=2;Max Pool Size=20;"))
            {
                dbConnection.Open();
                using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))
                {
                    s.DestinationTableName = prodSalesData.TableName;

                    foreach (var column in prodSalesData.Columns)
                        s.ColumnMappings.Add(column.ToString(), column.ToString());

                    s.WriteToServer(prodSalesData);
                }
            }
        }
    }
}

'nuget' is not recognized but other nuget commands working

In Visual Studio:

Tools -> Nuget Package Manager -> Package Manager Console.

In PM:

Install-Package NuGet.CommandLine

Close Visual Studio and open it again.

JPA EntityManager: Why use persist() over merge()?

Persist and merge are for two different purposes (they aren't alternatives at all).

(edited to expand differences information)

persist:

  • Insert a new register to the database
  • Attach the object to the entity manager.

merge:

  • Find an attached object with the same id and update it.
  • If exists update and return the already attached object.
  • If doesn't exist insert the new register to the database.

persist() efficiency:

  • It could be more efficient for inserting a new register to a database than merge().
  • It doesn't duplicates the original object.

persist() semantics:

  • It makes sure that you are inserting and not updating by mistake.

Example:

{
    AnyEntity newEntity;
    AnyEntity nonAttachedEntity;
    AnyEntity attachedEntity;

    // Create a new entity and persist it        
    newEntity = new AnyEntity();
    em.persist(newEntity);

    // Save 1 to the database at next flush
    newEntity.setValue(1);

    // Create a new entity with the same Id than the persisted one.
    AnyEntity nonAttachedEntity = new AnyEntity();
    nonAttachedEntity.setId(newEntity.getId());

    // Save 2 to the database at next flush instead of 1!!!
    nonAttachedEntity.setValue(2);
    attachedEntity = em.merge(nonAttachedEntity);

    // This condition returns true
    // merge has found the already attached object (newEntity) and returns it.
    if(attachedEntity==newEntity) {
            System.out.print("They are the same object!");
    }

    // Set 3 to value
    attachedEntity.setValue(3);
    // Really, now both are the same object. Prints 3
    System.out.println(newEntity.getValue());

    // Modify the un attached object has no effect to the entity manager
    // nor to the other objects
    nonAttachedEntity.setValue(42);
}

This way only exists 1 attached object for any register in the entity manager.

merge() for an entity with an id is something like:

AnyEntity myMerge(AnyEntity entityToSave) {
    AnyEntity attached = em.find(AnyEntity.class, entityToSave.getId());
    if(attached==null) {
            attached = new AnyEntity();
            em.persist(attached);
    }
    BeanUtils.copyProperties(attached, entityToSave);

    return attached;
}

Although if connected to MySQL merge() could be as efficient as persist() using a call to INSERT with ON DUPLICATE KEY UPDATE option, JPA is a very high level programming and you can't assume this is going to be the case everywhere.

Is there any publicly accessible JSON data source to test with real world data?

Twitter has a public API which returns JSON, for example -

A GET request to:

https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=mralexgray&count=1,

EDIT: Removed due to twitter restricting their API with OAUTH requirements...

{"errors": [{"message": "The Twitter REST API v1 is no longer active. Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.", "code": 68}]}

Replacing it with a simple example of the Github API - that returns a tree, of in this case, my repositories...

https://api.github.com/users/mralexgray/repos

I won't include the output, as it's long.. (returns 30 repos at a time) ... But here is proof of it's tree-ed-ness.

enter image description here

Bootstrap 3.0 Popovers and tooltips

You just need to enable the tooltip:

$('some id or class that you add to the above a tag').popover({
    trigger: "hover" 
})

What is the best way to delete a value from an array in Perl?

I think your solution is the simplest and most maintainable.

The rest of the post documents the difficulty of turning tests on elements into splice offsets. Thus, making it a more complete answer.

Look at the gyrations you have to go through to have an efficient (i.e. one-pass) algorithm to turn tests on list items into indexes. And it's not that intuitive at all.

sub array_remove ( \@& ) { 
    my ( $arr_ref, $test_block ) = @_;
    my $sp_start  = 0;
    my $sp_len    = 0;
    for ( my $inx = 0; $inx <= $#$arr_ref; $inx++ ) {
        local $_ = $arr_ref->[$inx];
        next unless $test_block->( $_ );
        if ( $sp_len > 0 && $inx > $sp_start + $sp_len ) {
            splice( @$arr_ref, $sp_start, $sp_len );
            $inx    = $inx - $sp_len;
            $sp_len = 0;
        }
        $sp_start = $inx if ++$sp_len == 1;
    }
    splice( @$arr_ref, $sp_start, $sp_len ) if $sp_len > 0;
    return;
}

How do I edit a file after I shell to a Docker container?

I use "docker run" (not "docker exec"), and I'm in a restricted zone where we cannot install an editor. But I have an editor on the Docker host.

My workaround is: Bind mount a volume from the Docker host to the container (https://docs.docker.com/engine/reference/run/#/volume-shared-filesystems), and edit the file outside the container. It looks like this:

docker run -v /outside/dir:/container/dir

This is mostly for experimenting, and later I'd change the file when building the image.

python - checking odd/even numbers and changing outputs on number size

1. another odd testing function

Ok, the assignment was handed in 8+ years ago, but here is another solution based on bit shifting operations:

def isodd(i):
    return(bool(i>>0&1))

testing gives:

>>> isodd(2)
False
>>> isodd(3)
True
>>> isodd(4)
False

2. Nearest Odd number alternative approach

However, instead of a code that says "give me this precise input (an integer odd number) or otherwise I won't do anything" I also like robust codes that say, "give me a number, any number, and I'll give you the nearest pyramid to that number".

In that case this function is helpful, and gives you the nearest odd (e.g. any number f such that 6<=f<8 is set to 7 and so on.)

def nearodd(f):
    return int(f/2)*2+1

Example output:

nearodd(4.9)
5

nearodd(7.2)
7

nearodd(8)
9  

using extern template (C++11)

If you have used extern for functions before, exactly same philosophy is followed for templates. if not, going though extern for simple functions may help. Also, you may want to put the extern(s) in header file and include the header when you need it.

CSS, Images, JS not loading in IIS

One suggestion I have found helpful in the past when developing sites in localhost test environment when working with a copy of production site. Make sure that you comment out the canonical tags:

  <!--<base href="http://www.example.com/">//-->

Making a POST call instead of GET using urllib2

Do it in stages, and modify the object, like this:

# make a string with the request type in it:
method = "POST"
# create a handler. you can specify different handlers here (file uploads etc)
# but we go for the default
handler = urllib2.HTTPHandler()
# create an openerdirector instance
opener = urllib2.build_opener(handler)
# build a request
data = urllib.urlencode(dictionary_of_POST_fields_or_None)
request = urllib2.Request(url, data=data)
# add any other information you want
request.add_header("Content-Type",'application/json')
# overload the get method function with a small anonymous function...
request.get_method = lambda: method
# try it; don't forget to catch the result
try:
    connection = opener.open(request)
except urllib2.HTTPError,e:
    connection = e

# check. Substitute with appropriate HTTP code.
if connection.code == 200:
    data = connection.read()
else:
    # handle the error case. connection.read() will still contain data
    # if any was returned, but it probably won't be of any use

This way allows you to extend to making PUT, DELETE, HEAD and OPTIONS requests too, simply by substituting the value of method or even wrapping it up in a function. Depending on what you're trying to do, you may also need a different HTTP handler, e.g. for multi file upload.

Can the :not() pseudo-class have multiple arguments?

If you're using SASS in your project, I've built this mixin to make it work the way we all want it to:

@mixin not($ignorList...) {
    //if only a single value given
    @if (length($ignorList) == 1){
        //it is probably a list variable so set ignore list to the variable
        $ignorList: nth($ignorList,1);
    }
    //set up an empty $notOutput variable
    $notOutput: '';
    //for each item in the list
    @each $not in $ignorList {
        //generate a :not([ignored_item]) segment for each item in the ignore list and put them back to back
        $notOutput: $notOutput + ':not(#{$not})';
    }
    //output the full :not() rule including all ignored items
    &#{$notOutput} {
        @content;
    }
}

it can be used in 2 ways:

Option 1: list the ignored items inline

input {
  /*non-ignored styling goes here*/
  @include not('[type="radio"]','[type="checkbox"]'){
    /*ignored styling goes here*/
  }
}

Option 2: list the ignored items in a variable first

$ignoredItems:
  '[type="radio"]',
  '[type="checkbox"]'
;

input {
  /*non-ignored styling goes here*/
  @include not($ignoredItems){
    /*ignored styling goes here*/
  }
}

Outputted CSS for either option

input {
    /*non-ignored styling goes here*/
}

input:not([type="radio"]):not([type="checkbox"]) {
    /*ignored styling goes here*/
}

Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org

If you're running on a Mac you could just search for Install Certificates.command on the spotlight and hit enter.

Changing Underline color

Problem with border-bottom is the extra distance between the text and the line. Problem with text-decoration-color is lack of browser support. Therefore my solution is the use of a background-image with a line. This supports any markup, color(s) and style of the line. top (12px in my example) is dependent on line-height of your text.

 u {
    text-decoration: none;
    background: transparent url(blackline.png) repeat-x 0px 12px;
}

What are the differences between the urllib, urllib2, urllib3 and requests module?

To get the content of a url:

try: # Try importing requests first.
    import requests
except ImportError: 
    try: # Try importing Python3 urllib
        import urllib.request
    except AttributeError: # Now importing Python2 urllib
        import urllib


def get_content(url):
    try:  # Using requests.
        return requests.get(url).content # Returns requests.models.Response.
    except NameError:  
        try: # Using Python3 urllib.
            with urllib.request.urlopen(index_url) as response:
                return response.read() # Returns http.client.HTTPResponse.
        except AttributeError: # Using Python3 urllib.
            return urllib.urlopen(url).read() # Returns an instance.

It's hard to write Python2 and Python3 and request dependencies code for the responses because they urlopen() functions and requests.get() function return different types:

  • Python2 urllib.request.urlopen() returns a http.client.HTTPResponse
  • Python3 urllib.urlopen(url) returns an instance
  • Request request.get(url) returns a requests.models.Response

Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

Update using NuGet Package Manager Console in your Visual Studio

Update-Package -reinstall Microsoft.AspNet.Mvc

Use of alloc init instead of new

I am very late to this but I want to mention that that new is actually unsafe in the Obj-C with Swift world. Swift will only create a default init method if you do not create any other initializer. Calling new on a swift class with a custom initializer will cause a crash. If you use alloc/init then the compiler will properly complain that init does not exist.

Android 6.0 Marshmallow. Cannot write to SD Card

Android changed how permissions work with Android 6.0 that's the reason for your errors. You have to actually request and check if the permission was granted by user to use. So permissions in manifest file will only work for api below 21. Check this link for a snippet of how permissions are requested in api23 http://android-developers.blogspot.nl/2015/09/google-play-services-81-and-android-60.html?m=1

Code:-

If (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_RC);
            return;
        }`


` @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == STORAGE_PERMISSION_RC) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //permission granted  start reading
            } else {
                Toast.makeText(this, "No permission to read external storage.", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

Detecting when Iframe content has loaded (Cross browser)

For anyone using Ember, this should work as expected:

<iframe onLoad={{action 'actionName'}}  frameborder='0' src={{iframeSrc}} />

What is the use of the square brackets [] in sql statements?

Column names can contain characters and reserved words that will confuse the query execution engine, so placing brackets around them at all times prevents this from happening. Easier than checking for an issue and then dealing with it, I guess.

Join between tables in two different databases?

SELECT *
FROM A.tableA JOIN B.tableB 

or

SELECT *
  FROM A.tableA JOIN B.tableB
  ON A.tableA.id = B.tableB.a_id;

Java check if boolean is null

A boolean cannot be null in java.

A Boolean, however, can be null.

If a boolean is not assigned a value (say a member of a class) then it will be false by default.

Java :Add scroll into text area

My naive assumption was that the size of scroll pane will be determined automatically...

The only solution that actually worked for me was explicitly seeting bounds of JScrollPane:

import javax.swing.*;

public class MyFrame extends JFrame {

    public MyFrame()
    {
        setBounds(100, 100, 491, 310);
        getContentPane().setLayout(null);

        JTextArea textField = new JTextArea();
        textField.setEditable(false);

        String str = "";
        for (int i = 0; i < 50; ++i)
            str += "Some text\n";
        textField.setText(str);

        JScrollPane scroll = new JScrollPane(textField);
        scroll.setBounds(10, 11, 455, 249);                     // <-- THIS

        getContentPane().add(scroll);
        setLocationRelativeTo ( null );
    }
}

Maybe it will help some future visitors :)

Matplotlib - Move X-Axis label downwards, but not X-Axis Ticks

use labelpad parameter:

pl.xlabel("...", labelpad=20)

or set it after:

ax.xaxis.labelpad = 20

Increasing the Command Timeout for SQL command

it takes this command about 2 mins to return the data as there is a lot of data

Probably, Bad Design. Consider using paging here.

default connection time is 30 secs, how do I increase this

As you are facing a timeout on your command, therefore you need to increase the timeout of your sql command. You can specify it in your command like this

// Setting command timeout to 2 minutes
scGetruntotals.CommandTimeout = 120;

How to completely remove borders from HTML table

In a bootstrap environment here is my solution:

    <table style="border-collapse: collapse; border: none;">
        <tr style="border: none;">
            <td style="border: none;">
            </td>
        </tr>
    </table>    

Create Word Document using PHP in Linux

There are 2 options to create quality word documents. Use COM to communicate with word (this requires a windows php server at least). Use openoffice and it's API to create and save documents in word format.

Read whole ASCII file into C++ std::string

I think best way is to use string stream. simple and quick !!!

#include <fstream>
#include <iostream>
#include <sstream> //std::stringstream
int main() {
    std::ifstream inFile;
    inFile.open("inFileName"); //open the input file

    std::stringstream strStream;
    strStream << inFile.rdbuf(); //read the file
    std::string str = strStream.str(); //str holds the content of the file

    std::cout << str << "\n"; //you can do anything with the string!!!
}

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

Just as a follow up for anyone still running into this – I had added the ServicePointManager.SecurityProfile options as noted in the solution:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

And yet I continued to get the same “The request was aborted: Could not create SSL/TLS secure channel” error. I was attempting to connect to some older voice servers with HTTPS SOAP API interfaces (i.e. voice mail, IP phone systems etc… installed years ago). These only support SSL3 connections as they were last updated years ago.

One would think including SSl3 in the list of SecurityProtocols would do the trick here, but it didn’t. The only way I could force the connection was to include ONLY the Ssl3 protocol and no others:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

Then the connection goes through – seems like a bug to me but this didn’t start throwing errors until recently on tools I provide for these servers that have been out there for years – I believe Microsoft has started rolling out system changes that have updated this behavior to force TLS connections unless there is no other alternative.

Anyway – if you’re still running into this against some old sites/servers, it’s worth giving it a try.

How to use OKHTTP to make a post request?

  1. Add the following to the build.gradle

compile 'com.squareup.okhttp3:okhttp:3.7.0'

  1. Create a new thread, in the new thread add the following code.
OkHttpClient client = new OkHttpClient();
MediaType MIMEType= MediaType.parse("application/json; charset=utf-8");
RequestBody requestBody = RequestBody.create (MIMEType,"{}");
Request request = new Request.Builder().url(url).post(requestBody).build();
Response response = client.newCall(request).execute();

PHP $_POST not working?

I had something similar this evening which was driving me batty. Submitting a form was giving me the values in $_REQUEST but not in $_POST.

Eventually I noticed that there were actually two requests going through on the network tab in firebug; first a POST with a 301 response, then a GET with a 200 response.

Hunting about the interwebs it sounded like most people thought this was to do with mod_rewrite causing the POST request to redirect and thus change to a GET.

In my case it wasn't mod_rewrite to blame, it was something far simpler... my URL for the POST also contained a GET query string which was starting without a trailing slash on the URL. It was this causing apache to redirect.

Spot the difference...

Bad: http://blah.de.blah/my/path?key=value&otherkey=othervalue
Good: http://blah.de.blah/my/path/?key=value&otherkey=othervalue

The bottom one doesn't cause a redirect and gives me $_POST!

Getting path relative to the current working directory?

You can use Environment.CurrentDirectory to get the current directory, and FileSystemInfo.FullPath to get the full path to any location. So, fully qualify both the current directory and the file in question, and then check whether the full file name starts with the directory name - if it does, just take the appropriate substring based on the directory name's length.

Here's some sample code:

using System;
using System.IO;

class Program
{
    public static void Main(string[] args)
    {
        string currentDir = Environment.CurrentDirectory;
        DirectoryInfo directory = new DirectoryInfo(currentDir);
        FileInfo file = new FileInfo(args[0]);

        string fullDirectory = directory.FullName;
        string fullFile = file.FullName;

        if (!fullFile.StartsWith(fullDirectory))
        {
            Console.WriteLine("Unable to make relative path");
        }
        else
        {
            // The +1 is to avoid the directory separator
            Console.WriteLine("Relative path: {0}",
                              fullFile.Substring(fullDirectory.Length+1));
        }
    }
}

I'm not saying it's the most robust thing in the world (symlinks could probably confuse it) but it's probably okay if this is just a tool you'll be using occasionally.

SQL ORDER BY multiple columns

Yes, the sorting is different.

Items in the ORDER BY list are applied in order.
Later items only order peers left from the preceding step.

Why don't you just try?

Remove pattern from string with gsub

Just to point out that there is an approach using functions from the tidyverse, which I find more readable than gsub:

a %>% stringr::str_remove(pattern = ".*_")

How to set the java.library.path from Eclipse

the easiest way would to use the eclipse IDE itself. Go to the menu and set build path. Make it point to the JAVA JDK and JRE file path in your directory. afterwards you can check the build path where compiled files are going to be set. in the bin folder by default though. The best thing would be to allow eclipse to handle itself the build path and only to edit it similar to the solution that is given above

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

If you are using tomcat as your server runtime and you get this error in tests (because tomcat runtime is not available during tests) than it makes make sense to include tomcat el runtime instead of the one from glassfish). This would be:

    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-el-api</artifactId>
        <version>8.5.14</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-jasper-el</artifactId>
        <version>8.5.14</version>
        <scope>test</scope>
    </dependency>

Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

Note that, in Java 8, 'ia' above must be Integer[] and not int[]. Arrays.asList() of an int array returns a list with a single element. When using OP's code snippet, the compiler will catch the issue, but some methods (e.g. Collections.shuffle()) will silently fail to do what you expect.

PostgreSQL "DESCRIBE TABLE"

This should be the solution:

SELECT * FROM information_schema.columns
WHERE table_schema = 'your_schema'
   AND table_name   = 'your_table'

Splitting a continuous variable into equal sized groups

cut, when not given explicit break points divides values into bins of same width, they won't contain an equal number of items in general:

x <- c(1:4,10)
lengths(split(x, cut(x, 2)))
# (0.991,5.5]    (5.5,10] 
#           4           1 

Hmisc::cut2 and ggplot2::cut_number use quantiles, which will usually create groups of same size (in term of number of elements) if the data is well spread and of decent size, it's not always the case however. mltools::bin_data can give different results but is also based on quantiles.

These functions don't always give neat results when the data contains a small number of distinct values :

x <- rep(c(1:20),c(15, 7, 10, 3, 9, 3, 4, 9, 3, 2,
                   23, 2, 4, 1, 1, 7, 18, 37, 6, 2))

table(x)
# x
#  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 
# 15  7 10  3  9  3  4  9  3  2 23  2  4  1  1  7 18 37  6  2   

table(Hmisc::cut2(x, g=4))
# [ 1, 6) [ 6,12) [12,19) [19,20] 
#      44      44      70       8

table(ggplot2::cut_number(x, 4))
# [1,5]  (5,11] (11,18] (18,20] 
#    44      44      70       8

table(mltools::bin_data(x, bins=4, binType = "quantile"))
# [1, 5)  [5, 11) [11, 18) [18, 20] 
#     35       30       56       45

This is not clear if the optimal solution has been found here.

What is the best binning approach is a subjective matter, but one reasonable way to approach it is to look for the bins that minimize the variance around the expected bin size.

The function smart_cut from (my) package cutr proposes such feature. It's computationally heavy though and should be reserved to cases where cut points and unique values are few (which happen to be usually the case where it matters).

# devtools::install_github("moodymudskipper/cutr")
table(cutr::smart_cut(x, list(4, "balanced"), "g"))
# [1,6)  [6,12) [12,18) [18,20] 
# 44      44      33      45 

We see the groups are much better balanced.

"balanced" in the call can in fact be replaced by a custom function to optimize or restrict the bins as desired if the method based on variance isn't enough.

How to remove new line characters from a string?

just do that

s = s.Replace("\n", String.Empty).Replace("\t", String.Empty).Replace("\r", String.Empty);

Count table rows

We have another way to find out the number of rows in a table without running a select query on that table.

Every MySQL instance has information_schema database. If you run the following query, it will give complete details about the table including the approximate number of rows in that table.

select * from information_schema.TABLES where table_name = 'table_name'\G

How to easily resize/optimize an image size with iOS?

The easiest and most straightforward way to resize your images would be this

float actualHeight = image.size.height;
float actualWidth = image.size.width;
float imgRatio = actualWidth/actualHeight;
float maxRatio = 320.0/480.0;

if(imgRatio!=maxRatio){
    if(imgRatio < maxRatio){
        imgRatio = 480.0 / actualHeight;
        actualWidth = imgRatio * actualWidth;
        actualHeight = 480.0;
    }
    else{
        imgRatio = 320.0 / actualWidth;
        actualHeight = imgRatio * actualHeight;
        actualWidth = 320.0;
    }
}
CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
UIGraphicsBeginImageContext(rect.size);
[image drawInRect:rect];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

What is dtype('O'), in pandas?

'O' stands for object.

#Loading a csv file as a dataframe
import pandas as pd 
train_df = pd.read_csv('train.csv')
col_name = 'Name of Employee'

#Checking the datatype of column name
train_df[col_name].dtype

#Instead try printing the same thing
print train_df[col_name].dtype

The first line returns: dtype('O')

The line with the print statement returns the following: object

Swift - Remove " character from string

Replacing for Removing is not quite logical. String.filter allows to iterate a string char by char and keep only true assertion.

Swift 4 & 5

var aString = "Optional(\"5\")"

aString = aString.filter { $0 != "\"" }

> Optional(5)

Or to extend

var aString = "Optional(\"5\")"

let filteredChars = "\"\n\t"

aString = aString.filter { filteredChars.range(of: String($0)) == nil }

> Optional(5)

How to install MySQLi on MacOS

This article is clearly explained, how to install MySqli with EachApache. This works for me too.

To install mysqli using EachApache:

  1. Login to WHM as 'root' user.

  2. Either search for "EasyApache" or go to Software > EasyApache

  3. Scroll down and select a build option (Previously Saved Config)

  4. Click Start "Start customizing based on profile"

  5. Select the version of Apache and click "Next Step".

  6. Select the version of PHP and click "Next Step".

  7. Chose additional options within the "Short Options List"

  8. Select "Exhaustive Options List" and look for "MySQL Improved extension"

  9. Click "Save and Build"

Merge 2 arrays of objects

let mergeArray = arrA.filter(aItem => !arrB.find(bItem => aItem.name === bItem.name))

postgresql - add boolean column to table set default

In psql alter column query syntax like this

Alter table users add column priv_user boolean default false ;

boolean value (true-false) save in DB like (t-f) value .

get client time zone from browser

you could use moment-timezone to guess the timezone:

> moment.tz.guess()
"America/Asuncion"

What characters are allowed in an email address?

Check for @ and . and then send an email for them to verify.

I still can't use my .name email address on 20% of the sites on the internet because someone screwed up their email validation, or because it predates the new addresses being valid.

Is it possible to decrypt SHA1

SHA1 is a cryptographic hash function, so the intention of the design was to avoid what you are trying to do.

However, breaking a SHA1 hash is technically possible. You can do so by just trying to guess what was hashed. This brute-force approach is of course not efficient, but that's pretty much the only way.

So to answer your question: yes, it is possible, but you need significant computing power. Some researchers estimate that it costs $70k - $120k.

As far as we can tell today, there is also no other way but to guess the hashed input. This is because operations such as mod eliminate information from your input. Suppose you calculate mod 5 and you get 0. What was the input? Was it 0, 5 or 500? You see, you can't really 'go back' in this case.

The entity type <type> is not part of the model for the current context

For me the issue was that I used the connection string generated by ADO.Net Model (.edmx). Changing the connection string solved my issue.

Extracting specific columns from a data frame

Using the dplyr package, if your data.frame is called df1:

library(dplyr)

df1 %>%
  select(A, B, E)

This can also be written without the %>% pipe as:

select(df1, A, B, E)

What is float in Java?

In JAVA, values like:

  1. 8.5
  2. 3.9
  3. (and so on..)

Is assumed as double and not float.

You can also perform a cast in order to solve the problem:

float b = (float) 3.5;

Another solution:

float b = 3.5f;