Programs & Examples On #Mod rewrite

URL rewriting module for the Apache web server. It is commonly used for so-called "pretty" URLs, but also provides the power and flexibility to perform various request handling tasks beyond simple substitutions.

How does RewriteBase work in .htaccess

RewriteBase is only useful in situations where you can only put a .htaccess at the root of your site. Otherwise, you may be better off placing your different .htaccess files in different directories of your site and completely omitting the RewriteBase directive.

Lately, for complex sites, I've been taking them out, because it makes deploying files from testing to live just one more step complicated.

No input file specified

Run ulimit -n 2048

And restart php/php-fpm

apache mod_rewrite is not working or not enabled

On centOS7 I changed the file /etc/httpd/conf/httpd.conf

from AllowOverride None to AllowOverride All

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

Only change the web folder permission through this command:

sudo chmod 755 -R your_folder

Force SSL/https using .htaccess and mod_rewrite

PHP Solution

Borrowing directly from Gordon's very comprehensive answer, I note that your question mentions being page-specific in forcing HTTPS/SSL connections.

function forceHTTPS(){
  $httpsURL = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
  if( count( $_POST )>0 )
    die( 'Page should be accessed with HTTPS, but a POST Submission has been sent here. Adjust the form to point to '.$httpsURL );
  if( !isset( $_SERVER['HTTPS'] ) || $_SERVER['HTTPS']!=='on' ){
    if( !headers_sent() ){
      header( "Status: 301 Moved Permanently" );
      header( "Location: $httpsURL" );
      exit();
    }else{
      die( '<script type="javascript">document.location.href="'.$httpsURL.'";</script>' );
    }
  }
}

Then, as close to the top of these pages which you want to force to connect via PHP, you can require() a centralised file containing this (and any other) custom functions, and then simply run the forceHTTPS() function.

HTACCESS / mod_rewrite Solution

I have not implemented this kind of solution personally (I have tended to use the PHP solution, like the one above, for it's simplicity), but the following may be, at least, a good start.

RewriteEngine on

# Check for POST Submission
RewriteCond %{REQUEST_METHOD} !^POST$

# Forcing HTTPS
RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{SERVER_PORT} 80
# Pages to Apply
RewriteCond %{REQUEST_URI} ^something_secure [OR]
RewriteCond %{REQUEST_URI} ^something_else_secure
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

# Forcing HTTP
RewriteCond %{HTTPS} =on [OR]
RewriteCond %{SERVER_PORT} 443
# Pages to Apply
RewriteCond %{REQUEST_URI} ^something_public [OR]
RewriteCond %{REQUEST_URI} ^something_else_public
RewriteRule .* http://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

apache redirect from non www to www

I found it easier (and more usefull) to use ServerAlias when using multiple vhosts.

<VirtualHost x.x.x.x:80>
    ServerName www.example.com
    ServerAlias example.com
    ....
</VirtualHost>

This also works with https vhosts.

Forbidden You don't have permission to access / on this server

Found my solution on Apache/2.2.15 (Unix).

And Thanks for answer from @QuantumHive:

First: I finded all

Order allow,deny
Deny from all

instead of

Order allow,deny

Allow from all

and then:

I setted

#
# Control access to UserDir directories.  The following is an example
# for a site where these directories are restricted to read-only.
#
#<Directory /var/www/html>
#    AllowOverride FileInfo AuthConfig Limit
#    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
#    <Limit GET POST OPTIONS>
#        Order allow,deny
#        Allow from all
#    </Limit>
#    <LimitExcept GET POST OPTIONS>
#        Order deny,allow
#        Deny from all
#    </LimitExcept>
#</Directory>

Remove the previous "#" annotation to

#
# Control access to UserDir directories.  The following is an example
# for a site where these directories are restricted to read-only.
#
<Directory /var/www/html>
    AllowOverride FileInfo AuthConfig Limit
    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
    <Limit GET POST OPTIONS>
        Order allow,deny
        Allow from all
    </Limit>
    <LimitExcept GET POST OPTIONS>
        Order deny,allow
        Deny from all
    </LimitExcept>
</Directory>

ps. my WebDir is: /var/www/html

URL rewriting with PHP

PHP is not what you are looking for, check out mod_rewrite

htaccess redirect to https://www

To redirect http:// or https:// to https://www you can use the following rule on all versions of apache :

RewriteEngine on

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ https://www.example.com%{REQUEST_URI} [NE,L,R]

Apache 2.4

RewriteEngine on

RewriteCond %{REQUEST_SCHEME} http [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ https://www.example.com%{REQUEST_URI} [NE,L,R]

Note that The %{REQUEST_SCHEME} variable is available for use since apache 2.4 .

Generic htaccess redirect www to non-www

If you want to do this in the httpd.conf file, you can do it without mod_rewrite (and apparently it's better for performance).

<VirtualHost *>
  ServerName www.example.com
  Redirect 301 / http://example.com/
</VirtualHost>

I got that answer here: https://serverfault.com/questions/120488/redirect-url-within-apache-virtualhost/120507#120507

How to check whether mod_rewrite is enable on server?

If this code is in your .htaccess file (without the check for mod_rewrite.c)

DirectoryIndex index.php
RewriteEngine on

RewriteCond $1 !^(index\.php|assets|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php/$1 [L,QSA]

and you can visit any page on your site with getting a 500 server error I think it's safe to say mod rewrite is switched on.

How to remove "index.php" in codeigniter's path

Perfect solution [ tested on localhost as well as on real domain ]

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L] 

.htaccess not working on localhost with XAMPP

Just had a similar issue

Resolved it by checking in httpd.conf

     # AllowOverride controls what directives may be placed in .htaccess files.
     # It can be "All", "None", or any combination of the keywords:
     #   Options FileInfo AuthConfig Limit
     #
     AllowOverride All   <--- make sure this is not set to "None"

It is worth bearing in mind I tried (from Mark's answer) the "put garbage in the .htaccess" which did give a server error - but even though it was being read, it wasn't being acted on due to no overrides allowed.

How to prevent a file from direct URL Access?

rosipov's rule works great!

I use it on live sites to display a blank or special message ;) in place of a direct access attempt to files I'd rather to protect a bit from direct view. I think it's more fun than a 403 Forbidden.

So taking rosipov's rule to redirect any direct request to {gif,jpg,js,txt} files to 'messageforcurious' :

RewriteEngine on 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?domain\.ltd [NC] 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?domain\.ltd.*$ [NC] 
RewriteRule \.(gif|jpg|js|txt)$ /messageforcurious [L]

I see it as a polite way to disallow direct acces to, say, a CMS sensible files like xml, javascript... with security in mind: To all these bots scrawling the web nowadays, I wonder what their algo will make from my 'messageforcurious'.

Header set Access-Control-Allow-Origin in .htaccess doesn't work

Be careful on:

 Header add Access-Control-Allow-Origin "*"

This is not judicious at all to grant access to everybody. It's preferable to allow a list of know trusted host only...

Header add Access-Control-Allow-Origin "http://aaa.example"
Header add Access-Control-Allow-Origin "http://bbb.example"
Header add Access-Control-Allow-Origin "http://ccc.example"

Regards,

404 Not Found The requested URL was not found on this server

For me, using OS X Catalina: Changing from AllowOverride None to AllowOverride All is the one that works.

httpd.conf is located on /etc/apache2/httpd.conf.

Env: PHP7. MySQL8.

Tips for debugging .htaccess rewrite rules

(Similar to Doin idea) To show what is being matched, I use this code

$keys = array_keys($_GET);
foreach($keys as $i=>$key){
    echo "$i => $key <br>";
}

Save it to r.php on the server root and then do some tests in .htaccess
For example, i want to match urls that do not start with a language prefix

RewriteRule ^(?!(en|de)/)(.*)$ /r.php?$1&$2 [L] #$1&$2&...
RewriteRule ^(.*)$ /r.php?nomatch [L] #report nomatch and exit

How to enable mod_rewrite for Apache 2.2

For my situation, I had

RewriteEngine On

in my .htaccess, along with the module being loaded, and it was not working.

The solution to my problem was to edit my vhost entry to inlcude

AllowOverride all

in the <Directory> section for the site in question.

How to debug .htaccess RewriteRule not working

If you have access to apache bin directory you can use,

httpd -M to check loaded modules first.

 info_module (shared)
 isapi_module (shared)
 log_config_module (shared)
 cache_disk_module (shared)
 mime_module (shared)
 negotiation_module (shared)
 proxy_module (shared)
 proxy_ajp_module (shared)
 rewrite_module (shared)
 setenvif_module (shared)
 socache_shmcb_module (shared)
 ssl_module (shared)
 status_module (shared)
 version_module (shared)
 php5_module (shared)

After that simple directives like Options -Indexes or deny from all will solidify that .htaccess are working correctly.

How do you enable mod_rewrite on any OS?

Nope, mod_rewrite is an Apache module and has nothing to do with PHP.

To activate the module, the following line in httpd.conf needs to be active:

LoadModule rewrite_module modules/mod_rewrite.so

to see whether it is already active, try putting a .htaccess file into a web directory containing the line

RewriteEngine on

if this works without throwing a 500 internal server error, and the .htaccess file gets parsed, URL rewriting works.

.htaccess rewrite to redirect root URL to subdirectory

This seemed the simplest solution:

RewriteEngine on
RewriteCond %{REQUEST_URI} ^/$
RewriteRule (.*) http://www.example.com/store [R=301,L]

I was getting redirect loops with some of the other solutions.

.htaccess redirect all pages to new domain

If the new domain you are redirecting your old site to is on a diffrent host, you can simply use a Redirect

Redirect 301 / http://newdomain.com

This will redirect all requests from olddomain to the newdomain .

Redirect directive will not work or may cause a Redirect loop if your newdomain and olddomain both are on same host, in that case you'll need to use mod-rewrite to redirect based on the requested host header.

RewriteEngine on


RewriteCond %{HTTP_HOST} ^(www\.)?olddomain\.com$
RewriteRule ^ http://newdomain.com%{REQUEST_URI} [NE,L,R] 

How to use .htaccess in WAMP Server?

Open the httpd.conf file and search for

"rewrite"

, then remove

"#"

at the starting of the line,so the line looks like.

LoadModule rewrite_module modules/mod_rewrite.so

then restart the wamp.

htaccess remove index.php from url

Some may get a 403 with the method listed above using mod_rewrite. Another solution to rewite index.php out is as follows:

<IfModule mod_rewrite.c> 

RewriteEngine On

# Put your installation directory here:
RewriteBase /

# Do not enable rewriting for files or directories that exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]

</IfModule> 

How to debug Apache mod_rewrite

Based on Ben's answer you you could do the following when running apache on Linux (Debian in my case).

First create the file rewrite-log.load

/etc/apache2/mods-availabe/rewrite-log.load

RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 3

Then enter

$ a2enmod rewrite-log

followed by

$ service apache2 restart

And when you finished with debuging your rewrite rules

$ a2dismod rewrite-log && service apache2 restart

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

I had the same issue when I changed the home directory of one use. In my case it was because of selinux. I used the below to fix the issue:

selinuxenabled 0
setenforce 0

.htaccess - how to force "www." in a generic way?

This is an older question, and there are many different ways to do this. The most complete answer, IMHO, is found here: https://gist.github.com/vielhuber/f2c6bdd1ed9024023fe4 . (Pasting and formatting the code here didn't work for me)

Htaccess: add/remove trailing slash from URL

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
## hide .html extension
# To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+).html
RewriteRule ^ %1 [R=301,L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)/\s
RewriteRule ^ %1 [R=301,L]

## To internally redirect /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^\.]+)$ $1.html [L]


<Files ~"^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</Files>

This removes html code or php if you supplement it. Allows you to add trailing slash and it come up as well as the url without the trailing slash all bypassing the 404 code. Plus a little added security.

how to use "AND", "OR" for RewriteCond on Apache?

After many struggles and to achive a general, flexible and more readable solution, in my case I ended up saving the ORs results into ENV variables and doing the ANDs of those variables.

# RESULT_ONE = A OR B
RewriteRule ^ - [E=RESULT_ONE:False]
RewriteCond ...A... [OR]
RewriteCond ...B...
RewriteRule ^ - [E=RESULT_ONE:True]

# RESULT_TWO = C OR D
RewriteRule ^ - [E=RESULT_TWO:False]
RewriteCond ...C... [OR]
RewriteCond ...D...
RewriteRule ^ - [E=RESULT_TWO:True]

# if ( RESULT_ONE AND RESULT_TWO ) then ( RewriteRule ...something... )
RewriteCond %{ENV:RESULT_ONE} =True
RewriteCond %{ENV:RESULT_TWO} =True
RewriteRule ...something...

Requirements:

How to check if mod_rewrite is enabled in php?

For IIS heros and heroins:

No need to look for mod_rewrite. Just install Rewrite 2 module and then import .htaccess files.

.htaccess mod_rewrite - how to exclude directory from rewrite rule

Try this rule before your other rules:

RewriteRule ^(admin|user)($|/) - [L]

This will end the rewriting process.

Redirect all to index.php using htaccess

Silly answer but if you can't figure out why its not redirecting check that the following is enabled for the web folder ..

AllowOverride All

This will enable you to run htaccess which must be running! (there are alternatives but not on will cause problems https://httpd.apache.org/docs/2.4/mod/core.html#allowoverride)

Input button target="_blank" isn't causing the link to load in a new window/tab

Just use the javascript window.open function with the second parameter at "_blank"

<button onClick="javascript:window.open('http://www.facebook.com', '_blank');">facebook</button>

jQuery: value.attr is not a function

The second parameter of the callback function passed to each() will contain the actual DOM element and not a jQuery wrapper object. You can call the getAttribute() method of the element:

$('#category_sorting_form_save').click(function() {
    var elements = $("#category_sorting_elements > div");
    $.each(elements, function(key, value) {
        console.info(key, ": ", value);
        console.info("cat_id: ", value.getAttribute('cat_id'));
    });
});

Or wrap the element in a jQuery object yourself:

$('#category_sorting_form_save').click(function() {
    var elements = $("#category_sorting_elements > div");
    $.each(elements, function(key, value) {
        console.info(key, ": ", value);
        console.info("cat_id: ", $(value).attr('cat_id'));
    });
});

Or simply use $(this):

$('#category_sorting_form_save').click(function() {
    var elements = $("#category_sorting_elements > div");
    $.each(elements, function() {
        console.info("cat_id: ", $(this).attr('cat_id'));
    });
});

Partition Function COUNT() OVER possible using DISTINCT

Necromancing:

It's relativiely simple to emulate a COUNT DISTINCT over PARTITION BY with MAX via DENSE_RANK:

;WITH baseTable AS
(
    SELECT 'RM1' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM1' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR2' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR2' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR3' AS ADR
    UNION ALL SELECT 'RM3' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM3' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM3' AS RM, 'ADR2' AS ADR
)
,CTE AS
(
    SELECT RM, ADR, DENSE_RANK() OVER(PARTITION BY RM ORDER BY ADR) AS dr 
    FROM baseTable
)
SELECT
     RM
    ,ADR

    ,COUNT(CTE.ADR) OVER (PARTITION BY CTE.RM ORDER BY ADR) AS cnt1 
    ,COUNT(CTE.ADR) OVER (PARTITION BY CTE.RM) AS cnt2 
    -- Not supported
    --,COUNT(DISTINCT CTE.ADR) OVER (PARTITION BY CTE.RM ORDER BY CTE.ADR) AS cntDist
    ,MAX(CTE.dr) OVER (PARTITION BY CTE.RM ORDER BY CTE.RM) AS cntDistEmu 
FROM CTE

Note:
This assumes the fields in question are NON-nullable fields.
If there is one or more NULL-entries in the fields, you need to subtract 1.

Get the _id of inserted document in Mongo database in NodeJS

A shorter way than using second parameter for the callback of collection.insert would be using objectToInsert._id that returns the _id (inside of the callback function, supposing it was a successful operation).

The Mongo driver for NodeJS appends the _id field to the original object reference, so it's easy to get the inserted id using the original object:

collection.insert(objectToInsert, function(err){
   if (err) return;
   // Object inserted successfully.
   var objectId = objectToInsert._id; // this will return the id of object inserted
});

Why is it common to put CSRF prevention tokens in cookies?

Using a cookie to provide the CSRF token to the client does not allow a successful attack because the attacker cannot read the value of the cookie and therefore cannot put it where the server-side CSRF validation requires it to be.

The attacker will be able to cause a request to the server with both the auth token cookie and the CSRF cookie in the request headers. But the server is not looking for the CSRF token as a cookie in the request headers, it's looking in the payload of the request. And even if the attacker knows where to put the CSRF token in the payload, they would have to read its value to put it there. But the browser's cross-origin policy prevents reading any cookie value from the target website.

The same logic does not apply to the auth token cookie, because the server is expects it in the request headers and the attacker does not have to do anything special to put it there.

How to change Screen buffer size in Windows Command Prompt from batch script

I'm expanding upon a comment that I posted here as most people won't notice the comment.

https://lifeboat.com/programs/console.exe is a compiled version of the Visual Basic program described at https://stackoverflow.com/a/4694566/1752929. My version simply sets the buffer height to 32766 which is the maximum buffer height available. It does not adjust anything else. If there is a lot of demand, I could create a more flexible program but generally you can just set other variables in your shortcut layout tab.

Following is the target I use in my shortcut where I wish to start in the f directory. (I have to set the directory this way as Windows won't let you set it any other way if you wish to run the command prompt as administrator.)

C:\Windows\System32\cmd.exe /k "console & cd /d c:\f"

How can I change the image of an ImageView?

If you created imageview using xml file then follow the steps.

Solution 1:

Step 1: Create an XML file

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="#cc8181"
  >

  <ImageView
      android:id="@+id/image"
      android:layout_width="50dip"
      android:layout_height="fill_parent" 
      android:src="@drawable/icon"
      android:layout_marginLeft="3dip"
      android:scaleType="center"/>

</LinearLayout>

Step 2: create an Activity

ImageView img= (ImageView) findViewById(R.id.image);
img.setImageResource(R.drawable.my_image);

Solution 2:

If you created imageview from Java Class

ImageView img = new ImageView(this);
img.setImageResource(R.drawable.my_image);

Failed to build gem native extension — Rails install

sudo apt-get install ruby-dev

worked for me

Getting the WordPress Post ID of current post

you can use $post->ID for current id.

Trying to check if username already exists in MySQL database using PHP

change your query to like.

$username = mysql_real_escape_string($username); // escape string before passing it to query.
$query = mysql_query("SELECT username FROM Users WHERE username='".$username."'");

However, MySQL is deprecated. You should instead use MySQLi or PDO

Why is there no xrange function in Python3?

One way to fix up your python2 code is:

import sys

if sys.version_info >= (3, 0):
    def xrange(*args, **kwargs):
        return iter(range(*args, **kwargs))

Git push rejected after feature branch rebase

The problem is that git push assumes that remote branch can be fast-forwarded to your local branch, that is that all the difference between local and remote branches is in local having some new commits at the end like that:

Z--X--R         <- origin/some-branch (can be fast-forwarded to Y commit)
       \        
        T--Y    <- some-branch

When you perform git rebase commits D and E are applied to new base and new commits are created. That means after rebase you have something like that:

A--B--C------F--G--D'--E'   <- feature-branch
       \  
        D--E                <- origin/feature-branch

In that situation remote branch can't be fast-forwarded to local. Though, theoretically local branch can be merged into remote (obviously you don't need it in that case), but as git push performs only fast-forward merges it throws and error.

And what --force option does is just ignoring state of remote branch and setting it to the commit you're pushing into it. So git push --force origin feature-branch simply overrides origin/feature-branch with local feature-branch.

In my opinion, rebasing feature branches on master and force-pushing them back to remote repository is OK as long as you're the only one who works on that branch.

Android Studio doesn't see device

Check device driver if your device is Galaxy install Kise will search your driver

submit form on click event using jquery

it's because the name of the submit button is named "submit", change it to anything but "submit", try "submitme" and retry it. It should then work.

How to perform a real time search and filter on a HTML table

i have an jquery plugin for this. It uses jquery-ui also. You can see an example here http://jsfiddle.net/tugrulorhan/fd8KB/1/

$("#searchContainer").gridSearch({
            primaryAction: "search",
            scrollDuration: 0,
            searchBarAtBottom: false,
            customScrollHeight: -35,
            visible: {
                before: true,
                next: true,
                filter: true,
                unfilter: true
            },
            textVisible: {
                before: true,
                next: true,
                filter: true,
                unfilter: true
            },
            minCount: 2
        });

How to get memory usage at runtime using C++?

The existing answers are better for how to get the correct value, but I can at least explain why getrusage isn't working for you.

man 2 getrusage:

The above struct [rusage] was taken from BSD 4.3 Reno. Not all fields are meaningful under Linux. Right now (Linux 2.4, 2.6) only the fields ru_utime, ru_stime, ru_minflt, ru_majflt, and ru_nswap are maintained.

error C4996: 'scanf': This function or variable may be unsafe in c programming

Another way to suppress the error: Add this line at the top in C/C++ file:

#define _CRT_SECURE_NO_WARNINGS

How to make a window always stay on top in .Net?

Set the form's .TopMost property to true.

You probably don't want to leave it this way all the time: set it when your external process starts and put it back when it finishes.

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

You can give yourself permissions to fix this problem.

Right click on cacerts > choose properties > select Securit tab > Allow all permissions to all the Group and user names.

This worked for me.

Text blinking jQuery

You can try the jQuery UI Pulsate effect:

http://docs.jquery.com/UI/Effects/Pulsate

Maintain model of scope when changing between views in AngularJS

An alternative to services is to use the value store.

In the base of my app I added this

var agentApp = angular.module('rbAgent', ['ui.router', 'rbApp.tryGoal', 'rbApp.tryGoal.service', 'ui.bootstrap']);

agentApp.value('agentMemory',
    {
        contextId: '',
        sessionId: ''
    }
);
...

And then in my controller I just reference the value store. I don't think it holds thing if the user closes the browser.

angular.module('rbAgent')
.controller('AgentGoalListController', ['agentMemory', '$scope', '$rootScope', 'config', '$state', function(agentMemory, $scope, $rootScope, config, $state){

$scope.config = config;
$scope.contextId = agentMemory.contextId;
...

What's the difference between an Angular component and module

Component is the template(view) + a class (Typescript code) containing some logic for the view + metadata(to tell angular about from where to get data it needs to display the template).

Modules basically group the related components, services together so that you can have chunks of functionality which can then run independently. For example, an app can have modules for features, for grouping components for a particular feature of your app, such as a dashboard, which you can simply grab and use inside another application.

Could not load file or assembly Exception from HRESULT: 0x80131040

I have issue with itextsharp and itextsharp.xmlworker dlls for exception-from-hresult-0x80131040 so I have removed those both dlls from references and downloaded new dlls directly from nuget packages, which resolved my issue.

May be this method can be useful to resolved the issue to other people.

How can I run a windows batch file but hide the command window?

1,Download the bat to exe converter and install it 2,Run the bat to exe application 3,Download .pco images if you want to make good looking exe 4,specify the bat file location(c:\my.bat) 5,Specify the location for saving the exe(ex:c:/my.exe) 6,Select Version Information Tab 7,Choose the icon file (downloaded .pco image) 8,if you want fill the information like version,comapny name etc 9,change the tab to option 10,Select the invisible application(This will hide the command prompt while running the application) 11,Choose 32 bit(if you select 64 bit exe will work only in 32 bit OS) 12,Compile 13,Copy the exe to the location where bat file executed properly 14,Run the exe

What's the better (cleaner) way to ignore output in PowerShell?

I just did some tests of the four options that I know about.

Measure-Command {$(1..1000) | Out-Null}

TotalMilliseconds : 76.211

Measure-Command {[Void]$(1..1000)}

TotalMilliseconds : 0.217

Measure-Command {$(1..1000) > $null}

TotalMilliseconds : 0.2478

Measure-Command {$null = $(1..1000)}

TotalMilliseconds : 0.2122

## Control, times vary from 0.21 to 0.24
Measure-Command {$(1..1000)}

TotalMilliseconds : 0.2141

So I would suggest that you use anything but Out-Null due to overhead. The next important thing, to me, would be readability. I kind of like redirecting to $null and setting equal to $null myself. I use to prefer casting to [Void], but that may not be as understandable when glancing at code or for new users.

I guess I slightly prefer redirecting output to $null.

Do-Something > $null

Edit

After stej's comment again, I decided to do some more tests with pipelines to better isolate the overhead of trashing the output.

Here are some tests with a simple 1000 object pipeline.

## Control Pipeline
Measure-Command {$(1..1000) | ?{$_ -is [int]}}

TotalMilliseconds : 119.3823

## Out-Null
Measure-Command {$(1..1000) | ?{$_ -is [int]} | Out-Null}

TotalMilliseconds : 190.2193

## Redirect to $null
Measure-Command {$(1..1000) | ?{$_ -is [int]} > $null}

TotalMilliseconds : 119.7923

In this case, Out-Null has about a 60% overhead and > $null has about a 0.3% overhead.

Addendum 2017-10-16: I originally overlooked another option with Out-Null, the use of the -inputObject parameter. Using this the overhead seems to disappear, however the syntax is different:

Out-Null -inputObject ($(1..1000) | ?{$_ -is [int]})

And now for some tests with a simple 100 object pipeline.

## Control Pipeline
Measure-Command {$(1..100) | ?{$_ -is [int]}}

TotalMilliseconds : 12.3566

## Out-Null
Measure-Command {$(1..100) | ?{$_ -is [int]} | Out-Null}

TotalMilliseconds : 19.7357

## Redirect to $null
Measure-Command {$(1..1000) | ?{$_ -is [int]} > $null}

TotalMilliseconds : 12.8527

Here again Out-Null has about a 60% overhead. While > $null has an overhead of about 4%. The numbers here varied a bit from test to test (I ran each about 5 times and picked the middle ground). But I think it shows a clear reason to not use Out-Null.

Difference between static and shared libraries?

-------------------------------------------------------------------------
|  +-  |    Shared(dynamic)       |   Static Library (Linkages)         |
-------------------------------------------------------------------------
|Pros: | less memory use          |   an executable, using own libraries|
|      |                          |     ,coming with the program,       |
|      |                          |   doesn't need to worry about its   |
|      |                          |   compilebility subject to libraries|
-------------------------------------------------------------------------
|Cons: | implementations of       |   bigger memory uses                |
|      | libraries may be altered |                                     |
|      | subject to OS  and its   |                                     |
|      | version, which may affect|                                     |
|      | the compilebility and    |                                     |
|      | runnability of the code  |                                     |
-------------------------------------------------------------------------

How can I display a tooltip on an HTML "option" tag?

I don't think this would be possible to do across all browsers.

W3Schools reports that the option events exist in all browsers, but after setting up this test demo. I can only get it to work for Firefox (not Chrome or IE), I haven't tested it on other browsers.

Firefox also allows mouseenter and mouseleave but this is not reported on the w3schools page.


Update: Honestly, from looking at the example code you provided, I wouldn't even use a select box. I think it would look nicer with a slider. I've updated your demo. I had to make a few minor changes to your ratings object (adding a level number) and the safesurf tab. But I left pretty much everything else intact.

How do I get multiple subplots in matplotlib?

Iterating through all subplots sequentially:

fig, axes = plt.subplots(nrows, ncols)

for ax in axes.flatten():
    ax.plot(x,y)

Accessing a specific index:

for row in range(nrows):
    for col in range(ncols):
        axes[row,col].plot(x[row], y[col])

jQuery UI Dialog window loaded within AJAX style jQuery UI Tabs

curious - why doesn't the 'nothing easier than this' answer (above) not work? it looks logical? http://206.251.38.181/jquery-learn/ajax/iframe.html

Get href attribute on jQuery

var a_href = $('div.cpt').find('h2 a').attr('href');

should be

var a_href = $(this).find('div.cpt').find('h2 a').attr('href');

In the first line, your query searches the entire document. In the second, the query starts from your tr element and only gets the element underneath it. (You can combine the finds if you like, I left them separate to illustrate the point.)

How do I format a date as ISO 8601 in moment.js?

moment().toISOString(); // or format() - see below

http://momentjs.com/docs/#/displaying/as-iso-string/

Update Based on the answer: by @sennet and the comment by @dvlsg (see Fiddle) it should be noted that there is a difference between format and toISOString. Both are correct but the underlying process differs. toISOString converts to a Date object, sets to UTC then uses the native Date prototype function to output ISO8601 in UTC with milliseconds (YYYY-MM-DD[T]HH:mm:ss.SSS[Z]). On the other hand, format uses the default format (YYYY-MM-DDTHH:mm:ssZ) without milliseconds and maintains the timezone offset.

I've opened an issue as I think it can lead to unexpected results.

Creating a BLOB from a Base64 string in JavaScript

For image data, I find it simpler to use canvas.toBlob (asynchronous)

function b64toBlob(b64, onsuccess, onerror) {
    var img = new Image();

    img.onerror = onerror;

    img.onload = function onload() {
        var canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;

        var ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

        canvas.toBlob(onsuccess);
    };

    img.src = b64;
}

var base64Data = 'data:image/jpg;base64,/9j/4AAQSkZJRgABAQA...';
b64toBlob(base64Data,
    function(blob) {
        var url = window.URL.createObjectURL(blob);
        // do something with url
    }, function(error) {
        // handle error
    });

C function that counts lines in file

while(!feof(fp))
{
  ch = fgetc(fp);
  if(ch == '\n')
  {
    lines++;
  }
}

But please note: Why is “while ( !feof (file) )” always wrong?.

What's the difference between an argument and a parameter?

Oracle's Java tutorials define this distinction thusly: "Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order."

A more detailed discussion of parameters and arguments: https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html

How to compile multiple java source files in command line

OR you could just use javac file1.java and then also use javac file2.java afterwards.

How do I use a compound drawable instead of a LinearLayout that contains an ImageView and a TextView

if for some reason you need to add via code, you can use this:

mTextView.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);

where left, top, right bottom are Drawables

Draw text in OpenGL ES

Look at the "Sprite Text" sample in the GLSurfaceView samples.

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

nothing new but still want to share my method:

+(NSString*) getDateStringFromSrcFormat:(NSString *) srcFormat destFormat:(NSString *)
destFormat scrString:(NSString *) srcString
{
    NSString *dateString = srcString;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //[dateFormatter setDateFormat:@"MM-dd-yyyy"];
    [dateFormatter setDateFormat:srcFormat];
    NSDate *date = [dateFormatter dateFromString:dateString];

    // Convert date object into desired format
    //[dateFormatter setDateFormat:@"yyyy-MM-dd"];
    [dateFormatter setDateFormat:destFormat];
    NSString *newDateString = [dateFormatter stringFromDate:date];
    return newDateString;
}

How to overcome root domain CNAME restrictions?

Sipwiz is correct the only way to do this properly is the HTTP and DNS hybrid approach. My registrar is a re-seller for Tucows and they offer root domain forwarding as a free value added service.

If your domain is blah.com they will ask you where you would like the domain forwarded to, and you type in www.blah.com. They assign the A record to their apache server and automaticly add blah.com as a DNS vhost. The vhost responds with an HTTP 302 error redirecting them to the proper URL. It's simple to script/setup and can be handled by low end would otherwise be scrapped hardware.

Run the following command for an example: curl -v eclecticengineers.com

Importing csv file into R - numeric values read as characters

If you're dealing with large datasets (i.e. datasets with a high number of columns), the solution noted above can be manually cumbersome, and requires you to know which columns are numeric a priori.

Try this instead.

char_data <- read.csv(input_filename, stringsAsFactors = F)
num_data <- data.frame(data.matrix(char_data))
numeric_columns <- sapply(num_data,function(x){mean(as.numeric(is.na(x)))<0.5})
final_data <- data.frame(num_data[,numeric_columns], char_data[,!numeric_columns])

The code does the following:

  1. Imports your data as character columns.
  2. Creates an instance of your data as numeric columns.
  3. Identifies which columns from your data are numeric (assuming columns with less than 50% NAs upon converting your data to numeric are indeed numeric).
  4. Merging the numeric and character columns into a final dataset.

This essentially automates the import of your .csv file by preserving the data types of the original columns (as character and numeric).

What are the differences between a pointer variable and a reference variable in C++?

There is one fundamental difference between pointers and references that I didn't see anyone had mentioned: references enable pass-by-reference semantics in function arguments. Pointers, although it is not visible at first do not: they only provide pass-by-value semantics. This has been very nicely described in this article.

Regards, &rzej

Maven: Failed to retrieve plugin descriptor error

Mac OSX 10.7.5: I tried setting my proxy in the settings.xml file (as mentioned by posters above) in the /conf directory and also in the ~/.m2 directory, but still I got this error. I downloaded the latest version of Maven (3.1.1), and set my PATH variable to reflect the latest install, and it worked for me right off the shelf without any error.

Dynamically update values of a chartjs chart

Here is how to do it in the last version of ChartJs:

setInterval(function(){
    chart.data.datasets[0].data[5] = 80;
    chart.data.labels[5] = "Newly Added";
    chart.update();
}

Look at this clear video

or test it in jsfiddle

How to sparsely checkout only one single file from a git repository?

If you have edited a local version of a file and wish to revert to the original version maintained on the central server, this can be easily achieved using Git Extensions.

  • Initially the file will be marked for commit, since it has been modified
  • Select (double click) the file in the file tree menu
  • The revision tree for the single file is listed.
  • Select the top/HEAD of the tree and right click save as
  • Save the file to overwrite the modified local version of the file
  • The file now has the correct version and will no longer be marked for commit!

Easy!

How do I add 1 day to an NSDate?

Swift 4.0 (same as Swift 3.0 in this wonderful answer just making it clear for rookies like me)

let today = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: today)

Vue.JS: How to call function after page loaded?

// vue js provides us `mounted()`. this means `onload` in javascript.

mounted () {
  // we can implement any method here like
   sampleFun () {
      // this is the sample method you can implement whatever you want
   }
}

npm install gives error "can't find a package.json file"

In my case there was mistake in my package.json:

npm ERR! package.json must be actual JSON, not just JavaScript.

Creating a BAT file for python script

Open a command line (? Win+R, cmd, ? Enter) and type python -V, ? Enter.

You should get a response back, something like Python 2.7.1.

If you do not, you may not have Python installed. Fix this first.

Once you have Python, your batch file should look like

@echo off
python c:\somescript.py %*
pause

This will keep the command window open after the script finishes, so you can see any errors or messages. Once you are happy with it you can remove the 'pause' line and the command window will close automatically when finished.

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

The accepted answer is fabulous in explaining the history. I find this table explain it very well from official doc on 'how CMD and ENTRYPOINT interact': enter image description here

Bootstrap 4 card-deck with number of columns based on viewport

This answer is for those who are using Bootstrap 4.1+ and for those who care about IE 11 as well

Card-deck does not adapt the number visible of cards according to the viewport size.

Above methods work but do not support IE. With the below method, you can achieve similar functionality and responsive cards.

You can manage the number of cards to show/hide in different breakpoints.

In Bootstrap 4.1+ columns are same height by default, just make sure your card/content uses all available space. Run the snippet, you'll understand

_x000D_
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
    <div class="row">_x000D_
        <div class="col-sm-6 col-lg-4 mb-3">_x000D_
            <div class="card mb-3 h-100">_x000D_
_x000D_
                <div class="card-body">_x000D_
                    <h5 class="card-title">Card title</h5>_x000D_
                    <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
                    <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="col-sm-6 col-lg-4 mb-3">_x000D_
            <div class="card mb-3 h-100">_x000D_
                <div class="card-body">_x000D_
                    <h5 class="card-title">Card title</h5>_x000D_
                    <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
                    <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="col-sm-6 col-lg-4 mb-3">_x000D_
            <div class="card mb-3 h-100">_x000D_
                <div class="card-body">_x000D_
                    <h5 class="card-title">Card title</h5>_x000D_
                    <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
                    <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jQuery: Check if div with certain class name exists

$('div').hasClass('mydivclass')// Returns true if the class exist.

Remote branch is not showing up in "git branch -r"

I had the same issue. It seems the easiest solution is to just remove the remote, readd it, and fetch.

How can I remove the decimal part from JavaScript number?

If you don't care about rouding, just convert the number to a string, then remove everything after the period including the period. This works whether there is a decimal or not.

const sEpoch = ((+new Date()) / 1000).toString();
const formattedEpoch = sEpoch.split('.')[0];

Meaning of $? (dollar question mark) in shell scripts

Minimal POSIX C exit status example

To understand $?, you must first understand the concept of process exit status which is defined by POSIX. In Linux:

  • when a process calls the exit system call, the kernel stores the value passed to the system call (an int) even after the process dies.

    The exit system call is called by the exit() ANSI C function, and indirectly when you do return from main.

  • the process that called the exiting child process (Bash), often with fork + exec, can retrieve the exit status of the child with the wait system call

Consider the Bash code:

$ false
$ echo $?
1

The C "equivalent" is:

false.c

#include <stdlib.h> /* exit */

int main(void) {
    exit(1);
}

bash.c

#include <unistd.h> /* execl */
#include <stdlib.h> /* fork */
#include <sys/wait.h> /* wait, WEXITSTATUS */
#include <stdio.h> /* printf */

int main(void) {
    if (fork() == 0) {
        /* Call false. */
        execl("./false", "./false", (char *)NULL);
    }
    int status;
    /* Wait for a child to finish. */
    wait(&status);
    /* Status encodes multiple fields,
     * we need WEXITSTATUS to get the exit status:
     * http://stackoverflow.com/questions/3659616/returning-exit-code-from-child
     **/
    printf("$? = %d\n", WEXITSTATUS(status));
}

Compile and run:

g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o bash bash.c
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o false false.c
./bash

Output:

$? = 1

In Bash, when you hit enter, a fork + exec + wait happens like above, and bash then sets $? to the exit status of the forked process.

Note: for built-in commands like echo, a process need not be spawned, and Bash just sets $? to 0 to simulate an external process.

Standards and documentation

POSIX 7 2.5.2 "Special Parameters" http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_05_02 :

? Expands to the decimal exit status of the most recent pipeline (see Pipelines).

man bash "Special Parameters":

The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed. [...]

? Expands to the exit status of the most recently executed foreground pipeline.

ANSI C and POSIX then recommend that:

  • 0 means the program was successful

  • other values: the program failed somehow.

    The exact value could indicate the type of failure.

    ANSI C does not define the meaning of any vaues, and POSIX specifies values larger than 125: What is the meaning of "POSIX"?

Bash uses exit status for if

In Bash, we often use the exit status $? implicitly to control if statements as in:

if true; then
  :
fi

where true is a program that just returns 0.

The above is equivalent to:

true
result=$?
if [ $result = 0 ]; then
  :
fi

And in:

if [ 1 = 1 ]; then
  :
fi

[ is just an program with a weird name (and Bash built-in that behaves like it), and 1 = 1 ] its arguments, see also: Difference between single and double square brackets in Bash

NSArray + remove item from array

As others suggested, NSMutableArray has methods to do so but sometimes you are forced to use NSArray, I'd use:

NSArray* newArray = [oldArray subarrayWithRange:NSMakeRange(1, [oldArray count] - 1)];

This way, the oldArray stays as it was but a newArray will be created with the first item removed.

Is there a way to rollback my last push to Git?

Since you are the only user:

git reset --hard HEAD@{1}
git push -f
git reset --hard HEAD@{1}

( basically, go back one commit, force push to the repo, then go back again - remove the last step if you don't care about the commit )

Without doing any changes to your local repo, you can also do something like:

git push -f origin <sha_of_previous_commit>:master

Generally, in published repos, it is safer to do git revert and then git push

How to use org.apache.commons package?

You are supposed to download the jar files that contain these libraries. Libraries may be used by adding them to the classpath.

For Commons Net you need to download the binary files from Commons Net download page. Then you have to extract the file and add the commons-net-2-2.jar file to some location where you can access it from your application e.g. to /lib.

If you're running your application from the command-line you'll have to define the classpath in the java command: java -cp .;lib/commons-net-2-2.jar myapp. More info about how to set the classpath can be found from Oracle documentation. You must specify all directories and jar files you'll need in the classpath excluding those implicitely provided by the Java runtime. Notice that there is '.' in the classpath, it is used to include the current directory in case your compiled class is located in the current directory.

For more advanced reading, you might want to read about how to define the classpath for your own jar files, or the directory structure of a war file when you're creating a web application.

If you are using an IDE, such as Eclipse, you have to remember to add the library to your build path before the IDE will recognize it and allow you to use the library.

Git error on git pull (unable to update local ref)

Speaking from a PC user - Reboot.

Honestly, it worked for me. I've solved two strange git issues I thought were corruptions this way.

What is the difference between a field and a property?

Properties expose fields. Fields should (almost always) be kept private to a class and accessed via get and set properties. Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class.

public class MyClass
{
    // this is a field.  It is private to your class and stores the actual data.
    private string _myField;

    // this is a property. When accessed it uses the underlying field,
    // but only exposes the contract, which will not be affected by the underlying field
    public string MyProperty
    {
        get
        {
            return _myField;
        }
        set
        {
            _myField = value;
        }
    }

    // This is an AutoProperty (C# 3.0 and higher) - which is a shorthand syntax
    // used to generate a private field for you
    public int AnotherProperty { get; set; } 
}

@Kent points out that Properties are not required to encapsulate fields, they could do a calculation on other fields, or serve other purposes.

@GSS points out that you can also do other logic, such as validation, when a property is accessed, another useful feature.

In Android, how do I set margins in dp programmatically?

You should use LayoutParams to set your button margins:

LayoutParams params = new LayoutParams(
        LayoutParams.WRAP_CONTENT,      
        LayoutParams.WRAP_CONTENT
);
params.setMargins(left, top, right, bottom);
yourbutton.setLayoutParams(params);

Depending on what layout you're using you should use RelativeLayout.LayoutParams or LinearLayout.LayoutParams.

And to convert your dp measure to pixel, try this:

Resources r = mContext.getResources();
int px = (int) TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP,
        yourdpmeasure, 
        r.getDisplayMetrics()
);

Javascript Get Element by Id and set the value

<html>
<head>
<script>
function updateTextarea(element)
{
document.getElementById(element).innerText = document.getElementById("ment").value;
}
</script>
</head>
<body>

<input type="text" value="Enter your text here." id = "ment" style = " border: 1px solid grey; margin-bottom: 4px;"  

onKeyUp="updateTextarea('myDiv')" />

<br>

<textarea id="myDiv" ></textarea>

</body>
</html>

How to send email to multiple address using System.Net.Mail

 string[] MultiEmails = email.Split(',');
 foreach (string ToEmail in MultiEmails)
 {
    message.To.Add(new MailAddress(ToEmail)); //adding multiple email addresses
 }

Attach a body onload event with JS

This takes advantage of DOMContentLoaded - which fires before onload - but allows you to stick in all your unobtrusiveness...

window.onload - Dean Edwards - The blog post talks more about it - and here is the complete code copied from the comments of that same blog.

// Dean Edwards/Matthias Miller/John Resig

function init() {
  // quit if this function has already been called
  if (arguments.callee.done) return;

  // flag this function so we don't do the same thing twice
  arguments.callee.done = true;

  // kill the timer
  if (_timer) clearInterval(_timer);

  // do stuff
};

/* for Mozilla/Opera9 */
if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
  document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
  var script = document.getElementById("__ie_onload");
  script.onreadystatechange = function() {
    if (this.readyState == "complete") {
      init(); // call the onload handler
    }
  };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
  var _timer = setInterval(function() {
    if (/loaded|complete/.test(document.readyState)) {
      init(); // call the onload handler
    }
  }, 10);
}

/* for other browsers */
window.onload = init;

Create a new cmd.exe window from within another cmd.exe prompt

start cmd.exe 

opens a separate window

start file.cmd 

opens the batch file and executes it in another command prompt

undefined reference to `std::ios_base::Init::Init()'

Most of these linker errors occur because of missing libraries.

I added the libstdc++.6.dylib in my Project->Targets->Build Phases-> Link Binary With Libraries.

That solved it for me on Xcode 6.3.2 for iOS 8.3

Cheers!

DateTime "null" value

DateTime? MyDateTime{get;set;}

MyDateTime = (dr["f1"] == DBNull.Value) ? (DateTime?)null : ((DateTime)dr["f1"]);

Find the most popular element in int[] array

I hope this helps. public class Ideone { public static void main(String[] args) throws java.lang.Exception {

    int[] a = {1,2,3,4,5,6,7,7,7};
    int len = a.length;

    System.out.println(len);


    for (int i = 0; i <= len - 1; i++) {

        while (a[i] == a[i + 1]) {
            System.out.println(a[i]);

            break;
        }


    }


}

}

Installing python module within code

This should work:

import subprocess

def install(name):
    subprocess.call(['pip', 'install', name])

XAMPP Apache won't start

It's simple if you guys have and use your skype ports turn them ports off from the skype settings->Connections and unmark the port like where it sez ports 80 till 443.

Problem Solved!!!

ReferenceError: document is not defined (in plain JavaScript)

This happened with me because I was using Next JS which has server side rendering. When you are using server side rendering there is no browser. Hence, there will not be any variable window or document. Hence this error shows up.

Work around :

If you are using Next JS you can use the dynamic rendering to prevent server side rendering for the component.

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(() => import('../components/List'), {
  ssr: false
})

export default () => <DynamicComponentWithNoSSR />

If you are using any other server side rendering library. Then add the code that you want to run at the client side in componentDidMount. If you are using React Hooks then use useEffects in the place of componentsDidMount.

import React, {useState, useEffects} from 'react';

const DynamicComponentWithNoSSR = <>Some JSX</>

export default function App(){

[a,setA] = useState();
useEffect(() => {
    setA(<DynamicComponentWithNoSSR/>)
  });


return (<>{a}<>)
}

References :

  1. https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr
  2. https://reactjs.org/docs/hooks-effect.html

java collections - keyset() vs entrySet() in map

Every time you call itr2.next() you are getting a distinct value. Not the same value. You should only call this once in the loop.

Iterator<String> itr2 = keys.iterator();
    while(itr2.hasNext()){
        String v = itr2.next();
        System.out.println("Key: "+v+" ,value: "+m.get(v));
    }

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

I was able to get around this loading the headers before the HTML with php, and it worked very well.

<?php 
header( 'X-UA-Compatible: IE=edge,chrome=1' );
header( 'content: width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no' );
include('ix.html');
?> 

ix.html is the content I wanted to load after sending the headers.

How do you add an ActionListener onto a JButton in Java

I'm didn't totally follow, but to add an action listener, you just call addActionListener (from Abstract Button). If this doesn't totally answer your question, can you provide some more details?

MySQL JDBC Driver 5.1.33 - Time Zone Issue

i Got error similar to yours but my The server time zone value is 'Afr. centrale Ouest' so i did these steps :

MyError (on IntelliJ IDEA Community Edition):

    InvalidConnectionAttributeException: The server time zone value 'Afr. centrale Ouest' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to u....

I faced this issue when I upgraded my mysql server to SQL Server 8.0 (MYSQL80).

The simplest solution to this problem is just write the below command in your MYSQL Workbench -

  SET GLOBAL time_zone = '+1:00'

The value after the time-zone will be equal to GMT+/- Difference in your timezone. The above example is for North Africa(GMT+1:00) / or for India(GMT+5:30). It will solve the issue.

Enter the Following code in your Mysql Workbench and execute quesry

[source link for question/problem ]

[source link for answer]

[Solution ScreenShot ]

Using the rJava package on Win7 64 bit with R

I solved the issue by uninstalling apparently redundant Java software from my windows 7 x64 machine. I achieved this by first uninstalling all Java applications and then installing a fresh Java version. (Later I pointed R 3.4.3 x86_64-w64-mingw32 to the Java path, just to mention though I don't think this was the real issue.) Today only Java 8 Update 161 (64-bit) 8.0.1610.12 was left then. After this, install.packages("rJava"); library(rJava) did work perfectly.

How can I know which radio button is selected via jQuery?

You can call Function onChange()

  <input type="radio" name="radioName" value="1" onchange="radio_changed($(this).val())" /> 1 <br />
  <input type="radio" name="radioName" value="2" onchange="radio_changed($(this).val())"  /> 2 <br />
  <input type="radio" name="radioName" value="3"  onchange="radio_changed($(this).val())" /> 3 <br />

<script>
function radio_changed(val){
    alert(val);
}
</script>

How to iterate over the keys and values with ng-repeat in AngularJS?

If you would like to edit the property value with two way binding:

<tr ng-repeat="(key, value) in data">
    <td>{{key}}<input type="text" ng-model="data[key]"></td>
</tr>

How can I use a carriage return in a HTML tooltip?

Just use JavaScript. Then compatible with most and older browsers. Use the escape sequence \n for newline.

   document.getElementById("ElementID").title = 'First Line text \n Second line text'

convert nan value to zero

You can use lambda function, an example for 1D array:

import numpy as np
a = [np.nan, 2, 3]
map(lambda v:0 if np.isnan(v) == True else v, a)

This will give you the result:

[0, 2, 3]

C++ equivalent of java's instanceof

Instanceof implementation without dynamic_cast

I think this question is still relevant today. Using the C++11 standard you are now able to implement a instanceof function without using dynamic_cast like this:

if (dynamic_cast<B*>(aPtr) != nullptr) {
  // aPtr is instance of B
} else {
  // aPtr is NOT instance of B
}

But you're still reliant on RTTI support. So here is my solution for this problem depending on some Macros and Metaprogramming Magic. The only drawback imho is that this approach does not work for multiple inheritance.

InstanceOfMacros.h

#include <set>
#include <tuple>
#include <typeindex>

#define _EMPTY_BASE_TYPE_DECL() using BaseTypes = std::tuple<>;
#define _BASE_TYPE_DECL(Class, BaseClass) \
  using BaseTypes = decltype(std::tuple_cat(std::tuple<BaseClass>(), Class::BaseTypes()));
#define _INSTANCE_OF_DECL_BODY(Class)                                 \
  static const std::set<std::type_index> baseTypeContainer;           \
  virtual bool instanceOfHelper(const std::type_index &_tidx) {       \
    if (std::type_index(typeid(ThisType)) == _tidx) return true;      \
    if (std::tuple_size<BaseTypes>::value == 0) return false;         \
    return baseTypeContainer.find(_tidx) != baseTypeContainer.end();  \
  }                                                                   \
  template <typename... T>                                            \
  static std::set<std::type_index> getTypeIndexes(std::tuple<T...>) { \
    return std::set<std::type_index>{std::type_index(typeid(T))...};  \
  }

#define INSTANCE_OF_SUB_DECL(Class, BaseClass) \
 protected:                                    \
  using ThisType = Class;                      \
  _BASE_TYPE_DECL(Class, BaseClass)            \
  _INSTANCE_OF_DECL_BODY(Class)

#define INSTANCE_OF_BASE_DECL(Class)                                                    \
 protected:                                                                             \
  using ThisType = Class;                                                               \
  _EMPTY_BASE_TYPE_DECL()                                                               \
  _INSTANCE_OF_DECL_BODY(Class)                                                         \
 public:                                                                                \
  template <typename Of>                                                                \
  typename std::enable_if<std::is_base_of<Class, Of>::value, bool>::type instanceOf() { \
    return instanceOfHelper(std::type_index(typeid(Of)));                               \
  }

#define INSTANCE_OF_IMPL(Class) \
  const std::set<std::type_index> Class::baseTypeContainer = Class::getTypeIndexes(Class::BaseTypes());

Demo

You can then use this stuff (with caution) as follows:

DemoClassHierarchy.hpp*

#include "InstanceOfMacros.h"

struct A {
  virtual ~A() {}
  INSTANCE_OF_BASE_DECL(A)
};
INSTANCE_OF_IMPL(A)

struct B : public A {
  virtual ~B() {}
  INSTANCE_OF_SUB_DECL(B, A)
};
INSTANCE_OF_IMPL(B)

struct C : public A {
  virtual ~C() {}
  INSTANCE_OF_SUB_DECL(C, A)
};
INSTANCE_OF_IMPL(C)

struct D : public C {
  virtual ~D() {}
  INSTANCE_OF_SUB_DECL(D, C)
};
INSTANCE_OF_IMPL(D)

The following code presents a small demo to verify rudimentary the correct behavior.

InstanceOfDemo.cpp

#include <iostream>
#include <memory>
#include "DemoClassHierarchy.hpp"

int main() {
  A *a2aPtr = new A;
  A *a2bPtr = new B;
  std::shared_ptr<A> a2cPtr(new C);
  C *c2dPtr = new D;
  std::unique_ptr<A> a2dPtr(new D);

  std::cout << "a2aPtr->instanceOf<A>(): expected=1, value=" << a2aPtr->instanceOf<A>() << std::endl;
  std::cout << "a2aPtr->instanceOf<B>(): expected=0, value=" << a2aPtr->instanceOf<B>() << std::endl;
  std::cout << "a2aPtr->instanceOf<C>(): expected=0, value=" << a2aPtr->instanceOf<C>() << std::endl;
  std::cout << "a2aPtr->instanceOf<D>(): expected=0, value=" << a2aPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "a2bPtr->instanceOf<A>(): expected=1, value=" << a2bPtr->instanceOf<A>() << std::endl;
  std::cout << "a2bPtr->instanceOf<B>(): expected=1, value=" << a2bPtr->instanceOf<B>() << std::endl;
  std::cout << "a2bPtr->instanceOf<C>(): expected=0, value=" << a2bPtr->instanceOf<C>() << std::endl;
  std::cout << "a2bPtr->instanceOf<D>(): expected=0, value=" << a2bPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "a2cPtr->instanceOf<A>(): expected=1, value=" << a2cPtr->instanceOf<A>() << std::endl;
  std::cout << "a2cPtr->instanceOf<B>(): expected=0, value=" << a2cPtr->instanceOf<B>() << std::endl;
  std::cout << "a2cPtr->instanceOf<C>(): expected=1, value=" << a2cPtr->instanceOf<C>() << std::endl;
  std::cout << "a2cPtr->instanceOf<D>(): expected=0, value=" << a2cPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "c2dPtr->instanceOf<A>(): expected=1, value=" << c2dPtr->instanceOf<A>() << std::endl;
  std::cout << "c2dPtr->instanceOf<B>(): expected=0, value=" << c2dPtr->instanceOf<B>() << std::endl;
  std::cout << "c2dPtr->instanceOf<C>(): expected=1, value=" << c2dPtr->instanceOf<C>() << std::endl;
  std::cout << "c2dPtr->instanceOf<D>(): expected=1, value=" << c2dPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "a2dPtr->instanceOf<A>(): expected=1, value=" << a2dPtr->instanceOf<A>() << std::endl;
  std::cout << "a2dPtr->instanceOf<B>(): expected=0, value=" << a2dPtr->instanceOf<B>() << std::endl;
  std::cout << "a2dPtr->instanceOf<C>(): expected=1, value=" << a2dPtr->instanceOf<C>() << std::endl;
  std::cout << "a2dPtr->instanceOf<D>(): expected=1, value=" << a2dPtr->instanceOf<D>() << std::endl;

  delete a2aPtr;
  delete a2bPtr;
  delete c2dPtr;

  return 0;
}

Output:

a2aPtr->instanceOf<A>(): expected=1, value=1
a2aPtr->instanceOf<B>(): expected=0, value=0
a2aPtr->instanceOf<C>(): expected=0, value=0
a2aPtr->instanceOf<D>(): expected=0, value=0

a2bPtr->instanceOf<A>(): expected=1, value=1
a2bPtr->instanceOf<B>(): expected=1, value=1
a2bPtr->instanceOf<C>(): expected=0, value=0
a2bPtr->instanceOf<D>(): expected=0, value=0

a2cPtr->instanceOf<A>(): expected=1, value=1
a2cPtr->instanceOf<B>(): expected=0, value=0
a2cPtr->instanceOf<C>(): expected=1, value=1
a2cPtr->instanceOf<D>(): expected=0, value=0

c2dPtr->instanceOf<A>(): expected=1, value=1
c2dPtr->instanceOf<B>(): expected=0, value=0
c2dPtr->instanceOf<C>(): expected=1, value=1
c2dPtr->instanceOf<D>(): expected=1, value=1

a2dPtr->instanceOf<A>(): expected=1, value=1
a2dPtr->instanceOf<B>(): expected=0, value=0
a2dPtr->instanceOf<C>(): expected=1, value=1
a2dPtr->instanceOf<D>(): expected=1, value=1

Performance

The most interesting question which now arises is, if this evil stuff is more efficient than the usage of dynamic_cast. Therefore I've written a very basic performance measurement app.

InstanceOfPerformance.cpp

#include <chrono>
#include <iostream>
#include <string>
#include "DemoClassHierarchy.hpp"

template <typename Base, typename Derived, typename Duration>
Duration instanceOfMeasurement(unsigned _loopCycles) {
  auto start = std::chrono::high_resolution_clock::now();
  volatile bool isInstanceOf = false;
  for (unsigned i = 0; i < _loopCycles; ++i) {
    Base *ptr = new Derived;
    isInstanceOf = ptr->template instanceOf<Derived>();
    delete ptr;
  }
  auto end = std::chrono::high_resolution_clock::now();
  return std::chrono::duration_cast<Duration>(end - start);
}

template <typename Base, typename Derived, typename Duration>
Duration dynamicCastMeasurement(unsigned _loopCycles) {
  auto start = std::chrono::high_resolution_clock::now();
  volatile bool isInstanceOf = false;
  for (unsigned i = 0; i < _loopCycles; ++i) {
    Base *ptr = new Derived;
    isInstanceOf = dynamic_cast<Derived *>(ptr) != nullptr;
    delete ptr;
  }
  auto end = std::chrono::high_resolution_clock::now();
  return std::chrono::duration_cast<Duration>(end - start);
}

int main() {
  unsigned testCycles = 10000000;
  std::string unit = " us";
  using DType = std::chrono::microseconds;

  std::cout << "InstanceOf performance(A->D)  : " << instanceOfMeasurement<A, D, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "InstanceOf performance(A->C)  : " << instanceOfMeasurement<A, C, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "InstanceOf performance(A->B)  : " << instanceOfMeasurement<A, B, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "InstanceOf performance(A->A)  : " << instanceOfMeasurement<A, A, DType>(testCycles).count() << unit
            << "\n"
            << std::endl;
  std::cout << "DynamicCast performance(A->D) : " << dynamicCastMeasurement<A, D, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "DynamicCast performance(A->C) : " << dynamicCastMeasurement<A, C, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "DynamicCast performance(A->B) : " << dynamicCastMeasurement<A, B, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "DynamicCast performance(A->A) : " << dynamicCastMeasurement<A, A, DType>(testCycles).count() << unit
            << "\n"
            << std::endl;
  return 0;
}

The results vary and are essentially based on the degree of compiler optimization. Compiling the performance measurement program using g++ -std=c++11 -O0 -o instanceof-performance InstanceOfPerformance.cpp the output on my local machine was:

InstanceOf performance(A->D)  : 699638 us
InstanceOf performance(A->C)  : 642157 us
InstanceOf performance(A->B)  : 671399 us
InstanceOf performance(A->A)  : 626193 us

DynamicCast performance(A->D) : 754937 us
DynamicCast performance(A->C) : 706766 us
DynamicCast performance(A->B) : 751353 us
DynamicCast performance(A->A) : 676853 us

Mhm, this result was very sobering, because the timings demonstrates that the new approach is not much faster compared to the dynamic_cast approach. It is even less efficient for the special test case which tests if a pointer of A is an instance ofA. BUT the tide turns by tuning our binary using compiler otpimization. The respective compiler command is g++ -std=c++11 -O3 -o instanceof-performance InstanceOfPerformance.cpp. The result on my local machine was amazing:

InstanceOf performance(A->D)  : 3035 us
InstanceOf performance(A->C)  : 5030 us
InstanceOf performance(A->B)  : 5250 us
InstanceOf performance(A->A)  : 3021 us

DynamicCast performance(A->D) : 666903 us
DynamicCast performance(A->C) : 698567 us
DynamicCast performance(A->B) : 727368 us
DynamicCast performance(A->A) : 3098 us

If you are not reliant on multiple inheritance, are no opponent of good old C macros, RTTI and template metaprogramming and are not too lazy to add some small instructions to the classes of your class hierarchy, then this approach can boost your application a little bit with respect to its performance, if you often end up with checking the instance of a pointer. But use it with caution. There is no warranty for the correctness of this approach.

Note: All demos were compiled using clang (Apple LLVM version 9.0.0 (clang-900.0.39.2)) under macOS Sierra on a MacBook Pro Mid 2012.

Edit: I've also tested the performance on a Linux machine using gcc (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609. On this platform the perfomance benefit was not so significant as on macOs with clang.

Output (without compiler optimization):

InstanceOf performance(A->D)  : 390768 us
InstanceOf performance(A->C)  : 333994 us
InstanceOf performance(A->B)  : 334596 us
InstanceOf performance(A->A)  : 300959 us

DynamicCast performance(A->D) : 331942 us
DynamicCast performance(A->C) : 303715 us
DynamicCast performance(A->B) : 400262 us
DynamicCast performance(A->A) : 324942 us

Output (with compiler optimization):

InstanceOf performance(A->D)  : 209501 us
InstanceOf performance(A->C)  : 208727 us
InstanceOf performance(A->B)  : 207815 us
InstanceOf performance(A->A)  : 197953 us

DynamicCast performance(A->D) : 259417 us
DynamicCast performance(A->C) : 256203 us
DynamicCast performance(A->B) : 261202 us
DynamicCast performance(A->A) : 193535 us

Forward declaration of a typedef in C++

I replaced the typedef (using to be specific) with inheritance and constructor inheritance (?).

Original

using CallStack = std::array<StackFrame, MAX_CALLSTACK_DEPTH>;

Replaced

struct CallStack // Not a typedef to allow forward declaration.
  : public std::array<StackFrame, MAX_CALLSTACK_DEPTH>
{
  typedef std::array<StackFrame, MAX_CALLSTACK_DEPTH> Base;
  using Base::Base;
};

This way I was able to forward declare CallStack with:

class CallStack;

How to store JSON object in SQLite database

https://github.com/app-z/Json-to-SQLite

At first generate Plain Old Java Objects from JSON http://www.jsonschema2pojo.org/

Main method

void createDb(String dbName, String tableName, List dataList, Field[] fields){ ...

Fields name will create dynamically

C# function to return array

You're trying to return variable Labels of type ArtworkData instead of array, therefore this needs to be in the method signature as its return type. You need to modify your code as such:

public static ArtworkData[] GetDataRecords(int UsersID)
{
    ArtworkData[] Labels;
    Labels = new ArtworkData[3];

    return Labels;
}

Array[] is actually an array of Array, if that makes sense.

How to display (print) vector in Matlab?

You might try this way:

fprintf('%s: (%i,%i,%i)\r\n','Answer',1,2,3)

I hope this helps.

R apply function with multiple parameters

If your function have two vector variables and must compute itself on each value of them (as mentioned by @Ari B. Friedman) you can use mapply as follows:

vars1<-c(1,2,3)
vars2<-c(10,20,30)
mult_one<-function(var1,var2)
{
   var1*var2
}
mapply(mult_one,vars1,vars2)

which gives you:

> mapply(mult_one,vars1,vars2)
[1] 10 40 90

How do I unset an element in an array in javascript?

Don't use delete as it won't remove an element from an array it will only set it as undefined, which will then not be reflected correctly in the length of the array.

If you know the key you should use splice i.e.

myArray.splice(key, 1);

For someone in Steven's position you can try something like this:

for (var key in myArray) {
    if (key == 'bar') {
        myArray.splice(key, 1);
    }
}

or

for (var key in myArray) {
    if (myArray[key] == 'bar') {
        myArray.splice(key, 1);
    }
}

How to declare an array of strings in C++?

Instead of that macro, might I suggest this one:

template<typename T, int N>
inline size_t array_size(T(&)[N])
{
    return N;
}

#define ARRAY_SIZE(X)   (sizeof(array_size(X)) ? (sizeof(X) / sizeof((X)[0])) : -1)

1) We want to use a macro to make it a compile-time constant; the function call's result is not a compile-time constant.

2) However, we don't want to use a macro because the macro could be accidentally used on a pointer. The function can only be used on compile-time arrays.

So, we use the defined-ness of the function to make the macro "safe"; if the function exists (i.e. it has non-zero size) then we use the macro as above. If the function does not exist we return a bad value.

jQuery Popup Bubble/Tooltip

Tiptip is also a nice library.

How to handle change text of span

Span does not have 'change' event by default. But you can add this event manually.

Listen to the change event of span.

$("#span1").on('change',function(){
     //Do calculation and change value of other span2,span3 here
     $("#span2").text('calculated value');
});

And wherever you change the text in span1. Trigger the change event manually.

$("#span1").text('test').trigger('change'); 

Transfer data between databases with PostgreSQL

This worked for me to copy a table remotely from my localhost to Heroku's postgresql:

pg_dump -C -t source_table -h localhost source_db | psql -h destination_host -U destination_user -p destination_port destination_db

This creates the table for you.

For the other direction (from Heroku to local) pg_dump -C -t source_table -h source_host -U source_user -p source_port source_db | psql -h localhost destination_db

How do you get the path to the Laravel Storage folder?

For Laravel version >=5.1

storage_path()

The storage_path function returns the fully qualified path to the storage directory:

$path = storage_path();

You may also use the storage_path function to generate a fully qualified path to a given file relative to the storage directory:

$app_path = storage_path('app');
$file_path = storage_path('app/file.txt');

Source: Laravel Doc

How is Docker different from a virtual machine?

1. Lightweight

This is probably the first impression for many docker learners.

First, docker images are usually smaller than VM images, makes it easy to build, copy, share.

Second, Docker containers can start in several milliseconds, while VM starts in seconds.

2. Layered File System

This is another key feature of Docker. Images have layers, and different images can share layers, make it even more space-saving and faster to build.

If all containers use Ubuntu as their base images, not every image has its own file system, but share the same underline ubuntu files, and only differs in their own application data.

3. Shared OS Kernel

Think of containers as processes!

All containers running on a host is indeed a bunch of processes with different file systems. They share the same OS kernel, only encapsulates system library and dependencies.

This is good for most cases(no extra OS kernel maintains) but can be a problem if strict isolations are necessary between containers.

Why it matters?

All these seem like improvements, not revolution. Well, quantitative accumulation leads to qualitative transformation.

Think about application deployment. If we want to deploy a new software(service) or upgrade one, it is better to change the config files and processes instead of creating a new VM. Because Creating a VM with updated service, testing it(share between Dev & QA), deploying to production takes hours, even days. If anything goes wrong, you got to start again, wasting even more time. So, use configuration management tool(puppet, saltstack, chef etc.) to install new software, download new files is preferred.

When it comes to docker, it's impossible to use a newly created docker container to replace the old one. Maintainance is much easier!Building a new image, share it with QA, testing it, deploying it only takes minutes(if everything is automated), hours in the worst case. This is called immutable infrastructure: do not maintain(upgrade) software, create a new one instead.

It transforms how services are delivered. We want applications, but have to maintain VMs(which is a pain and has little to do with our applications). Docker makes you focus on applications and smooths everything.

Putting -moz-available and -webkit-fill-available in one width (css property)

CSS will skip over style declarations it doesn't understand. Mozilla-based browsers will not understand -webkit-prefixed declarations, and WebKit-based browsers will not understand -moz-prefixed declarations.

Because of this, we can simply declare width twice:

elem {
    width: 100%;
    width: -moz-available;          /* WebKit-based browsers will ignore this. */
    width: -webkit-fill-available;  /* Mozilla-based browsers will ignore this. */
    width: fill-available;
}

The width: 100% declared at the start will be used by browsers which ignore both the -moz and -webkit-prefixed declarations or do not support -moz-available or -webkit-fill-available.

JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)

This error occurs when you are sending JSON data to server. Maybe in your string you are trying to add new line character by using /n.

If you add / before /n, it should work, you need to escape new line character.

"Hello there //n start coding"

The result should be as following

Hello there
start coding

Mapping over values in a python dictionary

While my original answer missed the point (by trying to solve this problem with the solution to Accessing key in factory of defaultdict), I have reworked it to propose an actual solution to the present question.

Here it is:

class walkableDict(dict):
  def walk(self, callback):
    try:
      for key in self:
        self[key] = callback(self[key])
    except TypeError:
      return False
    return True

Usage:

>>> d = walkableDict({ k1: v1, k2: v2 ... })
>>> d.walk(f)

The idea is to subclass the original dict to give it the desired functionality: "mapping" a function over all the values.

The plus point is that this dictionary can be used to store the original data as if it was a dict, while transforming any data on request with a callback.

Of course, feel free to name the class and the function the way you want (the name chosen in this answer is inspired by PHP's array_walk() function).

Note: Neither the try-except block nor the return statements are mandatory for the functionality, they are there to further mimic the behavior of the PHP's array_walk.

What is the difference between dynamic programming and greedy approach?

the major difference between greedy method and dynamic programming is in greedy method only one optimal decision sequence is ever generated and in dynamic programming more than one optimal decision sequence may be generated.

List of Timezone IDs for use with FindTimeZoneById() in C#?

var timeZoneInfos = TimeZoneInfo.GetSystemTimeZones();

The above gives you a list of timezones, which includes the ids.

Breaking a list into multiple columns in Latex

By combining the multicol package and enumitem package packages it is easy to define environments that are multi-column analogues of the enumerate and itemize environments:

\documentclass{article}
\usepackage{enumitem}
\usepackage{multicol}

\newlist{multienum}{enumerate}{1}
\setlist[multienum]{
    label=\alph*),
    before=\begin{multicols}{2},
    after=\end{multicols}
}

\newlist{multiitem}{itemize}{1}
\setlist[multiitem]{
    label=\textbullet,
    before=\begin{multicols}{2},
    after=\end{multicols}
}

\begin{document}

  \textsf{Two column enumerate}
  \begin{multienum}
    \item item 1
    \item item 2
    \item item 3
    \item item 4
    \item item 5
    \item item 6
  \end{multienum}

  \textsf{Two column itemize}
  \begin{multiitem}
    \item item 1
    \item item 2
    \item item 3
    \item item 4
    \item item 5
    \item item 6
  \end{multiitem}

\end{document}

The output is what you would hope for:

enter image description here

Updating a dataframe column in spark

importing col, when from pyspark.sql.functions and updating fifth column to integer(0,1,2) based on the string(string a, string b, string c) into a new DataFrame.

from pyspark.sql.functions import col, when 

data_frame_temp = data_frame.withColumn("col_5",when(col("col_5") == "string a", 0).when(col("col_5") == "string b", 1).otherwise(2))

Where to find the win32api module for Python?

I've found that UC Irvine has a great collection of python modules, pywin32 (win32api) being one of many listed there. I'm not sure how they do with keeping up with the latest versions of these modules but it hasn't let me down yet.

UC Irvine Python Extension Repository - http://www.lfd.uci.edu/~gohlke/pythonlibs

pywin32 module - http://www.lfd.uci.edu/~gohlke/pythonlibs/#pywin32

shell script to remove a file if it already exist

Don't bother checking if the file exists, just try to remove it.

rm -f /p/a/t/h
# or
rm /p/a/t/h 2> /dev/null

Note that the second command will fail (return a non-zero exit status) if the file did not exist, but the first will succeed owing to the -f (short for --force) option. Depending on the situation, this may be an important detail.

But more likely, if you are appending to the file it is because your script is using >> to redirect something into the file. Just replace >> with >. It's hard to say since you've provided no code.

Note that you can do something like test -f /p/a/t/h && rm /p/a/t/h, but doing so is completely pointless. It is quite possible that the test will return true but the /p/a/t/h will fail to exist before you try to remove it, or worse the test will fail and the /p/a/t/h will be created before you execute the next command which expects it to not exist. Attempting this is a classic race condition. Don't do it.

clk'event vs rising_edge()

The linked comment is incorrect : 'L' to '1' will produce a rising edge.

In addition, if your clock signal transitions from 'H' to '1', rising_edge(clk) will (correctly) not trigger while (clk'event and clk = '1') (incorrectly) will.

Granted, that may look like a contrived example, but I have seen clock waveforms do that in real hardware, due to failures elsewhere.

Sorting dictionary keys in python

[v[0] for v in sorted(foo.items(), key=lambda(k,v): (v,k))]

Write to CSV file and export it?

A comment about Will's answer, you might want to replace HttpContext.Current.Response.End(); with HttpContext.Current.ApplicationInstance.CompleteRequest(); The reason is that Response.End() throws a System.Threading.ThreadAbortException. It aborts a thread. If you have an exception logger, it will be littered with ThreadAbortExceptions, which in this case is expected behavior.

Intuitively, sending a CSV file to the browser should not raise an exception.

See here for more Is Response.End() considered harmful?

Download/Stream file from URL - asp.net

If you are looking for a .NET Core version of @Dallas's answer, use the below.

        Stream stream = null;

        //This controls how many bytes to read at a time and send to the client
        int bytesToRead = 10000;

        // Buffer to read bytes in chunk size specified above
        byte[] buffer = new Byte[bytesToRead];

        // The number of bytes read
        try
        {
            //Create a WebRequest to get the file
            HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(@"file url");

            //Create a response for this request
            HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();

            if (fileReq.ContentLength > 0)
                fileResp.ContentLength = fileReq.ContentLength;

            //Get the Stream returned from the response
            stream = fileResp.GetResponseStream();

            // prepare the response to the client. resp is the client Response
            var resp = HttpContext.Response;

            //Indicate the type of data being sent
            resp.ContentType = "application/octet-stream";

            //Name the file 
            resp.Headers.Add("Content-Disposition", "attachment; filename=test.zip");
            resp.Headers.Add("Content-Length", fileResp.ContentLength.ToString());

            int length;
            do
            {
                // Verify that the client is connected.
                if (!HttpContext.RequestAborted.IsCancellationRequested)
                {
                    // Read data into the buffer.
                    length = stream.Read(buffer, 0, bytesToRead);

                    // and write it out to the response's output stream
                    resp.Body.Write(buffer, 0, length);


                    //Clear the buffer
                    buffer = new Byte[bytesToRead];
                }
                else
                {
                    // cancel the download if client has disconnected
                    length = -1;
                }
            } while (length > 0); //Repeat until no data is read
        }
        finally
        {
            if (stream != null)
            {
                //Close the input stream
                stream.Close();
            }
        }

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

tl;dr:

concat and append currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True to silence it. In the future the default will change to not sort, so it's best to specify either sort=True or False now, or better yet ensure that your non-concatenation indices match.


The warning is new in pandas 0.23.0:

In a future version of pandas pandas.concat() and DataFrame.append() will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned, link.

More information from linked very old github issue, comment by smcinerney :

When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.

This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.

After some time the parameter sort was implemented in pandas.concat and DataFrame.append:

sort : boolean, default None

Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.

Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.

This has no effect when join='inner', which already preserves the order of the non-concatenation axis.

So if both DataFrames have the same columns in the same order, there is no warning and no sorting:

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])

print (pd.concat([df1, df2]))
   a  b
0  1  0
1  2  8
0  4  7
1  5  3

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])

print (pd.concat([df1, df2]))
   b  a
0  0  1
1  8  2
0  7  4
1  3  5

But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort is explicitly set (sort=None is the default value):

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])

print (pd.concat([df1, df2]))

FutureWarning: Sorting because non-concatenation axis is not aligned.

   a  b
0  1  0
1  2  8
0  4  7
1  5  3

print (pd.concat([df1, df2], sort=True))
   a  b
0  1  0
1  2  8
0  4  7
1  5  3

print (pd.concat([df1, df2], sort=False))
   b  a
0  0  1
1  8  2
0  7  4
1  3  5

If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a and b from df1 with a and b from df2 in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.

Lastly, if you pass sort=True, columns are sorted alphanumerically. If sort=False and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]}, 
                    columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]}, 
                    columns=['c','b','a','d'])

print (pd.concat([df1, df2]))

FutureWarning: Sorting because non-concatenation axis is not aligned.

   a  b    c    d    e
0  1  0  NaN  NaN  5.0
1  2  8  NaN  NaN  0.0
0  4  7  2.0  7.0  NaN
1  5  3  8.0  0.0  NaN

print (pd.concat([df1, df2], sort=True))
   a  b    c    d    e
0  1  0  NaN  NaN  5.0
1  2  8  NaN  NaN  0.0
0  4  7  2.0  7.0  NaN
1  5  3  8.0  0.0  NaN

print (pd.concat([df1, df2], sort=False))

   b  a    e    c    d
0  0  1  5.0  NaN  NaN
1  8  2  0.0  NaN  NaN
0  7  4  NaN  2.0  7.0
1  3  5  NaN  8.0  0.0

In your code:

placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
                                                       .append(placement_by_video_summary_new, sort=True)
                                                       .sort_index()

Bootstrap 4 - Responsive cards in card-columns

I have created a Cards Layout - 3 cards in a row using Bootstrap 4 / CSS3 (of course its responsive). The following example uses basic Bootstrap 4 classes such as container, row, col-x, list-group and list-group-item. Thought to share here if someone is interested in this sort of a layout.

enter image description here

HTML

<div class="container">
  <div class="row">
    <div class="col-sm-12 col-md-4">
      <div class="custom-column">
        <div class="custom-column-header">Header</div>
        <div class="custom-column-content">
          <ul class="list-group">
            <li class="list-group-item"><i class="fa fa-check"></i> Cras justo odio</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Dapibus ac facilisis in</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Morbi leo risus</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Porta ac consectetur ac</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Vestibulum at eros</li>
          </ul>
        </div>
        <div class="custom-column-footer"><button class="btn btn-primary btn-lg">Click here</button></div>
      </div>
    </div>
    <div class="col-sm-12 col-md-4">
      <div class="custom-column">        
        <div class="custom-column-header">Header</div>
        <div class="custom-column-content">
          <ul class="list-group">
            <li class="list-group-item"><i class="fa fa-check"></i> Cras justo odio</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Dapibus ac facilisis in</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Morbi leo risus</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Porta ac consectetur ac</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Vestibulum at eros</li>
          </ul>
        </div>
        <div class="custom-column-footer"><button class="btn btn-primary btn-lg">Click here</button></div>
      </div>
    </div>
    <div class="col-sm-12 col-md-4">
      <div class="custom-column">
        <div class="custom-column-header">Header</div>
        <div class="custom-column-content">
          <ul class="list-group">
            <li class="list-group-item"><i class="fa fa-check"></i> Cras justo odio</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Dapibus ac facilisis in</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Morbi leo risus</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Porta ac consectetur ac</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Vestibulum at eros</li>
          </ul>
        </div>
        <div class="custom-column-footer"><button class="btn btn-primary btn-lg">Click here</button></div>
      </div>
    </div>
  </div>
</div>

CSS / SCSS

$primary-color: #ccc;
$col-bg-color: #eee;
$col-footer-bg-color: #eee;
$col-header-bg-color: #007bff;
$col-content-bg-color: #fff;

body {
  background-color: $primary-color;
}  

.custom-column {  
  background-color: $col-bg-color;
  border: 5px solid $col-bg-color;    
  padding: 10px;
  box-sizing: border-box;  
}

.custom-column-header {
  font-size: 24px;
  background-color: #007bff;  
  color: white;
  padding: 15px;  
  text-align: center;
}

.custom-column-content {
  background-color: $col-content-bg-color;
  border: 2px solid white;  
  padding: 20px;  
}

.custom-column-footer {
  background-color: $col-footer-bg-color;   
  padding-top: 20px;
  text-align: center;
}

Link :- https://codepen.io/anjanasilva/pen/JmdOpb

Is it possible to program iPhone in C++

First off, saying Objective-C is "insane" is humorous- I have the Bjarne Stroustrup C++ book sitting by my side which clocks in at 1020 pages. Apple's PDF on Objective-C is 141.

If you want to use UIKit it will be very, very difficult for you to do anything in C++. Any serious iPhone app that conforms to Apple's UI will need it's UI portions to be written in Objective-C. Only if you're writing an OpenGL game can you stick almost entirely to C/C++.

if (boolean == false) vs. if (!boolean)

Note: With ConcurrentMap you can use the more efficient

values.putIfAbsent(NoteColumns.CREATED_DATE, now);

I prefer the less verbose solution and avoid methods like IsTrue or IsFalse or their like.

Knockout validation

If you don't want to use the KnockoutValidation library you can write your own. Here's an example for a Mandatory field.

Add a javascript class with all you KO extensions or extenders, and add the following:

ko.extenders.required = function (target, overrideMessage) {
    //add some sub-observables to our observable
    target.hasError = ko.observable();
    target.validationMessage = ko.observable();

    //define a function to do validation
    function validate(newValue) {
    target.hasError(newValue ? false : true);
    target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
    }

    //initial validation
    validate(target());

    //validate whenever the value changes
    target.subscribe(validate);

    //return the original observable
    return target;
};

Then in your viewModel extend you observable by:

self.dateOfPayment: ko.observable().extend({ required: "" }),

There are a number of examples online for this style of validation.

PowerShell: how to grep command output?

Your problem is that alias emits a stream of AliasInfo objects, rather than a stream of strings. This does what I think you want.

alias | out-string -stream | select-string Alias

or as a function

function grep {
  $input | out-string -stream | select-string $args
}

alias | grep Alias

When you don't handle things that are in the pipeline (like when you just ran 'alias'), the shell knows to use the ToString() method on each object (or use the output formats specified in the ETS info).

Comparing two byte arrays in .NET

Let's add one more!

Recently Microsoft released a special NuGet package, System.Runtime.CompilerServices.Unsafe. It's special because it's written in IL, and provides low-level functionality not directly available in C#.

One of its methods, Unsafe.As<T>(object) allows casting any reference type to another reference type, skipping any safety checks. This is usually a very bad idea, but if both types have the same structure, it can work. So we can use this to cast a byte[] to a long[]:

bool CompareWithUnsafeLibrary(byte[] a1, byte[] a2)
{
    if (a1.Length != a2.Length) return false;

    var longSize = (int)Math.Floor(a1.Length / 8.0);
    var long1 = Unsafe.As<long[]>(a1);
    var long2 = Unsafe.As<long[]>(a2);

    for (var i = 0; i < longSize; i++)
    {
        if (long1[i] != long2[i]) return false;
    }

    for (var i = longSize * 8; i < a1.Length; i++)
    {
        if (a1[i] != a2[i]) return false;
    }

    return true;
}

Note that long1.Length would still return the original array's length, since it's stored in a field in the array's memory structure.

This method is not quite as fast as other methods demonstrated here, but it is a lot faster than the naive method, doesn't use unsafe code or P/Invoke or pinning, and the implementation is quite straightforward (IMO). Here are some BenchmarkDotNet results from my machine:

BenchmarkDotNet=v0.10.3.0, OS=Microsoft Windows NT 6.2.9200.0
Processor=Intel(R) Core(TM) i7-4870HQ CPU 2.50GHz, ProcessorCount=8
Frequency=2435775 Hz, Resolution=410.5470 ns, Timer=TSC
  [Host]     : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0
  DefaultJob : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0

                 Method |          Mean |    StdDev |
----------------------- |-------------- |---------- |
          UnsafeLibrary |   125.8229 ns | 0.3588 ns |
          UnsafeCompare |    89.9036 ns | 0.8243 ns |
           JSharpEquals | 1,432.1717 ns | 1.3161 ns |
 EqualBytesLongUnrolled |    43.7863 ns | 0.8923 ns |
              NewMemCmp |    65.4108 ns | 0.2202 ns |
            ArraysEqual |   910.8372 ns | 2.6082 ns |
          PInvokeMemcmp |    52.7201 ns | 0.1105 ns |

I've also created a gist with all the tests.

How to represent the double quotes character (") in regex?

Firstly, double quote character is nothing special in regex - it's just another character, so it doesn't need escaping from the perspective of regex.

However, because java uses double quotes to delimit String constants, if you want to create a string in java with a double quote in it, you must escape them.

This code will test if your String matches:

if (str.matches("\".*\"")) {
    // this string starts and end with a double quote
}

Note that you don't need to add start and end of input markers (^ and $) in the regex, because matches() requires that the whole input be matched to return true - ^ and $ are implied.

SQL Server, division returns zero

Simply mutiply the bottom of the division by 1.0 (or as many decimal places as you want)

PRINT @set1 
PRINT @set2 
SET @weight= @set1 / @set2 *1.00000; 
PRINT @weight

using href links inside <option> tag

    <select name="career" id="career" onchange="location = this.value;">
        <option value="resume" selected> All Applications </option>
        <option value="resume&j=14">Seo Expert</option>
        <option value="resume&j=21">Project Manager</option>
        <option value="resume&j=33">Php Developer</option>
    </select>

Check if starting characters of a string are alphabetical in T-SQL

You don't need to use regex, LIKE is sufficient:

WHERE my_field LIKE '[a-zA-Z][a-zA-Z]%'

Assuming that by "alphabetical" you mean only latin characters, not anything classified as alphabetical in Unicode.

Note - if your collation is case sensitive, it's important to specify the range as [a-zA-Z]. [a-z] may exclude A or Z. [A-Z] may exclude a or z.

How to make div background color transparent in CSS

From https://developer.mozilla.org/en-US/docs/Web/CSS/background-color

To set background color:

/* Hexadecimal value with color and 100% transparency*/
background-color: #11ffee00;  /* Fully transparent */

/* Special keyword values */
background-color: transparent;

/* HSL value with color and 100% transparency*/
background-color: hsla(50, 33%, 25%, 1.00);  /* 100% transparent */

/* RGB value with color and 100% transparency*/
background-color: rgba(117, 190, 218, 1.0);  /* 100% transparent */

Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

In my case, I disabled McAfee and then successfully installed tensorflow2.0 RC

Error : Index was outside the bounds of the array.

You have declared an array that can store 8 elements not 9.

this.posStatus = new int[8]; 

It means postStatus will contain 8 elements from index 0 to 7.

How to uncheck checked radio button

This simple script allows you to uncheck an already checked radio button. Works on all javascript enabled browsers.

_x000D_
_x000D_
var allRadios = document.getElementsByName('re');_x000D_
var booRadio;_x000D_
var x = 0;_x000D_
for(x = 0; x < allRadios.length; x++){_x000D_
  allRadios[x].onclick = function() {_x000D_
    if(booRadio == this){_x000D_
      this.checked = false;_x000D_
      booRadio = null;_x000D_
    } else {_x000D_
      booRadio = this;_x000D_
    }_x000D_
  };_x000D_
}
_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>
_x000D_
_x000D_
_x000D_

align an image and some text on the same line without using div width?

Floating will result in wrapping if space is not available.

You can use display:inline and white-space:nowrap to achieve this. Fiddle

<div id="container" style="white-space:nowrap">

    <div id="image" style="display:inline;">
        <img src="tree.png"/>
    </div>

    <div id="texts" style="display:inline; white-space:nowrap;"> 
        A very long text(about 300 words) 
    </div>

</div>?

ActionBarActivity cannot resolve a symbol

Make sure that in the path to the project there is no foldername having whitespace. While creating a project the specified path folders must not contain any space in their naming.

How to run specific test cases in GoogleTest

Summarising @Rasmi Ranjan Nayak and @nogard answers and adding another option:

On the console

You should use the flag --gtest_filter, like

--gtest_filter=Test_Cases1*

(You can also do this in Properties|Configuration Properties|Debugging|Command Arguments)

On the environment

You should set the variable GTEST_FILTER like

export GTEST_FILTER = "Test_Cases1*"

On the code

You should set a flag filter, like

::testing::GTEST_FLAG(filter) = "Test_Cases1*";

such that your main function becomes something like

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    ::testing::GTEST_FLAG(filter) = "Test_Cases1*";
    return RUN_ALL_TESTS();
}

See section Running a Subset of the Tests for more info on the syntax of the string you can use.

How can I delay a :hover effect in CSS?

You can use transitions to delay the :hover effect you want, if the effect is CSS-based.

For example

div{
    transition: 0s background-color;
}

div:hover{
    background-color:red;    
    transition-delay:1s;
}

this will delay applying the the hover effects (background-color in this case) for one second.


Demo of delay on both hover on and off:

_x000D_
_x000D_
div{_x000D_
    display:inline-block;_x000D_
    padding:5px;_x000D_
    margin:10px;_x000D_
    border:1px solid #ccc;_x000D_
    transition: 0s background-color;_x000D_
    transition-delay:1s;_x000D_
}_x000D_
div:hover{_x000D_
    background-color:red;_x000D_
}
_x000D_
<div>delayed hover</div>
_x000D_
_x000D_
_x000D_

Demo of delay only on hover on:

_x000D_
_x000D_
div{_x000D_
    display:inline-block;_x000D_
    padding:5px;_x000D_
    margin:10px;_x000D_
    border:1px solid #ccc;_x000D_
    transition: 0s background-color;_x000D_
}_x000D_
div:hover{_x000D_
    background-color:red;    _x000D_
    transition-delay:1s;_x000D_
}
_x000D_
<div>delayed hover</div>
_x000D_
_x000D_
_x000D_


Vendor Specific Extentions for Transitions and W3C CSS3 transitions

Select a dummy column with a dummy value in SQL?

Try this:

select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;

How do I "select Android SDK" in Android Studio?

Give SDK path in local.properties file as

sdk.dir=C\:\\Users\\System43\\AppData\\Local\\Android\\sdk

and give latest version in compilesdk in gradle file.

Get the generated SQL statement from a SqlCommand object?

This solution works for me right now. Maybe it is usefull to someone. Please excuse all the redundancy.

    Public Shared Function SqlString(ByVal cmd As SqlCommand) As String
    Dim sbRetVal As New System.Text.StringBuilder()
    For Each item As SqlParameter In cmd.Parameters
        Select Case item.DbType
            Case DbType.String
                sbRetVal.AppendFormat("DECLARE {0} AS VARCHAR(255)", item.ParameterName)
                sbRetVal.AppendLine()
                sbRetVal.AppendFormat("SET {0} = '{1}'", item.ParameterName, item.Value)
                sbRetVal.AppendLine()

            Case DbType.DateTime
                sbRetVal.AppendFormat("DECLARE {0} AS DATETIME", item.ParameterName)
                sbRetVal.AppendLine()
                sbRetVal.AppendFormat("SET {0} = '{1}'", item.ParameterName, item.Value)
                sbRetVal.AppendLine()

            Case DbType.Guid
                sbRetVal.AppendFormat("DECLARE {0} AS UNIQUEIDENTIFIER", item.ParameterName)
                sbRetVal.AppendLine()
                sbRetVal.AppendFormat("SET {0} = '{1}'", item.ParameterName, item.Value)
                sbRetVal.AppendLine()

            Case DbType.Int32
                sbRetVal.AppendFormat("DECLARE {0} AS int", item.ParameterName)
                sbRetVal.AppendLine()
                sbRetVal.AppendFormat("SET {0} = {1}", item.ParameterName, item.Value)
                sbRetVal.AppendLine()

            Case Else
                Stop

        End Select
    Next

    sbRetVal.AppendLine("")
    sbRetVal.AppendLine(cmd.CommandText)

    Return sbRetVal.ToString()
End Function

Groovy built-in REST/HTTP client?

HTTPBuilder is it. Very easy to use.

import groovyx.net.http.HTTPBuilder

def http = new HTTPBuilder('https://google.com')
def html = http.get(path : '/search', query : [q:'waffles'])

It is especially useful if you need error handling and generally more functionality than just fetching content with GET.

List of tables, db schema, dump etc using the Python sqlite3 API

I'm not familiar with the Python API but you can always use

SELECT * FROM sqlite_master;

How do I use PHP to get the current year?

use a PHP date() function.

and the format is just going to be Y. Capital Y is going to be a four digit year.

<?php echo date("Y"); ?>

Run / Open VSCode from Mac Terminal

Sometimes, just adding the shell command doesn't work. We need to check whether visual studio code is available in "Applications" folder or not. That was the case for me.

The moment you download VS code, it stays in "Downloads" folder and terminal doesn't pick up from there. So, I manually moved my VS code to "Applications" folder to access from Terminal.

Step 1: Download VS code, which will give a zipped folder.

Step 2: Run it, which will give a exe kinda file in downloads folder.

Step 3: Move it to "Applications" folder manually.

Step 4: Open VS code, "Command+Shift+P" and run the shell command.

Step 5: Restart the terminal.

Step 6: Typing "Code ." on terminal should work now.

How to POST URL in data of a curl request

I don't think it's necessary to use semi-quotes around the variables, try:

curl -XPOST 'http://localhost/Service' -d "path=%2fxyz%2fpqr%2ftest%2f&fileName=1.doc"

%2f is the escape code for a /.

http://www.december.com/html/spec/esccodes.html

Also, do you need to specify a port? ( just checking :) )

What encoding/code page is cmd.exe using?

Command CHCP shows the current codepage. It has three digits: 8xx and is different from Windows 12xx. So typing a English-only text you wouldn't see any difference, but an extended codepage (like Cyrillic) will be printed wrongly.

jQuery - If element has class do this

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

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

But you can also simplify this to:

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

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

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

How can I listen for keypress event on the whole page?

I think this does the best job

https://angular.io/api/platform-browser/EventManager

for instance in app.component

constructor(private eventManager: EventManager) {
    const removeGlobalEventListener = this.eventManager.addGlobalEventListener(
      'document',
      'keypress',
      (ev) => {
        console.log('ev', ev);
      }
    );
  }

Equivalent of shell 'cd' command to change the working directory?

import os

abs_path = 'C://a/b/c'
rel_path = './folder'

os.chdir(abs_path)
os.chdir(rel_path)

You can use both with os.chdir(abs_path) or os.chdir(rel_path), there's no need to call os.getcwd() to use a relative path.

How to downgrade Xcode to previous version?

I'm assuming you are having at least OSX 10.7, so go ahead into the applications folder (Click on Finder icon > On the Sidebar, you'll find "Applications", click on it ), delete the "Xcode" icon. That will remove Xcode from your system completely. Restart your mac.

Now go to https://developer.apple.com/download/more/ and download an older version of Xcode, as needed and install. You need an Apple ID to login to that portal.

How to affect other elements when one element is hovered

Only this worked for me:

#container:hover .cube { background-color: yellow; }

Where .cube is CssClass of the #cube.

Tested in Firefox, Chrome and Edge.

Android how to convert int to String?

Use this String.valueOf(value);

cmd line rename file with date and time

I tried to do the same:

<fileName>.<ext> --> <fileName>_<date>_<time>.<ext> 

I found that :

rename 's/(\w+)(\.\w+)/$1'$(date +"%Y%m%d_%H%M%S)'$2/' *

Is JavaScript's "new" keyword considered harmful?

I think "new" adds clarity to the code. And clarity is worth everything. Good to know there are pitfalls, but avoiding them by avoiding clarity doesn't seem like the way for me.

gpg decryption fails with no secret key error

I have solved this problem, try to use root privileges, such as sudo gpg ... I think that gpg elevated without permissions does not refer to file permissions, but system

how to count the total number of lines in a text file using python

For the people saying to use with open ("filename.txt","r") as f you can do anyname = open("filename.txt","r")

def main():

    file = open("infile.txt",'r')
    count = 0
    for line in file:
            count+=1

    print (count)

main ()

bash: pip: command not found

Do following:

sudo apt update
sudo apt install python3-pip
source ~/.bashrc

This will surely install pip with all its dependencies. PS this is for python 3 if you want for python 2 replace python3 from the second command to python

sudo apt install python-pip

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!!!
}

Passive Link in Angular 2 - <a href=""> equivalent

In my case deleting href attribute solve problem as long there is a click function assign to a.

Finding diff between current and last version

to show individual changes in a commit, to head.

git show Head~0

to show accumulated changes in a commit, to head.

git diff Head~0

where 0 is the desired number of commits.

gdb: how to print the current line or find the current line number?

I do get the same information while debugging. Though not while I am checking the stacktrace. Most probably you would have used the optimization flag I think. Check this link - something related.

Try compiling with -g3 remove any optimization flag. Then it might work. HTH!

Jmeter - get current date and time

JMeter is using java SimpleDateFormat

For UTC with timezone use this

${__time(yyyy-MM-dd'T'hh:mm:ssX)}

How to remove duplicate white spaces in string using Java?

String str = "   Text    with    multiple    spaces    ";
str = org.apache.commons.lang3.StringUtils.normalizeSpace(str);
// str = "Text with multiple spaces"

Convert JS Object to form data

Maybe you're looking for this, a code that receive your javascript object, create a FormData object from it and then POST it to your server using new Fetch API:

    let myJsObj = {'someIndex': 'a value'};

    let datos = new FormData();
    for (let i in myJsObj){
        datos.append( i, myJsObj[i] );
    }

    fetch('your.php', {
        method: 'POST',
        body: datos
    }).then(response => response.json())
        .then(objson => {
            console.log('Success:', objson);
        })
        .catch((error) => {
            console.error('Error:', error);
        });

Efficient iteration with index in Scala

The proposed solutions suffer from the fact that they either explicitly iterate over a collection or stuff the collection into a function. It is more natural to stick with the usual idioms of Scala and put the index inside the usual map- or foreach-methods. This can be done using memoizing. The resulting code might look like

myIterable map (doIndexed(someFunction))

Here is a way to achieve this purpose. Consider the following utility:

object TraversableUtil {
    class IndexMemoizingFunction[A, B](f: (Int, A) => B) extends Function1[A, B] {
        private var index = 0
        override def apply(a: A): B = {
            val ret = f(index, a)
            index += 1
            ret
        }
    }

    def doIndexed[A, B](f: (Int, A) => B): A => B = {
        new IndexMemoizingFunction(f)
    }
}

This is already all you need. You can apply this for instance as follows:

import TraversableUtil._
List('a','b','c').map(doIndexed((i, char) => char + i))

which results in the list

List(97, 99, 101)

This way, you can use the usual Traversable-functions at the expense of wrapping your effective function. Enjoy!

Invalid column name sql error

You probably need quotes around those string fields, but, you should be using parameterized queries!

cmd.CommandText = "INSERT INTO Data ([Name],PhoneNo,Address) VALUES (@name, @phone, @address)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@name", txtName.Text);
cmd.Parameters.AddWithValue("@phone", txtPhone.Text);
cmd.Parameters.AddWithValue("@address", txtAddress.Text);
cmd.Connection = connection;

Incidentally, your original query could have been fixed like this (note the single quotes):

"VALUES ('" + txtName.Text + "','" + txtPhone.Text + "','" + txtAddress.Text + "');";

but this would have made it vulnerable to SQL Injection attacks since a user could type in

'; drop table users; -- 

into one of your textboxes. Or, more mundanely, poor Daniel O'Reilly would break your query every time.

Linq to Sql: Multiple left outer joins

In VB.NET using Function,

Dim query = From order In dc.Orders
            From vendor In 
            dc.Vendors.Where(Function(v) v.Id = order.VendorId).DefaultIfEmpty()
            From status In 
            dc.Status.Where(Function(s) s.Id = order.StatusId).DefaultIfEmpty()
            Select Order = order, Vendor = vendor, Status = status 

Find the line number where a specific word appears with "grep"

Use grep -n to get the line number of a match.

I don't think there's a way to get grep to start on a certain line number. For that, use sed. For example, to start at line 10 and print the line number and line for matching lines, use:

sed -n '10,$ { /regex/ { =; p; } }' file

To get only the line numbers, you could use

grep -n 'regex' | sed 's/^\([0-9]\+\):.*$/\1/'

Or you could simply use sed:

sed -n '/regex/=' file

Combining the two sed commands, you get:

sed -n '10,$ { /regex/= }' file

How do I make an Event in the Usercontrol and have it handled in the Main Form?

You need to create an event handler for the user control that is raised when an event from within the user control is fired. This will allow you to bubble the event up the chain so you can handle the event from the form.

When clicking Button1 on the UserControl, i'll fire Button1_Click which triggers UserControl_ButtonClick on the form:

User control:

[Browsable(true)] [Category("Action")] 
[Description("Invoked when user clicks button")]
public event EventHandler ButtonClick;

protected void Button1_Click(object sender, EventArgs e)
{
    //bubble the event up to the parent
    if (this.ButtonClick!= null)
        this.ButtonClick(this, e);               
}

Form:

UserControl1.ButtonClick += new EventHandler(UserControl_ButtonClick);

protected void UserControl_ButtonClick(object sender, EventArgs e)
{
    //handle the event 
}

Notes:

  • Newer Visual Studio versions suggest that instead of if (this.ButtonClick!= null) this.ButtonClick(this, e); you can use ButtonClick?.Invoke(this, e);, which does essentially the same, but is shorter.

  • The Browsable attribute makes the event visible in Visual Studio's designer (events view), Category shows it in the "Action" category, and Description provides a description for it. You can omit these attributes completely, but making it available to the designer it is much more comfortable, since VS handles it for you.

Permission denied when launch python script via bash

Did you include

#!/usr/bin/python

as your first line?

Can I mask an input text in a bat file?

Another option, along the same lines as Blorgbeard is out's, is to use something like:

SET /P pw=C:\^>

The ^ escapes the > so that the password prompt will look like a standard cmd console prompt.

Remove all newlines from inside a string

or you can try this:

string1 = 'Hello \n World'
tmp = string1.split()
string2 = ' '.join(tmp)

AngularJS 1.2 $injector:modulerr

If you go through the official tutorial of angularjs https://docs.angularjs.org/tutorial/step_07

Note: Starting with AngularJS version 1.2, ngRoute is in its own module and must be loaded by loading the additional angular-route.js file, which we download via Bower above.

Also please note from ngRoute api https://docs.angularjs.org/api/ngRoute

Installation First include angular-route.js in your HTML:

You can download this file from the following places:

Google CDN e.g. //ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-route.js Bower e.g. bower install [email protected] code.angularjs.org e.g. "//code.angularjs.org/X.Y.Z/angular-route.js" where X.Y.Z is the AngularJS version you are running.

Then load the module in your application by adding it as a dependent module:

angular.module('app', ['ngRoute']); With that you're ready to get started!

Is there a JSON equivalent of XQuery/XPath?

JMESPath seems to be very popular these days (as of 2020) and addresses a number of issues with JSONPath. It's available for many languages.

Why do I have to "git push --set-upstream origin <branch>"?

TL;DR: git branch --set-upstream-to origin/solaris


The answer to the question you asked—which I'll rephrase a bit as "do I have to set an upstream"—is: no, you don't have to set an upstream at all.

If you do not have upstream for the current branch, however, Git changes its behavior on git push, and on other commands as well.

The complete push story here is long and boring and goes back in history to before Git version 1.5. To shorten it a whole lot, git push was implemented poorly.1 As of Git version 2.0, Git now has a configuration knob spelled push.default which now defaults to simple. For several versions of Git before and after 2.0, every time you ran git push, Git would spew lots of noise trying to convince you to set push.default just to get git push to shut up.

You do not mention which version of Git you are running, nor whether you have configured push.default, so we must guess. My guess is that you are using Git version 2-point-something, and that you have set push.default to simple to get it to shut up. Precisely which version of Git you have, and what if anything you have push.default set to, does matter, due to that long and boring history, but in the end, the fact that you're getting yet another complaint from Git indicates that your Git is configured to avoid one of the mistakes from the past.

What is an upstream?

An upstream is simply another branch name, usually a remote-tracking branch, associated with a (regular, local) branch.

Every branch has the option of having one (1) upstream set. That is, every branch either has an upstream, or does not have an upstream. No branch can have more than one upstream.

The upstream should, but does not have to be, a valid branch (whether remote-tracking like origin/B or local like master). That is, if the current branch B has upstream U, git rev-parse U should work. If it does not work—if it complains that U does not exist—then most of Git acts as though the upstream is not set at all. A few commands, like git branch -vv, will show the upstream setting but mark it as "gone".

What good is an upstream?

If your push.default is set to simple or upstream, the upstream setting will make git push, used with no additional arguments, just work.

That's it—that's all it does for git push. But that's fairly significant, since git push is one of the places where a simple typo causes major headaches.

If your push.default is set to nothing, matching, or current, setting an upstream does nothing at all for git push.

(All of this assumes your Git version is at least 2.0.)

The upstream affects git fetch

If you run git fetch with no additional arguments, Git figures out which remote to fetch from by consulting the current branch's upstream. If the upstream is a remote-tracking branch, Git fetches from that remote. (If the upstream is not set or is a local branch, Git tries fetching origin.)

The upstream affects git merge and git rebase too

If you run git merge or git rebase with no additional arguments, Git uses the current branch's upstream. So it shortens the use of these two commands.

The upstream affects git pull

You should never2 use git pull anyway, but if you do, git pull uses the upstream setting to figure out which remote to fetch from, and then which branch to merge or rebase with. That is, git pull does the same thing as git fetch—because it actually runs git fetch—and then does the same thing as git merge or git rebase, because it actually runs git merge or git rebase.

(You should usually just do these two steps manually, at least until you know Git well enough that when either step fails, which they will eventually, you recognize what went wrong and know what to do about it.)

The upstream affects git status

This may actually be the most important. Once you have an upstream set, git status can report the difference between your current branch and its upstream, in terms of commits.

If, as is the normal case, you are on branch B with its upstream set to origin/B, and you run git status, you will immediately see whether you have commits you can push, and/or commits you can merge or rebase onto.

This is because git status runs:

  • git rev-list --count @{u}..HEAD: how many commits do you have on B that are not on origin/B?
  • git rev-list --count HEAD..@{u}: how many commits do you have on origin/B that are not on B?

Setting an upstream gives you all of these things.

How come master already has an upstream set?

When you first clone from some remote, using:

$ git clone git://some.host/path/to/repo.git

or similar, the last step Git does is, essentially, git checkout master. This checks out your local branch master—only you don't have a local branch master.

On the other hand, you do have a remote-tracking branch named origin/master, because you just cloned it.

Git guesses that you must have meant: "make me a new local master that points to the same commit as remote-tracking origin/master, and, while you're at it, set the upstream for master to origin/master."

This happens for every branch you git checkout that you do not already have. Git creates the branch and makes it "track" (have as an upstream) the corresponding remote-tracking branch.

But this doesn't work for new branches, i.e., branches with no remote-tracking branch yet.

If you create a new branch:

$ git checkout -b solaris

there is, as yet, no origin/solaris. Your local solaris cannot track remote-tracking branch origin/solaris because it does not exist.

When you first push the new branch:

$ git push origin solaris

that creates solaris on origin, and hence also creates origin/solaris in your own Git repository. But it's too late: you already have a local solaris that has no upstream.3

Shouldn't Git just set that, now, as the upstream automatically?

Probably. See "implemented poorly" and footnote 1. It's hard to change now: There are millions4 of scripts that use Git and some may well depend on its current behavior. Changing the behavior requires a new major release, nag-ware to force you to set some configuration field, and so on. In short, Git is a victim of its own success: whatever mistakes it has in it, today, can only be fixed if the change is either mostly invisible, clearly-much-better, or done slowly over time.

The fact is, it doesn't today, unless you use --set-upstream or -u during the git push. That's what the message is telling you.

You don't have to do it like that. Well, as we noted above, you don't have to do it at all, but let's say you want an upstream. You have already created branch solaris on origin, through an earlier push, and as your git branch output shows, you already have origin/solaris in your local repository.

You just don't have it set as the upstream for solaris.

To set it now, rather than during the first push, use git branch --set-upstream-to. The --set-upstream-to sub-command takes the name of any existing branch, such as origin/solaris, and sets the current branch's upstream to that other branch.

That's it—that's all it does—but it has all those implications noted above. It means you can just run git fetch, then look around, then run git merge or git rebase as appropriate, then make new commits and run git push, without a bunch of additional fussing-around.


1To be fair, it was not clear back then that the initial implementation was error-prone. That only became clear when every new user made the same mistakes every time. It's now "less poor", which is not to say "great".

2"Never" is a bit strong, but I find that Git newbies understand things a lot better when I separate out the steps, especially when I can show them what git fetch actually did, and they can then see what git merge or git rebase will do next.

3If you run your first git push as git push -u origin solaris—i.e., if you add the -u flag—Git will set origin/solaris as the upstream for your current branch if (and only if) the push succeeds. So you should supply -u on the first push. In fact, you can supply it on any later push, and it will set or change the upstream at that point. But I think git branch --set-upstream-to is easier, if you forgot.

4Measured by the Austin Powers / Dr Evil method of simply saying "one MILLLL-YUN", anyway.

How do I implement __getattribute__ without an infinite recursion error?

How is the __getattribute__ method used?

It is called before the normal dotted lookup. If it raises AttributeError, then we call __getattr__.

Use of this method is rather rare. There are only two definitions in the standard library:

$ grep -Erl  "def __getattribute__\(self" cpython/Lib | grep -v "/test/"
cpython/Lib/_threading_local.py
cpython/Lib/importlib/util.py

Best Practice

The proper way to programmatically control access to a single attribute is with property. Class D should be written as follows (with the setter and deleter optionally to replicate apparent intended behavior):

class D(object):
    def __init__(self):
        self.test2=21

    @property
    def test(self):
        return 0.

    @test.setter
    def test(self, value):
        '''dummy function to avoid AttributeError on setting property'''

    @test.deleter
    def test(self):
        '''dummy function to avoid AttributeError on deleting property'''

And usage:

>>> o = D()
>>> o.test
0.0
>>> o.test = 'foo'
>>> o.test
0.0
>>> del o.test
>>> o.test
0.0

A property is a data descriptor, thus it is the first thing looked for in the normal dotted lookup algorithm.

Options for __getattribute__

You several options if you absolutely need to implement lookup for every attribute via __getattribute__.

  • raise AttributeError, causing __getattr__ to be called (if implemented)
  • return something from it by
    • using super to call the parent (probably object's) implementation
    • calling __getattr__
    • implementing your own dotted lookup algorithm somehow

For example:

class NoisyAttributes(object):
    def __init__(self):
        self.test=20
        self.test2=21
    def __getattribute__(self, name):
        print('getting: ' + name)
        try:
            return super(NoisyAttributes, self).__getattribute__(name)
        except AttributeError:
            print('oh no, AttributeError caught and reraising')
            raise
    def __getattr__(self, name):
        """Called if __getattribute__ raises AttributeError"""
        return 'close but no ' + name    


>>> n = NoisyAttributes()
>>> nfoo = n.foo
getting: foo
oh no, AttributeError caught and reraising
>>> nfoo
'close but no foo'
>>> n.test
getting: test
20

What you originally wanted.

And this example shows how you might do what you originally wanted:

class D(object):
    def __init__(self):
        self.test=20
        self.test2=21
    def __getattribute__(self,name):
        if name=='test':
            return 0.
        else:
            return super(D, self).__getattribute__(name)

And will behave like this:

>>> o = D()
>>> o.test = 'foo'
>>> o.test
0.0
>>> del o.test
>>> o.test
0.0
>>> del o.test

Traceback (most recent call last):
  File "<pyshell#216>", line 1, in <module>
    del o.test
AttributeError: test

Code review

Your code with comments. You have a dotted lookup on self in __getattribute__. This is why you get a recursion error. You could check if name is "__dict__" and use super to workaround, but that doesn't cover __slots__. I'll leave that as an exercise to the reader.

class D(object):
    def __init__(self):
        self.test=20
        self.test2=21
    def __getattribute__(self,name):
        if name=='test':
            return 0.
        else:      #   v--- Dotted lookup on self in __getattribute__
            return self.__dict__[name]

>>> print D().test
0.0
>>> print D().test2
...
RuntimeError: maximum recursion depth exceeded in cmp

I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error

Scripts are raw java embedded in the page code, and if you declare variables in your scripts, then they become local variables embedded in the page.

In contrast, JSTL works entirely with scoped attributes, either at page, request or session scope. You need to rework your scriptlet to fish test out as an attribute:

<c:set var="test" value="test1"/>
<%
  String resp = "abc";
  String test = pageContext.getAttribute("test");
  resp = resp + test;
  pageContext.setAttribute("resp", resp);
%>
<c:out value="${resp}"/>

If you look at the docs for <c:set>, you'll see you can specify scope as page, request or session, and it defaults to page.

Better yet, don't use scriptlets at all: they make the baby jesus cry.

How to send email via Django?

For Django version 1.7, if above solutions dont work then try the following

in settings.py add

#For email
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

EMAIL_USE_TLS = True

EMAIL_HOST = 'smtp.gmail.com'

EMAIL_HOST_USER = '[email protected]'

#Must generate specific password for your app in [gmail settings][1]
EMAIL_HOST_PASSWORD = 'app_specific_password'

EMAIL_PORT = 587

#This did the trick
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

The last line did the trick for django 1.7

PHP: Get key from array?

Another way to use key($array) in a foreach loop is by using next($array) at the end of the loop, just make sure each iteration calls the next() function (in case you have complex branching inside the loop)

Resource interpreted as stylesheet but transferred with MIME type text/html (seems not related with web server)

If nodejs and using express the below code works...

res.set('Content-Type', 'text/css');

Twitter Bootstrap hide css class and jQuery

This is what I do for those situations:

I don't start the html element with class 'hide', but I put style="display: none".

This is because bootstrap jquery modifies the style attribute and not the classes to hide/unhide.

Example:

<button type="button" id="btn_cancel" class="btn default" style="display: none">Cancel</button>

or

<button type="button" id="btn_cancel" class="btn default display-hide">Cancel</button>

Later on, you can run all the following that will work:

$('#btn_cancel').toggle() // toggle between hide/unhide
$('#btn_cancel').hide()
$('#btn_cancel').show()

You can also uso the class of Twitter Bootstrap 'display-hide', which also works with the jQuery IU .toggle() method.

CSS Input with width: 100% goes outside parent's bound

Padding is essentially added to the width, therefore when you say width:100% and padding: 5px 10px you're actually adding 20px to the 100% width.

MySQL: ignore errors when importing?

Use the --force (-f) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.

For example:

mysql -u userName -p -f -D dbName < script.sql

Why does git perform fast-forward merges by default?

Fast-forward merging makes sense for short-lived branches, but in a more complex history, non-fast-forward merging may make the history easier to understand, and make it easier to revert a group of commits.

Warning: Non-fast-forwarding has potential side effects as well. Please review https://sandofsky.com/blog/git-workflow.html, avoid the 'no-ff' with its "checkpoint commits" that break bisect or blame, and carefully consider whether it should be your default approach for master.

alt text
(From nvie.com, Vincent Driessen, post "A successful Git branching model")

Incorporating a finished feature on develop

Finished features may be merged into the develop branch to add them to the upcoming release:

$ git checkout develop
Switched to branch 'develop'
$ git merge --no-ff myfeature
Updating ea1b82a..05e9557
(Summary of changes)
$ git branch -d myfeature
Deleted branch myfeature (was 05e9557).
$ git push origin develop

The --no-ff flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward. This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature.

Jakub Narebski also mentions the config merge.ff:

By default, Git does not create an extra merge commit when merging a commit that is a descendant of the current commit. Instead, the tip of the current branch is fast-forwarded.
When set to false, this variable tells Git to create an extra merge commit in such a case (equivalent to giving the --no-ff option from the command line).
When set to 'only', only such fast-forward merges are allowed (equivalent to giving the --ff-only option from the command line).


The fast-forward is the default because:

  • short-lived branches are very easy to create and use in Git
  • short-lived branches often isolate many commits that can be reorganized freely within that branch
  • those commits are actually part of the main branch: once reorganized, the main branch is fast-forwarded to include them.

But if you anticipate an iterative workflow on one topic/feature branch (i.e., I merge, then I go back to this feature branch and add some more commits), then it is useful to include only the merge in the main branch, rather than all the intermediate commits of the feature branch.

In this case, you can end up setting this kind of config file:

[branch "master"]
# This is the list of cmdline options that should be added to git-merge 
# when I merge commits into the master branch.

# The option --no-commit instructs git not to commit the merge
# by default. This allows me to do some final adjustment to the commit log
# message before it gets commited. I often use this to add extra info to
# the merge message or rewrite my local branch names in the commit message
# to branch names that are more understandable to the casual reader of the git log.

# Option --no-ff instructs git to always record a merge commit, even if
# the branch being merged into can be fast-forwarded. This is often the
# case when you create a short-lived topic branch which tracks master, do
# some changes on the topic branch and then merge the changes into the
# master which remained unchanged while you were doing your work on the
# topic branch. In this case the master branch can be fast-forwarded (that
# is the tip of the master branch can be updated to point to the tip of
# the topic branch) and this is what git does by default. With --no-ff
# option set, git creates a real merge commit which records the fact that
# another branch was merged. I find this easier to understand and read in
# the log.

mergeoptions = --no-commit --no-ff

The OP adds in the comments:

I see some sense in fast-forward for [short-lived] branches, but making it the default action means that git assumes you... often have [short-lived] branches. Reasonable?

Jefromi answers:

I think the lifetime of branches varies greatly from user to user. Among experienced users, though, there's probably a tendency to have far more short-lived branches.

To me, a short-lived branch is one that I create in order to make a certain operation easier (rebasing, likely, or quick patching and testing), and then immediately delete once I'm done.
That means it likely should be absorbed into the topic branch it forked from, and the topic branch will be merged as one branch. No one needs to know what I did internally in order to create the series of commits implementing that given feature.

More generally, I add:

it really depends on your development workflow:

  • if it is linear, one branch makes sense.
  • If you need to isolate features and work on them for a long period of time and repeatedly merge them, several branches make sense.

See "When should you branch?"

Actually, when you consider the Mercurial branch model, it is at its core one branch per repository (even though you can create anonymous heads, bookmarks and even named branches)
See "Git and Mercurial - Compare and Contrast".

Mercurial, by default, uses anonymous lightweight codelines, which in its terminology are called "heads".
Git uses lightweight named branches, with injective mapping to map names of branches in remote repository to names of remote-tracking branches.
Git "forces" you to name branches (well, with the exception of a single unnamed branch, which is a situation called a "detached HEAD"), but I think this works better with branch-heavy workflows such as topic branch workflow, meaning multiple branches in a single repository paradigm.

Angular 2 ngfor first, last, index loop

Here is how its done in Angular 6

<li *ngFor="let user of userObservable ; first as isFirst">
   <span *ngIf="isFirst">default</span>
</li>

Note the change from let first = first to first as isFirst

Python 2.7 getting user input and manipulating as string without quotations

Use raw_input() instead of input():

testVar = raw_input("Ask user for something.")

input() actually evaluates the input as Python code. I suggest to never use it. raw_input() returns the verbatim string entered by the user.

ASP.Net MVC How to pass data from view to controller

<form action="myController/myAction" method="POST">
 <input type="text" name="valueINeed" />
 <input type="submit" value="View Report" />
</form> 

controller:

[HttpPost]
public ActionResult myAction(string valueINeed)
{
   //....
}

Chrome, Javascript, window.open in new tab

if you use window.open(url, '_blank') , it will be blocked(popup blocker) on Chrome,Firefox etc

try this,

$('#myButton').click(function () {
    var redirectWindow = window.open('http://google.com', '_blank');
    redirectWindow.location;
});

working js fiddle for this http://jsfiddle.net/safeeronline/70kdacL4/2/

working js fiddle for ajax window open http://jsfiddle.net/safeeronline/70kdacL4/1/

ASP.NET Temporary files cleanup

Just an update on more current OS's (Vista, Win7, etc.) - the temp file path has changed may be different based on several variables. The items below are not definitive, however, they are a few I have encountered:

"temp" environment variable setting - then it would be:

%temp%\Temporary ASP.NET Files

Permissions and what application/process (VS, IIS, IIS Express) is running the .Net compiler. Accessing the C:\WINDOWS\Microsoft.NET\Framework folders requires elevated permissions and if you are not developing under an account with sufficient permissions then this folder might be used:

c:\Users\[youruserid]\AppData\Local\Temp\Temporary ASP.NET Files

There are also cases where the temp folder can be set via config for a machine or site specific using this:

<compilation tempDirectory="d:\MyTempPlace" />

I even have a funky setup at work where we don't run Admin by default, plus the IT guys have login scripts that set %temp% and I get temp files in 3 different locations depending on what is compiling things! And I'm still not certain about how these paths get picked....sigh.

Still, dthrasher is correct, you can just delete these and VS and IIS will just recompile them as needed.

Meaning of "[: too many arguments" error from if [] (square brackets)

I have had same problem with my scripts. But when I did some modifications it worked for me. I did like this :-

export k=$(date "+%k");
if [ $k -ge 16 ] 
    then exit 0; 
else 
    echo "good job for nothing"; 
fi;

that way I resolved my problem. Hope that will help for you too.

How to store custom objects in NSUserDefaults

Swift 3

class MyObject: NSObject, NSCoding  {
    let name : String
    let url : String
    let desc : String

    init(tuple : (String,String,String)){
        self.name = tuple.0
        self.url = tuple.1
        self.desc = tuple.2
    }
    func getName() -> String {
        return name
    }
    func getURL() -> String{
        return url
    }
    func getDescription() -> String {
        return desc
    }
    func getTuple() -> (String, String, String) {
        return (self.name,self.url,self.desc)
    }

    required init(coder aDecoder: NSCoder) {
        self.name = aDecoder.decodeObject(forKey: "name") as? String ?? ""
        self.url = aDecoder.decodeObject(forKey: "url") as? String ?? ""
        self.desc = aDecoder.decodeObject(forKey: "desc") as? String ?? ""
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(self.name, forKey: "name")
        aCoder.encode(self.url, forKey: "url")
        aCoder.encode(self.desc, forKey: "desc")
    }
    }

to store and retrieve:

func save() {
            let data  = NSKeyedArchiver.archivedData(withRootObject: object)
            UserDefaults.standard.set(data, forKey:"customData" )
        }
        func get() -> MyObject? {
            guard let data = UserDefaults.standard.object(forKey: "customData") as? Data else { return nil }
            return NSKeyedUnarchiver.unarchiveObject(with: data) as? MyObject
        }

Elevating process privilege programmatically?

This code puts the above all together and restarts the current wpf app with admin privs:

if (IsAdministrator() == false)
{
    // Restart program and run as admin
    var exeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
    ProcessStartInfo startInfo = new ProcessStartInfo(exeName);
    startInfo.Verb = "runas";
    System.Diagnostics.Process.Start(startInfo);
    Application.Current.Shutdown();
    return;
}

private static bool IsAdministrator()
{
    WindowsIdentity identity = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(identity);
    return principal.IsInRole(WindowsBuiltInRole.Administrator);
}


// To run as admin, alter exe manifest file after building.
// Or create shortcut with "as admin" checked.
// Or ShellExecute(C# Process.Start) can elevate - use verb "runas".
// Or an elevate vbs script can launch programs as admin.
// (does not work: "runas /user:admin" from cmd-line prompts for admin pass)

Update: The app manifest way is preferred:

Right click project in visual studio, add, new application manifest file, change the file so you have requireAdministrator set as shown in the above.

A problem with the original way: If you put the restart code in app.xaml.cs OnStartup, it still may start the main window briefly even though Shutdown was called. My main window blew up if app.xaml.cs init was not run and in certain race conditions it would do this.

In Java, how to find if first character in a string is upper case without regex

we can find upper case letter by using regular expression as well

private static void findUppercaseFirstLetterInString(String content) {
    Matcher m = Pattern
            .compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(
                    content);
    System.out.println("Given input string : " + content);
    while (m.find()) {
        if (m.group(1).equals(m.group(1).toUpperCase())) {
            System.out.println("First Letter Upper case match found :"
                    + m.group());
        }
    }
}

for detailed example . please visit http://www.onlinecodegeek.com/2015/09/how-to-determines-if-string-starts-with.html

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

In my case, it's related to the Toggle Vrapper Icon in the Eclipse.

If you are getting the bold black cursor, then the icon must be enabled. So, click on the Toggle Vrapper Icon to disable. It's located in the Eclipse's Toolbar. Please see the attached image for the clarity.

enter image description here

no debugging symbols found when using gdb

The most frequent cause of "no debugging symbols found" when -g is present is that there is some "stray" -s or -S argument somewhere on the link line.

From man ld:

   -s
   --strip-all
       Omit all symbol information from the output file.

   -S
   --strip-debug
       Omit debugger symbol information (but not all symbols) from the output file.

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

I had the same error. My issue was using the wrong parameter name when binding.

Notice :tokenHash in the query, but :token_hash when binding. Fixing one or the other resolves the error in this instance.

// Prepare DB connection
$sql = 'INSERT INTO rememberedlogins (token_hash,user_id,expires_at)
        VALUES (:tokenHash,:user_id,:expires_at)';
$db = static::getDB();
$stmt = $db->prepare($sql);

// Bind values
$stmt->bindValue(':token_hash',$hashed_token,PDO::PARAM_STR);

How do I build an import library (.lib) AND a DLL in Visual C++?

you also should specify def name in the project settings here:

Configuration > Properties/Input/Advanced/Module > Definition File

#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)

If you are adding a foreign key and faced this error, it could be the value in the child table is not present in the parent table.

Let's say for the column to which the foreign key has to be added has all values set to 0 and the value is not available in the table you are referencing it.

You can set some value which is present in the parent table and then adding foreign key worked for me.

javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context

Ftrujillo's answer works well but if you only have one package to scan this is the shortest form::

    @Bean
    public Jaxb2Marshaller marshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setContextPath("your.package.to.scan");
        return marshaller;
    }

How to sort a list of strings numerically?

real problem is that sort sorts things alphanumerically. So if you have a list ['1', '2', '10', '19'] and run sort you get ['1', '10'. '19', '2']. ie 10 comes before 2 because it looks at the first character and sorts starting from that. It seems most methods in python return things in that order. For example if you have a directory named abc with the files labelled as 1.jpg, 2.jpg etc say up to 15.jpg and you do file_list=os.listdir(abc) the file_list is not ordered as you expect but rather as file_list=['1.jpg', '11.jpg'---'15.jpg', '2.jpg]. If the order in which files are processed is important (presumably that's why you named them numerically) the order is not what you think it will be. You can avoid this by using "zeros" padding. For example if you have a list alist=['01', '03', '05', '10', '02','04', '06] and you run sort on it you get the order you wanted. alist=['01', '02' etc] because the first character is 0 which comes before 1. The amount of zeros padding you need is determined by the largest value in the list.For example if the largest is say between 100 and 1000 you need to pad single digits as 001, 002 ---010,011--100, 101 etc.

How to convert a hex string to hex number

Use int function with second parameter 16, to convert a hex string to an integer. Finally, use hex function to convert it back to a hexadecimal number.

print hex(int("0xAD4", 16) + int("0x200", 16)) # 0xcd4

Instead you could directly do

print hex(int("0xAD4", 16) + 0x200) # 0xcd4

How do I catch a PHP fatal (`E_ERROR`) error?

I need to handle fatal errors for production to instead show a static styled 503 Service Unavailable HTML output. This is surely a reasonable approach to "catching fatal errors". This is what I've done:

I have a custom error handling function "error_handler" which will display my "503 service unavailable" HTML page on any E_ERROR, E_USER_ERROR, etc. This will now be called on the shutdown function, catching my fatal error,

function fatal_error_handler() {

    if (@is_array($e = @error_get_last())) {
        $code = isset($e['type']) ? $e['type'] : 0;
        $msg = isset($e['message']) ? $e['message'] : '';
        $file = isset($e['file']) ? $e['file'] : '';
        $line = isset($e['line']) ? $e['line'] : '';
        if ($code>0)
            error_handler($code, $msg, $file, $line);
    }
}
set_error_handler("error_handler");
register_shutdown_function('fatal_error_handler');

in my custom error_handler function, if the error is E_ERROR, E_USER_ERROR, etc. I also call @ob_end_clean(); to empty the buffer, thus removing PHP's "fatal error" message.

Take important note of the strict isset() checking and @ silencing functions since we don’t want our error_handler scripts to generate any errors.

In still agreeing with keparo, catching fatal errors does defeat the purpose of "FATAL error" so it's not really intended for you to do further processing. Do not run any mail() functions in this shutdown process as you will certainly back up the mail server or your inbox. Rather log these occurrences to file and schedule a cron job to find these error.log files and mail them to administrators.

The infamous java.sql.SQLException: No suitable driver found

No matter how old this thread becomes, people would continue to face this issue.

My Case: I have the latest (at the time of posting) OpenJDK and maven setup. I had tried all methods given above, with/out maven and even solutions on sister posts on StackOverflow. I am not using any IDE or anything else, running from bare CLI to demonstrate only the core logic.

Here's what finally worked.

  • Download the driver from the official site. (for me it was MySQL https://www.mysql.com/products/connector/). Use your flavour here.
  • Unzip the given jar file in the same directory as your java project. You would get a directory structure like this. If you look carefully, this exactly relates to what we try to do using Class.forName(....). The file that we want is the com/mysql/jdbc/Driver.class

https://i.imgur.com/VgpwatQ.png

  • Compile the java program containing the code.
javac App.java
  • Now load the director as a module by running
java --module-path com/mysql/jdbc -cp ./ App

This would load the (extracted) package manually, and your java program would find the required Driver class.


  • Note that this was done for the mysql driver, other drivers might require minor changes.
  • If your vendor provides a .deb image, you can get the jar from /usr/share/java/your-vendor-file-here.jar

Byte and char conversion in Java

new String(byteArray, Charset.defaultCharset())

This will convert a byte array to the default charset in java. It may throw exceptions depending on what you supply with the byteArray.

JavaScript and Threads

See http://caniuse.com/#search=worker for the most up-to-date support info.

The following was the state of support circa 2009.


The words you want to google for are JavaScript Worker Threads

Apart from from Gears there's nothing available right now, but there's plenty of talk about how to implement this so I guess watch this question as the answer will no doubt change in future.

Here's the relevant documentation for Gears: WorkerPool API

WHATWG has a Draft Recommendation for worker threads: Web Workers

And there's also Mozilla’s DOM Worker Threads


Update: June 2009, current state of browser support for JavaScript threads

Firefox 3.5 has web workers. Some demos of web workers, if you want to see them in action:

The Gears plugin can also be installed in Firefox.

Safari 4, and the WebKit nightlies have worker threads:

Chrome has Gears baked in, so it can do threads, although it requires a confirmation prompt from the user (and it uses a different API to web workers, although it will work in any browser with the Gears plugin installed):

  • Google Gears WorkerPool Demo (not a good example as it runs too fast to test in Chrome and Firefox, although IE runs it slow enough to see it blocking interaction)

IE8 and IE9 can only do threads with the Gears plugin installed

Eliminating NAs from a ggplot

Try remove_missing instead with vars = the_variable. It is very important that you set the vars argument, otherwise remove_missing will remove all rows that contain an NA in any column!! Setting na.rm = TRUE will suppress the warning message.

ggplot(data = remove_missing(MyData, na.rm = TRUE, vars = the_variable),aes(x= the_variable, fill=the_variable, na.rm = TRUE)) + 
       geom_bar(stat="bin") 

How to create a drop shadow only on one side of an element?

I think this is what you're after?

_x000D_
_x000D_
.shadow {_x000D_
  -webkit-box-shadow: 0 0 0 4px white, 0 6px 4px black;_x000D_
  -moz-box-shadow: 0 0 0 4px white, 0 6px 4px black;_x000D_
  box-shadow: 0 0 0 4px white, 0 6px 4px black;_x000D_
}
_x000D_
<div class="shadow">wefwefwef</div>
_x000D_
_x000D_
_x000D_

How should strace be used?

Minimal runnable example

If a concept is not clear, there is a simpler example that you haven't seen that explains it.

In this case, that example is the Linux x86_64 assembly freestanding (no libc) hello world:

hello.S

.text
.global _start
_start:
    /* write */
    mov $1, %rax    /* syscall number */
    mov $1, %rdi    /* stdout */
    mov $msg, %rsi  /* buffer */
    mov $len, %rdx  /* buffer len */
    syscall

    /* exit */
    mov $60, %rax   /* exit status */
    mov $0, %rdi    /* syscall number */
    syscall
msg:
    .ascii "hello\n"
len = . - msg

GitHub upstream.

Assemble and run:

as -o hello.o hello.S
ld -o hello.out hello.o
./hello.out

Outputs the expected:

hello

Now let's use strace on that example:

env -i ASDF=qwer strace -o strace.log -s999 -v ./hello.out arg0 arg1
cat strace.log

We use:

strace.log now contains:

execve("./hello.out", ["./hello.out", "arg0", "arg1"], ["ASDF=qwer"]) = 0
write(1, "hello\n", 6)                  = 6
exit(0)                                 = ?
+++ exited with 0 +++

With such a minimal example, every single character of the output is self evident:

  • execve line: shows how strace executed hello.out, including CLI arguments and environment as documented at man execve

  • write line: shows the write system call that we made. 6 is the length of the string "hello\n".

    = 6 is the return value of the system call, which as documented in man 2 write is the number of bytes written.

  • exit line: shows the exit system call that we've made. There is no return value, since the program quit!

More complex examples

The application of strace is of course to see which system calls complex programs are actually doing to help debug / optimize your program.

Notably, most system calls that you are likely to encounter in Linux have glibc wrappers, many of them from POSIX.

Internally, the glibc wrappers use inline assembly more or less like this: How to invoke a system call via sysenter in inline assembly?

The next example you should study is a POSIX write hello world:

main.c

#define _XOPEN_SOURCE 700
#include <unistd.h>

int main(void) {
    char *msg = "hello\n";
    write(1, msg, 6);
    return 0;
}

Compile and run:

gcc -std=c99 -Wall -Wextra -pedantic -o main.out main.c
./main.out

This time, you will see that a bunch of system calls are being made by glibc before main to setup a nice environment for main.

This is because we are now not using a freestanding program, but rather a more common glibc program, which allows for libc functionality.

Then, at the every end, strace.log contains:

write(1, "hello\n", 6)                  = 6
exit_group(0)                           = ?
+++ exited with 0 +++

So we conclude that the write POSIX function uses, surprise!, the Linux write system call.

We also observe that return 0 leads to an exit_group call instead of exit. Ha, I didn't know about this one! This is why strace is so cool. man exit_group then explains:

This system call is equivalent to exit(2) except that it terminates not only the calling thread, but all threads in the calling process's thread group.

And here is another example where I studied which system call dlopen uses: https://unix.stackexchange.com/questions/226524/what-system-call-is-used-to-load-libraries-in-linux/462710#462710

Tested in Ubuntu 16.04, GCC 6.4.0, Linux kernel 4.4.0.

Separating class code into a header and cpp file

You leave the declarations in the header file:

class A2DD
{
  private:
  int gx;
  int gy;

  public:
    A2DD(int x,int y); // leave the declarations here
    int getSum();
};

And put the definitions in the implementation file.

A2DD::A2DD(int x,int y) // prefix the definitions with the class name
{
  gx = x;
  gy = y;
}

int A2DD::getSum()
{
  return gx + gy;
}

You could mix the two (leave getSum() definition in the header for instance). This is useful since it gives the compiler a better chance at inlining for example. But it also means that changing the implementation (if left in the header) could trigger a rebuild of all the other files that include the header.

Note that for templates, you need to keep it all in the headers.