Programs & Examples On #Sapi

SAPI is Microsoft's Speech API which provides text-to-speech (TTS) and speech recognition (SR) functionality to applications.

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

I was also facing the same issue until I added the type="module" to the script.

Before it was like this

<script src="../src/main.js"></script>

And after changing it to

<script type="module" src="../src/main.js"></script>

It worked perfectly.

Specifying ssh key in ansible playbook file

You can use the ansible.cfg file, it should look like this (There are other parameters which you might want to include):

[defaults]
inventory = <PATH TO INVENTORY FILE>
remote_user = <YOUR USER>
private_key_file =  <PATH TO KEY_FILE>

Hope this saves you some typing

YouTube Autoplay not working

This code allows you to autoplay iframe video

<iframe src="https://www.youtube.com/embed/2MpUj-Aua48?rel=0&modestbranding=1&autohide=1&mute=1&showinfo=0&controls=0&autoplay=1"  width="560" height="315"  frameborder="0" allowfullscreen></iframe>

Here Is working fiddle

Install pip in docker

While T. Arboreus's answer might fix the issues with resolving 'archive.ubuntu.com', I think the last error you're getting says that it doesn't know about the packages php5-mcrypt and python-pip. Nevertheless, the reduced Dockerfile of you with just these two packages worked for me (using Debian 8.4 and Docker 1.11.0), but I'm not quite sure if that could be the case because my host system is different than yours.

FROM ubuntu:14.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    php5-mcrypt \
    python-pip

However, according to this answer you should think about installing the python3-pip package instead of the python-pip package when using Python 3.x.

Furthermore, to make the php5-mcrypt package installation working, you might want to add the universe repository like it's shown right here. I had trouble with the add-apt-repository command missing in the Ubuntu Docker image so I installed the package software-properties-common at first to make the command available.

Splitting up the statements and putting apt-get update and apt-get install into one RUN command is also recommended here.

Oh and by the way, you actually don't need the -y flag at apt-get update because there is nothing that has to be confirmed automatically.

Finally:

FROM ubuntu:14.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    software-properties-common
RUN add-apt-repository universe
RUN apt-get update && apt-get install -y \
    apache2 \
    curl \
    git \
    libapache2-mod-php5 \
    php5 \
    php5-mcrypt \
    php5-mysql \
    python3.4 \
    python3-pip

Remark: The used versions (e.g. of Ubuntu) might be outdated in the future.

ssh : Permission denied (publickey,gssapi-with-mic)

Setting PasswordAuthentication to yes, is not the best way to go , is not as secure as using private and public keys for authentication !

First make sure that that you have the fallowing permissions set, on the server side.

First check your home dir (SERVER SIDE)

[vini@random ~]$ ls -ld ~

drwx------. 3 vini vini 127 Nov 23 15:29 /home/vini

if it is not like this, run

chmod 0700 /home/your_home

Now check .ssh folder

[vini@random ~]$ ls -ld  /home/vini/.ssh/

drwx------. 2 vini vini 29 Nov 23 15:28 /home/vini/.ssh/

if it is not looking like this, run

chmod 0700 /home/your_home/.ssh

now make sure that authorized_keys looks like this

[vini@venon ~]$ ls -ld  /home/vini/.ssh/authorized_keys 

-rw-------. 1 vini vini 393 Nov 23 15:28 /home/vini/.ssh/authorized_keys

or just run

chmod 0600 /home/your_home/.ssh/authorized_keys

After that go to /etc/ssh/sshd_config

For best security set

PermitRootLogin no

PubkeyAuthentication yes

keep as yes for testing purposes

PasswordAuthentication yes

Make sure that

ChallengeResponseAuthentication no

Comment those lines for GSSAPI

# #GSSAPIAuthentication yes
# #GSSAPICleanupCredentials no

Make sure that is set to UsePAM yes

UsePAM yes

now restart sshd service

systemctl restart sshd 

on the client side

cd /home/your_home/.ssh

generate new keys; setting a password is optional but is a good idea

ssh-keygen -t rsa -b 2048  

copy pub key to your server

ssh-copy-id -i id_rsa.pub user_name@server_ip 

start ssh agent 

eval $(ssh-agent)

ssh-add /home/user/.ssh/your_private_key

now your are good to go !

ssh user_name@server_ip

if everything works just fine

make a backup of your private key and then deny PasswordAuthentication

PasswordAuthentication no 

Restart you server

now anyone trying to ssh into your server, without your keys should get

vini@random: Permission denied (publickey).

keep script kids away from your business, and good luck

How can I enable the MySQLi extension in PHP 7?

In Ubuntu, you need to uncomment this line in file php.ini which is located at /etc/php/7.0/apache2/php.ini:

extension=php_mysqli.so

turn typescript object into json string

TS gets compiled to JS which then executed. Therefore you have access to all of the objects in the JS runtime. One of those objects is the JSON object. This contains the following methods:

  • JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
  • JSON.stringify() method converts a JavaScript object or value to a JSON string.

Example:

_x000D_
_x000D_
const jsonString = '{"employee":{ "name":"John", "age":30, "city":"New York" }}';_x000D_
_x000D_
_x000D_
const JSobj = JSON.parse(jsonString);_x000D_
_x000D_
console.log(JSobj);_x000D_
console.log(typeof JSobj);_x000D_
_x000D_
const JSON_string = JSON.stringify(JSobj);_x000D_
_x000D_
console.log(JSON_string);_x000D_
console.log(typeof JSON_string);
_x000D_
_x000D_
_x000D_

Forward X11 failed: Network error: Connection refused

The D-Bus error can be fixed with dbus-launch :

dbus-launch command

Applying an ellipsis to multiline text

If you also have multiple elements and you want a link with read more button after ellipsis, take a look on https://stackoverflow.com/a/51418807/10104342

If you want something like this:

Every month first 10 TB are are not charged. All other traffic... Read more

java.lang.IllegalStateException: Fragment not attached to Activity

I Found Very Simple Solution isAdded() method which is one of the fragment method to identify that this current fragment is attached to its Activity or not.

we can use this like everywhere in fragment class like:

if(isAdded())
{

// using this method, we can do whatever we want which will prevent   **java.lang.IllegalStateException: Fragment not attached to Activity** exception.

}

How to fix symbol lookup error: undefined symbol errors in a cluster environment

yum update

helped me out. After I had

wget: symbol lookup error: wget: undefined symbol: psl_latest

Laravel: Error [PDOException]: Could not Find Driver in PostgreSQL

I had the same issue. This is what worked for me.

There are 2 php.ini files:

  • C:\wamp\bin\apache\apache2.4.9\bin
  • C:\wamp\bin\php\php5.5.12

NOTE: This is using my version of PHP and Apache, change to what yours are.

The php.ini file located in the both folders is what you need to update, the extentions:

  • extension=php_pdo_pgsql.dll
  • extension=php_pgsql.dll

These are what you need to uncomment (remove the ; symbol).

Restart both Wamp and the Command Prompt.

Hopefully it will work for you :).

How to manually force a commit in a @Transactional method?

I had a similar use case during testing hibernate event listeners which are only called on commit.

The solution was to wrap the code to be persistent into another method annotated with REQUIRES_NEW. (In another class) This way a new transaction is spawned and a flush/commit is issued once the method returns.

Tx prop REQUIRES_NEW

Keep in mind that this might influence all the other tests! So write them accordingly or you need to ensure that you can clean up after the test ran.

How to get an IFrame to be responsive in iOS Safari?

The problem, it seems, is that Mobile Safari will refuse to obey the width of your iFrame if the document it contains is wider than what you have specified. Example:

http://jsbin.com/hapituto/1

On a desktop browser, you will see an iFrame and a Div both set to 300px. The contents is wider so you can scroll the iFrame.

On mobile safari, however, you will notice that the iFrame is auto-expanded to the width of the content.

My guess is that this is a workaround for long-standing issues with scrolling content within a page. In the past, if you had a large scrolling iframe on a touch device, you'd get 'stuck' in the iframe as that would be scrolling instead of the page itself. It appears Apple has decided that the default behavior of an iFrame is 'no scroll' and expands to prevent it.

One option may be this workaround. Instead of assuming the iFrame will scroll, place the iframe in a DIV that you do have control over and let that scroll.

example: http://jsbin.com/zakedaja/1

Example markup:

<div style="overflow: scroll; -webkit-overflow-scrolling: touch; width: 300px;">
   <iframe src="http://jsbin.com/roredora/1/" style="width: 600px;"></iframe>
</div>

On mobile safari, you can now scroll the contents of the now fully-expanded iFrame via the div that is containing it.

The catch: This looks really ugly on a desktop browser, as now you have double scrollbars. So you may have to do some browser detection with JS to get around this.

PHP: maximum execution time when importing .SQL data file

Best solution for this error when i tried some points. Follow this steps to solve this issue:

  1. locate the file [XAMPP Installation Directory]\php\php.ini (e.g. C:\xampp\php\php.ini)
  2. open php.ini in Notepad or any Text editor
  3. locate the line containing max_execution_time and
  4. increase the value from 30 to some larger number (e.g. set: max_execution_time = 90)
  5. then restart Apache web server from the XAMPP control panel

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

Go to your web.config/App.config to verify which .net runtime you are using

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>

Here is the solution:

  1. .NET 4.6 and above. You don’t need to do any additional work to support TLS 1.2, it’s supported by default.

  2. .NET 4.5. TLS 1.2 is supported, but it’s not a default protocol. You need to opt-in to use it. The following code will make TLS 1.2 default, make sure to execute it before making a connection to secured resource:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

  1. .NET 4.0. TLS 1.2 is not supported, but if you have .NET 4.5 (or above) installed on the system then you still can opt in for TLS 1.2 even if your application framework doesn’t support it. The only problem is that SecurityProtocolType in .NET 4.0 doesn’t have an entry for TLS1.2, so we’d have to use a numerical representation of this enum value:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

  1. .NET 3.5 or below. TLS 1.2 is not supported (*) and there is no workaround. Upgrade your application to more recent version of the framework.

Disable password authentication for SSH

The one-liner to disable SSH password authentication:

sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config && service ssh restart

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

I got the same error and I changed my version from 4 to 3 and it is solved:

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <!-- Ensure correct version of MVC -->
    <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
    </dependentAssembly>
</assemblyBinding>

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

I ran into this issue when I forgot to set my Connections.config file to "copy always"

BareMessage = "Unable to open configSource file 'Connections.config'."

WhatsApp API (java/python)

From my blog

courtesy

There is a secret pilot program which WhatsApp is working on with selected businesses

News coverage:

For some of my technical experiments, I was trying to figure out how beneficial and feasible it is to implement bots for different chat platforms in terms of market share and so possibilities of adaptation. Especially when you have bankruptly failed twice, it's important to validate ideas and fail more faster.

Popular chat platforms like Messenger, Slack, Skype etc. have happily (in the sense officially) provided APIs for bots to interact with, but WhatsApp has not yet provided any API.

However, since many years, a lot of activities has happened around this - struggle towards automated interaction with WhatsApp platform:

  1. Bots App Bots App is interesting because it shows that something is really tried and tested.

  2. Yowsup A project still actively developed to interact with WhatsApp platform.

  3. Yallagenie Yallagenie claim that there is a demo bot which can be interacted with at +971 56 112 6652

  4. Hubtype Hubtype is working towards having a bot platform for WhatsApp for business.

  5. Fred Fred's task was to automate WhatsApp conversations, however since it was not officially supported by WhatsApp - it was shut down.

  6. Oye Gennie A bot blocked by WhatsApp.

  7. App/Website to WhatsApp We can use custom URL schemes and Android intent system to interact with WhatsApp but still NOT WhatsApp API.

  8. Chat API daemon Probably created by inspecting the API calls in WhatsApp web version. NOT affiliated with WhatsApp.

  9. WhatsBot Deactivated WhatsApp bot. Created during a hackathon.

  10. No API claim WhatsApp co-founder clearly stated this in a conference that they did not had any plans for APIs for WhatsApp.

  11. Bot Ware They probably are expecting WhatsApp to release their APIs for chat bot platforms.

  12. Vixi They seems to be talking about how some platform which probably would work for WhatsApp. There is no clarity as such.

  13. Unofficial API This API can shut off any time.

    And the number goes on...

Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

I followed everything from here: https://cloud.google.com/compute/docs/instances/connecting-to-instance#generatesshkeypair

But still there was an error and SSH keys in my instance metadata wasn't getting recognized.

Solution: Check if your ssh key has any new-line. When I copied my public key using cat, it added into-lines into the key, thus breaking the key. Had to manually check any line-breaks and correct it.

JDBC connection to MSSQL server in windows authentication mode

Try following these steps:

  1. Add the integratedSecurity=true to JDBC URL like this:

    Url: jdbc:sqlserver://<<Server>>:<<Port>>;databasename=<<DatabaseName>>;integratedsecurity=true 
    
  2. Make sure to add the sqljdbc driver 4 or above version (sqljdbc.jar) in your project build path:

    java.sql.DatabaseMetaData metaData = connection.getMetaData();
    System.out.println("Driver version:" + metaData.getDriverVersion());
    
  3. Add the VM argument for your project:

    • Find the sqljdbc_auth.dll file from DB installed server (C:\Program Files\sqljdbc_4.0\enu\auth\x86), or download from this link.

    • Place the dll file in your project folder and specify the VM argument like this: VM Argument: -Djava.library.path="<<DLL File path till folder>>"

      NOTE: Check your java version 32/64 bit then add 32/64 bit version dll file accordingly.

How do I configure different environments in Angular.js?

Very late to the thread, but a technique I've used, pre-Angular, is to take advantage of JSON and the flexibility of JS to dynamically reference collection keys, and use inalienable facts of the environment (host server name, current browser language, etc.) as inputs to selectively discriminate/prefer suffixed key names within a JSON data structure.

This provides not merely deploy-environment context (per OP) but any arbitrary context (such as language) to provide i18n or any other variance required simultaneously, and (ideally) within a single configuration manifest, without duplication, and readably obvious.

IN ABOUT 10 LINES VANILLA JS

Overly-simplified but classic example: An API endpoint base URL in a JSON-formatted properties file that varies per environment where (natch) the host server will also vary:

    ...
    'svcs': {
        'VER': '2.3',
        'API@localhost': 'http://localhost:9090/',
        '[email protected]': 'https://www.uat.productionwebsite.com:9090/res/',
        '[email protected]': 'https://www.productionwebsite.com:9090/api/res/'
    },
    ...

A key to the discrimination function is simply the server hostname in the request.

This, naturally, can be combined with an additional key based on the user's language settings:

    ...
    'app': {
        'NAME': 'Ferry Reservations',
        'NAME@fr': 'Réservations de ferry',
        'NAME@de': 'Fähren Reservierungen'
    },
    ...

The scope of the discrimination/preference can be confined to individual keys (as above) where the "base" key is only overwritten if there's a matching key+suffix for the inputs to the function -- or an entire structure, and that structure itself recursively parsed for matching discrimination/preference suffixes:

    'help': {
        'BLURB': 'This pre-production environment is not supported. Contact Development Team with questions.',
        'PHONE': '808-867-5309',
        'EMAIL': '[email protected]'
    },
    '[email protected]': {
        'BLURB': 'Please contact Customer Service Center',
        'BLURB@fr': 'S\'il vous plaît communiquer avec notre Centre de service à la clientèle',
        'BLURB@de': 'Bitte kontaktieren Sie unseren Kundendienst!!1!',
        'PHONE': '1-800-CUS-TOMR',
        'EMAIL': '[email protected]'
    },

SO, if a visiting user to the production website has German (de) language preference setting, the above configuration would collapse to:

    'help': {
        'BLURB': 'Bitte kontaktieren Sie unseren Kundendienst!!1!',
        'PHONE': '1-800-CUS-TOMR',
        'EMAIL': '[email protected]'
    },

What does such a magical preference/discrimination JSON-rewriting function look like? Not much:

// prefer(object,suffix|[suffixes]) by/par/durch storsoc
// prefer({ a: 'apple', a@env: 'banana', b: 'carrot' },'env') -> { a: 'banana', b: 'carrot' }
function prefer(o,sufs) {
    for (var key in o) {
        if (!o.hasOwnProperty(key)) continue; // skip non-instance props
        if(key.split('@')[1]) { // suffixed!
            // replace root prop with the suffixed prop if among prefs
            if(o[key] && sufs.indexOf(key.split('@')[1]) > -1) o[key.split('@')[0]] = JSON.parse(JSON.stringify(o[key]));

            // and nuke the suffixed prop to tidy up
            delete o[key];

            // continue with root key ...
            key = key.split('@')[0];
        }

        // ... in case it's a collection itself, recurse it!
        if(o[key] && typeof o[key] === 'object') prefer(o[key],sufs);

    };
};

In our implementations, which include Angular and pre-Angular websites, we simply bootstrap the configuration well ahead of other resource calls by placing the JSON within a self-executing JS closure, including the prefer() function, and fed basic properties of hostname and language-code (and accepts any additional arbitrary suffixes you might need):

(function(prefs){ var props = {
    'svcs': {
        'VER': '2.3',
        'API@localhost': 'http://localhost:9090/',
        '[email protected]': 'https://www.uat.productionwebsite.com:9090/res/',
        '[email protected]': 'https://www.productionwebsite.com:9090/api/res/'
    },
    ...
    /* yadda yadda moar JSON und bisque */

    function prefer(o,sufs) {
        // body of prefer function, broken for e.g.
    };

    // convert string and comma-separated-string to array .. and process it
    prefs = [].concat( ( prefs.split ? prefs.split(',') : prefs ) || []);
    prefer(props,prefs);
    window.app_props = JSON.parse(JSON.stringify(props));
})([location.hostname, ((window.navigator.userLanguage || window.navigator.language).split('-')[0])  ] );

A pre-Angular site would now have a collapsed (no @ suffixed keys) window.app_props to refer to.

An Angular site, as a bootstrap/init step, simply copies the dead-dropped props object into $rootScope, and (optionally) destroys it from global/window scope

app.constant('props',angular.copy(window.app_props || {})).run( function ($rootScope,props) { $rootScope.props = props; delete window.app_props;} );

to be subsequently injected into controllers:

app.controller('CtrlApp',function($log,props){ ... } );

or referred to from bindings in views:

<span>{{ props.help.blurb }} {{ props.help.email }}</span>

Caveats? The @ character is not valid JS/JSON variable/key naming, but so far accepted. If that's a deal-breaker, substitute for any convention you like, such as "__" (double underscore) as long as you stick to it.

The technique could be applied server-side, ported to Java or C# but your efficiency/compactness may vary.

Alternately, the function/convention could be part of your front-end compile script, so that the full gory all-environment/all-language JSON is never transmitted over the wire.

UPDATE

We've evolved usage of this technique to allow multiple suffixes to a key, to avoid being forced to use collections (you still can, as deeply as you want), and as well to honor the order of the preferred suffixes.

Example (also see working jsFiddle):

var o = { 'a':'apple', 'a@dev':'apple-dev', 'a@fr':'pomme',
          'b':'banana', 'b@fr':'banane', 'b@dev&fr':'banane-dev',
          'c':{ 'o':'c-dot-oh', 'o@fr':'c-point-oh' }, 'c@dev': { 'o':'c-dot-oh-dev', 'o@fr':'c-point-oh-dev' } };

/*1*/ prefer(o,'dev');        // { a:'apple-dev', b:'banana',     c:{o:'c-dot-oh-dev'}   }
/*2*/ prefer(o,'fr');         // { a:'pomme',     b:'banane',     c:{o:'c-point-oh'}     }
/*3*/ prefer(o,'dev,fr');     // { a:'apple-dev', b:'banane-dev', c:{o:'c-point-oh-dev'} }
/*4*/ prefer(o,['fr','dev']); // { a:'pomme',     b:'banane-dev', c:{o:'c-point-oh-dev'} }
/*5*/ prefer(o);              // { a:'apple',     b:'banana',     c:{o:'c-dot-oh'}       }

1/2 (basic usage) prefers '@dev' keys, discards all other suffixed keys

3 prefers '@dev' over '@fr', prefers '@dev&fr' over all others

4 (same as 3 but prefers '@fr' over '@dev')

5 no preferred suffixes, drops ALL suffixed properties

It accomplishes this by scoring each suffixed property and promoting the value of a suffixed property to the non-suffixed property when iterating over the properties and finding a higher-scored suffix.

Some efficiencies in this version, including removing dependence on JSON to deep-copy, and only recursing into objects that survive the scoring round at their depth:

function prefer(obj,suf) {
    function pr(o,s) {
        for (var p in o) {
            if (!o.hasOwnProperty(p) || !p.split('@')[1] || p.split('@@')[1] ) continue; // ignore: proto-prop OR not-suffixed OR temp prop score
            var b = p.split('@')[0]; // base prop name
            if(!!!o['@@'+b]) o['@@'+b] = 0; // +score placeholder
            var ps = p.split('@')[1].split('&'); // array of property suffixes
            var sc = 0; var v = 0; // reset (running)score and value
            while(ps.length) {
                // suffix value: index(of found suffix in prefs)^10
                v = Math.floor(Math.pow(10,s.indexOf(ps.pop())));
                if(!v) { sc = 0; break; } // found suf NOT in prefs, zero score (delete later)
                sc += v;
            }
            if(sc > o['@@'+b]) { o['@@'+b] = sc; o[b] = o[p]; } // hi-score! promote to base prop
            delete o[p];
        }
        for (var p in o) if(p.split('@@')[1]) delete o[p]; // remove scores
        for (var p in o) if(typeof o[p] === 'object') pr(o[p],s); // recurse surviving objs
    }
    if( typeof obj !== 'object' ) return; // validate
    suf = ( (suf || suf === 0 ) && ( suf.length || suf === parseFloat(suf) ) ? suf.toString().split(',') : []); // array|string|number|comma-separated-string -> array-of-strings
    pr(obj,suf.reverse());
}

Stop embedded youtube iframe?

Talvi's answer may still work, but that Youtube Javascript API has been marked as deprecated. You should now be using the newer Youtube IFrame API.

The documentation provides a few ways to accomplish video embedding, but for your goal, you'd include the following:

//load the IFrame Player API code asynchronously
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

//will be youtube player references once API is loaded
var players = [];

//gets called once the player API has loaded
function onYouTubeIframeAPIReady() {
    $('.myiframeclass').each(function() {
        var frame = $(this);

        //create each instance using the individual iframe id
        var player = new YT.Player(frame.attr('id'));

        players.push(player);
    });
}

//global stop button click handler
$('#mybutton').click(function(){

    //loop through each Youtube player instance and call stopVideo()
    for (var i in players) {
        var player = players[i];
        player.stopVideo();
    }
});

Cannot get Kerberos service ticket: KrbException: Server not found in Kerberos database (7)

I hope this helps .. I got this same error message (Server not found in Kerberos database (7)) but this occurs after the successful use of the keytab to login.

The error message occurs when we attempt to use the credentials to do LDAP searches against AD.

This has only started happening since java 1.6.0_34 - it worked with 1.6.0_31 which I think was previous release. The error occurs because the java doesn't trust that the KDC it is communicating with for LDAP is actually part of the Kerberos realm. In our case, I think it is because the LDAP connection is made with the server name found via the round-robin'd resolved query. That is, java resolves realm.example.com, but gets any one of kdc1.example.com or kdc2.example .com ..etc). They must have tightened the checking betweeen these releases.

In our case the problem was worked around by setting the ldap server name directly rather than relying on DNS.

But investigations continue.

PHP MySQL Google Chart JSON - Complete Example

Some might encounter this error either locally or on the server:

syntax error var data = new google.visualization.DataTable(<?=$jsonTable?>);

This means that their environment does not support short tags the solution is to use this instead:

<?php echo $jsonTable; ?>

And everything should work fine!

How to Logout of an Application Where I Used OAuth2 To Login With Google?

If any one want it in Java, Here is my Answer, For this you have to call Another Thread.

deleted object would be re-saved by cascade (remove deleted object from associations)

If you don't know, which collection holds your object

In my case it was really hard to apply TomAnderson's solution, since I didn't know what is the collection, which holds a link to an object, so here's the way to know, which objects holds the link to the deleted one: in the debugger you should enter the lowest execution stack level before the exception is thrown, there should be a variable called entityEntry, so you get a PersistenceContext object from this variable: entityEntry.persistenceContext.

For me persistenceContext was an instance of StatefulPersistenceContext and this implementation has private field parentsByChild, from which you can retrieve information about the collection, which contains the element.

I was using Eclipse debugger, so it was kinda hard to retrieve this private field in a straight way, so I used Detail Formatter (How can I watch private fields of other objects directly in the IDE when debugging?)

After getting this information, TomAnderson's solution can be applied.

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

(In Windows and Apache 2.2.x)

The "Forbidden" error is also the result of not having virtual hosts defined.

As noted by Julien, if you intend to use virtual hosts.conf, then go to the httpd file and uncomment the following line:

#Include conf/extra/httpd-vhosts.conf

Then add your virtual hosts definitions in conf/extra/httpd-vhosts.conf and restart Apache.

PHP Fatal error: Call to undefined function mssql_connect()

I am using IIS and mysql (directly downloaded, without wamp or xampp) My php was installed in c:\php I was getting the error of "call to undefined function mysql_connect()" For me the change of extension_dir worked. This is what I did. In the php.ini, Originally, I had this line

; On windows: extension_dir = "ext"

I changed it to:

; On windows: extension_dir = "C:\php\ext"

And it worked. Of course, I did the other things also like uncommenting the dll extensions etc, as explained in others remarks.

Remove padding or margins from Google Charts

There's a theme available specifically for this

options: {
  theme: 'maximized'
}

from the Google chart docs:

Currently only one theme is available:

'maximized' - Maximizes the area of the chart, and draws the legend and all of the labels inside the chart area. Sets the following options:

chartArea: {width: '100%', height: '100%'},
legend: {position: 'in'},
titlePosition: 'in', axisTitlesPosition: 'in',
hAxis: {textPosition: 'in'}, vAxis: {textPosition: 'in'}

How to ssh connect through python Paramiko with ppk public key

To create a valid DSA format private key supported by Paramiko in Puttygen.

Click on Conversions then Export OpenSSH Key

enter image description here

Regex to match any character including new lines

You want to use "multiline".

$string =~ /(START)(.+?)(END)/m;

Select from one table where not in another

You can LEFT JOIN the two tables. If there is no corresponding row in the second table, the values will be NULL.

SELECT id FROM partmaster LEFT JOIN product_details ON (...) WHERE product_details.part_num IS NULL

Problem in running .net framework 4.0 website on iis 7.0

Step 1: Open IIS and click the server name Step 2. Double click “ISAPI and CGI Restrictions” Step 3. Right click ASP.NET v4.0.30319 and select “allow”

After Stopping and Starting the World Wide Web Publishing Service

1.Go to Start > All Programs > Administrative Tools > Services. 2.In the services list, right-click World Wide Web Publishing Service, and then click Stop (to stop the service), Start (to start it after it has been stopped), or Restart (to restart the service when it is running).

Pramesh

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

try my code In JavaScript

 var settings = {
              "url": "https://myinboxhub.co.in/example",
              "method": "GET",
              "timeout": 0,
              "headers": {},
            };
        $.ajax(settings).done(function (response) {
          console.log(response);
            if (response.auth) { 
                console.log('on success');
            } 
        }).fail(function (jqXHR, exception) { 
                var msg = '';
                if (jqXHR.status === '(failed)net::ERR_INTERNET_DISCONNECTED') {
                    
                        msg = 'Uncaught Error.\n' + jqXHR.responseText; 
                }
                if (jqXHR.status === 0) {
                        msg = 'Not connect.\n Verify Network.';
                } else if (jqXHR.status == 413) {
                        msg = 'Image size is too large.'; 
                }  else if (jqXHR.status == 404) {
                        msg = 'Requested page not found. [404]'; 
                } else if (jqXHR.status == 405) {
                        msg = 'Image size is too large.'; 
                } else if (jqXHR.status == 500) {
                        msg = 'Internal Server Error [500].'; 
                } else if (exception === 'parsererror') {
                        msg = 'Requested JSON parse failed.'; 
                } else if (exception === 'timeout') {
                        msg = 'Time out error.'; 
                } else if (exception === 'abort') {
                        msg = 'Ajax request aborted.'; 
                } else {
                        msg = 'Uncaught Error.\n' + jqXHR.responseText; 
                }
                console.log(msg);
        });;

In PHP

header('Content-type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");

Script not served by static file handler on IIS7.5

One of the worst case scenario I just solved is - having conflicting entry in Web.config.

On my local machine I didn't had .woff extension registered in IIS, so I added it using Web.config. But on production server .woff had mime type registered. This caused application level conflict.

Funny part is there are no error logged for this. Just a guess work (first time of course).

So for me solution was just to remove and/or elements from web.config.

Padding a table row

You could simply add this style to the table.

table {
    border-spacing: 15px;
}

HTTP 404 when accessing .svc file in IIS

I've had the same problem today.

For me, the solution was to go into IIS, right-click on the new Web Site name, select Properties, ASP.Net, and change the ASP.Net version from "1.1.4322" (which it had set as the default) to 2.0.50727.

Once I'd done that, I could right-click on the .svc file, click on "Browse" and see the friendly Service webpage.

Solving SharePoint Server 2010 - 503. The service is unavailable, After installation

I had trouble finding the applicationhost.config file. It was in c:\windows\System32\inetsrv\ (Server2008) or the c:\windows\System32\inetsrv\config\ (Server2008r2).

After I changed that setting, I also had to change the way IIS loads the aspnet_filter.dll. Open the IIS Manager, go under "Sites", "SharePoint - 80", in the "IIS" grouping, under the "ISAPI Filters", make sure that all of the "Executable" paths point to ...Microsoft.NET\Framework64\v#.#.####\aspnet_filter.dll. Some of mine were pointed to the \Framework\ (not 64).

You also need to restart the WWW service to reload the new settings.

Permissions error when connecting to EC2 via SSH on Mac OSx

+1

I noticed that for some AMIs like Amazon Linux, [email protected] would work. But for an ubuntu image, I had to use ubuntu@ instead. It was never a problem with the .pem, just with the user name.

Permission denied (publickey,keyboard-interactive)

You may want to double check the authorized_keys file permissions:

$ chmod 600 ~/.ssh/authorized_keys

Newer SSH server versions are very picky on this respect.

Remove Server Response Header IIS7

Or add in web.config:

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <remove name="X-AspNet-Version" />
            <remove name="X-AspNetMvc-Version" />
            <remove name="X-Powered-By" />
            <!-- <remove name="Server" />  this one doesn't work -->
        </customHeaders>
    </httpProtocol>
</system.webServer>

What is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!

So one day, I decided that I'd had enough. I would learn piano. Seeing people like Elton John command such mastery of the keyboard assured me that this was what I wanted to do.

Actually learning piano was a huge letdown. Even after completing eight grades of piano lessons, I was still not impressed with how my mental image of playing piano was so different from my original vision of enjoying the activity.

However, what I thoroughly enjoyed was my mere three grades of rudiments of music theory. I learned about the construction of music. I was finally able to step from the world of performing written music to writing my own music. Subsequently, I was able to start playing what I wanted to play.


Don't try to dazzle new programmers, especially young programmers. The whole notion of "less than ten lines of simple code" seems to elicit a mood of "Show me something clever".

You can show a new programmer something clever. You can then teach that same programmer how to replicate this "performance". But this is not what gets them hooked on programming. Teach them the rudiments, and let them synthesize their own clever ten lines of code.

I would show a new programmer the following Python code:

input = open("input.txt", "r")
output = open("output.txt", "w")

for line in input:
    edited_line = line
    edited_line = edited_line.replace("EDTA", "ethylenediaminetetraacetic acid")
    edited_line = edited_line.replace("ATP", "adenosine triphosphate")
    output.write(edited_line)

I realize that I don't need to assign line to edited_line. However, that's just to keep things clear, and to show that I'm not editing the original document.

In less than ten lines, I've verbosified a document. Of course, also be sure to show the new programmer all the string methods that are available. More importantly, I've showed three fundamentally interesting things I can do: variable assignment, a loop, file IO, and use of the standard library.

I think you'll agree that this code doesn't dazzle. In fact, it's a little boring. No - actually, it's very boring. But show that code to a new programmer and see if that programmer can't repurpose every part of that script to something much more interesting within the week, if not the day. Sure, it'll be distasteful to you (maybe using this script to make a simple HTML parser), but everything else just takes time and experience.

Adding external library into Qt Creator project

I would like to add for the sake of completeness that you can also add just the LIBRARY PATH where it will look for a dependent library (which may not be directly referenced in your code but a library you use may need it).

For comparison, this would correspond to what LIBPATH environment does but its kind of obscure in Qt Creator and not well documented.

The way i came around this is following:

LIBS += -L"$$_PRO_FILE_PWD_/Path_to_Psapi_lib/"

Essentially if you don't provide the actual library name, it adds the path to where it will search dependent libraries. The difference in syntax is small but this is very useful to supply just the PATH where to look for dependent libraries. It sometime is just a pain to supply each path individual library where you know they are all in certain folder and Qt Creator will pick them up.

Setting Timeout Value For .NET Web Service

Try setting the timeout value in your web service proxy class:

WebReference.ProxyClass myProxy = new WebReference.ProxyClass();
myProxy.Timeout = 100000; //in milliseconds, e.g. 100 seconds

Where do you include the jQuery library from? Google JSAPI? CDN?

I wouldn't want any public site that I developed to depend on any external site, and thus, I'd host jQuery myself.

Are you willing to have an outage on your site when the other (Google, jquery.com, etc.) goes down? Less dependencies is the key.

Open file dialog box in JavaScript

Actually, you don't need all that stuff with opacity, visibility, <input> styling, etc. Just take a look:

<a href="#">Just click me.</a>
<script type="text/javascript">
    $("a").click(function() {
        // creating input on-the-fly
        var input = $(document.createElement("input"));
        input.attr("type", "file");
        // add onchange handler if you wish to get the file :)
        input.trigger("click"); // opening dialog
        return false; // avoiding navigation
    });
</script>

Demo on jsFiddle. Tested in Chrome 30.0 and Firefox 24.0. Didn't work in Opera 12.16, however.

How to use XPath in Python?

You can use the simple soupparser from lxml

Example:

from lxml.html.soupparser import fromstring

tree = fromstring("<a>Find me!</a>")
print tree.xpath("//a/text()")

What is the difference between the float and integer data type when the size is the same?

Floats are used to store a wider range of number than can be fit in an integer. These include decimal numbers and scientific notation style numbers that can be bigger values than can fit in 32 bits. Here's the deep dive into them: http://en.wikipedia.org/wiki/Floating_point

php is null or empty?

This is not a bug but PHP normal behavior. It happens because the == operator in PHP doesn't check for type.

'' == null == 0 == false

If you want also to check if the values have the same type, use === instead. To study in deep this difference, please read the official documentation.

Delete branches in Bitbucket

Step 1 : Login in Bitbucket

Step 2 : Select Your Repository in Repositories list. enter image description here

Step 3 : Select branches in left hand side menu. enter image description here

Step4 : Cursor point on branch click on three dots (...) Select Delete (See in Bellow Image) enter image description here

Artisan, creating tables in database

In order to give a value in the table, we need to give a command:

php artisan make:migration create_users_table

and after then this command line

php artisan migrate

......

Get Value of Row in Datatable c#

for (Int32 i = 1; i < dt_pattern.Rows.Count - 1; i++){ double yATmax = ToDouble(dt_pattern.Rows[i]["Ampl"].ToString()) + AT; }

if you want to get around the + 1 issue

MySQL INSERT INTO ... VALUES and SELECT

just use a subquery right there like:

INSERT INTO table1 VALUES ("A string", 5, (SELECT ...)).

NodeJS - What does "socket hang up" actually mean?

After a long debug into node js code, mongodb connection string, checking CORS etc, For me just switching to a different port number server.listen(port); made it work, into postman, try that too. No changes to proxy settings just the defaults.

How to round a numpy array?

Numpy provides two identical methods to do this. Either use

np.round(data, 2)

or

np.around(data, 2)

as they are equivalent.

See the documentation for more information.


Examples:

>>> import numpy as np
>>> a = np.array([0.015, 0.235, 0.112])
>>> np.round(a, 2)
array([0.02, 0.24, 0.11])
>>> np.around(a, 2)
array([0.02, 0.24, 0.11])
>>> np.round(a, 1)
array([0. , 0.2, 0.1])

Regex pattern inside SQL Replace function?

Wrapping the solution inside a SQL function could be useful if you want to reuse it. I'm even doing it at the cell level, that's why I'm putting this as a different answer:

CREATE FUNCTION [dbo].[fnReplaceInvalidChars] (@string VARCHAR(300))
RETURNS VARCHAR(300)
BEGIN
    DECLARE @str VARCHAR(300) = @string;
    DECLARE @Pattern VARCHAR (20) = '%[^a-zA-Z0-9]%';
    DECLARE @Len INT;
    SELECT @Len = LEN(@String); 
    WHILE @Len > 0 
    BEGIN
        SET @Len = @Len - 1;
        IF (PATINDEX(@Pattern,@str) > 0)
            BEGIN
                SELECT @str = STUFF(@str, PATINDEX(@Pattern,@str),1,'');    
            END
        ELSE
        BEGIN
            BREAK;
        END
    END     
    RETURN @str
END

DLL and LIB files - what and why?

A DLL is a library of functions that are shared among other executable programs. Just look in your windows/system32 directory and you will find dozens of them. When your program creates a DLL it also normally creates a lib file so that the application *.exe program can resolve symbols that are declared in the DLL.

A .lib is a library of functions that are statically linked to a program -- they are NOT shared by other programs. Each program that links with a *.lib file has all the code in that file. If you have two programs A.exe and B.exe that link with C.lib then each A and B will both contain the code in C.lib.

How you create DLLs and libs depend on the compiler you use. Each compiler does it differently.

How to disable scrolling in UITableView table when the content fits on the screen

So there's are multiple answers and requires a all content at once place so I'm adding this answer:

If you're using AutoLayout, by setting this only should work for you:

  • In code:

tableView.alwaysBounceVertical = false

  • or In Interface Builder:

Just find this option and untick "Bounce Vertically" option.

Here's the reference:

enter image description here

If you're not using AutoLayout:

 override func viewDidLayoutSubviews() {
    // Enable scrolling based on content height
    tableView.isScrollEnabled = tableView.contentSize.height > tableView.frame.size.height
 }

Why and how to fix? IIS Express "The specified port is in use"

For me, the Google Chrome browser was the process which was using the port. Even after I closed Chrome, I found that the process still persisted (I allow Chrome to "run in background" so that I can receive desktop notifications). I went into Task Manager, and killed the Chrome browser process, and then started my web application, it worked like a charm.

How do I make an image smaller with CSS?

CSS 3 introduces the background-size property, but support is not universal.

Having the browser resize the image is inefficient though, the large image still has to be downloaded. You should resize it server side (caching the result) and use that instead. It will use less bandwidth and work in more browsers.

How do you implement a class in C?

GTK is built entirely on C and it uses many OOP concepts. I have read through the source code of GTK and it is pretty impressive, and definitely easier to read. The basic concept is that each "class" is simply a struct, and associated static functions. The static functions all accept the "instance" struct as a parameter, do whatever then need, and return results if necessary. For Example, you may have a function "GetPosition(CircleStruct obj)". The function would simply dig through the struct, extract the position numbers, probably build a new PositionStruct object, stick the x and y in the new PositionStruct, and return it. GTK even implements inheritance this way by embedding structs inside structs. pretty clever.

What is the difference between "mvn deploy" to a local repo and "mvn install"?

Ken, good question. I should be more explicit in the The Definitive Guide about the difference. "install" and "deploy" serve two different purposes in a build. "install" refers to the process of installing an artifact in your local repository. "deploy" refers to the process of deploying an artifact to a remote repository.

Example:

  1. When I run a large multi-module project on a my machine, I'm going to usually run "mvn install". This is going to install all of the generated binary software artifacts (usually JARs) in my local repository. Then when I build individual modules in the build, Maven is going to retrieve the dependencies from the local repository.

  2. When it comes time to deploy snapshots or releases, I'm going to run "mvn deploy". Running this is going to attempt to deploy the files to a remote repository or server. Usually I'm going to be deploying to a repository manager such as Nexus

It is true that running "deploy" is going to require some extra configuration, you are going to have to supply a distributionManagement section in your POM.

How to animate GIFs in HTML document?

try

_x000D_
_x000D_
<img src="https://cdn.glitch.com/0e4d1ff3-5897-47c5-9711-d026c01539b8%2Fbddfd6e4434f42662b009295c9bab86e.gif?v=1573157191712" alt="this slowpoke moves"  width="250" alt="404 image"/>
_x000D_
_x000D_
_x000D_

and switch the src with your source. If the alt pops up, try a different url. If it doesn't work, restart your computer or switch your browser.

How can I define an interface for an array of objects with Typescript?

Use like this!

interface Iinput {
  label: string
  placeholder: string
  register: any
  type?: string
  required: boolean
}


// This is how it can be done

const inputs: Array<Iinput> = [
  {
    label: "Title",
    placeholder: "Bought something",
    register: register,
    required: true,
  },
]

Automatically create an Enum based on values in a database lookup table?

Word up, I as well got tired of writing out enumerations based on Id / Name db table columns, copying and pasting stuff from queries in SSMS.

Below is a super dirty stored procedure that takes as input a table name, the column name you want to use for the c# enumeration name, and the column name that you want to use for the c# enumeration value.

Most of theses table names I work with a) end with "s" b) have a [TABLENAME]Id column and c) have a [TABLENAME]Name column, so there are a couple if statements that will assume that structure, in which case, the column name parameters are not required.

A little context for these examples - "Stonk" here doesn't really mean "stock" but kinda, the way I'm using "stonk" it means "a thing that has some numbers associated to it for a time period" But that's not important, it's just an example of table with this Id / Name schema. It looks like this:

CREATE TABLE StonkTypes (
    StonkTypeId TINYINT IDENTITY(1,1) PRIMARY KEY NOT NULL,
    StonkTypeName VARCHAR(200) NOT NULL CONSTRAINT UQ_StonkTypes_StonkTypeName UNIQUE (StonkTypeName)
)

After I create the proc, this statement:

EXEC CreateCSharpEnum 'StonkTypes'

Selects this string:

public enum StonkTypes { Stonk = 1, Bond = 2, Index = 3, Fund = 4, Commodity = 5, 
PutCallRatio = 6, }

Which I can copy and paste into a C# file.

I have a Stonks table and it has StonkId and StonkName columns so this exec:

EXEC CreateCSharpEnum 'Stonks'

Spits out:

public enum Stonks { SP500 = 1, DowJonesIndustrialAverage = 2, ..... }

But for that enum I want to use the "Symbol" column for the enum name values so this:

EXEC CreateCSharpEnum 'Stonks', 'Symbol'

Does the trick and renders:

public enum Stonks { SPY = 1, DIA = 2, ..... }

Without further ado, here is this dirty piece of craziness. Yeah, very dirty, but I'm kind of pleased with myself - it's SQL code that constructs SQL code that constructs C# code. Couple layers involved.


CREATE OR ALTER PROCEDURE CreateCSharpEnum
@TableName VARCHAR(MAX),
@EnumNameColumnName VARCHAR(MAX) = NULL,
@EnumValueColumnName VARCHAR(MAX) = NULL
AS

DECLARE @LastCharOfTableName VARCHAR(1)
SELECT @LastCharOfTableName = RIGHT(@TableName, 1)

PRINT 'Last char = [' + @LastCharOfTableName + ']'

DECLARE @TableNameWithoutS VARCHAR(MAX)
IF UPPER(@LastCharOfTableName) = 'S'
    SET @TableNameWithoutS = LEFT(@TableName, LEN(@TableName) - 1)
ELSE
    SET @TableNameWithoutS = @TableName

PRINT 'Table name without trailing s = [' + @TableNameWithoutS + ']'

IF @EnumNameColumnName IS NULL
    BEGIN
        SET @EnumNameColumnName = @TableNameWithoutS + 'Name'
    END

PRINT 'name col name = [' + @EnumNameColumnName + ']'

IF @EnumValueColumnName IS NULL
    SET @EnumValueColumnName = @TableNameWithoutS + 'Id'

PRINT 'value col name = [' + @EnumValueColumnName + ']'

-- replace spaces and punctuation
SET @EnumNameColumnName  = 'REPLACE(' + @EnumNameColumnName + ', '' '', '''')'
SET @EnumNameColumnName  = 'REPLACE(' + @EnumNameColumnName + ', ''&'', '''')'
SET @EnumNameColumnName  = 'REPLACE(' + @EnumNameColumnName + ', ''.'', '''')'
SET @EnumNameColumnName  = 'REPLACE(' + @EnumNameColumnName + ', ''('', '''')'
SET @EnumNameColumnName  = 'REPLACE(' + @EnumNameColumnName + ', '')'', '''')'

PRINT 'name col name with replace sql = [' + @EnumNameColumnName + ']'

DECLARE @SqlStr VARCHAR(MAX) = 'SELECT ' + @EnumNameColumnName  
+ ' + '' = ''' 
+ ' + LTRIM(RTRIM(STR(' + @EnumValueColumnName + '))) + '','' FROM ' + @TableName + ' ORDER BY ' + @EnumValueColumnName

PRINT 'sql that gets rows for enum body = [' + @SqlStr + ']'

CREATE TABLE #EnumRowsTemp (s VARCHAR(MAX))

INSERT 
INTO #EnumRowsTemp
EXEC(@SqlStr)

--SELECT * FROM #EnumRowsTemp

DECLARE @csharpenumbody VARCHAR(MAX) 
SELECT @csharpenumbody = COALESCE(@csharpenumbody + ' ', '') + s FROM #EnumRowsTemp

--PRINT @csharpenumbody

DECLARE @csharpenum VARCHAR(MAX) = 'public enum ' + @TableName + ' { ' + @csharpenumbody + ' }'

PRINT @csharpenum

SELECT @csharpenum

DROP TABLE #EnumRowsTemp

Please, be critical. One funky thing I didn't understand, how come I have to create and drop this #EnumRowsTemp table and not just "SELECT INTO #EnumRowsTemp" to create the temp table on the fly? I don't know the answer, I tried that and it didn't work. That's probably the least of the problems of this code...

As dirty as it may be... I hope this saves some of you fellow dorks a little bit of time.

Query Mongodb on month, day, year... of a datetime

how about storing the month in its own property since you need to query for it? less elegant than $where, but likely to perform better since it can be indexed.

How to add a response header on nginx when using proxy_pass?

add_header works as well with proxy_pass as without. I just today set up a configuration where I've used exactly that directive. I have to admit though that I've struggled as well setting this up without exactly recalling the reason, though.

Right now I have a working configuration and it contains the following (among others):

server {
    server_name  .myserver.com
    location / {
        proxy_pass  http://mybackend;
        add_header  X-Upstream  $upstream_addr;
    }
}

Before nginx 1.7.5 add_header worked only on successful responses, in contrast to the HttpHeadersMoreModule mentioned by Sebastian Goodman in his answer.

Since nginx 1.7.5 you can use the keyword always to include custom headers even in error responses. For example:

add_header X-Upstream $upstream_addr always;

Limitation: You cannot override the server header value using add_header.

"Connect failed: Access denied for user 'root'@'localhost' (using password: YES)" from php function

Is there a user account entry in the DB for root@localhost? In MySQL you can set different user account permissions by host. There could be several different accounts with the same name combined with the host they are connecting from. The most common are [email protected] and root@localhost. These can have different passwords and permissions. Make sure root@localhost exist and has the settings you expect.

I am willing to bet, based on your explanation, that this is the problem. Connecting from another PC uses a different account than root@localhost and the command line I think connects using [email protected].

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

Only changing the settings with the following command did not work in my environment:

curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'

I had to also ran the Force Merge API command:

curl -X POST "localhost:9200/my-index-000001/_forcemerge?pretty"

ref: Force Merge API

jQuery: Handle fallback for failed AJAX Request

Dougs answer is correct, but you actually can use $.getJSON and catch errors (not having to use $.ajax). Just chain the getJSON call with a call to the fail function:

$.getJSON('/foo/bar.json')
    .done(function() { alert('request successful'); })
    .fail(function() { alert('request failed'); });

Live demo: http://jsfiddle.net/NLDYf/5/

This behavior is part of the jQuery.Deferred interface.
Basically it allows you to attach events to an asynchronous action after you call that action, which means you don't have to pass the event function to the action.

Read more about jQuery.Deferred here: http://api.jquery.com/category/deferred-object/

How to find and replace string?

Here's the version I ended up writing that replaces all instances of the target string in a given string. Works on any string type.

template <typename T, typename U>
T &replace (
          T &str, 
    const U &from, 
    const U &to)
{
    size_t pos;
    size_t offset = 0;
    const size_t increment = to.size();

    while ((pos = str.find(from, offset)) != T::npos)
    {
        str.replace(pos, from.size(), to);
        offset = pos + increment;
    }

    return str;
}

Example:

auto foo = "this is a test"s;
replace(foo, "is"s, "wis"s);
cout << foo;

Output:

thwis wis a test

Note that even if the search string appears in the replacement string, this works correctly.

Change Primary Key

Sometimes when we do these steps:

 alter table my_table drop constraint my_pk; 
 alter table my_table add constraint my_pk primary key (city_id, buildtime, time);

The last statement fails with

ORA-00955 "name is already used by an existing object"

Oracle usually creates an unique index with the same name my_pk. In such a case you can drop the unique index or rename it based on whether the constraint is still relevant.

You can combine the dropping of primary key constraint and unique index into a single sql statement:

alter table my_table drop constraint my_pk drop index; 

check this: ORA-00955 "name is already used by an existing object"

PDF Editing in PHP?

I really had high hopes for dompdf (it is a cool idea) but the positioning issue are a major factor in my using fpdf. Though it is tedious as every element has to be set; it is powerful as all get out.

I lay an image underneath my workspace in the document to put my layout on top of to fit. Its always been sufficient even for columns (requires a tiny bit of php string calculation, but nothing too terribly heady).

Good luck.

Difference between string and text in rails?

String translates to "Varchar" in your database, while text translates to "text". A varchar can contain far less items, a text can be of (almost) any length.

For an in-depth analysis with good references check http://www.pythian.com/news/7129/text-vs-varchar/

Edit: Some database engines can load varchar in one go, but store text (and blob) outside of the table. A SELECT name, amount FROM products could, be a lot slower when using text for name than when you use varchar. And since Rails, by default loads records with SELECT * FROM... your text-columns will be loaded. This will probably never be a real problem in your or my app, though (Premature optimization is ...). But knowing that text is not always "free" is good to know.

Windows 7 environment variable not working in path

Also worth making sure you're using the command prompt as an administrator - the system lock on my work machine meant that the standard cmd just reported mvn could not be found when typing mvn --version

To use click 'start > all programs > accessories', right-click on 'command prompt' and select 'run as administrator'.

Can I draw rectangle in XML?

Quick and dirty way:

<View
    android:id="@+id/colored_bar"
    android:layout_width="48dp"
    android:layout_height="3dp"
    android:background="@color/bar_red" />

How can I use a search engine to search for special characters?

A great search engine for special characters that I recenetly found: amp-what?

You can even search by object name, like "arrow", "chess", etc...

NSPhotoLibraryUsageDescription key must be present in Info.plist to use camera roll

Add following code in info.plist file

<key>NSPhotoLibraryUsageDescription</key>
<string>My description about why I need this capability</string>

enter image description here

How to copy data from one table to another new table in MySQL?

CREATE TABLE newTable LIKE oldTable;

Then, to copy the data over

INSERT INTO newTable SELECT * FROM oldTable;

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()

Get the filename of a fileupload in a document through JavaScript

To get only uploaded file Name use this,

fake_path=document.getElementById('FileUpload1').value
alert(fake_path.split("\\").pop())

FileUpload1 value contains fake path, that you probably don't want, to avoid that use split and pop last element from your file.

How to use the TextWatcher class in Android?

Using TextWatcher in Android

Here is a sample code. Try using addTextChangedListener method of TextView

addTextChangedListener(new TextWatcher() {

        BigDecimal previousValue;
        BigDecimal currentValue;

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int
                count) {
            if (isFirstTimeChange) {
                return;
            }
            if (s.toString().length() > 0) {
                try {
                    currentValue = new BigDecimal(s.toString().replace(".", "").replace(',', '.'));
                } catch (Exception e) {
                    currentValue = new BigDecimal(0);
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            if (isFirstTimeChange) {
                return;
            }
            if (s.toString().length() > 0) {
                try {
                    previousValue = new BigDecimal(s.toString().replace(".", "").replace(',', '.'));
                } catch (Exception e) {
                    previousValue = new BigDecimal(0);
                }
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (isFirstTimeChange) {
                isFirstTimeChange = false;
                return;
            }
            if (currentValue != null && previousValue != null) {
                if ((currentValue.compareTo(previousValue) > 0)) {
                    //setBackgroundResource(R.color.devises_overview_color_green);
                    setBackgroundColor(flashOnColor);
                } else if ((currentValue.compareTo(previousValue) < 0)) {
                    //setBackgroundResource(R.color.devises_overview_color_red);

                    setBackgroundColor(flashOffColor);
                } else {
                    //setBackgroundColor(textColor);
                }
                handler.removeCallbacks(runnable);
                handler.postDelayed(runnable, 1000);
            }
        }
    });

How do I bind a List<CustomObject> to a WPF DataGrid?

Actually, to properly support sorting, filtering, etc. a CollectionViewSource should be used as a link between the DataGrid and the list, like this:

<Window.Resources>
  <CollectionViewSource x:Key="ItemCollectionViewSource" CollectionViewType="ListCollectionView"/>
</Window.Resources>   

The DataGrid line looks like this:

<DataGrid
  DataContext="{StaticResource ItemCollectionViewSource}"
  ItemsSource="{Binding}"
  AutoGenerateColumns="False">  

In the code behind, you link CollectionViewSource with your link.

CollectionViewSource itemCollectionViewSource;
itemCollectionViewSource = (CollectionViewSource)(FindResource("ItemCollectionViewSource"));
itemCollectionViewSource.Source = itemList;

For detailed example see my article on CoedProject: http://www.codeproject.com/Articles/683429/Guide-to-WPF-DataGrid-formatting-using-bindings

SELECT inside a COUNT

SELECT a AS current_a, COUNT(*) AS b,
   (SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d
   from t group by a order by b desc

JavaScript: Create and destroy class instance through class method

No. JavaScript is automatically garbage collected; the object's memory will be reclaimed only if the GC decides to run and the object is eligible for collection.

Seeing as that will happen automatically as required, what would be the purpose of reclaiming the memory explicitly?

How to set headers in http get request?

Pay attention that in http.Request header "Host" can not be set via Set method

req.Header.Set("Host", "domain.tld")

but can be set directly:

req.Host = "domain.tld":

req, err := http.NewRequest("GET", "http://10.0.0.1/", nil)
if err != nil {
    ...
}

req.Host = "domain.tld"
client := &http.Client{}
resp, err := client.Do(req)

How can I have a newline in a string in sh?

I wasn't really happy with any of the options here. This is what worked for me.

str=$(printf "%s" "first line")
str=$(printf "$str\n%s" "another line")
str=$(printf "$str\n%s" "and another line")

How can I set the request header for curl?

Just use the -H parameter several times:

curl -H "Accept-Charset: utf-8" -H "Content-Type: application/x-www-form-urlencoded" http://www.some-domain.com

Click in OK button inside an Alert (Selenium IDE)

1| Print Alert popup text and close -I

Alert alert = driver.switchTo().alert();
System.out.println(closeAlertAndGetItsText());

2| Print Alert popup text and close -II

Alert alert = driver.switchTo().alert();
System.out.println(alert.getText()); //Print Alert popup
alert.accept(); //Close Alert popup

3| Assert Alert popup text and close

Alert alert = driver.switchTo().alert();
assertEquals("Expected Value", closeAlertAndGetItsText());

How to get jSON response into variable from a jquery script

Here's the script, rewritten to use the suggestions above and a change to your no-cache method.

<?php
// Simpler way of making sure all no-cache headers get sent
// and understood by all browsers, including IE.
session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));

header('Content-type: application/json');

// set to return response=error
$arr = array ('response'=>'error','comment'=>'test comment here');
echo json_encode($arr);
?>

//the script above returns this:
{"response":"error","comment":"test comment here"}

<script type="text/javascript">
$.ajax({
    type: "POST",
    url: "process.php",
    data: dataString,
    dataType: "json",
    success: function (data) {
        if (data.response == 'captcha') {
            alert('captcha');
        } else if (data.response == 'success') {
            alert('success');
        } else {
            alert('sorry there was an error');
        }
    }

}); // Semi-colons after all declarations, IE is picky on these things.
</script>

The main issue here was that you had a typo in the JSON you were returning ("resonse" instead of "response". This meant that you were looking for the wrong property in the JavaScript code. One way of catching these problems in the future is to console.log the value of data and make sure the property you are looking for is there.

Learning how to use the Chrome debugger tools (or similar tools in Firefox/Safari/Opera/etc.) will also be invaluable.

in iPhone App How to detect the screen resolution of the device

Use this code it will help for getting any type of device's screen resolution

 [[UIScreen mainScreen] bounds].size.height
 [[UIScreen mainScreen] bounds].size.width

How to have Ellipsis effect on Text

You can use ellipsizeMode and numberOfLines. e.g

<Text ellipsizeMode='tail' numberOfLines={2}>
  This very long text should be truncated with dots in the beginning.
</Text>

https://facebook.github.io/react-native/docs/text.html

AttributeError: 'str' object has no attribute

The problem is in your playerMovement method. You are creating the string name of your room variables (ID1, ID2, ID3):

letsago = "ID" + str(self.dirDesc.values())

However, what you create is just a str. It is not the variable. Plus, I do not think it is doing what you think its doing:

>>>str({'a':1}.values())
'dict_values([1])'

If you REALLY needed to find the variable this way, you could use the eval function:

>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'

or the globals function:

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
    def test(self, name):
        print(globals()[name])

foo = Foo()
bar = 'Hello World!'
foo.text('bar')

However, instead I would strongly recommend you rethink you class(es). Your userInterface class is essentially a Room. It shouldn't handle player movement. This should be within another class, maybe GameManager or something like that.

Convert decimal to hexadecimal in UNIX shell script

xd() {
    printf "hex> "
    while read i
    do
        printf "dec  $(( 0x${i} ))\n\nhex> "
    done
}
dx() {
    printf "dec> "
    while read i
    do
        printf 'hex  %x\n\ndec> ' $i
    done
}

Angular 5 Service to read local .json file

First You have to inject HttpClient and Not HttpClientModule, second thing you have to remove .map((res:any) => res.json()) you won't need it any more because the new HttpClient will give you the body of the response by default , finally make sure that you import HttpClientModule in your AppModule :

import { HttpClient } from '@angular/common/http'; 
import { Observable } from 'rxjs';

@Injectable()
export class AppSettingsService {

   constructor(private http: HttpClient) {
        this.getJSON().subscribe(data => {
            console.log(data);
        });
    }

    public getJSON(): Observable<any> {
        return this.http.get("./assets/mydata.json");
    }
}

to add this to your Component:

@Component({
    selector: 'mycmp',
    templateUrl: 'my.component.html',
    styleUrls: ['my.component.css']
})
export class MyComponent implements OnInit {
    constructor(
        private appSettingsService : AppSettingsService 
    ) { }

   ngOnInit(){
       this.appSettingsService.getJSON().subscribe(data => {
            console.log(data);
        });
   }
}

Get current value selected in dropdown using jQuery

This is actually more efficient and has better readability in my opinion if you want to access your select with this or another variable

$('#select').find('option:selected')

In fact if I remember correctly phpStorm will attempt to auto correct the other method.

How can I add a table of contents to a Jupyter / JupyterLab notebook?

How about using a Browser plugin that gives you an overview of ANY html page. I have tried the following:

They both work pretty well for IPython Notebooks. I was reluctant to use the previous solutions as they seem a bit unstable and ended up using these extensions.

Makefile to compile multiple C programs?

############################################################################
# 'A Generic Makefile for Building Multiple main() Targets in $PWD'
# Author:  Robert A. Nader (2012)
# Email: naderra at some g
# Web: xiberix
############################################################################
#  The purpose of this makefile is to compile to executable all C source
#  files in CWD, where each .c file has a main() function, and each object
#  links with a common LDFLAG.
#
#  This makefile should suffice for simple projects that require building
#  similar executable targets.  For example, if your CWD build requires
#  exclusively this pattern:
#
#  cc -c $(CFLAGS) main_01.c
#  cc main_01.o $(LDFLAGS) -o main_01
#
#  cc -c $(CFLAGS) main_2..c
#  cc main_02.o $(LDFLAGS) -o main_02
#
#  etc, ... a common case when compiling the programs of some chapter,
#  then you may be interested in using this makefile.
#
#  What YOU do:
#
#  Set PRG_SUFFIX_FLAG below to either 0 or 1 to enable or disable
#  the generation of a .exe suffix on executables
#
#  Set CFLAGS and LDFLAGS according to your needs.
#
#  What this makefile does automagically:
#
#  Sets SRC to a list of *.c files in PWD using wildcard.
#  Sets PRGS BINS and OBJS using pattern substitution.
#  Compiles each individual .c to .o object file.
#  Links each individual .o to its corresponding executable.
#
###########################################################################
#
PRG_SUFFIX_FLAG := 0
#
LDFLAGS := 
CFLAGS_INC := 
CFLAGS := -g -Wall $(CFLAGS_INC)
#
## ==================- NOTHING TO CHANGE BELOW THIS LINE ===================
##
SRCS := $(wildcard *.c)
PRGS := $(patsubst %.c,%,$(SRCS))
PRG_SUFFIX=.exe
BINS := $(patsubst %,%$(PRG_SUFFIX),$(PRGS))
## OBJS are automagically compiled by make.
OBJS := $(patsubst %,%.o,$(PRGS))
##
all : $(BINS)
##
## For clarity sake we make use of:
.SECONDEXPANSION:
OBJ = $(patsubst %$(PRG_SUFFIX),%.o,$@)
ifeq ($(PRG_SUFFIX_FLAG),0)
        BIN = $(patsubst %$(PRG_SUFFIX),%,$@)
else
        BIN = $@
endif
## Compile the executables
%$(PRG_SUFFIX) : $(OBJS)
    $(CC) $(OBJ)  $(LDFLAGS) -o $(BIN)
##
## $(OBJS) should be automagically removed right after linking.
##
veryclean:
ifeq ($(PRG_SUFFIX_FLAG),0)
    $(RM) $(PRGS)
else
    $(RM) $(BINS)
endif
##
rebuild: veryclean all
##
## eof Generic_Multi_Main_PWD.makefile

C++ wait for user input

Several ways to do so, here are some possible one-line approaches:

  1. Use getch() (need #include <conio.h>).

  2. Use getchar() (expected for Enter, need #include <iostream>).

  3. Use cin.get() (expected for Enter, need #include <iostream>).

  4. Use system("pause") (need #include <iostream>).

    PS: This method will also print Press any key to continue . . . on the screen. (seems perfect choice for you :))


Edit: As discussed here, There is no completely portable solution for this. Question 19.1 of the comp.lang.c FAQ covers this in some depth, with solutions for Windows, Unix-like systems, and even MS-DOS and VMS.

What is an idiomatic way of representing enums in Go?

For a use case like this, it may be useful to use a string constant so it can be marshaled into a JSON string. In the following example, []Base{A,C,G,T} would get marshaled to ["adenine","cytosine","guanine","thymine"].

type Base string

const (
    A Base = "adenine"
    C      = "cytosine"
    G      = "guanine"
    T      = "thymine"
)

When using iota, the values get marshaled into integers. In the following example, []Base{A,C,G,T} would get marshaled to [0,1,2,3].

type Base int

const (
    A Base = iota
    C
    G
    T
)

Here's an example comparing both approaches:

https://play.golang.org/p/VvkcWvv-Tvj

How to break out from a ruby block?

Use the keyword next. If you do not want to continue to the next item, use break.

When next is used within a block, it causes the block to exit immediately, returning control to the iterator method, which may then begin a new iteration by invoking the block again:

f.each do |line|              # Iterate over the lines in file f
  next if line[0,1] == "#"    # If this line is a comment, go to the next
  puts eval(line)
end

When used in a block, break transfers control out of the block, out of the iterator that invoked the block, and to the first expression following the invocation of the iterator:

f.each do |line|             # Iterate over the lines in file f
  break if line == "quit\n"  # If this break statement is executed...
  puts eval(line)
end
puts "Good bye"              # ...then control is transferred here

And finally, the usage of return in a block:

return always causes the enclosing method to return, regardless of how deeply nested within blocks it is (except in the case of lambdas):

def find(array, target)
  array.each_with_index do |element,index|
    return index if (element == target)  # return from find
  end
  nil  # If we didn't find the element, return nil
end

Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime

Try this code:

CONVERT(varchar(15), date_started, 103)

Postgresql - unable to drop database because of some auto connections to DB

In macOS try to restart postgresql database through the console using the command:

brew services restart postgresql

How to parse a JSON string to an array using Jackson

The complete example with an array. Replace "constructArrayType()" by "constructCollectionType()" or any other type you need.

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

public class Sorting {

    private String property;

    private String direction;

    public Sorting() {

    }

    public Sorting(String property, String direction) {
        this.property = property;
        this.direction = direction;
    }

    public String getProperty() {
        return property;
    }

    public void setProperty(String property) {
        this.property = property;
    }

    public String getDirection() {
        return direction;
    }

    public void setDirection(String direction) {
        this.direction = direction;
    }

    public static void main(String[] args) throws JsonParseException, IOException {
        final String json = "[{\"property\":\"title1\", \"direction\":\"ASC\"}, {\"property\":\"title2\", \"direction\":\"DESC\"}]";
        ObjectMapper mapper = new ObjectMapper();
        Sorting[] sortings = mapper.readValue(json, TypeFactory.defaultInstance().constructArrayType(Sorting.class));
        System.out.println(sortings);
    }
}

error running apache after xampp install

I think killing the process which is uses that port is more easy to handle than changing the ports in config files. Here is how to do it in Windows. You can follow same procedure to Linux but different commands. Run command prompt as Administrator. Then type below command to find out all of processes using the port.

netstat -ano

There will be plenty of processes using various ports. So to get only port we need use findstr like below (here I use port 80)

netstat -ano | findstr 80

this will gave you result like this

TCP    0.0.0.0:80             0.0.0.0:0              LISTENING       7964

Last number is the process ID of the process. so what we have to do is kill the process using PID we can use taskkill command for that.

taskkill /PID 7964 /F

Run your server again. This time it will be able to run. This can uses for Mysql server too.

How to create JSON object Node.js

The JavaScript Object() constructor makes an Object that you can assign members to.

myObj = new Object()
myObj.key = value;
myObj[key2] = value2;   // Alternative

How to increase buffer size in Oracle SQL Developer to view all records?

Here is another cheat:

Limit your query if you don't really need all the rows. i.e.

WHERE rownum <= 10000

Then click on any cell of the results and do from your keyboard CTRL+END. This will force SQL Developer to scroll until the bottom result of your query.

This has the advantage of keeping the default behavior and use this on demand.

How to prevent robots from automatically filling up a form?

In my experience, if the form is just a "contact" form you don't need special measures. Spam get decently filtered by webmail services (you can track webform requests via server-scripts to see what effectively reach your email, of course I assume you have a good webmail service :D)

Btw I'm trying not to rely on sessions for this (like, counting how many times a button is clicked to prevent overloads).

I don't think that's good, Indeed what I want to achieve is receiving emails from users that do some particular action because those are the users I'm interested in (for example users that looked at "CV" page and used the proper contact form). So if the user do something I want, I start tracking its session and set a cookie (I always set session cookie, but when I don't start a session it is just a fake cookie made to believe the user has a session). If the user do something unwanted I don't bother keeping a session for him so no overload etc.

Also It would be nice for me that advertising services offer some kind of api(maybe that already exists) to see if the user "looked at the ad", it is likely that users looking at ads are real users, but if they are not real well at least you get 1 view anyway so nothing loss. (and trust me, ads controls are more sophisticated than anything you can do alone)

How can I set a dynamic model name in AngularJS?

To make the answer provided by @abourget more complete, the value of scopeValue[field] in the following line of code could be undefined. This would result in an error when setting subfield:

<textarea ng-model="scopeValue[field][subfield]"></textarea>

One way of solving this problem is by adding an attribute ng-focus="nullSafe(field)", so your code would look like the below:

<textarea ng-focus="nullSafe(field)" ng-model="scopeValue[field][subfield]"></textarea>

Then you define nullSafe( field ) in a controller like the below:

$scope.nullSafe = function ( field ) {
  if ( !$scope.scopeValue[field] ) {
    $scope.scopeValue[field] = {};
  }
};

This would guarantee that scopeValue[field] is not undefined before setting any value to scopeValue[field][subfield].

Note: You can't use ng-change="nullSafe(field)" to achieve the same result because ng-change happens after the ng-model has been changed, which would throw an error if scopeValue[field] is undefined.

How can I rotate an HTML <div> 90 degrees?

We can add the following to a particular tag in CSS:

-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);

In case of half rotation change 90 to 45.

Is there a way to detect if a browser window is not currently active?

The Chromium team is currently developing the Idle Detection API. It is available as an origin trial since Chrome 88, which is already the 2nd origin trial for this feature. An earlier origin trial went from Chrome 84 through Chrome 86.

It can also be enabled via a flag:

Enabling via chrome://flags

To experiment with the Idle Detection API locally, without an origin trial token, enable the #enable-experimental-web-platform-features flag in chrome://flags.

A demo can be found here:

https://idle-detection.glitch.me/

It has to be noted though that this API is permission-based (as it should be, otherwise this could be misused to monitor a user's behaviour!).

How to resolve "Server Error in '/' Application" error?

You may get this error when trying to browse an ASP.NET application.

The debug information shows that "This error can be caused by a virtual directory not being configured as an application in IIS."

However, this error occurs primarily out of two scenarios.

  1. When you create an new web application using Visual Studio .NET, it automatically creates the virtual directory and configures it as an application. However, if you manually create the virtual directory and it is not configured as an application, then you will not be able to browse the application and may get the above error. The debug information you get as mentioned above, is applicable to this scenario.

To resolve it, right click on the virtual directory - select properties and then click on "Create" next to the "Application" Label and the text box. It will automatically create the "application" using the virtual directory's name. Now the application can be accessed.

  1. When you have sub-directories in your application, you can have web.config file for the sub-directory. However, there are certain properties which cannot be set in the web.config of the sub-directory such as authentication, session state (you may see that the error message shows the line number where the authentication or session state is declared in the web.config of the sub-directory). The reason is, these settings cannot be overridden at the sub-directory level unless the sub-directory is also configured as an application (as mentioned in the above point).

Mostly, we have the practice of adding web.config in the sub-directory if we want to protect access to the sub-directory files (say, the directory is admin and we wish to protect the admin pages from unauthorized users).

Python: SyntaxError: keyword can't be an expression

I just got that problem when converting from % formatting to .format().

Previous code:

"SET !TIMEOUT_STEP %{USER_TIMEOUT_STEP}d" % {'USER_TIMEOUT_STEP' = 3}

Problematic syntax:

"SET !TIMEOUT_STEP {USER_TIMEOUT_STEP}".format('USER_TIMEOUT_STEP' = 3)

The problem is that format is a function that needs parameters. They cannot be strings. That is one of worst python error messages I've ever seen.

Corrected code:

"SET !TIMEOUT_STEP {USER_TIMEOUT_STEP}".format(USER_TIMEOUT_STEP = 3)

How can I read the client's machine/computer name from the browser?

Try getting the client computer name in Mozilla Firefox by using the code given below.

netscape.security.PrivilegeManager.enablePrivilege( 'UniversalXPConnect' ); 

var dnsComp = Components.classes["@mozilla.org/network/dns-service;1"]; 
var dnsSvc = dnsComp.getService(Components.interfaces.nsIDNSService);
var compName = dnsSvc.myHostName;

Also, the same piece of code can be put as an extension, and it can called from your web page.

Please find the sample code below.

Extension code:

var myExtension = {
  myListener: function(evt) {

//netscape.security.PrivilegeManager.enablePrivilege( 'UniversalXPConnect' ); 
var dnsComp = Components.classes["@mozilla.org/network/dns-service;1"]; 
var dnsSvc = dnsComp.getService(Components.interfaces.nsIDNSService);
var compName = dnsSvc.myHostName;
content.document.getElementById("compname").value = compName ;    
  }
}
document.addEventListener("MyExtensionEvent", function(e) { myExtension.myListener(e); }, false, true); //this event will raised from the webpage

Webpage Code:

<html>
<body onload = "load()">
<script>
function showcomp()
{
alert("your computer name is " + document.getElementById("compname").value);
}
function load()
{ 
//var element = document.createElement("MyExtensionDataElement");
//element.setAttribute("attribute1", "foobar");
//element.setAttribute("attribute2", "hello world");
//document.documentElement.appendChild(element);
var evt = document.createEvent("Events");
evt.initEvent("MyExtensionEvent", true, false);
//element.dispatchEvent(evt);
document.getElementById("compname").dispatchEvent(evt); //this raises the MyExtensionEvent event , which assigns the client computer name to the hidden variable.
}
</script>
<form name="login_form" id="login_form">
<input type = "text" name = "txtname" id = "txtnamee" tabindex = "1"/>
<input type="hidden" name="compname" value="" id = "compname" />
<input type = "button" onclick = "showcomp()" tabindex = "2"/>

</form>
</body>
</html>

web.xml is missing and <failOnMissingWebXml> is set to true

Select your project and select the "Deployment Descriptor" option and then choose "Generate Deployment Descriptor stub"

Java optional parameters

This is an old question maybe even before actual Optional type was introduced but these days you can consider few things: - use method overloading - use Optional type which has advantage of avoiding passing NULLs around Optional type was introduced in Java 8 before it was usually used from third party lib such as Google's Guava. Using optional as parameters / arguments can be consider as over-usage as the main purpose was to use it as a return time.

Ref: https://itcodehub.blogspot.com/2019/06/using-optional-type-in-java.html

Correct set of dependencies for using Jackson mapper

No, you can simply use com.fasterxml.jackson.databind.ObjectMapper. Most likely you forgot to fix your import-statements, delete all references to codehaus and you're golden.

How to convert NSDate into unix timestamp iphone sdk?

You can create a unix timestamp date from a date this way:

NSTimeInterval timestamp = [[NSDate date] timeIntervalSince1970];

EC2 Instance Cloning

There is no explicit Clone button. Basically what you do is create an image, or snapshot of an existing EC2 instance, and then spin up a new instance using that snapshot.

First create an image from an existing EC2 instance.

enter image description here


Check your snapshots list to see if the process is completed. This usually takes around 20 minutes depending on how large your instance drive is.

enter image description here


Then, you need to create a new instance and use that image as the AMI.

enter image description here

enter image description here

How do I pass a string into subprocess.Popen (using the stdin argument)?

Beware that Popen.communicate(input=s)may give you trouble ifsis too big, because apparently the parent process will buffer it before forking the child subprocess, meaning it needs "twice as much" used memory at that point (at least according to the "under the hood" explanation and linked documentation found here). In my particular case,swas a generator that was first fully expanded and only then written tostdin so the parent process was huge right before the child was spawned, and no memory was left to fork it:

File "/opt/local/stow/python-2.7.2/lib/python2.7/subprocess.py", line 1130, in _execute_child self.pid = os.fork() OSError: [Errno 12] Cannot allocate memory

Installing specific package versions with pip

You can even use a version range with pip install command. Something like this:

pip install 'stevedore>=1.3.0,<1.4.0'

And if the package is already installed and you want to downgrade it add --force-reinstall like this:

pip install 'stevedore>=1.3.0,<1.4.0' --force-reinstall

Merge two dataframes by index

This answer has been resolved for a while and all the available options are already out there. However in this answer I'll attempt to shed a bit more light on these options to help you understand when to use what.

This post will go through the following topics:

  • Merging with index under different conditions
    • options for index-based joins: merge, join, concat
    • merging on indexes
    • merging on index of one, column of other
  • effectively using named indexes to simplify merging syntax


Index-based joins

TL;DR

There are a few options, some simpler than others depending on the use case.

  1. DataFrame.merge with left_index and right_index (or left_on and right_on using named indexes)
  2. DataFrame.join (joins on index)
  3. pd.concat (joins on index)
PROS CONS
merge

• supports inner/left/right/full
• supports column-column, index-column, index-index joins

• can only join two frames at a time

join

• supports inner/left (default)/right/full
• can join multiple DataFrames at a time

• only supports index-index joins

concat

• specializes in joining multiple DataFrames at a time
• very fast (concatenation is linear time)

• only supports inner/full (default) joins
• only supports index-index joins


Index to index joins

Typically, an inner join on index would look like this:

left.merge(right, left_index=True, right_index=True)

Other types of joins (left, right, outer) follow similar syntax (and can be controlled using how=...).

Notable Alternatives

  1. DataFrame.join defaults to a left outer join on the index.

     left.join(right, how='inner',)
    

    If you happen to get ValueError: columns overlap but no suffix specified, you will need to specify lsuffix and rsuffix= arguments to resolve this. Since the column names are same, a differentiating suffix is required.

  2. pd.concat joins on the index and can join two or more DataFrames at once. It does a full outer join by default.

     pd.concat([left, right], axis=1, sort=False)
    

    For more information on concat, see this post.


Index to Column joins

To perform an inner join using index of left, column of right, you will use DataFrame.merge a combination of left_index=True and right_on=....

left.merge(right, left_index=True, right_on='key')

Other joins follow a similar structure. Note that only merge can perform index to column joins. You can join on multiple levels/columns, provided the number of index levels on the left equals the number of columns on the right.

join and concat are not capable of mixed merges. You will need to set the index as a pre-step using DataFrame.set_index.


This post is an abridged version of my work in Pandas Merging 101. Please follow this link for more examples and other topics on merging.

Letsencrypt add domain to existing certificate

This is how i registered my domain:

sudo letsencrypt --apache -d mydomain.com

Then it was possible to use the same command with additional domains and follow the instructions:

sudo letsencrypt --apache -d mydomain.com,x.mydomain.com,y.mydomain.com

How to take last four characters from a varchar?

Use the RIGHT() function: http://msdn.microsoft.com/en-us/library/ms177532(v=sql.105).aspx

SELECT RIGHT( '1234567890', 4 ); -- returns '7890'

SQL Server 2005 Using DateAdd to add a day to a date

DECLARE @MyDate datetime

-- ... set your datetime's initial value ...'

DATEADD(d, 1, @MyDate)

PyLint "Unable to import" error - how to set PYTHONPATH?

I had to update the system PYTHONPATH variable to add my App Engine path. In my case I just had to edit my ~/.bashrc file and add the following line:

export PYTHONPATH=$PYTHONPATH:/path/to/google_appengine_folder

In fact, I tried setting the init-hook first but this did not resolve the issue consistently across my code base (not sure why). Once I added it to the system path (probably a good idea in general) my issues went away.

How/when to use ng-click to call a route?

Another solution but without using ng-click which still works even for other tags than <a>:

<tr [routerLink]="['/about']">

This way you can also pass parameters to your route: https://stackoverflow.com/a/40045556/838494

(This is my first day with angular. Gentle feedback is welcome)

Can I automatically increment the file build version when using Visual Studio?

I came up with a solution similar to Christians but without depending on the Community MSBuild tasks, this is not an option for me as I do not want to install these tasks for all of our developers.

I am generating code and compiling to an Assembly and want to auto-increment version numbers. However, I can not use the VS 6.0.* AssemblyVersion trick as it auto-increments build numbers each day and breaks compatibility with Assemblies that use an older build number. Instead, I want to have a hard-coded AssemblyVersion but an auto-incrementing AssemblyFileVersion. I've accomplished this by specifying AssemblyVersion in the AssemblyInfo.cs and generating a VersionInfo.cs in MSBuild like this,

  <PropertyGroup>
    <Year>$([System.DateTime]::Now.ToString("yy"))</Year>
    <Month>$([System.DateTime]::Now.ToString("MM"))</Month>
    <Date>$([System.DateTime]::Now.ToString("dd"))</Date>
    <Time>$([System.DateTime]::Now.ToString("HHmm"))</Time>
    <AssemblyFileVersionAttribute>[assembly:System.Reflection.AssemblyFileVersion("$(Year).$(Month).$(Date).$(Time)")]</AssemblyFileVersionAttribute>
  </PropertyGroup>
  <Target Name="BeforeBuild">
    <WriteLinesToFile File="Properties\VersionInfo.cs" Lines="$(AssemblyFileVersionAttribute)" Overwrite="true">
    </WriteLinesToFile>
  </Target>

This will generate a VersionInfo.cs file with an Assembly attribute for AssemblyFileVersion where the version follows the schema of YY.MM.DD.TTTT with the build date. You must include this file in your project and build with it.

What is the difference between IEnumerator and IEnumerable?

An Enumerator shows you the items in a list or collection. Each instance of an Enumerator is at a certain position (the 1st element, the 7th element, etc) and can give you that element (IEnumerator.Current) or move to the next one (IEnumerator.MoveNext). When you write a foreach loop in C#, the compiler generates code that uses an Enumerator.

An Enumerable is a class that can give you Enumerators. It has a method called GetEnumerator which gives you an Enumerator that looks at its items. When you write a foreach loop in C#, the code that it generates calls GetEnumerator to create the Enumerator used by the loop.

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

I got the same error and ended up using a pre-built distribution of numpy available in SourceForge (similarly, a distribution of matplotlib can be obtained).

Builds for both 32-bit 2.7 and 3.3/3.4 are available.
PyCharm detected them straight away, of course.

Convert nullable bool? to bool

The complete way would be:

bool b1;
bool? b2 = ???;
if (b2.HasValue)
   b1 = b2.Value;

Or you can test for specific values using

bool b3 = (b2 == true); // b2 is true, not false or null

Python slice first and last element in list

These are all interesting but what if you have a version number and you don't know the size of any one segment in string from and you want to drop the last segment. Something like 20.0.1.300 and I want to end up with 20.0.1 without the 300 on the end. I have this so far:

str('20.0.1.300'.split('.')[:3])

which returns in list form as:

['20', '0', '1']

How do I get it back to into a single string separated by periods

20.0.1

Compute mean and standard deviation by group for multiple variables in a data.frame

Here's another take on the data.table answers, using @Carson's data, that's a bit more readable (and also a little faster, because of using lapply instead of sapply):

library(data.table)
set.seed(1)
dt = data.table(ID=c(1:3), Obs_1=rnorm(9), Obs_2=rnorm(9), Obs_3=rnorm(9))

dt[, c(mean = lapply(.SD, mean), sd = lapply(.SD, sd)), by = ID]
#   ID mean.Obs_1 mean.Obs_2 mean.Obs_3  sd.Obs_1  sd.Obs_2  sd.Obs_3
#1:  1  0.4854187 -0.3238542  0.7410611 1.1108687 0.2885969 0.1067961
#2:  2  0.4171586 -0.2397030  0.2041125 0.2875411 1.8732682 0.3438338
#3:  3 -0.3601052  0.8195368 -0.4087233 0.8105370 0.3829833 1.4705692

Does Hibernate create tables in the database automatically

Yes, Hibernate can be configured by way of the hibernate.hbm2ddl.auto property in the hibernate.cfg.xml file to automatically create tables in your DB in order to store your entities in them if the table doesn't already exist.

This can be handy during development where a new, in-memory, DB can be used and created a new on every run of the application or during testing.

How do you implement a circular buffer in C?

C style, simple ring buffer for integers. First use init than use put and get. If buffer does not contain any data it returns "0" zero.

//=====================================
// ring buffer address based
//=====================================
#define cRingBufCount   512
int     sRingBuf[cRingBufCount];    // Ring Buffer
int     sRingBufPut;                // Input index address
int     sRingBufGet;                // Output index address
Bool    sRingOverWrite;

void    GetRingBufCount(void)
{
int     r;
`       r= sRingBufPut - sRingBufGet;
        if ( r < cRingBufCount ) r+= cRingBufCount;
        return r; 
}

void    InitRingBuffer(void)
{
        sRingBufPut= 0;
        sRingBufGet= 0;
}       

void    PutRingBuffer(int d)
{
        sRingBuffer[sRingBufPut]= d;
        if (sRingBufPut==sRingBufGet)// both address are like ziro
        {
            sRingBufPut= IncRingBufferPointer(sRingBufPut);
            sRingBufGet= IncRingBufferPointer(sRingBufGet);
        }
        else //Put over write a data
        {
            sRingBufPut= IncRingBufferPointer(sRingBufPut);
            if (sRingBufPut==sRingBufGet)
            {
                sRingOverWrite= Ture;
                sRingBufGet= IncRingBufferPointer(sRingBufGet);
            }
        }
}

int     GetRingBuffer(void)
{
int     r;
        if (sRingBufGet==sRingBufPut) return 0;
        r= sRingBuf[sRingBufGet];
        sRingBufGet= IncRingBufferPointer(sRingBufGet);
        sRingOverWrite=False;
        return r;
}

int     IncRingBufferPointer(int a)
{
        a+= 1;
        if (a>= cRingBufCount) a= 0;
        return a;
}

Setting an environment variable before a command in Bash is not working for the second command in a pipe

A simple approach is to make use of ;

For example:

ENV=prod; ansible-playbook -i inventories/$ENV --extra-vars "env=$ENV"  deauthorize_users.yml --check

Facebook Graph API error code list

Facebook Developer Wiki (unofficial) contain not only list of FQL error codes but others too it's somehow updated but not contain full list of possible error codes.

There is no any official or updated (I mean really updated) list of error codes returned by Graph API. Every list that can be found online is outdated and not help that much...

There is official list describing some of API Errors and basic recovery tactics. Also there is couple of offcial lists for specific codes:

How do I view executed queries within SQL Server Management Studio?

If you want to see queries that are already executed there is no supported default way to do this. There are some workarounds you can try but don’t expect to find all.

You won’t be able to see SELECT statements for sure but there is a way to see other DML and DDL commands by reading transaction log (assuming database is in full recovery mode).

You can do this using DBCC LOG or fn_dblog commands or third party log reader like ApexSQL Log (note that tool comes with a price)

Now, if you plan on auditing statements that are going to be executed in the future then you can use SQL Profiler to catch everything.

Passing environment-dependent variables in webpack

Just another answer that is similar to @zer0chain's answer. However, with one distinction.

Setting webpack -p is sufficient.

It is the same as:

--define process.env.NODE_ENV="production"

And this is the same as

// webpack.config.js
const webpack = require('webpack');

module.exports = {
  //...

  plugins:[
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production')
    })
  ]
};

So you may only need something like this in package.json Node file:

{
  "name": "projectname",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "debug": "webpack -d",
    "production": "webpack -p"
  },
  "author": "prosti",
  "license": "ISC",
  "dependencies": {    
    "webpack": "^2.2.1",
    ...
  }
}

Just a few tips from the DefinePlugin:

The DefinePlugin allows you to create global constants which can be configured at compile time. This can be useful for allowing different behavior between development builds and release builds. For example, you might use a global constant to determine whether logging takes place; perhaps you perform logging in your development build but not in the release build. That's the sort of scenario the DefinePlugin facilitates.


That this is so you can check if you type webpack --help

Config options:
  --config  Path to the config file
                         [string] [default: webpack.config.js or webpackfile.js]
  --env     Enviroment passed to the config, when it is a function

Basic options:
  --context    The root directory for resolving entry point and stats
                                       [string] [default: The current directory]
  --entry      The entry point                                          [string]
  --watch, -w  Watch the filesystem for changes                        [boolean]
  --debug      Switch loaders to debug mode                            [boolean]
  --devtool    Enable devtool for better debugging experience (Example:
               --devtool eval-cheap-module-source-map)                  [string]
  -d           shortcut for --debug --devtool eval-cheap-module-source-map
               --output-pathinfo                                       [boolean]
  -p           shortcut for --optimize-minimize --define
               process.env.NODE_ENV="production" 

                      [boolean]
  --progress   Print compilation progress in percentage                [boolean]

How to display list of repositories from subversion server

If you enable svn via apache and a SVNParentPath directive, you can add a SVNListParentPath On directive to your svn location to get a list of all repositories.

Your apache conf should look similar to this:

<Location /svn>
  DAV svn
  SVNParentPath         "/net/svn/repositories"
  # optional auth stuff     

  SVNListParentPath On    #  <--- Add this line to enable listing of all repos
</Location>

Using Jquery AJAX function with datatype HTML

var datos = $("#id_formulario").serialize();
$.ajax({         
    url: "url.php",      
    type: "POST",                   
    dataType: "html",                 
    data: datos,                 
    success: function (prueba) { 
        alert("funciona!");
    }//FIN SUCCES

});//FIN  AJAX

Simple line plots using seaborn

It's possible to get this done using seaborn.lineplot() but it involves some additional work of converting numpy arrays to pandas dataframe. Here's a complete example:

# imports
import seaborn as sns
import numpy as np
import pandas as pd

# inputs
In [41]: num = np.array([1, 2, 3, 4, 5])
In [42]: sqr = np.array([1, 4, 9, 16, 25])

# convert to pandas dataframe
In [43]: d = {'num': num, 'sqr': sqr}
In [44]: pdnumsqr = pd.DataFrame(d)

# plot using lineplot
In [45]: sns.set(style='darkgrid')
In [46]: sns.lineplot(x='num', y='sqr', data=pdnumsqr)
Out[46]: <matplotlib.axes._subplots.AxesSubplot at 0x7f583c05d0b8>

And we get the following plot:

square plot

Trusting all certificates using HttpClient over HTTPS

I'm looked response from "emmby" (answered Jun 16 '11 at 21:29), item #4: "Create a custom SSLSocketFactory that uses the built-in certificate KeyStore, but falls back on an alternate KeyStore for anything that fails to verify with the default."

This is a simplified implementation. Load the system keystore & merge with application keystore.

public HttpClient getNewHttpClient() {
    try {
        InputStream in = null;
        // Load default system keystore
        KeyStore trusted = KeyStore.getInstance(KeyStore.getDefaultType()); 
        try {
            in = new BufferedInputStream(new FileInputStream(System.getProperty("javax.net.ssl.trustStore"))); // Normally: "/system/etc/security/cacerts.bks"
            trusted.load(in, null); // no password is "changeit"
        } finally {
            if (in != null) {
                in.close();
                in = null;
            }
        }

        // Load application keystore & merge with system
        try {
            KeyStore appTrusted = KeyStore.getInstance("BKS"); 
            in = context.getResources().openRawResource(R.raw.mykeystore);
            appTrusted.load(in, null); // no password is "changeit"
            for (Enumeration<String> e = appTrusted.aliases(); e.hasMoreElements();) {
                final String alias = e.nextElement();
                final KeyStore.Entry entry = appTrusted.getEntry(alias, null);
                trusted.setEntry(System.currentTimeMillis() + ":" + alias, entry, null);
            }
        } finally {
            if (in != null) {
                in.close();
                in = null;
            }
        }

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SSLSocketFactory sf = new SSLSocketFactory(trusted);
        sf.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

A simple mode to convert from JKS to BKS:

keytool -importkeystore -destkeystore cacerts.bks -deststoretype BKS -providerclass org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath bcprov-jdk16-141.jar -deststorepass changeit -srcstorepass changeit -srckeystore $JAVA_HOME/jre/lib/security/cacerts -srcstoretype JKS -noprompt

*Note: In Android 4.0 (ICS) the Trust Store has changed, more info: http://nelenkov.blogspot.com.es/2011/12/ics-trust-store-implementation.html

How to vertically center a container in Bootstrap?

The Flexible box way

Vertical alignment is now very simple by the use of Flexible box layout. Nowadays, this method is supported in a wide range of web browsers except Internet Explorer 8 & 9. Therefore we'd need to use some hacks/polyfills or different approaches for IE8/9.

In the following I'll show you how to do that in only 3 lines of text (regardless of old flexbox syntax).

Note: it's better to use an additional class instead of altering .jumbotron to achieve the vertical alignment. I'd use vertical-center class name for instance.

Example Here (A Mirror on jsbin).

<div class="jumbotron vertical-center"> <!-- 
                      ^--- Added class  -->
  <div class="container">
    ...
  </div>
</div>
.vertical-center {
  min-height: 100%;  /* Fallback for browsers do NOT support vh unit */
  min-height: 100vh; /* These two lines are counted as one :-)       */

  display: flex;
  align-items: center;
}

Important notes (Considered in the demo):

  1. A percentage values of height or min-height properties is relative to the height of the parent element, therefore you should specify the height of the parent explicitly.

  2. Vendor prefixed / old flexbox syntax omitted in the posted snippet due to brevity, but exist in the online example.

  3. In some of old web browsers such as Firefox 9 (in which I've tested), the flex container - .vertical-center in this case - won't take the available space inside the parent, therefore we need to specify the width property like: width: 100%.

  4. Also in some of web browsers as mentioned above, the flex item - .container in this case - may not appear at the center horizontally. It seems the applied left/right margin of auto doesn't have any effect on the flex item.
    Therefore we need to align it by box-pack / justify-content.

For further details and/or vertical alignment of columns, you could refer to the topic below:


The traditional way for legacy web browsers

This is the old answer I wrote at the time I answered this question. This method has been discussed here and it's supposed to work in Internet Explorer 8 and 9 as well. I'll explain it in short:

In inline flow, an inline level element can be aligned vertically to the middle by vertical-align: middle declaration. Spec from W3C:

middle
Align the vertical midpoint of the box with the baseline of the parent box plus half the x-height of the parent.

In cases that the parent - .vertical-center element in this case - has an explicit height, by any chance if we could have a child element having the exact same height of the parent, we would be able to move the baseline of the parent to the midpoint of the full-height child and surprisingly make our desired in-flow child - the .container - aligned to the center vertically.

Getting all together

That being said, we could create a full-height element within the .vertical-center by ::before or ::after pseudo elements and also change the default display type of it and the other child, the .container to inline-block.

Then use vertical-align: middle; to align the inline elements vertically.

Here you go:

<div class="jumbotron vertical-center">
  <div class="container">
    ...
  </div>
</div>
.vertical-center {
  height:100%;
  width:100%;

  text-align: center;  /* align the inline(-block) elements horizontally */
  font: 0/0 a;         /* remove the gap between inline(-block) elements */
}

.vertical-center:before {    /* create a full-height inline block pseudo=element */
  content: " ";
  display: inline-block;
  vertical-align: middle;    /* vertical alignment of the inline element */
  height: 100%;
}

.vertical-center > .container {
  max-width: 100%;

  display: inline-block;
  vertical-align: middle;  /* vertical alignment of the inline element */
                           /* reset the font property */
  font: 16px/1 "Helvetica Neue", Helvetica, Arial, sans-serif;
}

WORKING DEMO.

Also, to prevent unexpected issues in extra small screens, you can reset the height of the pseudo-element to auto or 0 or change its display type to none if needed so:

@media (max-width: 768px) {
  .vertical-center:before {
    height: auto;
    /* Or */
    display: none;
  }
}

UPDATED DEMO

And one more thing:

If there are footer/header sections around the container, it's better to position that elements properly (relative, absolute? up to you.) and add a higher z-index value (for assurance) to keep them always on the top of the others.

Inserting HTML elements with JavaScript

As others said the convenient jQuery prepend functionality can be emulated:

var html = '<div>Hello prepended</div>';
document.body.innerHTML = html + document.body.innerHTML;

While some say it is better not to "mess" with innerHTML, it is reliable in many use cases, if you know this:

If a <div>, <span>, or <noembed> node has a child text node that includes the characters (&), (<), or (>), innerHTML returns these characters as &amp, &lt and &gt respectively. Use Node.textContent to get a correct copy of these text nodes' contents.

https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML

Or:

var html = '<div>Hello prepended</div>';
document.body.insertAdjacentHTML('afterbegin', html)

insertAdjacentHTML is probably a good alternative: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

Not an enclosing class error Android Studio

startActivity(new Intent(this, Katra_home.class));

try this one it will be work

How to delete from a table where ID is in a list of IDs?

delete from t
where id in (1, 4, 6, 7)

How to print HTML content on click of a button, but not the page?

I Want See This

Example http://jsfiddle.net/35vAN/

    <html>
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js" > </script> 
<script type="text/javascript">

    function PrintElem(elem)
    {
        Popup($(elem).html());
    }

    function Popup(data) 
    {
        var mywindow = window.open('', 'my div', 'height=400,width=600');
        mywindow.document.write('<html><head><title>my div</title>');
        /*optional stylesheet*/ //mywindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
        mywindow.document.write('</head><body >');
        mywindow.document.write(data);
        mywindow.document.write('</body></html>');

        mywindow.print();
        mywindow.close();

        return true;
    }

</script>
</head>
<body>

<div id="mydiv">
    This will be printed. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a quam at nibh adipiscing interdum. Nulla vitae accumsan ante. 
</div>

<div>
    This will not be printed.
</div>

<div id="anotherdiv">
    Nor will this.
</div>

<input type="button" value="Print Div" onclick="PrintElem('#mydiv')" />

</body>

</html>

'was not declared in this scope' error

Here

{int y=((year-1)%100);int c=(year-1)/100;}

you declare and initialize the variables y, c, but you don't used them at all before they run out of scope. That's why you get the unused message.

Later in the function, y, c are undeclared, because the declarations you made only hold inside the block they were made in (the block between the braces {...}).

How to list files inside a folder with SQL Server

Create a SQLCLR assembly with external access permission that returns the list of files as a result set. There are many examples how to do this, eg. Yet another TVF: returning files from a directory or Trading in xp_cmdshell for SQLCLR (Part 1) - List Directory Contents.

ASP.NET Core 1.0 on IIS error 502.5

Had the same issue and all solutions didn't work. Found this gem and thought I'd pass along if it helps someone else. Install on Server 2012 R2 getting the DLL missing error, try to reinstall VS C++ 2015 and get an error. Fix is to do the following:

Seems the file C:\ProgramData\Package Cache\...\packages\Patch\x64\Windows8.1-KB2999226-x64.msu has problems being installed. Open admin command prompt do:

c:
mkdir tmp
mkdir tmp\tmp
move "C:\ProgramData\Package Cache\...\packages\Patch\x64\Windows8.1-KB2999226-x64.msu" c:\tmp
expand -F:* c:\tmp\Windows8.1-KB2999226-x64.msu c:\tmp\tmp
dism /online /add-package /packagepath:c:\tmp\tmp\Windows8.1-KB2999226-x64.cab

NOTE: replace the "..." with the correct folder name. After this reinstall the VS C++ 2015 package.

Improve subplot size/spacing with many subplots in matplotlib

You could try the subplot_tool()

plt.subplot_tool()

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied

You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:

cursor.execute('INSERT INTO images VALUES(?)', (img,))

Without the comma, (img) is just a grouped expression, not a tuple, and thus the img string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.

>>> len(img)
74
>>> len((img,))
1

If you find it easier to read, you can also use a list literal:

cursor.execute('INSERT INTO images VALUES(?)', [img])

Change type of varchar field to integer: "cannot be cast automatically to type integer"

this worked for me.

change varchar column to int

change_column :table_name, :column_name, :integer

got:

PG::DatatypeMismatch: ERROR:  column "column_name" cannot be cast automatically to type integer
HINT:  Specify a USING expression to perform the conversion.

chnged to

change_column :table_name, :column_name, 'integer USING CAST(column_name AS integer)'

How can I do division with variables in a Linux shell?

let's suppose

x=50
y=5

then

z=$((x/y))

this will work properly . But if you want to use / operator in case statements than it can't resolve it. enter code here In that case use simple strings like div or devide or something else. See the code

Select a Dictionary<T1, T2> with LINQ

var dictionary = (from x in y 
                  select new SomeClass
                  {
                      prop1 = value1,
                      prop2 = value2
                  }
                  ).ToDictionary(item => item.prop1);

That's assuming that SomeClass.prop1 is the desired Key for the dictionary.

How can I remove the top and right axis in matplotlib?

If you don't need ticks and such (e.g. for plotting qualitative illustrations) you could also use this quick workaround:

Make the axis invisible (e.g. with plt.gca().axison = False) and then draw them manually with plt.arrow.

Could not find module FindOpenCV.cmake ( Error in configuration process)

I am using Windows and get the same error message. I find another problem which is relevant. I defined OpenCV_DIR in my path at the end of the line. However when I typed "path" in the command line, my OpenCV_DIR was not shown. I found because Windows probably has a limit on how long the path can be, it cut my OpenCV_DIR to be only part of what I defined. So I removed some other part of the path, now it works.

Javascript reduce() on Object

This is not very difficult to implement yourself:

function reduceObj(obj, callback, initial) {
    "use strict";
    var key, lastvalue, firstIteration = true;
    if (typeof callback !== 'function') {
        throw new TypeError(callback + 'is not a function');
    }   
    if (arguments.length > 2) {
        // initial value set
        firstIteration = false;
        lastvalue = initial;
    }
    for (key in obj) {
        if (!obj.hasOwnProperty(key)) continue;
        if (firstIteration)
            firstIteration = false;
            lastvalue = obj[key];
            continue;
        }
        lastvalue = callback(lastvalue, obj[key], key, obj);
    }
    if (firstIteration) {
        throw new TypeError('Reduce of empty object with no initial value');
    }
    return lastvalue;
}

In action:

var o = {a: {value:1}, b: {value:2}, c: {value:3}};
reduceObj(o, function(prev, curr) { prev.value += cur.value; return prev;}, {value:0});
reduceObj(o, function(prev, curr) { return {value: prev.value + curr.value};});
// both == { value: 6 };

reduceObj(o, function(prev, curr) { return prev + curr.value; }, 0);
// == 6

You can also add it to the Object prototype:

if (typeof Object.prototype.reduce !== 'function') {
    Object.prototype.reduce = function(callback, initial) {
        "use strict";
        var args = Array.prototype.slice(arguments);
        args.unshift(this);
        return reduceObj.apply(null, args);
    }
}

Send Post Request with params using Retrofit

build.gradle

      compile 'com.google.code.gson:gson:2.6.2'

      compile 'com.squareup.retrofit2:retrofit:2.1.0'// compulsory

      compile 'com.squareup.retrofit2:converter-gson:2.1.0' //for retrofit conversion

Login APi Put Two Parameters

    {
        "UserId": "1234",
        "Password":"1234"
    }

Login Response

    {
        "UserId": "1234",
        "FirstName": "Keshav",
        "LastName": "Gera",
        "ProfilePicture": "312.113.221.1/GEOMVCAPI/Files/1.500534651736E12p.jpg"
    }

APIClient.java

    import retrofit2.Retrofit;
    import retrofit2.converter.gson.GsonConverterFactory;

    class APIClient {

        public static final String BASE_URL = "Your Base Url ";
        private static Retrofit retrofit = null;

        public static Retrofit getClient() {
            if (retrofit == null) {
                retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            }
            return retrofit;
        }
    }

APIInterface interface

    interface APIInterface {

        @POST("LoginController/Login")
        Call<LoginResponse> createUser(@Body LoginResponse login);
    }

Login Pojo

    package pojos;

    import com.google.gson.annotations.SerializedName;

    public class LoginResponse {


        @SerializedName("UserId")
        public String UserId;
        @SerializedName("FirstName")
        public String FirstName;
        @SerializedName("LastName")
        public String LastName;
        @SerializedName("ProfilePicture")
        public String ProfilePicture;
        @SerializedName("Password")
        public String Password;
        @SerializedName("ResponseCode")
        public String ResponseCode;
        @SerializedName("ResponseMessage")
        public String ResponseMessage;

        public LoginResponse(String UserId, String Password) {
            this.UserId = UserId;
            this.Password = Password;
        }

        public String getUserId() {
            return UserId;
        }

        public String getFirstName() {
            return FirstName;
        }

        public String getLastName() {
            return LastName;
        }

        public String getProfilePicture() {
            return ProfilePicture;
        }

        public String getResponseCode() {
            return ResponseCode;
        }

        public String getResponseMessage() {
            return ResponseMessage;
        }
    }

MainActivity

    package com.keshav.retrofitloginexampleworkingkeshav;

    import android.app.Dialog;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;

    import pojos.LoginResponse;
    import retrofit2.Call;
    import retrofit2.Callback;
    import retrofit2.Response;
    import utilites.CommonMethod;

    public class MainActivity extends AppCompatActivity {

        TextView responseText;
        APIInterface apiInterface;

        Button loginSub;
        EditText et_Email;
        EditText et_Pass;
        private Dialog mDialog;
        String userId;
        String password;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            apiInterface = APIClient.getClient().create(APIInterface.class);

            loginSub = (Button) findViewById(R.id.loginSub);
            et_Email = (EditText) findViewById(R.id.edtEmail);
            et_Pass = (EditText) findViewById(R.id.edtPass);

            loginSub.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (checkValidation()) {
                        if (CommonMethod.isNetworkAvailable(MainActivity.this))
                            loginRetrofit2Api(userId, password);
                        else
                            CommonMethod.showAlert("Internet Connectivity Failure", MainActivity.this);
                    }
                }
            });
        }

        private void loginRetrofit2Api(String userId, String password) {
            final LoginResponse login = new LoginResponse(userId, password);
            Call<LoginResponse> call1 = apiInterface.createUser(login);
            call1.enqueue(new Callback<LoginResponse>() {
                @Override
                public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                    LoginResponse loginResponse = response.body();

                    Log.e("keshav", "loginResponse 1 --> " + loginResponse);
                    if (loginResponse != null) {
                        Log.e("keshav", "getUserId          -->  " + loginResponse.getUserId());
                        Log.e("keshav", "getFirstName       -->  " + loginResponse.getFirstName());
                        Log.e("keshav", "getLastName        -->  " + loginResponse.getLastName());
                        Log.e("keshav", "getProfilePicture  -->  " + loginResponse.getProfilePicture());

                        String responseCode = loginResponse.getResponseCode();
                        Log.e("keshav", "getResponseCode  -->  " + loginResponse.getResponseCode());
                        Log.e("keshav", "getResponseMessage  -->  " + loginResponse.getResponseMessage());
                        if (responseCode != null && responseCode.equals("404")) {
                            Toast.makeText(MainActivity.this, "Invalid Login Details \n Please try again", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MainActivity.this, "Welcome " + loginResponse.getFirstName(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }

                @Override
                public void onFailure(Call<LoginResponse> call, Throwable t) {
                    Toast.makeText(getApplicationContext(), "onFailure called ", Toast.LENGTH_SHORT).show();
                    call.cancel();
                }
            });
        }

        public boolean checkValidation() {
            userId = et_Email.getText().toString();
            password = et_Pass.getText().toString();

            Log.e("Keshav", "userId is -> " + userId);
            Log.e("Keshav", "password is -> " + password);

            if (et_Email.getText().toString().trim().equals("")) {
                CommonMethod.showAlert("UserId Cannot be left blank", MainActivity.this);
                return false;
            } else if (et_Pass.getText().toString().trim().equals("")) {
                CommonMethod.showAlert("password Cannot be left blank", MainActivity.this);
                return false;
            }
            return true;
        }
    }

CommonMethod.java

    public class CommonMethod {


        public static final String DISPLAY_MESSAGE_ACTION =
                "com.codecube.broking.gcm";

        public static final String EXTRA_MESSAGE = "message";

        public  static boolean isNetworkAvailable(Context ctx) {
            ConnectivityManager connectivityManager
                    = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null && activeNetworkInfo.isConnected();
        }

        public static void showAlert(String message, Activity context) {

            final AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setMessage(message).setCancelable(false)
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {

                        }
                    });
            try {
                builder.show();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

activity_main.xml

    <LinearLayout android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:orientation="vertical"
        xmlns:android="http://schemas.android.com/apk/res/android">

            <ImageView
                android:id="@+id/imgLogin"
                android:layout_width="200dp"
                android:layout_height="150dp"
                android:layout_gravity="center"
                android:layout_marginTop="20dp"
                android:padding="5dp"
                android:background="@mipmap/ic_launcher_round"
                />

            <TextView
                android:id="@+id/txtLogo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/imgLogin"
                android:layout_centerHorizontal="true"
                android:text="Holostik Track and Trace"
                android:textSize="20dp"
                android:visibility="gone" />

            <android.support.design.widget.TextInputLayout
                android:id="@+id/textInputLayout1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/box_layout_margin_left"
                android:layout_marginRight="@dimen/box_layout_margin_right"
                android:layout_marginTop="8dp"
                android:padding="@dimen/text_input_padding">

                <EditText
                    android:id="@+id/edtEmail"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    android:ems="10"
                    android:fontFamily="sans-serif"
                    android:gravity="top"
                    android:hint="Login ID"
                    android:maxLines="10"
                    android:paddingLeft="@dimen/edit_input_padding"
                    android:paddingRight="@dimen/edit_input_padding"
                    android:paddingTop="@dimen/edit_input_padding"
                    android:singleLine="true"></EditText>

            </android.support.design.widget.TextInputLayout>

            <android.support.design.widget.TextInputLayout
                android:id="@+id/textInputLayout2"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/textInputLayout1"
                android:layout_marginLeft="@dimen/box_layout_margin_left"
                android:layout_marginRight="@dimen/box_layout_margin_right"
                android:padding="@dimen/text_input_padding">

                <EditText
                    android:id="@+id/edtPass"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:focusable="true"
                    android:fontFamily="sans-serif"
                    android:hint="Password"
                    android:inputType="textPassword"

                    android:singleLine="true" />

            </android.support.design.widget.TextInputLayout>

            <RelativeLayout
                android:id="@+id/rel12"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/textInputLayout2"
                android:layout_marginTop="10dp"
                android:layout_marginLeft="10dp"
                >

                <Button
                    android:id="@+id/loginSub"
                    android:layout_width="wrap_content"
                    android:layout_height="45dp"
                    android:layout_alignParentRight="true"
                    android:layout_centerVertical="true"
                    android:background="@drawable/border_button"
                    android:paddingLeft="30dp"
                    android:paddingRight="30dp"
                    android:layout_marginRight="10dp"
                    android:text="Login"
                    android:textColor="#ffffff" />    
            </RelativeLayout>

    </LinearLayout>

How do I work with dynamic multi-dimensional arrays in C?

Since C99, C has 2D arrays with dynamical bounds. If you want to avoid that such beast are allocated on the stack (which you should), you can allocate them easily in one go as the following

double (*A)[n] = malloc(sizeof(double[n][n]));

and that's it. You can then easily use it as you are used for 2D arrays with something like A[i][j]. And don't forget that one at the end

free(A);

Randy Meyers wrote series of articles explaining variable length arrays (VLAs).

Xpath for href element

Try below locator.

selenium.click("css=a[href*='listDetails.do'][id='oldcontent']");

or

selenium.click("xpath=//a[contains(@href,'listDetails.do') and @id='oldcontent']");

How to insert a data table into SQL Server database table?

From my understanding of the question,this can use a fairly straight forward solution.Anyway below is the method i propose ,this method takes in a data table and then using SQL statements to insert into a table in the database.Please mind that my solution is using MySQLConnection and MySqlCommand replace it with SqlConnection and SqlCommand.

public void InsertTableIntoDB_CreditLimitSimple(System.Data.DataTable tblFormat)
    {
        for (int i = 0; i < tblFormat.Rows.Count; i++)
        {

            String InsertQuery = string.Empty;

            InsertQuery = "INSERT INTO customercredit " +
                          "(ACCOUNT_CODE,NAME,CURRENCY,CREDIT_LIMIT) " +
                          "VALUES ('" + tblFormat.Rows[i]["AccountCode"].ToString() + "','" + tblFormat.Rows[i]["Name"].ToString() + "','" + tblFormat.Rows[i]["Currency"].ToString() + "','" + tblFormat.Rows[i]["CreditLimit"].ToString() + "')";



            using (MySqlConnection destinationConnection = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
            using (var dbcm = new MySqlCommand(InsertQuery, destinationConnection))
            {
                destinationConnection.Open();
                dbcm.ExecuteNonQuery();
            }
        }
    }//CreditLimit

Removing the fragment identifier from AngularJS urls (# symbol)

Follow 2 steps-
1. First set the $locationProvider.html5Mode(true) in your app config file.
For eg -
angular.module('test', ['ui.router']) .config(function($stateProvider, $urlRouterProvider, $locationProvider) { $locationProvider.html5Mode(true); $urlRouterProvider.otherwise('/'); });

2.Second set the <base> inside your main page.
For eg ->
<base href="/">

The $location service will automatically fallback to the hash-part method for browsers that do not support the HTML5 History API.

Python For loop get index

Use the enumerate() function to generate the index along with the elements of the sequence you are looping over:

for index, w in enumerate(loopme):
    print "CURRENT WORD IS", w, "AT CHARACTER", index 

Swift presentViewController

I had a similar issue but in my case, the solution was to dispatch the action as an async task in the main queue

DispatchQueue.main.async {
    let vc = self.storyboard?.instantiateViewController(withIdentifier: myVCID) as! myVCName
    self.present(vc, animated: true, completion: nil)
}

No converter found capable of converting from type to type

Simple Solution::

use {nativeQuery=true} in your query.

for example

  @Query(value = "select d.id,d.name,d.breed,d.origin from Dog d",nativeQuery = true)
        
    List<Dog> findALL();

When do I need to use Begin / End Blocks and the Go keyword in SQL Server?

After wrestling with this problem today my opinion is this: BEGIN...END brackets code just like {....} does in C languages, e.g. code blocks for if...else and loops

GO is (must be) used when succeeding statements rely on an object defined by a previous statement. USE database is a good example above, but the following will also bite you:

alter table foo add bar varchar(8);
-- if you don't put GO here then the following line will error as it doesn't know what bar is.
update foo set bar = 'bacon';
-- need a GO here to tell the interpreter to execute this statement, otherwise the Parser will lump it together with all successive statements.

It seems to me the problem is this: the SQL Server SQL Parser, unlike the Oracle one, is unable to realise that you're defining a new symbol on the first line and that it's ok to reference in the following lines. It doesn't "see" the symbol until it encounters a GO token which tells it to execute the preceding SQL since the last GO, at which point the symbol is applied to the database and becomes visible to the parser.

Why it doesn't just treat the semi-colon as a semantic break and apply statements individually I don't know and wish it would. Only bonus I can see is that you can put a print() statement just before the GO and if any of the statements fail the print won't execute. Lot of trouble for a minor gain though.

How to display two digits after decimal point in SQL Server

select cast(your_float_column as decimal(10,2))
from your_table

decimal(10,2) means you can have a decimal number with a maximal total precision of 10 digits. 2 of them after the decimal point and 8 before.
The biggest possible number would be 99999999.99

How to delete node from XML file using C#

DocumentElement is the root node of the document so childNodes[1] doesn't exist in that document. childNodes[0] would be the <Settings> node

jQuery event to trigger action when a div is made visible

The following code (pulled from http://maximeparmentier.com/2012/11/06/bind-show-hide-events-with-jquery/) will enable you to use $('#someDiv').on('show', someFunc);.

(function ($) {
  $.each(['show', 'hide'], function (i, ev) {
    var el = $.fn[ev];
    $.fn[ev] = function () {
      this.trigger(ev);
      return el.apply(this, arguments);
    };
  });
})(jQuery);

Getting View's coordinates relative to the root layout

You can use `

view.getLocationOnScreen(int[] location)

;` to get location of your view correctly.

But there is a catch if you use it before layout has been inflated you will get wrong position.

Solution to this problem is adding ViewTreeObserver like this :-

Declare globally the array to store x y position of your view

 int[] img_coordinates = new int[2];

and then add ViewTreeObserver on your parent layout to get callback for layout inflation and only then fetch position of view otherwise you will get wrong x y coordinates

  // set a global layout listener which will be called when the layout pass is completed and the view is drawn
            parentViewGroup.getViewTreeObserver().addOnGlobalLayoutListener(
                    new ViewTreeObserver.OnGlobalLayoutListener() {
                        public void onGlobalLayout() {
                            //Remove the listener before proceeding
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                parentViewGroup.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                            } else {
                                parentViewGroup.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                            }

                            // measure your views here
                            fab.getLocationOnScreen(img_coordinates);
                        }
                    }
            );

and then use it like this

xposition = img_coordinates[0];
yposition =  img_coordinates[1];

How can I know if a process is running?

Despite of supported API from .Net frameworks regarding checking existing process by process ID, those functions are very slow. It costs a huge amount of CPU cycles to run Process.GetProcesses() or Process.GetProcessById/Name().

A much quicker method to check a running process by ID is to use native API OpenProcess(). If return handle is 0, the process doesn't exist. If handle is different than 0, the process is running. There's no guarantee this method would work 100% at all time due to permission.

Refused to apply inline style because it violates the following Content Security Policy directive

Another method is to use the CSSOM (CSS Object Model), via the style property on a DOM node.

var myElem = document.querySelector('.my-selector');
myElem.style.color = 'blue';

More details on CSSOM: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.style

As mentioned by others, enabling unsafe-line for css is another method to solve this.

Escape double quote in VB string

Did you try using double-quotes? Regardless, no one in 2011 should be limited by the native VB6 shell command. Here's a function that uses ShellExecuteEx, much more versatile.

Option Explicit

Private Const SEE_MASK_DEFAULT = &H0

Public Enum EShellShowConstants
        essSW_HIDE = 0
        essSW_SHOWNORMAL = 1
        essSW_SHOWMINIMIZED = 2
        essSW_MAXIMIZE = 3
        essSW_SHOWMAXIMIZED = 3
        essSW_SHOWNOACTIVATE = 4
        essSW_SHOW = 5
        essSW_MINIMIZE = 6
        essSW_SHOWMINNOACTIVE = 7
        essSW_SHOWNA = 8
        essSW_RESTORE = 9
        essSW_SHOWDEFAULT = 10
End Enum

Private Type SHELLEXECUTEINFO
        cbSize        As Long
        fMask         As Long
        hwnd          As Long
        lpVerb        As String
        lpFile        As String
        lpParameters  As String
        lpDirectory   As String
        nShow         As Long
        hInstApp      As Long
        lpIDList      As Long     'Optional
        lpClass       As String   'Optional
        hkeyClass     As Long     'Optional
        dwHotKey      As Long     'Optional
        hIcon         As Long     'Optional
        hProcess      As Long     'Optional
End Type

Private Declare Function ShellExecuteEx Lib "shell32.dll" Alias "ShellExecuteExA" (lpSEI As SHELLEXECUTEINFO) As Long

Public Function ExecuteProcess(ByVal FilePath As String, ByVal hWndOwner As Long, ShellShowType As EShellShowConstants, Optional EXEParameters As String = "", Optional LaunchElevated As Boolean = False) As Boolean
    Dim SEI As SHELLEXECUTEINFO

    On Error GoTo Err

    'Fill the SEI structure
    With SEI
        .cbSize = Len(SEI)                  ' Bytes of the structure
        .fMask = SEE_MASK_DEFAULT           ' Check MSDN for more info on Mask
        .lpFile = FilePath                  ' Program Path
        .nShow = ShellShowType              ' How the program will be displayed
        .lpDirectory = PathGetFolder(FilePath)
        .lpParameters = EXEParameters       ' Each parameter must be separated by space. If the lpFile member specifies a document file, lpParameters should be NULL.
        .hwnd = hWndOwner                   ' Owner window handle

        ' Determine launch type (would recommend checking for Vista or greater here also)
        If LaunchElevated = True Then ' And m_OpSys.IsVistaOrGreater = True
            .lpVerb = "runas"
        Else
            .lpVerb = "Open"
        End If
    End With

     ExecuteProcess = ShellExecuteEx(SEI)   ' Execute the program, return success or failure

    Exit Function
Err:
    ' TODO: Log Error
    ExecuteProcess = False
End Function

Private Function PathGetFolder(psPath As String) As String
    On Error Resume Next
    Dim lPos As Long
    lPos = InStrRev(psPath, "\")
    PathGetFolder = Left$(psPath, lPos - 1)
End Function

How to update two tables in one statement in SQL Server 2005?

You can write update statement for one table and then a trigger on first table update, which update second table

In practice, what are the main uses for the new "yield from" syntax in Python 3.3?

Wherever you invoke a generator from within a generator you need a "pump" to re-yield the values: for v in inner_generator: yield v. As the PEP points out there are subtle complexities to this which most people ignore. Non-local flow-control like throw() is one example given in the PEP. The new syntax yield from inner_generator is used wherever you would have written the explicit for loop before. It's not merely syntactic sugar, though: It handles all of the corner cases that are ignored by the for loop. Being "sugary" encourages people to use it and thus get the right behaviors.

This message in the discussion thread talks about these complexities:

With the additional generator features introduced by PEP 342, that is no longer the case: as described in Greg's PEP, simple iteration doesn't support send() and throw() correctly. The gymnastics needed to support send() and throw() actually aren't that complex when you break them down, but they aren't trivial either.

I can't speak to a comparison with micro-threads, other than to observe that generators are a type of paralellism. You can consider the suspended generator to be a thread which sends values via yield to a consumer thread. The actual implementation may be nothing like this (and the actual implementation is obviously of great interest to the Python developers) but this does not concern the users.

The new yield from syntax does not add any additional capability to the language in terms of threading, it just makes it easier to use existing features correctly. Or more precisely it makes it easier for a novice consumer of a complex inner generator written by an expert to pass through that generator without breaking any of its complex features.

Django URL Redirect

The other methods work fine, but you can also use the good old django.shortcut.redirect.

The code below was taken from this answer.

In Django 2.x:

from django.shortcuts import redirect
from django.urls import path, include

urlpatterns = [
    # this example uses named URL 'hola-home' from app named hola
    # for more redirect's usage options: https://docs.djangoproject.com/en/2.1/topics/http/shortcuts/
    path('', lambda request: redirect('hola/', permanent=True)),
    path('hola/', include('hola.urls')),
]

How to Install Sublime Text 3 using Homebrew

To install Sublime Text 3 run:

brew install --cask sublime-text

reference: https://formulae.brew.sh/cask/sublime-text

jwt check if token expired

Sadly @Andrés Montoya answer has a flaw which is related to how he compares the obj. I found a solution here which should solve this:

const now = Date.now().valueOf() / 1000

if (typeof decoded.exp !== 'undefined' && decoded.exp < now) {
    throw new Error(`token expired: ${JSON.stringify(decoded)}`)
}
if (typeof decoded.nbf !== 'undefined' && decoded.nbf > now) {
    throw new Error(`token expired: ${JSON.stringify(decoded)}`)
}

Thanks to thejohnfreeman!

How can you flush a write using a file descriptor?

If you want to go the other way round (associate FILE* with existing file descriptor), use fdopen() :

                                                          FDOPEN(P)

NAME

       fdopen - associate a stream with a file descriptor

SYNOPSIS

       #include <stdio.h>

       FILE *fdopen(int fildes, const char *mode);

Type datetime for input parameter in procedure

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

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

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

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

So in your case, you should try:

declare @a datetime
declare @b datetime 

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

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

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

So change this line here to this:

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

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

Scraping html tables into R data frames using the XML package

library(RCurl)
library(XML)

# Download page using RCurl
# You may need to set proxy details, etc.,  in the call to getURL
theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
webpage <- getURL(theurl)
# Process escape characters
webpage <- readLines(tc <- textConnection(webpage)); close(tc)

# Parse the html tree, ignoring errors on the page
pagetree <- htmlTreeParse(webpage, error=function(...){})

# Navigate your way through the tree. It may be possible to do this more efficiently using getNodeSet
body <- pagetree$children$html$children$body 
divbodyContent <- body$children$div$children[[1]]$children$div$children[[4]]
tables <- divbodyContent$children[names(divbodyContent)=="table"]

#In this case, the required table is the only one with class "wikitable sortable"  
tableclasses <- sapply(tables, function(x) x$attributes["class"])
thetable  <- tables[which(tableclasses=="wikitable sortable")]$table

#Get columns headers
headers <- thetable$children[[1]]$children
columnnames <- unname(sapply(headers, function(x) x$children$text$value))

# Get rows from table
content <- c()
for(i in 2:length(thetable$children))
{
   tablerow <- thetable$children[[i]]$children
   opponent <- tablerow[[1]]$children[[2]]$children$text$value
   others <- unname(sapply(tablerow[-1], function(x) x$children$text$value)) 
   content <- rbind(content, c(opponent, others))
}

# Convert to data frame
colnames(content) <- columnnames
as.data.frame(content)

Edited to add:

Sample output

                     Opponent Played Won Drawn Lost Goals for Goals against  % Won
    1               Argentina     94  36    24   34       148           150  38.3%
    2                Paraguay     72  44    17   11       160            61  61.1%
    3                 Uruguay     72  33    19   20       127            93  45.8%
    ...

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

It was that easy for me - the class which contains the test methods must be public. :)

Python: URLError: <urlopen error [Errno 10060]

This is because of the proxy settings. I also had the same problem, under which I could not use any of the modules which were fetching data from the internet. There are simple steps to follow:
1. open the control panel
2. open internet options
3. under connection tab open LAN settings
4. go to advance settings and unmark everything, delete every proxy in there. Or u can just unmark the checkbox in proxy server this will also do the same
5. save all the settings by clicking ok.
you are done. try to run the programme again, it must work it worked for me at least

Change values of select box of "show 10 entries" of jquery datatable

you can achieve this easily without writing Js. Just add an attribute called data-page-length={put your number here}. see example below, I used 100 for example

<table id="datatable-keytable" data-page-length='100' class="p-table table table-bordered" width="100%">

Why compile Python code?

There's certainly a performance difference when running a compiled script. If you run normal .py scripts, the machine compiles it every time it is run and this takes time. On modern machines this is hardly noticeable but as the script grows it may become more of an issue.

C# RSA encryption/decryption with transmission

I'll share my very simple code for sample purpose. Hope it will help someone like me searching for quick code reference. My goal was to receive rsa signature from backend, then validate against input string using public key and store locally for future periodic verifications. Here is main part used for signature verification:

        ...
        var signature = Get(url); // base64_encoded signature received from server
        var inputtext= "inputtext"; // this is main text signature was created for
        bool result = VerifySignature(inputtext, signature);
        ...

    private bool VerifySignature(string input, string signature)
    {
        var result = false;
        using (var cps=new RSACryptoServiceProvider())
        {
            // converting input and signature to Bytes Arrays to pass to VerifyData rsa method to verify inputtext was signed using privatekey corresponding to public key we have below
            byte[] inputtextBytes = Encoding.UTF8.GetBytes(input);
            byte[] signatureBytes  = Convert.FromBase64String(signature);

            cps.FromXmlString("<RSAKeyValue><Modulus>....</Modulus><Exponent>....</Exponent></RSAKeyValue>"); // xml formatted publickey
            result = cps.VerifyData(inputtextBytes , new SHA1CryptoServiceProvider(), signatureBytes  );
        }

        return result;
    }

PHP: How to get referrer URL?

Underscore. Not space.

$_SERVER['HTTP_REFERER']

Textarea to resize based on content length

Alciende's answer didn't quite work for me in Safari for whatever reason just now, but did after a minor modification:

function textAreaAdjust(o) {
    o.style.height = "1px";
    setTimeout(function() {
        o.style.height = (o.scrollHeight)+"px";
    }, 1);
}

Hope this helps someone

How to link an image and target a new window

If you use script to navigate to the page, use the open method with the target _blank to open a new window / tab:

<img src="..." alt="..." onclick="window.open('anotherpage.html', '_blank');" />

However, if you want search engines to find the page, you should just wrap the image in a regular link instead.

Responsive font size in CSS

I use these CSS classes, and they make my text fluid on any screen size:

.h1-fluid {
    font-size: calc(1rem + 3vw);
    line-height: calc(1.4rem + 4.8vw);
}

.h2-fluid {
    font-size: calc(1rem + 2vw);
    line-height: calc(1.4rem + 2.4vw);
}

.h3-fluid {
    font-size: calc(1rem + 1vw);
    line-height: calc(1.4rem + 1.2vw);
}

.p-fluid {
    font-size: calc(1rem + 0.5vw);
    line-height: calc(1.4rem + 0.6vw);
}

Python convert csv to xlsx

With my library pyexcel,

 $ pip install pyexcel pyexcel-xlsx

you can do it in one command line:

from pyexcel.cookbook import merge_all_to_a_book
# import pyexcel.ext.xlsx # no longer required if you use pyexcel >= 0.2.2 
import glob


merge_all_to_a_book(glob.glob("your_csv_directory/*.csv"), "output.xlsx")

Each csv will have its own sheet and the name will be their file name.

How do I set a background-color for the width of text, not the width of the entire element, using CSS?

A little late to game but thought I would add my 2 cents...

To avoid adding the extra mark-up of an inner span you could change the <h1> display property from block to inline (catch is you would have ensure the elements after the <h1> are block elements.

HTML

<h1>  
The Last Will and Testament of
Eric Jones</h1> 
<p>Some other text</p>

CSS

h1{
    display:inline;
    background-color:green;
    color:#fff;
}

Result
enter image description here
JSFIDDLE http://jsfiddle.net/J7VBV/

In javascript, how do you search an array for a substring match

For a fascinating examination of some of the alternatives and their efficiency, see John Resig's recent posts:

(The problem discussed there is slightly different, with the haystack elements being prefixes of the needle and not the other way around, but most solutions are easy to adapt.)

How to add an extra language input to Android?

I don't know about sliding the space bar. I have a small box on the left of my keyboard that indicates which language is selected ( when english is selected it shows the words EN with a small microphone on top. Being that I also have spanish as one of my languages, I just tap that button and it swithces back and forth from spanish to english.

Python Turtle, draw text with on screen with larger font

Use the optional font argument to turtle.write(), from the docs:

turtle.write(arg, move=False, align="left", font=("Arial", 8, "normal"))
 Parameters:

  • arg – object to be written to the TurtleScreen
  • move – True/False
  • align – one of the strings “left”, “center” or right”
  • font – a triple (fontname, fontsize, fonttype)

So you could do something like turtle.write("messi fan", font=("Arial", 16, "normal")) to change the font size to 16 (default is 8).

How to get Android crash logs?

Base on this POST, use this class as replacement of "TopExceptionHandler"

class TopExceptionHandler implements Thread.UncaughtExceptionHandler {
private Thread.UncaughtExceptionHandler defaultUEH;
private Activity app = null;
private String line;

public TopExceptionHandler(Activity app) {
    this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
    this.app = app;
}

public void uncaughtException(Thread t, Throwable e) {




    StackTraceElement[] arr = e.getStackTrace();
    String report = e.toString()+"\n\n";
    report += "--------- Stack trace ---------\n\n";
    for (int i=0; i<arr.length; i++) {
        report += "    "+arr[i].toString()+"\n";
    }
    report += "-------------------------------\n\n";

    // If the exception was thrown in a background thread inside
    // AsyncTask, then the actual exception can be found with getCause

    report += "--------- Cause ---------\n\n";
    Throwable cause = e.getCause();
    if(cause != null) {
        report += cause.toString() + "\n\n";
        arr = cause.getStackTrace();
        for (int i=0; i<arr.length; i++) {
            report += "    "+arr[i].toString()+"\n";
        }
    }
    report += "-------------------------------\n\n";

    try {
        FileOutputStream trace = app.openFileOutput("stack.trace",
                Context.MODE_PRIVATE);
        trace.write(report.getBytes());
        trace.close();



        Intent i = new Intent(Intent.ACTION_SEND);
        i.setType("message/rfc822");
        i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"[email protected]"});
        i.putExtra(Intent.EXTRA_SUBJECT, "crash report azar");
        String body = "Mail this to [email protected]: " + "\n" + trace + "\n";
        i.putExtra(Intent.EXTRA_TEXT   , body);
        try {
            startActivity(Intent.createChooser(i, "Send mail..."));
        } catch (android.content.ActivityNotFoundException ex) {
           // Toast.makeText(MyActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
        }






      //  ReaderScopeActivity.this.startActivity(Intent.createChooser(sendIntent, "Title:"));

        //ReaderScopeActivity.this.deleteFile("stack.trace");

    } catch(IOException ioe) {
        // ...
    }

    defaultUEH.uncaughtException(t, e);
}

private void startActivity(Intent chooser) {
}

}

.....

in same java class file (Activity) .....

Public class MainActivity.....

.....

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Thread.setDefaultUncaughtExceptionHandler(new TopExceptionHandler(this));

.....

How to use sed/grep to extract text between two words?

All the above solutions have deficiencies where the last search string is repeated elsewhere in the string. I found it best to write a bash function.

    function str_str {
      local str
      str="${1#*${2}}"
      str="${str%%$3*}"
      echo -n "$str"
    }

    # test it ...
    mystr="this is a string"
    str_str "$mystr" "this " " string"

How to print last two columns using awk

awk '{print $NF-1, $NF}'  inputfile

Note: this works only if at least two columns exist. On records with one column you will get a spurious "-1 column1"

Call a function on click event in Angular 2

Exact transfer to Angular2+ is as below:

<button (click)="myFunc()"></button>

also in your component file:

import { Component, OnInit } from "@angular/core";

@Component({
  templateUrl:"button.html" //this is the component which has the above button html
})

export class App implements OnInit{
  constructor(){}

  ngOnInit(){

  }

  myFunc(){
    console.log("function called");
  }
}

Find intersection of two nested lists?

Since intersect was defined, a basic list comprehension is enough:

>>> c3 = [intersect(c1, i) for i in c2]
>>> c3
[[32, 13], [28, 13, 7], [1, 6]]

Improvement thanks to S. Lott's remark and TM.'s associated remark:

>>> c3 = [list(set(c1).intersection(i)) for i in c2]
>>> c3
[[32, 13], [28, 13, 7], [1, 6]]

Export to CSV using jQuery and html

What if you have your data in CSV format and convert it to HTML for display on the web page? You may use the http://code.google.com/p/js-tables/ plugin. Check this example http://code.google.com/p/js-tables/wiki/Table As you are already using jQuery library I have assumed you are able to add other javascript toolkit libraries.

If the data is in CSV format, you should be able to use the generic 'application/octetstream' mime type. All the 3 mime types you have tried are dependent on the software installed on the clients computer.

mysql command for showing current configuration variables

What you are looking for is this:

SHOW VARIABLES;  

You can modify it further like any query:

SHOW VARIABLES LIKE '%max%';  

How to find difference between two Joda-Time DateTimes in minutes

Something like...

DateTime today = new DateTime();
DateTime yesterday = today.minusDays(1);

Duration duration = new Duration(yesterday, today);
System.out.println(duration.getStandardDays());
System.out.println(duration.getStandardHours());
System.out.println(duration.getStandardMinutes());

Which outputs

1
24
1440

or

System.out.println(Minutes.minutesBetween(yesterday, today).getMinutes());

Which is probably more what you're after

Best way to simulate "group by" from bash?

cat ip_addresses | sort | uniq -c | sort -nr | awk '{print $2 " " $1}'

this command would give you desired output

Extending the User model with custom fields in Django

Extending Django User Model (UserProfile) like a Pro

I've found this very useful: link

An extract:

from django.contrib.auth.models import User

class Employee(models.Model):
    user = models.OneToOneField(User)
    department = models.CharField(max_length=100)

>>> u = User.objects.get(username='fsmith')
>>> freds_department = u.employee.department

Changing one character in a string

A solution combining find and replace methods in a single line if statement could be:

```python
my_var = "stackoverflaw"
my_new_var = my_var.replace('a', 'o', 1) if my_var.find('s') != -1 else my_var
print(f"my_var = {my_var}")           # my_var = stackoverflaw
print(f"my_new_var = {my_new_var}")   # my_new_var = stackoverflow
```

How to get span tag inside a div in jQuery and assign a text?

function Errormessage(txt) {
    $("#message").fadeIn("slow");
    $("#message span:first").text(txt);
    // find the span inside the div and assign a text
    $("#message a.close-notify").click(function() {
        $("#message").fadeOut("slow");
    });
}

Merge / convert multiple PDF files into one PDF

You can see use the free and open source pdftools (disclaimer: I am the author of it).

It is basically a Python interface to the Latex pdfpages package.

To merge pdf files one by one, you can run:

pdftools --input-file file1.pdf --input-file file2.pdf --output output.pdf

To merge together all the pdf files in a directory, you can run:

pdftools --input-dir ./dir_with_pdfs --output output.pdf

TypeScript error: Type 'void' is not assignable to type 'boolean'

Your code is passing a function as an argument to find. That function takes an element argument (of type Conversation) and returns void (meaning there is no return value). TypeScript describes this as (element: Conversation) => void'

What TypeScript is saying is that the find function doesn't expect to receive a function that takes a Conversation and returns void. It expects a function that takes a Conversations, a number and a Conversation array, and that this function should return a boolean.

So bottom line is that you either need to change your code to pass in the values to find correctly, or else you need to provide an overload to the definition of find in your definition file that accepts a Conversation and returns void.

How to split a string literal across multiple lines in C / Objective-C?

You can also do:

NSString * query = @"SELECT * FROM foo "
                   @"WHERE "
                     @"bar = 42 "
                     @"AND baz = datetime() "
                   @"ORDER BY fizbit ASC";

Input from the keyboard in command line application

I have now been able to get Keyboard input in Swift by using the following:

In my main.swift file I declared a variable i and assigned to it the function GetInt() which I defined in Objective C. Through a so called Bridging Header where I declared the function prototype for GetInt I could link to main.swift. Here are the files:

main.swift:

var i: CInt = GetInt()
println("Your input is \(i) ");

Bridging Header:

#include "obj.m"

int GetInt();

obj.m:

#import <Foundation/Foundation.h>
#import <stdio.h>
#import <stdlib.h>

int GetInt()
{
    int i;
    scanf("%i", &i);
    return i;
}

In obj.m it is possible to include the c standard output and input, stdio.h, as well as the c standard library stdlib.h which enables you to program in C in Objective-C, which means there is no need for including a real swift file like user.c or something like that.

Hope I could help,

Edit: It is not possible to get String input through C because here I am using the CInt -> the integer type of C and not of Swift. There is no equivalent Swift type for the C char*. Therefore String is not convertible to string. But there are fairly enough solutions around here to get String input.

Raul

Creating the Singleton design pattern in PHP5

This is the example of create singleton on Database class

design patterns 1) singleton

class Database{
  public static $instance;
  public static function getInstance(){
    if(!isset(Database::$instance)){
    Database::$instance=new Database();

     return Database::$instance;
    }

  }

  $db=Database::getInstance();
  $db2=Database::getInstance();
  $db3=Database::getInstance();

  var_dump($db);
  var_dump($db2);
  var_dump($db3);

then out put is --

  object(Database)[1]
  object(Database)[1]
  object(Database)[1]

use only single instance not create 3 instance

See :hover state in Chrome Developer Tools

I could see the style by following below steps suggested by Babiker - "Right-click element, but DON'T move your mouse pointer away from the element, keep it in hover state. Choose inspect element via keyboard, as in hit up arrow and then Enter key."

For changing style follow above steps and then - Change your browser tab by pressing ctrl + TAB on the keyboard. Then click back on the tab you want to debug. Your hover screen will still be there. Now carefully take your mouse to developer tool area.

HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers

Old question but anyway !

Same thing happen to me this morning, everything was working fine for weeks before...... yes guess what ... I change my windows PC user account password yesterday night !!!!! (how stupid was I !!!)

So easy fix : IIS -> authentication -> Anonymous authentication -> edit and set the user and new PASSWORD !!!!!

How to remove provisioning profiles from Xcode

In Xcode 7:

  1. Go to Preferences > Accounts > Select your account and click View Details...
  2. In the Provisioning Profiles section, right click on the profile you want to delete and choose Move to Trash.
  3. Click Download all to get all the latest profiles for your account, or click Download next to the profile.
  4. Do a sanity check in your project's target(s) Build Settings so each target is indeed using the profile you want.

Not connecting to SQL Server over VPN

I have this issue a lot with Citrix Access Gateway. I usually get a timeout error. If you are able to connect to the database from a client on the network, but not from a remote client via VPN, you can forget most suggestions given here, because they all address server-side issues.

I am able to connect when I increase the timeout from the default (15 seconds) to 60 seconds, and for good measure, force the protocol to TCP/IP. These things can be done on the Options screen of the login dialog:

`

Call JavaScript function from C#

This may be helpful to you:

<script type="text/javascript">
    function Showalert() {
        alert('Profile not parsed!!');
        window.parent.parent.parent.location.reload();
    }
    function ImportingDone() {
        alert('Importing done successfull.!');
        window.parent.parent.parent.location.reload();
    }
</script>

if (SelectedRowCount == 0)
{
    ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "Showalert();", true);
}
else
{
    ScriptManager.RegisterStartupScript(this, GetType(), "importingdone", "ImportingDone();", true);
}

How would I get everything before a : in a string Python

Using index:

>>> string = "Username: How are you today?"
>>> string[:string.index(":")]
'Username'

The index will give you the position of : in string, then you can slice it.

If you want to use regex:

>>> import re
>>> re.match("(.*?):",string).group()
'Username'                       

match matches from the start of the string.

you can also use itertools.takewhile

>>> import itertools
>>> "".join(itertools.takewhile(lambda x: x!=":", string))
'Username'

Curl: Fix CURL (51) SSL error: no alternative certificate subject name matches

The common name in the certicate for api.evercam.io is for *.herokuapp.com and there are no alternative subject names in the certificate. This means, that the certificate for api.evercam.io does not match the hostname and therefore the certificate verification fails. Same as true for www.evercam.io, e.g. try https://www.evercam.io with a browser and you get the error message, that the name in the certificate does not match the hostname.

So it is a problem which needs to be fixed by evercam.io. If you don't care about security, man-in-the-middle attacks etc you might disable verification of the certificate (curl --insecure), but then you should ask yourself why you use https instead of http at all.

How do I prompt a user for confirmation in bash script?

Here's the function I use :

function ask_yes_or_no() {
    read -p "$1 ([y]es or [N]o): "
    case $(echo $REPLY | tr '[A-Z]' '[a-z]') in
        y|yes) echo "yes" ;;
        *)     echo "no" ;;
    esac
}

And an example using it:

if [[ "no" == $(ask_yes_or_no "Are you sure?") || \
      "no" == $(ask_yes_or_no "Are you *really* sure?") ]]
then
    echo "Skipped."
    exit 0
fi

# Do something really dangerous...
  • The output is always "yes" or "no"
  • It's "no" by default
  • Everything except "y" or "yes" returns "no", so it's pretty safe for a dangerous bash script
  • And it's case insensitive, "Y", "Yes", or "YES" work as "yes".

I hope you like it,
Cheers!

Calling onclick on a radiobutton list using javascript

I agree with @annakata that this question needs some more clarification, but here is a very, very basic example of how to setup an onclick event handler for the radio buttons:

<html>
 <head>
  <script type="text/javascript">
    window.onload = function() {

        var ex1 = document.getElementById('example1');
        var ex2 = document.getElementById('example2');
        var ex3 = document.getElementById('example3');

        ex1.onclick = handler;
        ex2.onclick = handler;
        ex3.onclick = handler;

    }

    function handler() {
        alert('clicked');
    }
  </script>
 </head>
 <body>
  <input type="radio" name="example1" id="example1" value="Example 1" />
  <label for="example1">Example 1</label>
  <input type="radio" name="example2" id="example2" value="Example 2" />
  <label for="example1">Example 2</label>
  <input type="radio" name="example3" id="example3" value="Example 3" />
  <label for="example1">Example 3</label>
 </body>
</html>

MySQL query String contains

Quite simple actually:

mysql_query("
SELECT *
FROM `table`
WHERE `column` LIKE '%{$needle}%'
");

The % is a wildcard for any characters set (none, one or many). Do note that this can get slow on very large datasets so if your database grows you'll need to use fulltext indices.

Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?

Operato union

select * from tableA where tableA.Field1 in (1,2,...999)
union
select * from tableA where tableA.Field1 in (1000,1001,...1999)
union
select * from tableA where tableA.Field1 in (2000,2001,...2999)

How do I correctly clone a JavaScript object?

Using Lodash:

var y = _.clone(x, true);

C++: Where to initialize variables in constructor

Option 1 allows you to initialize const members. This cannot be done with option 2 (as they are assigned to, not initialized).

Why must const members be intialized in the constructor initializer rather than in its body?

How to host a Node.Js application in shared hosting

Connect with SSH and follow these instructions to install Node on a shared hosting

In short you first install NVM, then you install the Node version of your choice with NVM.

wget -qO- https://cdn.rawgit.com/creationix/nvm/master/install.sh | bash

Your restart your shell (close and reopen your sessions). Then you

nvm install stable

to install the latest stable version for example. You can install any version of your choice. Check node --version for the node version you are currently using and nvm list to see what you've installed.

In bonus you can switch version very easily (nvm use <version>)

There's no need of PHP or whichever tricky workaround if you have SSH.

How to configure log4j to only keep log files for the last seven days?

I assume you're using RollingFileAppender? In which case, it has a property called MaxBackupIndex which you can set to limit the number of files. For example:

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=7
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

How to semantically add heading to a list

As Felipe Alsacreations has already said, the first option is fine.

If you want to ensure that nothing below the list is interpreted as belonging to the heading, that's exactly what the HTML5 sectioning content elements are for. So, for instance you could do

<h2>About Fruits</h2>
<section>
  <h3>Fruits I Like:</h3>
  <ul>
    <li>Apples</li>
    <li>Bananas</li>
    <li>Oranges</li>
  </ul>
</section>
<!-- anything here is part of the "About Fruits" section but does not 
     belong to the "Fruits I Like" section. -->

How to improve performance of ngRepeat over a huge dataset (angular.js)?

Another version @Steffomio

Instead of adding each item individually we can add items by chunks.

// chunks function from here: 
// http://stackoverflow.com/questions/8495687/split-array-into-chunks#11764168
var chunks = chunk(folders, 100);

//immediate display of our first set of items
$scope.items = chunks[0];

var delay = 100;
angular.forEach(chunks, function(value, index) {
    delay += 100;

    // skip the first chuck
    if( index > 0 ) {
        $timeout(function() {
            Array.prototype.push.apply($scope.items,value);
        }, delay);
    }       
});

xcode-select active developer directory error

I had to run this first

sudo xcode-select --reset

then

sudo xcode-select -switch /Library/Developer/CommandLineTools

and then it worked.

Difference between declaring variables before or in loop?

I think it depends on the compiler and is hard to give a general answer.

C# loop - break vs. continue

All have given a very good explanation. I am still posting my answer just to give an example if that can help.

// break statement
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        break; // It will force to come out from the loop
    }

    lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}

Here is the output:

0[Printed] 1[Printed] 2[Printed]

So 3[Printed] & 4[Printed] will not be displayed as there is break when i == 3

//continue statement
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        continue; // It will take the control to start point of loop
    }

    lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}

Here is the output:

0[Printed] 1[Printed] 2[Printed] 4[Printed]

So 3[Printed] will not be displayed as there is continue when i == 3

HTML5 textarea placeholder not appearing

use <textarea></textarea> instead of leaving a space between the opening and closing tags as <textarea> </textarea>

Can't install gems on OS X "El Capitan"

I ran across the same issue after installing El Capitan, I tried to install sass and compass into a symfony project, the following command returned the following error:

$ sudo gem install compass

ERROR: Error installing compass: ERROR: Failed to build gem native extension.

/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby extconf.rb 

checking for ffi.h... /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:434:in `try_do': The compiler failed to generate an executable file. (RuntimeError)

So I then tried to install sass with: $ sudo gem install sass

Got the same error message, after some googling I managed to install sass using the following command:

$ sudo gem install -n /usr/local/bin sass

The above worked for me with installing sass but did not work for installing compass. I read that someone somewhere had opened an instance of xcode then closed it again, then successfully ran the same command after which worked for them. I attempted to open xcode but was prompted with a message saying that the version of xcode installed was not compatible with El Capitan. So I then updated xcode from the app store, re-ran the following command which this time ran successfully:

$ sudo gem install -n /usr/local/bin compass

I was then able to run $ compass init

I now have all my gems working and can proceed to build some lovely sass stuff :)

Convert a dta file to csv without Stata software

I have not tried, but if you know Perl you can use the Parse-Stata-DtaReader module to convert the file for you.

The module has a command-line tool dta2csv, which can "convert Stata 8 and Stata 10 .dta files to csv"

illegal character in path

The string is surrounded by double quotes. Yes, that's not a valid character in a path.

You should probably tackle it at the source, but you can strip them out with:

        path = path.Replace("\"", "");

Does a valid XML file require an XML declaration?

It is only required if you aren't using the default values for version and encoding (which you are in that example).

Load a HTML page within another HTML page

You can use jQuery

<html> 
  <head> 
    <script src="jquery.js"></script> 
    <script> 
    $(function(){
      $("#divId").load("b.html"); 
    });
    </script> 
  </head> 

  <body> 
     <div id="divId" style="display:none;"></div>
  </body> 
</html>

on click event you can make it display block .

HTML encoding issues - "Â" character showing up instead of "&nbsp;"

Somewhere in that mess, the non-breaking spaces from the HTML template (the  s) are encoding as ISO-8859-1 so that they show up incorrectly as an "Â" character

That'd be encoding to UTF-8 then, not ISO-8859-1. The non-breaking space character is byte 0xA0 in ISO-8859-1; when encoded to UTF-8 it'd be 0xC2,0xA0, which, if you (incorrectly) view it as ISO-8859-1 comes out as " ". That includes a trailing nbsp which you might not be noticing; if that byte isn't there, then something else has mauled your document and we need to see further up to find out what.

What's the regexp, how does the templating work? There would seem to be a proper HTML parser involved somewhere if your &nbsp; strings are (correctly) being turned into U+00A0 NON-BREAKING SPACE characters. If so, you could just process your template natively in the DOM, and ask it to serialise using the ASCII encoding to keep non-ASCII characters as character references. That would also stop you having to do regex post-processing on the HTML itself, which is always a highly dodgy business.

Well anyway, for now you can add one of the following to your document's <head> and see if that makes it look right in the browser:

  • for HTML4: <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  • for HTML5: <meta charset="utf-8">

If you've done that, then any remaining problem is ActivePDF's fault.

How to append data to a json file?

import jsonlines

object1 = {
               "name": "name1",
               "url": "url1"
          }

object2 = {
               "name": "name2",
               "url": "url2"
          }   


# filename.jsonl is the name of the file
with jsonlines.open("filename.jsonl", "a") as writer:   # for writing
    writer.write(object1)
    writer.write(object2)

with jsonlines.open('filename.jsonl') as reader:      # for reading
    for obj in reader:
        print(obj)             

visit for more info https://jsonlines.readthedocs.io/en/latest/

Can I use git diff on untracked files?

For my interactive day-to-day gitting (where I diff the working tree against the HEAD all the time, and would like to have untracked files included in the diff), add -N/--intent-to-add is unusable, because it breaks git stash.

So here's my git diff replacement. It's not a particularly clean solution, but since I really only use it interactively, I'm OK with a hack:

d() {
    if test "$#" = 0; then
        (
            git diff --color
            git ls-files --others --exclude-standard |
                while read -r i; do git diff --color -- /dev/null "$i"; done
        ) | `git config --get core.pager`
    else
        git diff "$@"
    fi
}

Typing just d will include untracked files in the diff (which is what I care about in my workflow), and d args... will behave like regular git diff.

Notes:

  • We're using the fact here that git diff is really just individual diffs concatenated, so it's not possible to tell the d output from a "real diff" -- except for the fact that all untracked files get sorted last.
  • The only problem with this function is that the output is colorized even when redirected; but I can't be bothered to add logic for that.
  • I couldn't find any way to get untracked files included by just assembling a slick argument list for git diff. If someone figures out how to do this, or if maybe a feature gets added to git at some point in the future, please leave a note here!

Graphviz's executables are not found (Python 3.4)

when you add C:\Program Files (x86)\Graphviz2.38\bin to PATH, then you must close your IDE enviroment such as spyder and restart, you'll solve the "RuntimeError:make sure the Graphviz executables are on your systems' path"