Programs & Examples On #Visitor

The Visitor design pattern is a way of separating an algorithm from an object structure on which it operates. It is one of the Gang of Four's behavioral design patterns. When using this tag on implementation heavy questions - tag the code language the implementation is written in.

Error: the entity type requires a primary key

This exception message doesn't mean it requires a primary key to be defined in your database, it means it requires a primary key to be defined in your class.

Although you've attempted to do so:

private Guid _id;
[Key]
public Guid ID
{
    get { return _id; }
}

This has no effect, as Entity Framework ignores read-only properties. It has to: when it retrieves a Fruits record from the database, it constructs a Fruit object, and then calls the property setters for each mapped property. That's never going to work for read-only properties.

You need Entity Framework to be able to set the value of ID. This means the property needs to have a setter.

Drop all data in a pandas dataframe

Overwrite the dataframe with something like that

import pandas as pd

df = pd.DataFrame(None)

or if you want to keep columns in place

df = pd.DataFrame(columns=df.columns)

Is it safe to expose Firebase apiKey to the public?

Building on the answers of prufrofro and Frank van Puffelen here, I put together this setup that doesn't prevent scraping, but can make it slightly harder to use your API key.

Warning: To get your data, even with this method, one can for example simply open the JS console in Chrome and type:

firebase.database().ref("/get/all/the/data").once("value", function (data) {
    console.log(data.val());
});

Only the database security rules can protect your data.

Nevertheless, I restricted my production API key use to my domain name like this:

  1. https://console.developers.google.com/apis
  2. Select your Firebase project
  3. Credentials
  4. Under API keys, pick your Browser key. It should look like this: "Browser key (auto created by Google Service)"
  5. In "Accept requests from these HTTP referrers (web sites)", add the URL of your app (exemple: projectname.firebaseapp.com/* )

Now the app will only work on this specific domain name. So I created another API Key that will be private for localhost developement.

  1. Click Create credentials > API Key

By default, as mentioned by Emmanuel Campos, Firebase only whitelists localhost and your Firebase hosting domain.


In order to make sure I don't publish the wrong API key by mistake, I use one of the following methods to automatically use the more restricted one in production.

Setup for Create-React-App

In /env.development:

REACT_APP_API_KEY=###dev-key###

In /env.production:

REACT_APP_API_KEY=###public-key###

In /src/index.js

const firebaseConfig = {
  apiKey: process.env.REACT_APP_API_KEY,
  // ... 
};

android : Error converting byte to dex

In my case, using :

enter image description here

I had the issue during transformClassesWithDexFor when the maximum heap size for the Gradle daemon is superior to 4Go. By changing my ~/gradle.properties with org.gradle.jvmargs=-Xmx2048m (meaning I reduce the heap size to 2Go instead of 4Go) the dex then runs in a separate process and I no longer have the issue.

14:52:26.412 [WARN] [org.gradle.api.Project]

Running dex as a separate process.

To run dex in process, the Gradle daemon needs a larger heap.

It currently has 2048 MB.

For faster builds, increase the maximum heap size for the Gradle daemon to at least 4608 MB (based on the dexOptions.javaMaxHeapSize = 4g).

To do this set org.gradle.jvmargs=-Xmx4608M in the project gradle.properties.

How to get client IP address in Laravel 5+

If you call this function then you easily get the client's IP address. I have already used this in my existing project:

public function getUserIpAddr(){
       $ipaddress = '';
       if (isset($_SERVER['HTTP_CLIENT_IP']))
           $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
       else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
           $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
       else if(isset($_SERVER['HTTP_X_FORWARDED']))
           $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
       else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
           $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
       else if(isset($_SERVER['HTTP_FORWARDED']))
           $ipaddress = $_SERVER['HTTP_FORWARDED'];
       else if(isset($_SERVER['REMOTE_ADDR']))
           $ipaddress = $_SERVER['REMOTE_ADDR'];
       else
           $ipaddress = 'UNKNOWN';    
       return $ipaddress;
    }

Command failed due to signal: Segmentation fault: 11

In my case, IGListKit refactored their class named IGListSectionController to ListSectionController , while I already had a class named ListSectionController. I used find and replace and didn't know I had a class with the same name.

class ListSectionController : ListSectionController

I read the error message in full and concluded that this error can also happen when you have Circular dependencies. This wasn't mentioned in any of the comments, I hope this helps.

ValueError: max() arg is an empty sequence

When the length of v will be zero, it'll give you the value error.

You should check the length or you should check the list first whether it is none or not.

if list:
    k.index(max(list))

or

len(list)== 0

Android Studio Google JAR file causing GC overhead limit exceeded error

Android Studio 3.5.3

Find the Memory Settings (Cmd + Shift + A on Mac or click on Help and start typing "Memory Settings") under Preferences/ Settings and increase the IDE Heap Size and/ or the Daemon Heap Size to your satisfaction enter image description here

How to vertically center a container in Bootstrap?

for bootstrap4 vertical center of few items

d-flex for flex rules

flex-column for vertical direction on items

justify-content-center for centering

style='height: 300px;' must have for set points where center be calc or use h-100 class

then for horizontal center div d-flex justify-content-center and some container

so we have hierarhy of 3 tag: div-column -> div-row -> div-container

     <div class="d-flex flex-column justify-content-center bg-secondary" 
        style="height: 300px;">
        <div class="d-flex justify-content-center">
           <div class=bg-primary>Flex item</div>
        </div>
        <div class="d-flex justify-content-center">
           <div class=bg-primary>Flex item</div>
        </div>
      </div> 

Laravel Eloquent get results grouped by days

You can filter the results based on formatted date using mysql (See here for Mysql/Mariadb help) and use something like this in laravel-5.4:

Model::selectRaw("COUNT(*) views, DATE_FORMAT(created_at, '%Y %m %e') date")
    ->groupBy('date')
    ->get();

Can You Get A Users Local LAN IP Address Via JavaScript?

The WebRTC API can be used to retrieve the client's local IP.

However the browser may not support it, or the client may have disabled it for security reasons. In any case, one should not rely on this "hack" on the long term as it is likely to be patched in the future (see Cullen Fluffy Jennings's answer).

The ECMAScript 6 code below demonstrates how to do that.

/* ES6 */
const findLocalIp = (logInfo = true) => new Promise( (resolve, reject) => {
    window.RTCPeerConnection = window.RTCPeerConnection 
                            || window.mozRTCPeerConnection 
                            || window.webkitRTCPeerConnection;

    if ( typeof window.RTCPeerConnection == 'undefined' )
        return reject('WebRTC not supported by browser');

    let pc = new RTCPeerConnection();
    let ips = [];

    pc.createDataChannel("");
    pc.createOffer()
     .then(offer => pc.setLocalDescription(offer))
     .catch(err => reject(err));
    pc.onicecandidate = event => {
        if ( !event || !event.candidate ) {
            // All ICE candidates have been sent.
            if ( ips.length == 0 )
                return reject('WebRTC disabled or restricted by browser');

            return resolve(ips);
        }

        let parts = event.candidate.candidate.split(' ');
        let [base,componentId,protocol,priority,ip,port,,type,...attr] = parts;
        let component = ['rtp', 'rtpc'];

        if ( ! ips.some(e => e == ip) )
            ips.push(ip);

        if ( ! logInfo )
            return;

        console.log(" candidate: " + base.split(':')[1]);
        console.log(" component: " + component[componentId - 1]);
        console.log("  protocol: " + protocol);
        console.log("  priority: " + priority);
        console.log("        ip: " + ip);
        console.log("      port: " + port);
        console.log("      type: " + type);

        if ( attr.length ) {
            console.log("attributes: ");
            for(let i = 0; i < attr.length; i += 2)
                console.log("> " + attr[i] + ": " + attr[i+1]);
        }

        console.log();
    };
} );

Notice I write return resolve(..) or return reject(..) as a shortcut. Both of those functions do not return anything.

Then you may have something this :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Local IP</title>
</head>
<body>
    <h1>My local IP is</h1>
    <p id="ip">Loading..</p>
    <script src="ip.js"></script>
    <script>
    let p = document.getElementById('ip');
    findLocalIp().then(
        ips => {
            let s = '';
            ips.forEach( ip => s += ip + '<br>' );
            p.innerHTML = s;
        },
        err => p.innerHTML = err
    );
    </script>
</body>
</html>

send checkbox value in PHP form

replace:

$name = $_POST['name']; 
$email_address = $_POST['email']; 
$message = $_POST['tel']; 

with:

$name = $_POST['name']; 
$email_address = $_POST['email']; 
$message = $_POST['tel'];
if (isset($_POST['newsletter'])) {
  $checkBoxValue = "yes";
} else {
  $checkBoxValue = "no";
}

then replace this line of code:

$email_body = "You have received a new message. ".
    " Here are the details:\n Name: $name \n Email: $email_address \n Tel \n $message\n Newsletter \n $newsletter"

with:

$email_body = "You have received a new message. ".
    " Here are the details:\n Name: $name \n Email: $email_address \n Tel \n $message\n Newsletter \n $newsletter";

Number of visitors on a specific page

As Blexy already answered, go to "Behavior > Site Content > All Pages".

Just pay attention that "Behavior" appears two times in the left sidebar and we need to click on the second option:

                                                     sidebar

Best practice multi language website

Just a sub answer: Absolutely use translated urls with a language identifier in front of them: http://www.domain.com/nl/over-ons
Hybride solutions tend to get complicated, so I would just stick with it. Why? Cause the url is essential for SEO.

About the db translation: Is the number of languages more or less fixed? Or rather unpredictable and dynamic? If it is fixed, I would just add new columns, otherwise go with multiple tables.

But generally, why not use Drupal? I know everybody wants to build their own CMS cause it's faster, leaner, etc. etc. But that is just really a bad idea!

Java escape JSON String?

Consider Moshi's JsonWriter class (source). It has a wonderful API and it reduces copying to a minimum, everything is nicely streamed to the OutputStream.

OutputStream os = ...;
JsonWriter json = new JsonWriter(Okio.sink(os));
json
  .beginObject()
  .name("id").value(userID)
  .name("type").value(methodn)
  ...
  .endObject();

Insert PHP code In WordPress Page and Post

You can't use PHP in the WordPress back-end Page editor. Maybe with a plugin you can, but not out of the box.

The easiest solution for this is creating a shortcode. Then you can use something like this

function input_func( $atts ) {
    extract( shortcode_atts( array(
        'type' => 'text',
        'name' => '',
    ), $atts ) );

    return '<input name="' . $name . '" id="' . $name . '" value="' . (isset($_GET\['from'\]) && $_GET\['from'\] ? $_GET\['from'\] : '') . '" type="' . $type . '" />';
}
add_shortcode( 'input', 'input_func' );

See the Shortcode_API.

How do I count unique visitors to my site?

$user_ip=$_SERVER['REMOTE_ADDR'];

$check_ip = mysql_query("select userip from pageview where page='yourpage'  and userip='$user_ip'");
if(mysql_num_rows($check_ip)>=1)
{

}
else
{
  $insertview = mysql_query("insert into pageview values('','yourpage','$user_ip')");

  $updateview = mysql_query("update totalview set totalvisit = totalvisit+1 where page='yourpage' ");
}

code from talkerscode official tutorial if you have any problem http://talkerscode.com/webtricks/create-a-simple-pageviews-counter-using-php-and-mysql.php

SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed

To get it working, I had to go to myaccount.google.com -> "connected apps & sites", and turn "Allow less secure apps" to "ON" (near the bottom of the page).

Twitter - share button, but with image

I used this code to solve this problem.

<a href="https://twitter.com/intent/tweet?url=myUrl&text=myTitle" target="_blank"><img src="path_to_my_image"/></a>

You can check the tweet-button documentation here tweet-button

PHP: How to get referrer URL?

$_SERVER['HTTP_REFERER'] will give you the referrer page's URL if there exists any. If users use a bookmark or directly visit your site by manually typing in the URL, http_referer will be empty. Also if the users are posting to your page programatically (CURL) then they're not obliged to set the http_referer as well. You're missing all _, is that a typo?

File to import not found or unreadable: compass

I'm seeing this issue using Rails 4.0.2 and compass-rails 1.1.3

I got past this error by moving gem 'compass-rails' outside of the :assets group in my Gemfile

It looks something like this:

# stuff
gem 'compass-rails', '~> 1.1.3'
group :assets do
  # more stuff
end

How to implement a secure REST API with node.js

There are many questions about REST auth patterns here on SO. These are the most relevant for your question:

Basically you need to choose between using API keys (least secure as the key may be discovered by an unauthorized user), an app key and token combo (medium), or a full OAuth implementation (most secure).

TypeError: module.__init__() takes at most 2 arguments (3 given)

You may also do the following in Python 3.6.1

from Object import Object as Parent

and your class definition to:

class Visitor(Parent):

How to get Real IP from Visitor?

Proxies may send a HTTP_X_FORWARDED_FOR header but even that is optional.

Also keep in mind that visitors may share IP addresses; University networks, large companies and third-world/low-budget ISPs tend to share IPs over many users.

Getting visitors country from their IP

The User Country API has exactly what you need. Here is a sample code using file_get_contents() as you originally do:

$result = json_decode(file_get_contents('http://usercountry.com/v1.0/json/'.$cip), true);
$result['country']['name']; // this contains what you need

Fatal error: Out of memory, but I do have plenty of memory (PHP)

Please note that the error is Out of memory and is not Allowed memory size [..] exhausted.

So the memory leak is elsewhere on the system. It's possible that mysql server use a lot of system memory after this heavy query, leaving apache/php without it physical and swap.

This should explain the error always on the same line (and/or in the same script).

How to deny access to a file in .htaccess

I don't believe the currently accepted answer is correct. For example, I have the following .htaccess file in the root of a virtual server (apache 2.4):

<Files "reminder.php">
require all denied
require host localhost
require ip 127.0.0.1
require ip xxx.yyy.zzz.aaa
</Files>

This prevents external access to reminder.php which is in a subdirectory. I have a similar .htaccess file on my Apache 2.2 server with the same effect:

<Files "reminder.php">
        Order Deny,Allow
        Deny from all
        Allow from localhost
        Allow from 127.0.0.1
     Allow from xxx.yyy.zzz.aaa
</Files>

I don't know for sure but I suspect it's the attempt to define the subdirectory specifically in the .htaccess file, viz <Files ./inscription/log.txt> which is causing it to fail. It would be simpler to put the .htaccess file in the same directory as log.txt i.e. in the inscription directory and it will work there.

Radio button validation in javascript

document.forms[ 'forms1' ].onsubmit = function() {
    return [].some.call( this.elements, function( el ) {
        return el.type === 'radio' ? el.checked : false
    } )
}

Just something out of my head. Not sure the code is working.

Getting value of HTML text input

See my jsFiddle here: http://jsfiddle.net/fuDBL/

Whenever you change the email field, the link is updated automatically. This requires a small amount of jQuery. So now your form will work as needed, but your link will be updated dynamically so that when someone clicks on it, it contains what they entered in the email field. You should validate the input on the receiving page.

$('input[name="email"]').change(function(){
  $('#regLink').attr('href')+$('input[name="email"]').val();
});

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

Uninstallation :

sudo /Library/PostgreSQL/9.6/uninstall-postgresql.app/Contents/MacOS/installbuilder.sh

Removing the data file :

sudo rm -rf /Library/PostgreSQL

Removing the configs :

sudo rm /etc/postgres-reg.ini

And thats it.

Importing a function from a class in another file?

If, like me, you want to make a function pack or something that people can download then it's very simple. Just write your function in a python file and save it as the name you want IN YOUR PYTHON DIRECTORY. Now, in your script where you want to use this, you type:

from FILE NAME import FUNCTION NAME

Note - the parts in capital letters are where you type the file name and function name.

Now you just use your function however it was meant to be.

Example:

FUNCTION SCRIPT - saved at C:\Python27 as function_choose.py

def choose(a):
  from random import randint
  b = randint(0, len(a) - 1)
  c = a[b]
  return(c)

SCRIPT USING FUNCTION - saved wherever

from function_choose import choose
list_a = ["dog", "cat", "chicken"]
print(choose(list_a))

OUTPUT WILL BE DOG, CAT, OR CHICKEN

Hoped this helped, now you can create function packs for download!

--------------------------------This is for Python 2.7-------------------------------------

How to hide html source & disable right click and text copy?

Hiding HTML source isn't really possible. Disabling right-click only frustrates users who wish to do something constructive with your content (copy/paste content or forms, or print, for example).

If you're running a server-side scripting language you could obfuscate or minify the HTML, CSS and Javascript. This will make it harder for someone to copy your code or see how you've achieved certain effects.

Fatal error: Call to undefined function mb_strlen()

On Centos, RedHat, Fedora and other yum-my systems it is much simpler than the PHP manual suggests:

yum install php-mbstring
service httpd restart

Google Gson - deserialize list<class> object? (generic type)

For Kotlin simply:

import java.lang.reflect.Type
import com.google.gson.reflect.TypeToken
...
val type = object : TypeToken<List<T>>() {}.type

or, here is a useful function:

fun <T> typeOfList(): Type {
    return object : TypeToken<List<T>>() {}.type
}

Then, to use:

val type = typeOfList<YourMagicObject>()

Back to previous page with header( "Location: " ); in PHP

Its so simple just use this

header("location:javascript://history.go(-1)");

Its working fine for me

SyntaxError: Unexpected Identifier in Chrome's Javascript console

Write it as below

<script language="javascript">
var visitorName = 'Chuck';
var myOldString = 'Hello username. I hope you enjoy your stay username.';

var myNewString = myOldString.replace('username', visitorName);

document.write('Old String = ' + myOldString);
document.write('<br/>New string = ' + myNewString);
</script>

http://jsfiddle.net/h6xc4/23/

How to get the previous url using PHP

$_SERVER['HTTP_REFERER'] is the answer

IIS URL Rewrite and Web.config

Just tried this rule, and it worked with GoDaddy hosting since they've already have the Microsoft URL Rewriting module installed for every IIS 7 account.

<rewrite>
  <rules>
    <rule name="enquiry" stopProcessing="true">
      <match url="^enquiry$" />
      <action type="Rewrite" url="/Enquiry.aspx" />
    </rule>
  </rules>
</rewrite>

$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP

Look no more for IP addresses not being set in the expected header. Just do the following to inspect the whole server variables and figure out which one is suitable for your case:

print_r($_SERVER);

Get IP address of visitors using Flask for Python

If you use Nginx behind other balancer, for instance AWS Application Balancer, HTTP_X_FORWARDED_FOR returns list of addresses. It can be fixed like that:

if 'X-Forwarded-For' in request.headers:
    proxy_data = request.headers['X-Forwarded-For']
    ip_list = proxy_data.split(',')
    user_ip = ip_list[0]  # first address in list is User IP
else:
    user_ip = request.remote_addr  # For local development

Clearing Magento Log Data

Cleaning the Magento Logs using SSH :

login to shell(SSH) panel and go with root/shell folder.

execute the below command inside the shell folder

php -f log.php clean

enter this command to view the log data's size

php -f log.php status

This method will help you to clean the log data's very easy way.

How to merge two PDF files into one in Java?

Why not use the PDFMergerUtility of pdfbox?

PDFMergerUtility ut = new PDFMergerUtility();
ut.addSource(...);
ut.addSource(...);
ut.addSource(...);
ut.setDestinationFileName(...);
ut.mergeDocuments();

How to get visitor's location (i.e. country) using geolocation?

For developers looking for a full-featured geolocation utility, you can have a look at geolocator.js (I'm the author).

Example below will first try HTML5 Geolocation API to obtain the exact coordinates. If fails or rejected, it will fallback to Geo-IP look-up. Once it gets the coordinates, it will reverse-geocode the coordinates into an address.

var options = {
    enableHighAccuracy: true,
    timeout: 6000,
    maximumAge: 0,
    desiredAccuracy: 30,
    fallbackToIP: true, // if HTML5 geolocation fails or rejected
    addressLookup: true, // get detailed address information
    timezone: true, 
    map: "my-map" // this will even create a map for you
};

geolocator.locate(options, function (err, location) {
    console.log(err || location);
});

It supports geo-location (via HTML5 or IP lookups), geocoding, address look-ups (reverse geocoding), distance & durations, timezone information and more...

How to avoid mysql 'Deadlock found when trying to get lock; try restarting transaction'

For Java programmers using Spring, I've avoided this problem using an AOP aspect that automatically retries transactions that run into transient deadlocks.

See @RetryTransaction Javadoc for more info.

Making an svg image object clickable with onclick, avoiding absolute positioning

I wrapped the 'svg' tag in 'a' tag and put the onClick event in the 'a' tag

Django Cookies, how can I set them?

You could manually set the cookie, but depending on your use case (and if you might want to add more types of persistent/session data in future) it might make more sense to use Django's sessions feature. This will let you get and set variables tied internally to the user's session cookie. Cool thing about this is that if you want to store a lot of data tied to a user's session, storing it all in cookies will add a lot of weight to HTTP requests and responses. With sessions the session cookie is all that is sent back and forth (though there is the overhead on Django's end of storing the session data to keep in mind).

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

For easier use CI have updated this so you can just use

$this->load->helper('language');

and to translate text

lang('language line');

and if you want to warp it inside label then use optional parameter

lang('language line', 'element id');

This will output

// becomes <label for="form_item_id">language_key</label>

For good reading http://ellislab.com/codeigniter/user-guide/helpers/language_helper.html

How to get the browser viewport dimensions?

A solution that would conform to W3C standards would be to create a transparent div (for example dynamically with JavaScript), set its width and height to 100vw/100vh (Viewport units) and then get its offsetWidth and offsetHeight. After that, the element can be removed again. This will not work in older browsers because the viewport units are relatively new, but if you don't care about them but about (soon-to-be) standards instead, you could definitely go this way:

var objNode = document.createElement("div");
objNode.style.width  = "100vw";
objNode.style.height = "100vh";
document.body.appendChild(objNode);
var intViewportWidth  = objNode.offsetWidth;
var intViewportHeight = objNode.offsetHeight;
document.body.removeChild(objNode);

Of course, you could also set objNode.style.position = "fixed" and then use 100% as width/height - this should have the same effect and improve compatibility to some extent. Also, setting position to fixed might be a good idea in general, because otherwise the div will be invisible but consume some space, which will lead to scrollbars appearing etc.

How to make the window full screen with Javascript (stretching all over the screen)

Can you Try:

_x000D_
_x000D_
<script type="text/javascript">_x000D_
    function go_full_screen(){_x000D_
      var elem = document.documentElement;_x000D_
      if (elem.requestFullscreen) {_x000D_
        elem.requestFullscreen();_x000D_
      } else if (elem.msRequestFullscreen) {_x000D_
        elem.msRequestFullscreen();_x000D_
      } else if (elem.mozRequestFullScreen) {_x000D_
        elem.mozRequestFullScreen();_x000D_
      } else if (elem.webkitRequestFullscreen) {_x000D_
        elem.webkitRequestFullscreen();_x000D_
      }_x000D_
    }_x000D_
</script>_x000D_
_x000D_
<a href="#" onClick="go_full_screen();">Full Screen / Compress Screen</a>
_x000D_
_x000D_
_x000D_

Getting the client's time zone (and offset) in JavaScript

you can simply try this. it will return you current machine time

var _d = new Date(), t = 0, d = new Date(t*1000 + _d.getTime())

Simple PHP form: Attachment to email (code golf)

I haven't tested the email part of this (my test box does not send email) but I think it will work.

<?php
if ($_POST) {
$s = md5(rand());
mail('[email protected]', 'attachment', "--$s

{$_POST['m']}
--$s
Content-Type: application/octet-stream; name=\"f\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment

".chunk_split(base64_encode(join(file($_FILES['f']['tmp_name']))))."
--$s--", "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"$s\"");
exit;
}
?>
<form method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<textarea name="m"></textarea><br>
<input type="file" name="f"/><br>
<input type="submit">
</form>

Getting the location from an IP address

I wrote a bot using an API from ipapi.co, here's how you can get location for an IP address (e.g. 1.2.3.4) in php :

Set header :

$opts = array('http'=>array('method'=>"GET", 'header'=>"User-Agent: mybot.v0.7.1"));
$context = stream_context_create($opts);

Get JSON response

echo file_get_contents('https://ipapi.co/1.2.3.4/json/', false, $context);

of get a specific field (country, timezone etc.)

echo file_get_contents('https://ipapi.co/1.2.3.4/country/', false, $context);

When should I use the Visitor Design Pattern?

Visitor

Visitor allows one to add new virtual functions to a family of classes without modifying the classes themselves; instead, one creates a visitor class that implements all of the appropriate specializations of the virtual function

Visitor structure:

enter image description here

Use Visitor pattern if:

  1. Similar operations have to be performed on objects of different types grouped in a structure
  2. You need to execute many distinct and unrelated operations. It separates Operation from objects Structure
  3. New operations have to be added without change in object structure
  4. Gather related operations into a single class rather than force you to change or derive classes
  5. Add functions to class libraries for which you either do not have the source or cannot change the source

Even though Visitor pattern provides flexibility to add new operation without changing the existing code in Object, this flexibility has come with a drawback.

If a new Visitable object has been added, it requires code changes in Visitor & ConcreteVisitor classes. There is a workaround to address this issue : Use reflection, which will have impact on performance.

Code snippet:

import java.util.HashMap;

interface Visitable{
    void accept(Visitor visitor);
}

interface Visitor{
    void logGameStatistics(Chess chess);
    void logGameStatistics(Checkers checkers);
    void logGameStatistics(Ludo ludo);    
}
class GameVisitor implements Visitor{
    public void logGameStatistics(Chess chess){
        System.out.println("Logging Chess statistics: Game Completion duration, number of moves etc..");    
    }
    public void logGameStatistics(Checkers checkers){
        System.out.println("Logging Checkers statistics: Game Completion duration, remaining coins of loser");    
    }
    public void logGameStatistics(Ludo ludo){
        System.out.println("Logging Ludo statistics: Game Completion duration, remaining coins of loser");    
    }
}

abstract class Game{
    // Add game related attributes and methods here
    public Game(){

    }
    public void getNextMove(){};
    public void makeNextMove(){}
    public abstract String getName();
}
class Chess extends Game implements Visitable{
    public String getName(){
        return Chess.class.getName();
    }
    public void accept(Visitor visitor){
        visitor.logGameStatistics(this);
    }
}
class Checkers extends Game implements Visitable{
    public String getName(){
        return Checkers.class.getName();
    }
    public void accept(Visitor visitor){
        visitor.logGameStatistics(this);
    }
}
class Ludo extends Game implements Visitable{
    public String getName(){
        return Ludo.class.getName();
    }
    public void accept(Visitor visitor){
        visitor.logGameStatistics(this);
    }
}

public class VisitorPattern{
    public static void main(String args[]){
        Visitor visitor = new GameVisitor();
        Visitable games[] = { new Chess(),new Checkers(), new Ludo()};
        for (Visitable v : games){
            v.accept(visitor);
        }
    }
}

Explanation:

  1. Visitable (Element) is an interface and this interface method has to be added to a set of classes.
  2. Visitor is an interface, which contains methods to perform an operation on Visitable elements.
  3. GameVisitor is a class, which implements Visitor interface ( ConcreteVisitor).
  4. Each Visitable element accept Visitor and invoke a relevant method of Visitor interface.
  5. You can treat Game as Element and concrete games like Chess,Checkers and Ludo as ConcreteElements.

In above example, Chess, Checkers and Ludo are three different games ( and Visitable classes). On one fine day, I have encountered with a scenario to log statistics of each game. So without modifying individual class to implement statistics functionality, you can centralise that responsibility in GameVisitor class, which does the trick for you without modifying the structure of each game.

output:

Logging Chess statistics: Game Completion duration, number of moves etc..
Logging Checkers statistics: Game Completion duration, remaining coins of loser
Logging Ludo statistics: Game Completion duration, remaining coins of loser

Refer to

oodesign article

sourcemaking article

for more details

Decorator

pattern allows behaviour to be added to an individual object, either statically or dynamically, without affecting the behaviour of other objects from the same class

Related posts:

Decorator Pattern for IO

When to Use the Decorator Pattern?

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

In my MacBook i have solvet this error only when reinstall the new version of eclipse EE and remove local servers like xamp mysql or mamp but use only one of them ...

How to check if a file contains a specific string using Bash

Try this:

if [[ $(grep "SomeString" $File) ]] ; then
   echo "Found"
else
   echo "Not Found"
fi

How do I clone a github project to run locally?

git clone git://github.com/ryanb/railscasts-episodes.git

Difference between $.ajax() and $.get() and $.load()

Very basic but

  • $.load(): Load a piece of html into a container DOM.
  • $.get(): Use this if you want to make a GET call and play extensively with the response.
  • $.post(): Use this if you want to make a POST call and don’t want to load the response to some container DOM.
  • $.ajax(): Use this if you need to do something when XHR fails, or you need to specify ajax options (e.g. cache: true) on the fly.

undefined reference to WinMain@16 (codeblocks)

I was interested in setting up graphics for Code Blocks when I ran into a this error: (took me 2 hrs to solve it)

I guess you need to have a bit of luck with this. In my case i just changed the order of contents in Settings menu->Compiler and Debugger->Global compiler settings->Linker settings->Other Linker Options: The working sequence is: -lmingw32 -lSDL -lSDLmain

How do I get which JRadioButton is selected from a ButtonGroup

You could use getSelectedObjects() of ItemSelectable (superinterface of ButtonModel) which returns the list of selected items. In case of a radio button group it can only be one or none at all.

Save Screen (program) output to a file

The following command works for Screen version 4.06.02:

screen -L -Logfile Log_file_name_of_your_choice command_to_be_executed

From the man page of Screen:

-Logfile file : By default logfile name is "screenlog.0".
                You can set new logfile name with the "-Logfile" option.

You can check the existing version of Screen using screen -version. You can download and install the latest Screen version from https://www.gnu.org/software/screen/.

Comparing two java.util.Dates to see if they are in the same day

Joda-Time

As for adding a dependency, I'm afraid the java.util.Date & .Calendar really are so bad that the first thing I do to any new project is add the Joda-Time library. In Java 8 you can use the new java.time package, inspired by Joda-Time.

The core of Joda-Time is the DateTime class. Unlike java.util.Date, it understands its assigned time zone (DateTimeZone). When converting from j.u.Date, assign a zone.

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTimeQuébec = new DateTime( date , zone );

LocalDate

One way to verify if two date-times land on the same date is to convert to LocalDate objects.

That conversion depends on the assigned time zone. To compare LocalDate objects, they must have been converted with the same zone.

Here is a little utility method.

static public Boolean sameDate ( DateTime dt1 , DateTime dt2 )
{
    LocalDate ld1 = new LocalDate( dt1 );
    // LocalDate determination depends on the time zone.
    // So be sure the date-time values are adjusted to the same time zone.
    LocalDate ld2 = new LocalDate( dt2.withZone( dt1.getZone() ) );
    Boolean match = ld1.equals( ld2 );
    return match;
}

Better would be another argument, specifying the time zone rather than assuming the first DateTime object’s time zone should be used.

static public Boolean sameDate ( DateTimeZone zone , DateTime dt1 , DateTime dt2 )
{
    LocalDate ld1 = new LocalDate( dt1.withZone( zone ) );
    // LocalDate determination depends on the time zone.
    // So be sure the date-time values are adjusted to the same time zone.
    LocalDate ld2 = new LocalDate( dt2.withZone( zone ) );
    return ld1.equals( ld2 );
}

String Representation

Another approach is to create a string representation of the date portion of each date-time, then compare strings.

Again, the assigned time zone is crucial.

DateTimeFormatter formatter = ISODateTimeFormat.date();  // Static method.
String s1 = formatter.print( dateTime1 );
String s2 = formatter.print( dateTime2.withZone( dt1.getZone() )  );
Boolean match = s1.equals( s2 );
return match;

Span of Time

The generalized solution is to define a span of time, then ask if the span contains your target. This example code is in Joda-Time 2.4. Note that the "midnight"-related classes are deprecated. Instead use the withTimeAtStartOfDay method. Joda-Time offers three classes to represent a span of time in various ways: Interval, Period, and Duration.

Using the "Half-Open" approach where the beginning of the span is inclusive and the ending exclusive.

The time zone of the target can be different than the time zone of the interval.

DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime target = new DateTime( 2012, 3, 4, 5, 6, 7, timeZone );
DateTime start = DateTime.now( timeZone ).withTimeAtStartOfDay();
DateTime stop = start.plusDays( 1 ).withTimeAtStartOfDay();
Interval interval = new Interval( start, stop );
boolean containsTarget = interval.contains( target );

java.time

Java 8 and later comes with the java.time framework. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. See Tutorial.

The makers of Joda-Time have instructed us all to move to java.time as soon as is convenient. In the meantime Joda-Time continues as an actively maintained project. But expect future work to occur only in java.time and ThreeTen-Extra rather than Joda-Time.

To summarize java.time in a nutshell… An Instant is a moment on the timeline in UTC. Apply a time zone (ZoneId) to get a ZonedDateTime object. To move off the timeline, to get the vague indefinite idea of a date-time, use the "local" classes: LocalDateTime, LocalDate, LocalTime.

The logic discussed in the Joda-Time section of this Answer applies to java.time.

The old java.util.Date class has a new toInstant method for conversion to java.time.

Instant instant = yourJavaUtilDate.toInstant(); // Convert into java.time type.

Determining a date requires a time zone.

ZoneId zoneId = ZoneId.of( "America/Montreal" );

We apply that time zone object to the Instant to obtain a ZonedDateTime. From that we extract a date-only value (a LocalDate) as our goal is to compare dates (not hours, minutes, etc.).

ZonedDateTime zdt1 = ZonedDateTime.ofInstant( instant , zoneId );
LocalDate localDate1 = LocalDate.from( zdt1 );

Do the same to the second java.util.Date object we need for comparison. I’ll just use the current moment instead.

ZonedDateTime zdt2 = ZonedDateTime.now( zoneId );
LocalDate localDate2 = LocalDate.from( zdt2 );

Use the special isEqual method to test for the same date value.

Boolean sameDate = localDate1.isEqual( localDate2 );

Pandas groupby: How to get a union of strings

In [4]: df = read_csv(StringIO(data),sep='\s+')

In [5]: df
Out[5]: 
   A         B       C
0  1  0.749065    This
1  2  0.301084      is
2  3  0.463468       a
3  4  0.643961  random
4  1  0.866521  string
5  2  0.120737       !

In [6]: df.dtypes
Out[6]: 
A      int64
B    float64
C     object
dtype: object

When you apply your own function, there is not automatic exclusions of non-numeric columns. This is slower, though, than the application of .sum() to the groupby

In [8]: df.groupby('A').apply(lambda x: x.sum())
Out[8]: 
   A         B           C
A                         
1  2  1.615586  Thisstring
2  4  0.421821         is!
3  3  0.463468           a
4  4  0.643961      random

sum by default concatenates

In [9]: df.groupby('A')['C'].apply(lambda x: x.sum())
Out[9]: 
A
1    Thisstring
2           is!
3             a
4        random
dtype: object

You can do pretty much what you want

In [11]: df.groupby('A')['C'].apply(lambda x: "{%s}" % ', '.join(x))
Out[11]: 
A
1    {This, string}
2           {is, !}
3               {a}
4          {random}
dtype: object

Doing this on a whole frame, one group at a time. Key is to return a Series

def f(x):
     return Series(dict(A = x['A'].sum(), 
                        B = x['B'].sum(), 
                        C = "{%s}" % ', '.join(x['C'])))

In [14]: df.groupby('A').apply(f)
Out[14]: 
   A         B               C
A                             
1  2  1.615586  {This, string}
2  4  0.421821         {is, !}
3  3  0.463468             {a}
4  4  0.643961        {random}

How to center HTML5 Videos?

If you have a width in percent, you can do this :

_x000D_
_x000D_
video {_x000D_
  width: 50% !important;_x000D_
  height: auto !important;_x000D_
  margin: 0 auto;_x000D_
  display: block;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
_x000D_
  <video controls>_x000D_
    <source src="http://www.nasa.gov/downloadable/videos/sciencecasts-_total_eclipse_of_the_moon.mp4" type="video/mp4">_x000D_
      Your browser does not support HTML5 video._x000D_
  </video>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Error while installing json gem 'mkmf.rb can't find header files for ruby'

Xcode 11 / macOS Catalina

On Xcode 11 / macOS Catalina, the header files are no longer in the old location and the old /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg file is no longer available.

Instead, the headers are now installed to the /usr/include directory of the current SDK path:

/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include

Most of this directory can be found by using the output of xcrun --show-sdk-path. And if you add this path to the CPATH environment variable, then build scripts (including those called via bundle) will generally be able to find it.

I resolved this by setting my CPATH in my .zshrc file:

export CPATH="$(xcrun --show-sdk-path)/usr/include"

After opening a new shell (or running source .zshrc), I no longer receive the error message mkmf.rb can't find header files for ruby at /usr/lib/ruby/ruby.h and the rubygems install properly.

Note on Building to Non-macOS Platforms

If you are building to non-macOS platforms, such as iOS/tvOS/watchOS, this change will attempt to include the macOS SDK in those platforms, causing build errors. To resolve, either don't set CPATH environment variable on login, or temporarily set it to blank when running xcodebuild like so:

CPATH="" xcodebuild --some-args

How is Perl's @INC constructed? (aka What are all the ways of affecting where Perl modules are searched for?)

We will look at how the contents of this array are constructed and can be manipulated to affect where the Perl interpreter will find the module files.

  1. Default @INC

    Perl interpreter is compiled with a specific @INC default value. To find out this value, run env -i perl -V command (env -i ignores the PERL5LIB environmental variable - see #2) and in the output you will see something like this:

    $ env -i perl -V
    ...
    @INC:
     /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/site_perl/5.18.0
     /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/5.18.0
     .
    

Note . at the end; this is the current directory (which is not necessarily the same as the script's directory). It is missing in Perl 5.26+, and when Perl runs with -T (taint checks enabled).

To change the default path when configuring Perl binary compilation, set the configuration option otherlibdirs:

Configure -Dotherlibdirs=/usr/lib/perl5/site_perl/5.16.3

  1. Environmental variable PERL5LIB (or PERLLIB)

    Perl pre-pends @INC with a list of directories (colon-separated) contained in PERL5LIB (if it is not defined, PERLLIB is used) environment variable of your shell. To see the contents of @INC after PERL5LIB and PERLLIB environment variables have taken effect, run perl -V.

    $ perl -V
    ...
    %ENV:
      PERL5LIB="/home/myuser/test"
    @INC:
     /home/myuser/test
     /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/site_perl/5.18.0
     /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/5.18.0
     .
    
  2. -I command-line option

    Perl pre-pends @INC with a list of directories (colon-separated) passed as value of the -I command-line option. This can be done in three ways, as usual with Perl options:

    • Pass it on command line:

      perl -I /my/moduledir your_script.pl
      
    • Pass it via the first line (shebang) of your Perl script:

      #!/usr/local/bin/perl -w -I /my/moduledir
      
    • Pass it as part of PERL5OPT (or PERLOPT) environment variable (see chapter 19.02 in Programming Perl)

  3. Pass it via the lib pragma

    Perl pre-pends @INC with a list of directories passed in to it via use lib.

    In a program:

    use lib ("/dir1", "/dir2");
    

    On the command line:

    perl -Mlib=/dir1,/dir2
    

    You can also remove the directories from @INC via no lib.

  4. You can directly manipulate @INC as a regular Perl array.

    Note: Since @INC is used during the compilation phase, this must be done inside of a BEGIN {} block, which precedes the use MyModule statement.

    • Add directories to the beginning via unshift @INC, $dir.

    • Add directories to the end via push @INC, $dir.

    • Do anything else you can do with a Perl array.

Note: The directories are unshifted onto @INC in the order listed in this answer, e.g. default @INC is last in the list, preceded by PERL5LIB, preceded by -I, preceded by use lib and direct @INC manipulation, the latter two mixed in whichever order they are in Perl code.

References:

There does not seem to be a comprehensive @INC FAQ-type post on Stack Overflow, so this question is intended as one.

When to use each approach?

  • If the modules in a directory need to be used by many/all scripts on your site, especially run by multiple users, that directory should be included in the default @INC compiled into the Perl binary.

  • If the modules in the directory will be used exclusively by a specific user for all the scripts that user runs (or if recompiling Perl is not an option to change default @INC in previous use case), set the users' PERL5LIB, usually during user login.

    Note: Please be aware of the usual Unix environment variable pitfalls - e.g. in certain cases running the scripts as a particular user does not guarantee running them with that user's environment set up, e.g. via su.

  • If the modules in the directory need to be used only in specific circumstances (e.g. when the script(s) is executed in development/debug mode, you can either set PERL5LIB manually, or pass the -I option to perl.

  • If the modules need to be used only for specific scripts, by all users using them, use use lib/no lib pragmas in the program itself. It also should be used when the directory to be searched needs to be dynamically determined during runtime - e.g. from the script's command line parameters or script's path (see the FindBin module for very nice use case).

  • If the directories in @INC need to be manipulated according to some complicated logic, either impossible to too unwieldy to implement by combination of use lib/no lib pragmas, then use direct @INC manipulation inside BEGIN {} block or inside a special purpose library designated for @INC manipulation, which must be used by your script(s) before any other modules are used.

    An example of this is automatically switching between libraries in prod/uat/dev directories, with waterfall library pickup in prod if it's missing from dev and/or UAT (the last condition makes the standard "use lib + FindBin" solution fairly complicated. A detailed illustration of this scenario is in How do I use beta Perl modules from beta Perl scripts?.

  • An additional use case for directly manipulating @INC is to be able to add subroutine references or object references (yes, Virginia, @INC can contain custom Perl code and not just directory names, as explained in When is a subroutine reference in @INC called?).

Log4j2 configuration - No log4j2 configuration file found

In my case I had to put it in the bin folder of my project even the fact that my classpath is set to the src folder. I have no idea why, but it's worth a try.

Case insensitive std::string.find()

The new C++11 style:

#include <algorithm>
#include <string>
#include <cctype>

/// Try to find in the Haystack the Needle - ignore case
bool findStringIC(const std::string & strHaystack, const std::string & strNeedle)
{
  auto it = std::search(
    strHaystack.begin(), strHaystack.end(),
    strNeedle.begin(),   strNeedle.end(),
    [](char ch1, char ch2) { return std::toupper(ch1) == std::toupper(ch2); }
  );
  return (it != strHaystack.end() );
}

Explanation of the std::search can be found on cplusplus.com.

Forcing a postback

No, not from code behind. A postback is a request initiated from a page on the client back to itself on the server using the Http POST method. On the server side you can request a redirect but the will be Http GET request.

Nodejs convert string into UTF-8

Use the utf8 module from npm to encode/decode the string.

Installation:

npm install utf8

In a browser:

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

In Node.js:

const utf8 = require('utf8');

API:

Encode:

utf8.encode(string)

Encodes any given JavaScript string (string) as UTF-8, and returns the UTF-8-encoded version of the string. It throws an error if the input string contains a non-scalar value, i.e. a lone surrogate. (If you need to be able to encode non-scalar values as well, use WTF-8 instead.)

// U+00A9 COPYRIGHT SIGN; see http://codepoints.net/U+00A9
utf8.encode('\xA9');
// ? '\xC2\xA9'
// U+10001 LINEAR B SYLLABLE B038 E; see http://codepoints.net/U+10001
utf8.encode('\uD800\uDC01');
// ? '\xF0\x90\x80\x81'

Decode:

utf8.decode(byteString)

Decodes any given UTF-8-encoded string (byteString) as UTF-8, and returns the UTF-8-decoded version of the string. It throws an error when malformed UTF-8 is detected. (If you need to be able to decode encoded non-scalar values as well, use WTF-8 instead.)

utf8.decode('\xC2\xA9');
// ? '\xA9'

utf8.decode('\xF0\x90\x80\x81');
// ? '\uD800\uDC01'
// ? U+10001 LINEAR B SYLLABLE B038 E

Resources

Convert number to varchar in SQL with formatting

What is the value range? Is it 0 through 10? If so, then try:

SELECT REPLICATE('0',2-LEN(@t)) + CAST(@t AS VARCHAR)

That handles 0 through 9 as well as 10 through 99.

Now, tinyint can go up to the value of 255. If you want to handle > 99 through 255, then try this solution:

declare @t  TINYINT
set @t =233
SELECT ISNULL(REPLICATE('0',2-LEN(@t)),'') + CAST(@t AS VARCHAR)

To understand the solution, the expression to the left of the + calculates the number of zeros to prefix to the string.

In case of the value 3, the length is 1. 2 - 1 is 1. REPLICATE Adds one zero. In case of the value 10, the length is 2. 2 - 2 is 0. REPLICATE Adds nothing. In the case of the value 100, the length is -1 which produces a NULL. However, the null value is handled and set to an empty string.

Now if you decide that because tinyint can contain up to 255 and you want your formatting as three characters, just change the 2-LEN to 3-LEN in the left expression and you're set.

How does the keyword "use" work in PHP and can I import classes with it?

The issue is most likely you will need to use an auto loader that will take the name of the class (break by '\' in this case) and map it to a directory structure.

You can check out this article on the autoloading functionality of PHP. There are many implementations of this type of functionality in frameworks already.

I've actually implemented one before. Here's a link.

Python read-only property

Just my two cents, Silas Ray is on the right track, however I felt like adding an example. ;-)

Python is a type-unsafe language and thus you'll always have to trust the users of your code to use the code like a reasonable (sensible) person.

Per PEP 8:

Use one leading underscore only for non-public methods and instance variables.

To have a 'read-only' property in a class you can make use of the @property decoration, you'll need to inherit from object when you do so to make use of the new-style classes.

Example:

>>> class A(object):
...     def __init__(self, a):
...         self._a = a
...
...     @property
...     def a(self):
...         return self._a
... 
>>> a = A('test')
>>> a.a
'test'
>>> a.a = 'pleh'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

How to do SQL Like % in Linq?

Use such code

try
{
    using (DatosDataContext dtc = new DatosDataContext())
    {
        var query = from pe in dtc.Personal_Hgo
                    where SqlMethods.Like(pe.nombre, "%" + txtNombre.Text + "%")
                    select new
                    {
                        pe.numero
                        ,
                        pe.nombre
                    };
        dgvDatos.DataSource = query.ToList();
    }
}
catch (Exception ex)
{
    string mensaje = ex.Message;
}

Bootstrap push div content to new line

If your your list is dynamically generated with unknown number and your target is to always have last div in a new line set last div class to "col-xl-12" and remove other classes so it will always take a full row.

This is a copy of your code corrected so that last div always occupy a full row (I although removed unnecessary classes).

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="grid">_x000D_
  <div class="row">_x000D_
    <div class="col-sm-3">Under me should be a DIV</div>_x000D_
    <div class="col-md-6 col-sm-5">Under me should be a DIV</div>_x000D_
    <div class="col-xl-12">I am the last DIV and I always take a full row for my self!!</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can bcrypt have built-in salts?

This is bcrypt:

Generate a random salt. A "cost" factor has been pre-configured. Collect a password.

Derive an encryption key from the password using the salt and cost factor. Use it to encrypt a well-known string. Store the cost, salt, and cipher text. Because these three elements have a known length, it's easy to concatenate them and store them in a single field, yet be able to split them apart later.

When someone tries to authenticate, retrieve the stored cost and salt. Derive a key from the input password, cost and salt. Encrypt the same well-known string. If the generated cipher text matches the stored cipher text, the password is a match.

Bcrypt operates in a very similar manner to more traditional schemes based on algorithms like PBKDF2. The main difference is its use of a derived key to encrypt known plain text; other schemes (reasonably) assume the key derivation function is irreversible, and store the derived key directly.


Stored in the database, a bcrypt "hash" might look something like this:

$2a$10$vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa

This is actually three fields, delimited by "$":

  • 2a identifies the bcrypt algorithm version that was used.
  • 10 is the cost factor; 210 iterations of the key derivation function are used (which is not enough, by the way. I'd recommend a cost of 12 or more.)
  • vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa is the salt and the cipher text, concatenated and encoded in a modified Base-64. The first 22 characters decode to a 16-byte value for the salt. The remaining characters are cipher text to be compared for authentication.

This example is taken from the documentation for Coda Hale's ruby implementation.

In SSRS, why do I get the error "item with same key has already been added" , when I'm making a new report?

It appears that SSRS has an issue(at leastin version 2008) - I'm studying this website that explains it

Where it says if you have two columns(from 2 diff. tables) with the same name, then it'll cause that problem.

From source:

SELECT a.Field1, a.Field2, a.Field3, b.Field1, b.field99 FROM TableA a JOIN TableB b on a.Field1 = b.Field1

SQL handled it just fine, since I had prefixed each with an alias (table) name. But SSRS uses only the column name as the key, not table + column, so it was choking.

The fix was easy, either rename the second column, i.e. b.Field1 AS Field01 or just omit the field all together, which is what I did.

How do I use spaces in the Command Prompt?

Single quotation marks won't do in that case. You have to add quotation marks around each path and also enclose the whole command in quotation marks:

cmd /C ""C:\Program Files (x86)\WinRar\Rar.exe" a "D:\Hello 2\File.rar" "D:\Hello 2\*.*""

CSS: How to remove pseudo elements (after, before,...)?

You need to add a css rule that removes the after content (through a class)..


An update due to some valid comments.

The more correct way to completely remove/disable the :after rule is to use

p.no-after:after{content:none;}

as Gillian Lo Wong answered.


Original answer

You need to add a css rule that removes the after content (through a class)..

p.no-after:after{content:"";}

and add that class to your p when you want to with this line

$('p').addClass('no-after'); // replace the p selector with what you need...

a working example at : http://www.jsfiddle.net/G2czw/

Read a text file line by line in Qt

Use this code:

QFile inputFile(fileName);
if (inputFile.open(QIODevice::ReadOnly))
{
   QTextStream in(&inputFile);
   while (!in.atEnd())
   {
      QString line = in.readLine();
      ...
   }
   inputFile.close();
}

Pure JavaScript Send POST Data Without a Form

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

let data = {element: "barium"};

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

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

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

// ...

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

How do I include a path to libraries in g++

In your MakeFile or CMakeLists.txt you can set CMAKE_CXX_FLAGS as below:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/path/to/your/folder")

What's the most appropriate HTTP status code for an "item not found" error page

That's depending if userid is a resource identifier or additional parameter. If it is then it's ok to return 404 if not you might return other code like

400 (bad request) - indicates a bad request
or
412 (Precondition Failed) e.g. conflict by performing conditional update

More info in free InfoQ Explores: REST book.

How to fetch JSON file in Angular 2

You need to make an HTTP call to your games.json to retrieve it. Something like:

this.http.get(./app/resources/games.json).map

How to get element value in jQuery

You can do the same by using jQuery on().

$("#list").on('click','li',(function() {
    var selected = $(this).text();   //or .html()
    alert(selected);
})

swift 3.0 Data to String?

According to the Apple doc below, device token can not be decoded. So, I think the best thing to do is just leave it be.

https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html

Security Architecture

A device token is an opaque NSData instance that contains a unique identifier assigned by Apple to a specific app on a specific device. Only APNs can decode and read the contents of a device token. Each app instance receives its unique device token when it registers with APNs, and must then forward the token to its provider, as described in Configuring Remote Notification Support. The provider must include the device token in each push notification request that targets the associated device; APNs uses the device token to ensure the notification is delivered only to the unique app-device combination for which it is intended.

How to get value at a specific index of array In JavaScript?

shift can be used in places where you want to get the first element (index=0) of an array and chain with other array methods.

example:

const comps = [{}, {}, {}]
const specComp = comps
                  .map(fn1)
                  .filter(fn2)
                  .shift()

Remember shift mutates the array, which is very different from accessing via an indexer.

How to select all instances of a variable and edit variable name in Sublime

At this moment, 2020-10-17, if you select a text element and hit CTRL+SHIFT+ALT+M it will highlight every instance within the code chunk.

Full width layout with twitter bootstrap

Just create another class and add along with the bootstrap container class. You can also use container-fluid though.

<div class="container full-width">
    <div class="row">
        ....
    </div>
</div>

The CSS part is pretty simple

* {
    margin: 0;
    padding: 0;
}
.full-width {
    width: 100%;
    min-width: 100%;
    max-width: 100%;
}

Hope this helps, Thanks!

In Java, how do I check if a string contains a substring (ignoring case)?

How about matches()?

String string = "Madam, I am Adam";

// Starts with
boolean  b = string.startsWith("Mad");  // true

// Ends with
b = string.endsWith("dam");             // true

// Anywhere
b = string.indexOf("I am") >= 0;        // true

// To ignore case, regular expressions must be used

// Starts with
b = string.matches("(?i)mad.*");

// Ends with
b = string.matches("(?i).*adam");

// Anywhere
b = string.matches("(?i).*i am.*");

How to get URL parameters with Javascript?

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

So you can use:

myvar = getURLParameter('myvar');

How to find elements with 'value=x'?

The following worked for me:

$("[id=attached_docs][value=123]")

How to do error logging in CodeIgniter (PHP)

More oin regards to question part 4 How do you e-mail that error to an email address? The error_log function has email destination too. http://php.net/manual/en/function.error-log.php

Agha, here I found an example that shows a usage. Send errors message via email using error_log()

error_log($this->_errorMsg, 1, ADMIN_MAIL, "Content-Type: text/html; charset=utf8\r\nFrom: ".MAIL_ERR_FROM."\r\nTo: ".ADMIN_MAIL);

How do I use extern to share variables between source files?

extern tells the compiler to trust you that the memory for this variable is declared elsewhere, so it doesnt try to allocate/check memory.

Therefore, you can compile a file that has reference to an extern, but you can not link if that memory is not declared somewhere.

Useful for global variables and libraries, but dangerous because the linker does not type check.

How do I find all of the symlinks in a directory tree?

Kindly find below one liner bash script command to find all broken symbolic links recursively in any linux based OS

a=$(find / -type l); for i in $(echo $a); do file $i ; done |grep -i broken 2> /dev/null

What's an Aggregate Root?

From a broken link:

Within an Aggregate there is an Aggregate Root. The Aggregate Root is the parent Entity to all other Entities and Value Objects within the Aggregate.

A Repository operates upon an Aggregate Root.

More info can also be found here.

Transmitting newline character "\n"

Try to replace the \n with %0A just like you have spaces replaced with %20.

LINQ extension methods - Any() vs. Where() vs. Exists()

Any - boolean function that returns true when any of object in list satisfies condition set in function parameters. For example:

List<string> strings = LoadList();
boolean hasNonEmptyObject = strings.Any(s=>string.IsNullOrEmpty(s));

Where - function that returns list with all objects in list that satisfy condition set in function parameters. For example:

IEnumerable<string> nonEmptyStrings = strings.Where(s=> !string.IsNullOrEmpty(s));

Exists - basically the same as any but it's not generic - it's defined in List class, while Any is defined on IEnumerable interface.

How do I set the time zone of MySQL?

In my case, the solution was to set serverTimezone parameter in Advanced settings to an appropriate value (CET for my time zone).

As I use IntelliJ, I use its Database module. While adding a new connection to the database and after adding all relevant parameters in tab General, there was an error on "Test Connection" button. Again, the solution is to set serverTimezone parameter in tab Advanced.

How to use a PHP class from another file?

Use include_once instead.
This error means that you have already included this file.

include_once(LIB.'/class.php');

How to use mysql JOIN without ON condition?

MySQL documentation covers this topic.

Here is a synopsis. When using join or inner join, the on condition is optional. This is different from the ANSI standard and different from almost any other database. The effect is a cross join. Similarly, you can use an on clause with cross join, which also differs from standard SQL.

A cross join creates a Cartesian product -- that is, every possible combination of 1 row from the first table and 1 row from the second. The cross join for a table with three rows ('a', 'b', and 'c') and a table with four rows (say 1, 2, 3, 4) would have 12 rows.

In practice, if you want to do a cross join, then use cross join:

from A cross join B

is much better than:

from A, B

and:

from A join B -- with no on clause

The on clause is required for a right or left outer join, so the discussion is not relevant for them.

If you need to understand the different types of joins, then you need to do some studying on relational databases. Stackoverflow is not an appropriate place for that level of discussion.

How to urlencode data for curl command?

Having php installed I use this way:

URL_ENCODED_DATA=`php -r "echo urlencode('$DATA');"`

Wildcards in a Windows hosts file

I could not find a prohibition in writing, but by convention, the Windows hosts file closely follows the UNIX hosts file, and you cannot put wildcard hostname references into that file.

If you read the man page, it says:

DESCRIPTION
     The hosts file contains information regarding the known hosts on the net-
     work.  For each host a single line should be present with the following
     information:

           Internet address
           Official host name
           Aliases

Although it does say,

     Host names may contain any printable character other than a field delim-
     iter, newline, or comment character.

that is not true from a practical level.

Basically, the code that looks at the /etc/hosts file does not support a wildcard entry.

The workaround is to create all the entries in advance, maybe use a script to put a couple hundred entries at once.

How can I select an element by name with jQuery?

Personally, what I've done in the past is give them a common class id and used that to select them. It may not be ideal as they have a class specified that may not exist, but it makes the selection a hell of a lot easier. Just make sure you're unique in your classnames.

i.e. for the example above I'd use your selection by class. Better still would be to change the class name from bold to 'tcol1', so you don't get any accidental inclusions into the jQuery results. If bold does actually refer to a CSS class, you can always specify both in the class property - i.e. 'class="tcol1 bold"'.

In summary, if you can't select by Name, either use a complicated jQuery selector and accept any related performance hit or use Class selectors.

You can always limit the jQuery scope by including the table name i.e. $('#tableID > .bold')

That should restrict jQuery from searching the "world".

Its could still be classed as a complicated selector, but it quickly constrains any searching to within the table with the ID of '#tableID', so keeps the processing to a minimum.

An alternative of this if you're looking for more than 1 element within #table1 would be to look this up separately and then pass it to jQuery as this limits the scope, but saves a bit of processing to look it up each time.

var tbl = $('#tableID');
var boldElements = $('.bold',tbl);
var rows = $('tr',tbl);
if (rows.length) {
   var row1 = rows[0]; 
   var firstRowCells = $('td',row1); 
}

JQuery Validate Dropdown list

$(document).ready(function(){
$("#HoursEntry").change(function(){
var HoursEntry = $(#HoursEntry option:selected).val();
if(HoursEntry == "")
{
$("#HoursEntry").html("Please select");
return false;
}
});
});

convert base64 to image in javascript/jquery

You can just create an Image object and put the base64 as its src, including the data:image... part like this:

var image = new Image();
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);

It's what they call "Data URIs" and here's the compatibility table for inner peace.

Unable to connect to mongodb Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:L112

Quick Fix: I have the same problem to start the MongoDB and it was easily fixed by running the file mongod.exe (C:\Program Files\MongoDB\Server\3.2\bin) then run the file mongo.exe (C:\Program Files\MongoDB\Server\3.2\bin)..Problem fixed

How to select a node of treeview programmatically in c#?

Call the TreeView.OnAfterSelect() protected method after you programatically select the node.

How to prevent scrollbar from repositioning web page?

If changing size or after loading some data it is adding the scroll bar then you can try following, create class and apply this class.

.auto-scroll {
   overflow-y: overlay;
   overflow-x: overlay;
}

Remove a symlink to a directory

On CentOS, just run rm linkname and it will ask to "remove symbolic link?". Type Y and Enter, the link will be gone and the directory be safe.

how to bind datatable to datagridview in c#

// I built my datatable first, and populated it, columns, rows and all. //Then, once the datatable is functional, do the following to bind it to the DGV. NOTE: the DGV's AutoGenerateColumns property must be 'true' for this example, or the "assigning" of column names from datatable to dgv will not work. I also "added" my datatable to a dataset previously, but I don't think that is necessary.

 BindingSource SBind = new BindingSource();
 SBind.DataSource = dtSourceData;

 ADGView1.AutoGenerateColumns = true;  //must be "true" here
 ADGView1.Columns.Clear();
 ADGView1.DataSource = SBind;

 //set DGV's column names and headings from the Datatable properties
 for (int i = 0; i < ADGView1.Columns.Count; i++)
 {
       ADGView1.Columns[i].DataPropertyName = dtSourceData.Columns[i].ColumnName;
       ADGView1.Columns[i].HeaderText = dtSourceData.Columns[i].Caption;
 }
 ADGView1.Enabled = true;
 ADGView1.Refresh();

Using LIKE operator with stored procedure parameters

EG : COMPARE TO VILLAGE NAME

ALTER PROCEDURE POSMAST
(@COLUMN_NAME VARCHAR(50))
AS
SELECT * FROM TABLE_NAME
WHERE 
village_name LIKE + @VILLAGE_NAME + '%';

Volley JsonObjectRequest Post request not working

try to use this helper class

import java.io.UnsupportedEncodingException;
import java.util.Map;    
import org.json.JSONException;
import org.json.JSONObject;    
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

public class CustomRequest extends Request<JSONObject> {

    private Listener<JSONObject> listener;
    private Map<String, String> params;

    public CustomRequest(String url, Map<String, String> params,
            Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    public CustomRequest(int method, String url, Map<String, String> params,
            Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    protected Map<String, String> getParams()
            throws com.android.volley.AuthFailureError {
        return params;
    };

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        // TODO Auto-generated method stub
        listener.onResponse(response);
    }
}

In activity/fragment do use this

RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
CustomRequest jsObjRequest = new CustomRequest(Method.POST, url, params, this.createRequestSuccessListener(), this.createRequestErrorListener());

requestQueue.add(jsObjRequest);

Specifying colClasses in the read.csv

If you want to refer to names from the header rather than column numbers, you can use something like this:

fname <- "test.csv"
headset <- read.csv(fname, header = TRUE, nrows = 10)
classes <- sapply(headset, class)
classes[names(classes) %in% c("time")] <- "character"
dataset <- read.csv(fname, header = TRUE, colClasses = classes)

Bootstrap 3 2-column form layout

You can use the bootstrap grid system. as Yoann said


 <div class="container">
    <div class="row">
        <form role="form">
           <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputEmail1">Email address</label>
                        <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
                    </div>
                    <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputEmail1">Name</label>
                        <input type="text" class="form-control" id="exampleInputEmail1" placeholder="Enter Name">
                    </div>
                    <div class="clearfix"></div>
                    <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputPassword1">Password</label>
                        <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
                    </div>
                    <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputPassword1">Confirm Password</label>
                        <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Confirm Password">
                    </div>
          </form>
         <div class="clearfix">
      </div>
    </div>
</div>

How to activate an Anaconda environment

Use cmd instead of Powershell! I spent 2 hours before I switched to cmd and then it worked!

create Environment:

conda create -n your_environment_name

see list of conda environments:

conda env list

activate your environment:

conda activate your_environment_name

That's all folks

How can I multiply and divide using only bit shifting and adding?

This should work for multiplication:

.data

.text
.globl  main

main:

# $4 * $5 = $2

    addi $4, $0, 0x9
    addi $5, $0, 0x6

    add  $2, $0, $0 # initialize product to zero

Loop:   
    beq  $5, $0, Exit # if multiplier is 0,terminate loop
    andi $3, $5, 1 # mask out the 0th bit in multiplier
    beq  $3, $0, Shift # if the bit is 0, skip add
    addu $2, $2, $4 # add (shifted) multiplicand to product

Shift: 
    sll $4, $4, 1 # shift up the multiplicand 1 bit
    srl $5, $5, 1 # shift down the multiplier 1 bit
    j Loop # go for next  

Exit: #


EXIT: 
li $v0,10
syscall

How to read all of Inputstream in Server Socket JAVA

You can read your BufferedInputStream like this. It will read data till it reaches end of stream which is indicated by -1.

inputS = new BufferedInputStream(inBS);
byte[] buffer = new byte[1024];    //If you handle larger data use a bigger buffer size
int read;
while((read = inputS.read(buffer)) != -1) {
    System.out.println(read);
    // Your code to handle the data
}

How to detect Safari, Chrome, IE, Firefox and Opera browser?

This combines both Rob's original answer and Pilau's update for 2016

    var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
    // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
var isFirefox = typeof InstallTrigger !== 'undefined';   // Firefox 1.0+
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
    // At least Safari 3+: "[object HTMLElementConstructor]"
var isChrome = !!window.chrome && !isOpera;              // Chrome 1+
var isIE = /*@cc_on!@*/false || !!document.documentMode;
// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;
// Chrome 1+
var output = 'Detecting browsers by ducktyping:<hr>';
output += 'isFirefox: ' + isFirefox + '<br>';
output += 'isChrome: ' + isChrome + '<br>';
output += 'isSafari: ' + isSafari + '<br>';
output += 'isOpera: ' + isOpera + '<br>';
output += 'isIE: ' + isIE + '<br>';
output += 'isIE Edge: ' + isEdge + '<br>';
document.body.innerHTML = output;

How do I set the background color of Excel cells using VBA?

You can use either:

ActiveCell.Interior.ColorIndex = 28

or

ActiveCell.Interior.Color = RGB(255,0,0)

XML Error: There are multiple root elements

You need to enclose your <parent> elements in a surrounding element as XML Documents can have only one root node:

<parents> <!-- I've added this tag -->
    <parent>
        <child>
            Text
        </child>
    </parent>
    <parent>
        <child>
            <grandchild>
                Text
            </grandchild>
            <grandchild>
                Text
            </grandchild>
        </child>
        <child>
            Text
        </child>
    </parent>
</parents> <!-- I've added this tag -->

As you're receiving this markup from somewhere else, rather than generating it yourself, you may have to do this yourself by treating the response as a string and wrapping it with appropriate tags, prior to attempting to parse it as XML.

So, you've a couple of choices:

  1. Get the provider of the web service to return you actual XML that has one root node
  2. Pre-process the XML, as I've suggested above, to add a root node
  3. Pre-process the XML to split it into multiple chunks (i.e. one for each <parent> node) and process each as a distinct XML Document

If Python is interpreted, what are .pyc files?

Python (at least the most common implementation of it) follows a pattern of compiling the original source to byte codes, then interpreting the byte codes on a virtual machine. This means (again, the most common implementation) is neither a pure interpreter nor a pure compiler.

The other side of this is, however, that the compilation process is mostly hidden -- the .pyc files are basically treated like a cache; they speed things up, but you normally don't have to be aware of them at all. It automatically invalidates and re-loads them (re-compiles the source code) when necessary based on file time/date stamps.

About the only time I've seen a problem with this was when a compiled bytecode file somehow got a timestamp well into the future, which meant it always looked newer than the source file. Since it looked newer, the source file was never recompiled, so no matter what changes you made, they were ignored...

How to set cursor to input box in Javascript?

One of the things that can bite you is if you are using .onmousedown as your user interaction; when you do that, and then an attempt is immediately made to select a field, it won't happen, because the mouse is being held down on something else. So change to .onmouseup and viola, now focus() works, because the mouse is in an un-clicked state when the attempt to change focus is made.

How to change the CHARACTER SET (and COLLATION) throughout a database?

Beware that in Mysql, the utf8 character set is only a subset of the real UTF8 character set. In order to save one byte of storage, the Mysql team decided to store only three bytes of a UTF8 characters instead of the full four-bytes. That means that some east asian language and emoji aren't fully supported. To make sure you can store all UTF8 characters, use the utf8mb4 data type, and utf8mb4_bin or utf8mb4_general_ci in Mysql.

How to make rounded percentages add up to 100%

Here's a simpler Python implementation of @varun-vohra answer:

def apportion_pcts(pcts, total):
    proportions = [total * (pct / 100) for pct in pcts]
    apportions = [math.floor(p) for p in proportions]
    remainder = total - sum(apportions)
    remainders = [(i, p - math.floor(p)) for (i, p) in enumerate(proportions)]
    remainders.sort(key=operator.itemgetter(1), reverse=True)
    for (i, _) in itertools.cycle(remainders):
        if remainder == 0:
            break
        else:
            apportions[i] += 1
            remainder -= 1
    return apportions

You need math, itertools, operator.

How to allow only integers in a textbox?

Another solution is to use a RangeValidator where you set Type="Integer" like this:

<asp:RangeValidator runat="server"
    id="valrNumberOfPreviousOwners"
    ControlToValidate="txtNumberOfPreviousOwners"
    Type="Integer"
    MinimumValue="0"
    MaximumValue="999"
    CssClass="input-error"
    ErrorMessage="Please enter a positive integer."
    Display="Dynamic">
</asp:RangeValidator>

You can set reasonable values for the MinimumValue and MaximumValue attributes too.

HTML5 live streaming

Use ffmpeg + ffserver. It works!!! You can get a config file for ffserver from ffmpeg.org and accordingly set the values.

Time comparison

Java doesn't (yet) have a good built-in Time class (it has one for JDBC queries, but that's not what you want).

One option would be use the JodaTime APIs and its LocalTime class.

Sticking with just the built-in Java APIs, you are stuck with java.util.Date. You can use a SimpleDateFormat to parse the time, then the Date comparison functions to see if it is before or after some other time:

SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date ten = parser.parse("10:00");
Date eighteen = parser.parse("18:00");

try {
    Date userDate = parser.parse(someOtherDate);
    if (userDate.after(ten) && userDate.before(eighteen)) {
        ...
    }
} catch (ParseException e) {
    // Invalid date was entered
}

Or you could just use some string manipulations, perhaps a regular expression to extract just the hour and the minute portions, convert them to numbers and do a numerical comparison:

Pattern p = Pattern.compile("(\d{2}):(\d{2})");
Matcher m = p.matcher(userString);
if (m.matches() ) {
    String hourString = m.group(1);
    String minuteString = m.group(2);
    int hour = Integer.parseInt(hourString);
    int minute = Integer.parseInt(minuteString);

    if (hour >= 10 && hour <= 18) {
        ...
    }
}

It really all depends on what you are trying to accomplish.

Python lookup hostname from IP with 1 second timeout

>>> import socket
>>> socket.gethostbyaddr("69.59.196.211")
('stackoverflow.com', ['211.196.59.69.in-addr.arpa'], ['69.59.196.211'])

For implementing the timeout on the function, this stackoverflow thread has answers on that.

Coarse-grained vs fine-grained

Coarse-grained and Fine-grained both think about optimizing a number of servicess. But the difference is in the level. I like to explain with an example, you will understand easily.

Fine-grained: For example, I have 100 services like findbyId, findbyCategry, findbyName...... so on. Instead of that many services why we can not provide find(id, category, name....so on). So this way we can reduce the services. This is just an example, but the goal is how to optimize the number of services.

Coarse-grained: For example, I have 100 clients, each client have their own set of 100 services. So I have to provide 100*100 total services. It is very much difficult. Instead of that what I do is, I identify all common services which apply to most of the clients as one service set and remaining separately. For example in 100 services 50 services are common. So I have to manage 100*50 + 50 only.

Difference between map and collect in Ruby?

I've been told they are the same.

Actually they are documented in the same place under ruby-doc.org:

http://www.ruby-doc.org/core/classes/Array.html#M000249

  • ary.collect {|item| block } ? new_ary
  • ary.map {|item| block } ? new_ary
  • ary.collect ? an_enumerator
  • ary.map ? an_enumerator

Invokes block once for each element of self. Creates a new array containing the values returned by the block. See also Enumerable#collect.
If no block is given, an enumerator is returned instead.

a = [ "a", "b", "c", "d" ]
a.collect {|x| x + "!" }   #=> ["a!", "b!", "c!", "d!"]
a                          #=> ["a", "b", "c", "d"]

Python vs Cpython

Python is a language: a set of rules that can be used to write programs. There are several implementaions of this language.

No matter what implementation you take, they do pretty much the same thing: take the text of your program and interpret it, executing its instructions. None of them compile your code into C or any other language.

CPython is the original implementation, written in C. (The "C" part in "CPython" refers to the language that was used to write Python interpreter itself.)

Jython is the same language (Python), but implemented using Java.

IronPython interpreter was written in C#.

There's also PyPy - a Python interpreter written in Python. Make your pick :)

How to add calendar events in Android?

Just in case if someone needs this for Xamarin in c#:

        Intent intent = new Intent(Intent.ActionInsert);
        intent.SetData(Android.Provider.CalendarContract.Events.ContentUri);
        intent.PutExtra(Android.Provider.CalendarContract.ExtraEventBeginTime, Utils.Tools.CurrentTimeMillis(game.Date));
        intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.AllDay, false);
        intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.EventLocation, "Location");
        intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.Description, "Description");
        intent.PutExtra(Android.Provider.CalendarContract.ExtraEventEndTime, Utils.Tools.CurrentTimeMillis(game.Date.AddHours(2)));
        intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.Title, "Title");
        StartActivity(intent);

Helper Functions:

    private static readonly DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

    public static long CurrentTimeMillis(DateTime date)
    {
        return (long)(date.ToUniversalTime() - Jan1st1970).TotalMilliseconds;
    }

Only get hash value using md5sum (without filename)

You can use cut to split the line on spaces and return only the first such field:

md5=$(md5sum "$my_iso_file" | cut -d ' ' -f 1)

Why not use tables for layout in HTML?

Here's my programmer's answer from a simliar thread

Semantics 101

First take a look at this code and think about what's wrong here...

class car {
    int wheels = 4;
    string engine;
}

car mybike = new car();
mybike.wheels = 2;
mybike.engine = null;

The problem, of course, is that a bike is not a car. The car class is an inappropriate class for the bike instance. The code is error-free, but is semantically incorrect. It reflects poorly on the programmer.

Semantics 102

Now apply this to document markup. If your document needs to present tabular data, then the appropriate tag would be <table>. If you place navigation into a table however, then you're misusing the intended purpose of the <table> element. In the second case, you're not presenting tabular data -- you're (mis)using the <table> element to achieve a presentational goal.

Conclusion

Will visitors notice? No. Does your boss care? Maybe. Do we sometimes cut corners as programmers? Sure. But should we? No. Who benefits if you use semantic markup? You -- and your professional reputation. Now go and do the right thing.

concat scope variables into string in angular directive expression

It's not very clear what the problem is and what you are trying to accomplish from the code you posted, but I'll take a stab at it.

In general, I suggest calling a function on ng-click like so:

<a ng-click="navigateToPath()">click me</a>

obj.val1 & obj.val2 should be available on your controller's $scope, you dont need to pass those into a function from the markup.

then, in your controller:

$scope.navigateToPath = function(){
   var path = '/somePath/' + $scope.obj.val1 + '/' + $scope.obj.val2; //dont need the '#'
   $location.path(path)       
}

How to add a jar in External Libraries in android studio

Step 1: Download any JAR file for your Project.enter image description here

Step 2: Copy .jar file and past in libs folder.

enter image description here enter image description here

Step 3: Click on File > Project Structure >Select app > Dependencies

enter image description here

Step 4:

enter image description here

Step 5:

enter image description here

Step 6: After click Ok button then we can see the Dependencies add like this way:

enter image description here

How do I cancel a build that is in progress in Visual Studio?

I was hit by an unresponsive build and absolutely nothing would allow me to either kill or cancel the build. Even trying to end the task would trigger a user input window, saying that it could not be ended while the build is still going on (quite ironic because that was precisely the intention, to leave that broken state).

The build was taken care of by MSBuild, so the one way I found is to end its task. When forcing MSBuild.exe to end, VS will wake up and finally see the build as cancelled, allowing you to work again.

Hope this helps someone in the same situation.

Find the division remainder of a number

The remainder of a division can be discovered using the operator %:

>>> 26%7
5

In case you need both the quotient and the modulo, there's the builtin divmod function:

>>> seconds= 137
>>> minutes, seconds= divmod(seconds, 60)

How can I make a program wait for a variable change in javascript?

You can use properties:

Object.defineProperty MDN documentation

Example:

function def(varName, onChange) {
    var _value;

    Object.defineProperty(this, varName, {
        get: function() {
            return _value;
        },
        set: function(value) {
            if (onChange)
                onChange(_value, value);
            _value = value;
        }
    });

    return this[varName];
}

def('myVar', function (oldValue, newValue) {
    alert('Old value: ' + oldValue + '\nNew value: ' + newValue);
});

myVar = 1; // alert: Old value: undefined | New value: 1
myVar = 2; // alert: Old value: 1 | New value: 2

How can a file be copied?

Copying a file is a relatively straightforward operation as shown by the examples below, but you should instead use the shutil stdlib module for that.

def copyfileobj_example(source, dest, buffer_size=1024*1024):
    """      
    Copy a file from source to dest. source and dest
    must be file-like objects, i.e. any object with a read or
    write method, like for example StringIO.
    """
    while True:
        copy_buffer = source.read(buffer_size)
        if not copy_buffer:
            break
        dest.write(copy_buffer)

If you want to copy by filename you could do something like this:

def copyfile_example(source, dest):
    # Beware, this example does not handle any edge cases!
    with open(source, 'rb') as src, open(dest, 'wb') as dst:
        copyfileobj_example(src, dst)

How to check if "Radiobutton" is checked?

You can use switch like this:

XML Layout

<RadioGroup
            android:id="@+id/RG"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <RadioButton
                android:id="@+id/R1"
                android:layout_width="wrap_contnet"
                android:layout_height="wrap_content"
                android:text="R1" />

            <RadioButton
                android:id="@+id/R2"
                android:layout_width="wrap_contnet"
                android:layout_height="wrap_content"
                android:text="R2" />
</RadioGroup>

And JAVA Activity

switch (RG.getCheckedRadioButtonId()) {
        case R.id.R1:
            regAuxiliar = ultimoRegistro;
        case R.id.R2:
            regAuxiliar = objRegistro;
        default:
            regAuxiliar = null; // none selected
    }

You will also need to implement an onClick function with button or setOnCheckedChangeListener function to get required functionality.

Entity Framework Code First - two Foreign Keys from same table

Try this:

public class Team
{
    public int TeamId { get; set;} 
    public string Name { get; set; }

    public virtual ICollection<Match> HomeMatches { get; set; }
    public virtual ICollection<Match> AwayMatches { get; set; }
}

public class Match
{
    public int MatchId { get; set; }

    public int HomeTeamId { get; set; }
    public int GuestTeamId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public virtual Team HomeTeam { get; set; }
    public virtual Team GuestTeam { get; set; }
}


public class Context : DbContext
{
    ...

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Match>()
                    .HasRequired(m => m.HomeTeam)
                    .WithMany(t => t.HomeMatches)
                    .HasForeignKey(m => m.HomeTeamId)
                    .WillCascadeOnDelete(false);

        modelBuilder.Entity<Match>()
                    .HasRequired(m => m.GuestTeam)
                    .WithMany(t => t.AwayMatches)
                    .HasForeignKey(m => m.GuestTeamId)
                    .WillCascadeOnDelete(false);
    }
}

Primary keys are mapped by default convention. Team must have two collection of matches. You can't have single collection referenced by two FKs. Match is mapped without cascading delete because it doesn't work in these self referencing many-to-many.

How to prevent buttons from submitting forms

I'm not able to test this right now, but I would think you could use jQuery's preventDefault method.

How to convert Double to int directly?

All other answer are correct, but remember that if you cast double to int you will loss decimal value.. so 2.9 double become 2 int.

You can use Math.round(double) function or simply do :

(int)(yourDoubleValue + 0.5d)

How do I set multipart in axios with react?

ok. I tried the above two ways but it didnt work for me. After trial and error i came to know that actually the file was not getting saved in 'this.state.file' variable.

fileUpload = (e) => {
    let data = e.target.files
    if(e.target.files[0]!=null){
        this.props.UserAction.fileUpload(data[0], this.fallBackMethod)
    }
}

here fileUpload is a different js file which accepts two params like this

export default (file , callback) => {
const formData = new FormData();
formData.append('fileUpload', file);

return dispatch => {
    axios.put(BaseUrl.RestUrl + "ur/url", formData)
        .then(response => {
            callback(response.data);
        }).catch(error => {
         console.log("*****  "+error)
    });
}

}

don't forget to bind method in the constructor. Let me know if you need more help in this.

.substring error: "is not a function"

you can also quote string

''+document.location+''.substring(2,3);

How to upgrade docker container after its image changed

Update

This is mainly to query the container not to update as building images is the way to be done

I had the same issue so I created docker-run, a very simple command-line tool that runs inside a docker container to update packages in other running containers.

It uses docker-py to communicate with running docker containers and update packages or run any arbitrary single command

Examples:

docker run --rm -v /var/run/docker.sock:/tmp/docker.sock itech/docker-run exec

by default this will run date command in all running containers and return results but you can issue any command e.g. docker-run exec "uname -a"

To update packages (currently only using apt-get):

docker run --rm -v /var/run/docker.sock:/tmp/docker.sock itech/docker-run update

You can create and alias and use it as a regular command line e.g.

alias docker-run='docker run --rm -v /var/run/docker.sock:/tmp/docker.sock itech/docker-run'

Reload the page after ajax success

use this Reload page

success: function(data){
   if(data.success == true){ // if true (1)
      setTimeout(function(){// wait for 5 secs(2)
           location.reload(); // then reload the page.(3)
      }, 5000); 
   }
}

Handling 'Sequence has no elements' Exception

The value is null, you have to check why... (in addition to the implementation of the solutions proposed here)

Check the hardware Connections.

docker: executable file not found in $PATH

In the error message shown:

Error response from daemon: Cannot start container foo_1: \
    exec: "grunt serve": executable file not found in $PATH

It is complaining that it cannot find the executable grunt serve, not that it could not find the executable grunt with the argument serve. The most likely explanation for that specific error is running the command with the json syntax:

[ "grunt serve" ]

in something like your compose file. That's invalid since the json syntax requires you to split up each parameter that would normally be split by the shell on each space for you. E.g.:

[ "grunt", "serve" ]

The other possible way you can get both of those into a single parameter is if you were to quote them into a single arg in your docker run command, e.g.

docker run your_image_name "grunt serve"

and in that case, you need to remove the quotes so it gets passed as separate args to the run command:

docker run your_image_name grunt serve

For others seeing this, the executable file not found means that Linux does not see the binary you are trying to run inside your container with the default $PATH value. That could mean lots of possible causes, here are a few:

  • Did you remember to include the binary inside your image? If you run a multi-stage image, make sure that binary install is run in the final stage. Run your image with an interactive shell and verify it exists:

    docker run -it --rm your_image_name /bin/sh
    
  • Your path when shelling into the container may be modified for the interactive shell, particularly if you use bash, so you may need to specify the full path to the binary inside the container, or you may need to update the path in your Dockerfile with:

    ENV PATH=$PATH:/custom/dir/bin
    
  • The binary may not have execute bits set on it, so you may need to make it executable. Do that with chmod:

    RUN chmod 755 /custom/dir/bin/executable
    
  • If you run the image with a volume, that volume can overlay the directory where the executable exists in your image. Volumes do not merge with the image, they get mounted in the filesystem tree same as any other Linux filesystem mount. That means files from the parent filesystem at the mount point are no longer visible. (Note that named volumes are initialized by docker from the image content, but this only happens when the named volume is empty.) So the fix is to not mount volumes on top of paths where you have executables you want to run from the image.

explode string in jquery

What is row?

Either of these could be correct.

1) I assume that you capture your ajax response in a javascript variable 'row'. If that is the case, this would hold true.

var result=row.split('|');
    alert(result[2]);

otherwise

2) Use this where $(row) is a jQuery object.

var result=$(row).val().split('|');
    alert(result[2]);

[As mentioned in the other answer, you may have to use $(row).val() or $(row).text() or $(row).html() etc. depending on what $(row) is.]

How to activate the Bootstrap modal-backdrop?

Just append a div with that class to body, then remove it when you're done:

// Show the backdrop
$('<div class="modal-backdrop"></div>').appendTo(document.body);

// Remove it (later)
$(".modal-backdrop").remove();

Live Example:

_x000D_
_x000D_
$("input").click(function() {_x000D_
  var bd = $('<div class="modal-backdrop"></div>');_x000D_
  bd.appendTo(document.body);_x000D_
  setTimeout(function() {_x000D_
    bd.remove();_x000D_
  }, 2000);_x000D_
});
_x000D_
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />_x000D_
<script src="//code.jquery.com/jquery.min.js"></script>_x000D_
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>_x000D_
<p>Click the button to get the backdrop for two seconds.</p>_x000D_
<input type="button" value="Click Me">
_x000D_
_x000D_
_x000D_

How can I do a BEFORE UPDATED trigger with sql server?

The updated or deleted values are stored in DELETED. we can get it by the below method in trigger

Full example,

CREATE TRIGGER PRODUCT_UPDATE ON PRODUCTS
FOR UPDATE 
AS
BEGIN
DECLARE @PRODUCT_NAME_OLD VARCHAR(100)
DECLARE @PRODUCT_NAME_NEW VARCHAR(100)

SELECT @PRODUCT_NAME_OLD = product_name from DELETED
SELECT @PRODUCT_NAME_NEW = product_name from INSERTED

END

xls to csv converter

Quoting an answer from Scott Ming, which works with workbook containing multiple sheets:

Here is a python script getsheets.py (mirror), you should install pandas and xlrd before you use it.

Run this:

pip3 install pandas xlrd  # or `pip install pandas xlrd`

How does it works?

$ python3 getsheets.py -h
Usage: getsheets.py [OPTIONS] INPUTFILE

Convert a Excel file with multiple sheets to several file with one sheet.

Examples:

    getsheets filename

    getsheets filename -f csv

Options:
-f, --format [xlsx|csv]  Default xlsx.
-h, --help               Show this message and exit.

Convert to several xlsx:

$ python3 getsheets.py goods_temp.xlsx
Sheet.xlsx Done!
Sheet1.xlsx Done!

All Done!

Convert to several csv:

$ python3 getsheets.py goods_temp.xlsx -f csv
Sheet.csv Done!
Sheet1.csv Done!

All Done!

getsheets.py:

# -*- coding: utf-8 -*-

import click
import os
import pandas as pd


def file_split(file):
    s = file.split('.')
    name = '.'.join(s[:-1])  # get directory name
    return name


def getsheets(inputfile, fileformat):
    name = file_split(inputfile)
    try:
        os.makedirs(name)
    except:
        pass

    df1 = pd.ExcelFile(inputfile)
    for x in df1.sheet_names:
        print(x + '.' + fileformat, 'Done!')
        df2 = pd.read_excel(inputfile, sheetname=x)
        filename = os.path.join(name, x + '.' + fileformat)
        if fileformat == 'csv':
            df2.to_csv(filename, index=False)
        else:
            df2.to_excel(filename, index=False)
    print('\nAll Done!')


CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])


@click.command(context_settings=CONTEXT_SETTINGS)
@click.argument('inputfile')
@click.option('-f', '--format', type=click.Choice([
    'xlsx', 'csv']), default='xlsx', help='Default xlsx.')
def cli(inputfile, format):
    '''Convert a Excel file with multiple sheets to several file with one sheet.

    Examples:

    \b
        getsheets filename

    \b
        getsheets filename -f csv
    '''
    if format == 'csv':
        getsheets(inputfile, 'csv')
    else:
        getsheets(inputfile, 'xlsx')


cli()

Tomcat Server not starting with in 45 seconds

I got the solution for your requirement.

I'm also getting the same error in my eclipse Luna.

Go to Windows option -> select preference.

Than Select General -> Network Connection.

Than select the Active Provider as Manual.

Then restart the tomcat and run. It will work.

Hope it will help you.

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

Simple answer

If you are behind a proxy server, please set the proxy for curl. The curl is not able to connect to server so it shows wrong version number. Set proxy by opening subl ~/.curlrc or use any other text editor. Then add the following line to file: proxy= proxyserver:proxyport For e.g. proxy = 10.8.0.1:8080

If you are not behind a proxy, make sure that the curlrc file does not contain the proxy settings.

PostgreSQL: insert from another table

Just supply literal values in the SELECT:

INSERT INTO TABLE1 (id, col_1, col_2, col_3)
SELECT id, 'data1', 'data2', 'data3'
FROM TABLE2
WHERE col_a = 'something';

A select list can contain any value expression:

But the expressions in the select list do not have to reference any columns in the table expression of the FROM clause; they can be constant arithmetic expressions, for instance.

And a string literal is certainly a value expression.

jQuery bind to Paste Event, how to get the content of the paste

This work on all browser to get pasted value. And also to creating common method for all text box.

$("#textareaid").bind("paste", function(e){       
    var pastedData = e.target.value;
    alert(pastedData);
} )

Determine the type of an object?

For the sake of completeness, isinstance will not work for type checking of a subtype that is not an instance. While that makes perfect sense, none of the answers (including the accepted one) covers it. Use issubclass for that.

>>> class a(list):
...   pass
... 
>>> isinstance(a, list)
False
>>> issubclass(a, list)
True

Hide/Show Action Bar Option Menu Item for different fragments

By setting the Visibility of all items in Menu, the appbar menu or overflow menu will be Hide automatically

Example

 private Menu menu_change_language;
 ...
 ...
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
    ...
    ...
    menu_change_language = menu;
   menu_change_language.findItem(R.id.menu_change_language).setVisible(true);

    return super.onCreateOptionsMenu(menu);
}

Before going to other fragment use bellow code:

if(menu_change_language != null){                 
 menu_change_language.findItem(R.id.menu_change_language)
  .setVisible(false);
}

How to obfuscate Python code effectively?

I know it is an old question. Just want to add my funny obfuscated "Hello world!" in Python 3 and some tips ;)

#//'written in c++'

#include <iostream.h>
#define true false
import os
n = int(input())
_STACK_CALS=  [ ];
_i_CountCals__= (0x00)
while os.urandom(0x00 >> 0x01) or (1 & True):
  _i_CountCals__+= 0o0;break;# call shell command echo "hello world" > text.txt
""#print'hello'
__cal__= getattr( __builtins__  ,'c_DATATYPE_hFILE_radnom'[ 0x00 ]+'.h'[-1]+'getRndint'[3].lower() )
_o0wiXSysRdrct   =eval (  __cal__(0x63) + __cal__(104) + 'r_RUN_CALLER'[0] );
_i1CLS_NATIVE=  getattr (__builtins__ ,__cal__(101)+__cal__(118  )+_o0wiXSysRdrct ( 0b1100001 )+'LINE 2'[0].lower( ))#line 2 kernel call
__executeMAIN_0x07453320abef  =_i1CLS_NATIVE ( 'map');
def _Main():
    raise 0x06;return 0 # exit program with exit code 0
def _0o7af():_i1CLS_NATIVE('_int'.replace('_', 'programMain'[:2]))(''.join(  __executeMAIN_0x07453320abef( _o0wiXSysRdrct ,_STACK_CALS)));return;_Main()
for _INCREAMENT in [0]*1024:
    _STACK_CALS= [0x000 >> 0x001 ,True&False&True&False ,'c++', 'h', 'e', 'l', 'o',' ', 'w', 'o', 'r', 'l', 'd']
   
#if
for _INCREAMENT in [0]*1024:
    _STACK_CALS= [40, 111, 41, 46, 46] * n
    
""""""#print'word'
while True:
    break;
_0o7af();
while os.urandom(0x00 >> 0xfa) or (1 & True): # print "Hello, world!"
  _i_CountCals__-= 0o0;break;
  while os.urandom(0x00 >> 0x01) or (1 & True):
      _i_CountCals__ += 0o0;
      break;

It is possible to do manually, my tips are:

  • use eval and/or exec with encrypted strings

  • use [ord(i) for i in s] / ''.join(map(chr, [list of chars goes here])) as simple encryption/decryption

  • use obscure variable names

  • make it unreadable

  • Don't write just 1 or True, write 1&True&0x00000001 ;)

  • use different number systems

  • add confusing comments like "line 2" on line 10 or "it returns 0" on while loop.

  • use __builtins__

  • use getattr and setattr

Autocompletion of @author in Intellij

For Intellij IDEA Community 2019.1 you will need to follow these steps :

File -> New -> Edit File Templates.. -> Class -> /* Created by ${USER} on ${DATE} */

jQuery Validate Plugin - Trigger validation of single field

Use Validator.element():

Validates a single element, returns true if it is valid, false otherwise.

Here is the example shown in the API:

var validator = $( "#myform" ).validate();
validator.element( "#myselect" );

.valid() validates the entire form, as others have pointed out. The API says:

Checks whether the selected form is valid or whether all selected elements are valid.

SFTP in Python? (platform independent)

Twisted can help you with what you are doing, check out their documentation, there are plenty of examples. Also it is a mature product with a big developer/user community behind it.

How to vertically align label and input in Bootstrap 3?

None of these solutions worked for me. But I was able to get vertical centering by using <div class="form-row align-items-center"> for each form row, per the Bootstrap examples.

Constants in Kotlin -- what's a recommended way to create them?

local constants:

const val NAME = "name"

Global constants:

object MyConstants{
    val NAME = "name"
    val ID = "_id"
    var EMAIL = "email"
}

access MyConstants.NAME

How do I use LINQ Contains(string[]) instead of Contains(string)

Try the following.

string input = "someString";
string[] toSearchFor = GetSearchStrings();
var containsAll = toSearchFor.All(x => input.Contains(x));

how to determine size of tablespace oracle 11g

One of the way is Using below sql queries

--Size of All Table Space

--1. Used Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "USED SPACE(IN GB)" FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME
--2. Free Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "FREE SPACE(IN GB)" FROM   USER_FREE_SPACE GROUP BY TABLESPACE_NAME

--3. Both Free & Used
SELECT USED.TABLESPACE_NAME, USED.USED_BYTES AS "USED SPACE(IN GB)",  FREE.FREE_BYTES AS "FREE SPACE(IN GB)"
FROM
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS USED_BYTES FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME) USED
INNER JOIN
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS FREE_BYTES FROM  USER_FREE_SPACE GROUP BY TABLESPACE_NAME) FREE
ON (USED.TABLESPACE_NAME = FREE.TABLESPACE_NAME);

How to convert minutes to hours/minutes and add various time values together using jQuery?

I took the liberty of modifying ConorLuddy's answer to address both 24 hour time and 12 hour time.

function minutesToHHMM (mins, twentyFour = false) {
  let h = Math.floor(mins / 60);
  let m = mins % 60;
  m = m < 10 ? '0' + m : m;

  if (twentyFour) {
    h = h < 10 ? '0' + h : h;
    return `${h}:${m}`;
  } else {
    let a = 'am';
    if (h >= 12) a = 'pm';
    if (h > 12) h = h - 12;
    return `${h}:${m} ${a}`;
  }
}

How can I autoformat/indent C code in vim?

I like indent as mentioned above, but most often I want to format only a small section of the file that I'm working on. Since indent can take code from stdin, its really simple:

  1. Select the block of code you want to format with V or the like.
  2. Format by typing :!indent.

astyle takes stdin too, so you can use the same trick there.

Tomcat is not running even though JAVA_HOME path is correct

Set Environment Variable ([Windows Key]+[Pause Key], switch to "Advanced", click "Environment Variables", in "System Variables" (lower list), click "New" (or "Edit" if you already have it),

name: JAVA_HOME

value: C:\PROGRA~1\Java\JDK16~1.0_3

for C:\Program Files\Java\jdk1.6.0_32

click "ok",

go to "path" in "system variables",

add ; at the end of the line (unless there is already one there),

add: C:\PROGRA~1\Java\JDK16~1.0_3\bin

click "ok" through all. -- restart your computer (advisable)

C++ Compare char array with string

You're not working with strings. You're working with pointers. var1 is a char pointer (const char*). It is not a string. If it is null-terminated, then certain C functions will treat it as a string, but it is fundamentally just a pointer.

So when you compare it to a char array, the array decays to a pointer as well, and the compiler then tries to find an operator == (const char*, const char*).

Such an operator does exist. It takes two pointers and returns true if they point to the same address. So the compiler invokes that, and your code breaks.

IF you want to do string comparisons, you have to tell the compiler that you want to deal with strings, not pointers.

The C way of doing this is to use the strcmp function:

strcmp(var1, "dev");

This will return zero if the two strings are equal. (It will return a value greater than zero if the left-hand side is lexicographically greater than the right hand side, and a value less than zero otherwise.)

So to compare for equality you need to do one of these:

if (!strcmp(var1, "dev")){...}
if (strcmp(var1, "dev") == 0) {...}

However, C++ has a very useful string class. If we use that your code becomes a fair bit simpler. Of course we could create strings from both arguments, but we only need to do it with one of them:

std::string var1 = getenv("myEnvVar");

if(var1 == "dev")
{
   // do stuff
}

Now the compiler encounters a comparison between string and char pointer. It can handle that, because a char pointer can be implicitly converted to a string, yielding a string/string comparison. And those behave exactly as you'd expect.

pod has unbound PersistentVolumeClaims

You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.

When using storageClass Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.


To solve your issue:

  • Provide a PersistentVolume fulfilling the constraints of the claim (a size >= 100Mi)
  • Remove the storageClass-line from the PersistentVolumeClaim
  • Remove the StorageClass from your cluster

How do these pieces play together?

At creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.

The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.

The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.

A PersistentVolume without StorageClass is considered to be static.

"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.


Example PersistentVolume

In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: ckan-pv-home
  labels:
    type: local
spec:
  capacity:
    storage: 100Mi
  hostPath:
    path: "/mnt/data/ckan"

The PersistentVolumeSpec allows us to define multiple attributes. I chose a hostPath volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.


Additional Resources:

How to check the installed version of React-Native

Just Do a "npm audit" on your project directory and then go to your project package.json file. In the package.json file you will find all the versions and the package names.This should work irrespective of the OS.

Assigning more than one class for one event

Have you tried this:

 function doSomething() {
     if ($(this).hasClass('clickedTag')){
         // code here
     } else {
         // and here
     }
 }

 $('.tag1, .tag2').click(doSomething);

Handling of non breaking space: <p>&nbsp;</p> vs. <p> </p>

How about a workaround? In my case I took the value of the textarea in a jQuery variable, and changed all "<p>&nbsp" to <p class="clear"> and clear class to have certain height and margin, as the following example:

jQuery

tinyMCE.triggerSave();
var val = $('textarea').val();
val = val.replace(/<p>&nbsp/g, '<p class="clear">');

the val is then saved to the database with the new val.

CSS

p.clear{height: 2px; margin-bottom: 3px;}

You can adjust the height & margin as you wish. And since 'p' is a display: block element. it should give you the expected output.

Hope that helps!

Is it safe to expose Firebase apiKey to the public?

Building on the answers of prufrofro and Frank van Puffelen here, I put together this setup that doesn't prevent scraping, but can make it slightly harder to use your API key.

Warning: To get your data, even with this method, one can for example simply open the JS console in Chrome and type:

firebase.database().ref("/get/all/the/data").once("value", function (data) {
    console.log(data.val());
});

Only the database security rules can protect your data.

Nevertheless, I restricted my production API key use to my domain name like this:

  1. https://console.developers.google.com/apis
  2. Select your Firebase project
  3. Credentials
  4. Under API keys, pick your Browser key. It should look like this: "Browser key (auto created by Google Service)"
  5. In "Accept requests from these HTTP referrers (web sites)", add the URL of your app (exemple: projectname.firebaseapp.com/* )

Now the app will only work on this specific domain name. So I created another API Key that will be private for localhost developement.

  1. Click Create credentials > API Key

By default, as mentioned by Emmanuel Campos, Firebase only whitelists localhost and your Firebase hosting domain.


In order to make sure I don't publish the wrong API key by mistake, I use one of the following methods to automatically use the more restricted one in production.

Setup for Create-React-App

In /env.development:

REACT_APP_API_KEY=###dev-key###

In /env.production:

REACT_APP_API_KEY=###public-key###

In /src/index.js

const firebaseConfig = {
  apiKey: process.env.REACT_APP_API_KEY,
  // ... 
};

function to return a string in java

Your code is fine. There's no problem with returning Strings in this manner.

In Java, a String is a reference to an immutable object. This, coupled with garbage collection, takes care of much of the potential complexity: you can simply pass a String around without worrying that it would disapper on you, or that someone somewhere would modify it.

If you don't mind me making a couple of stylistic suggestions, I'd modify the code like so:

public String time_to_string(long t) // time in milliseconds
{
    if (t < 0)
    {
        return "-";
    }
    else
    {
        int secs = (int)(t/1000);
        int mins = secs/60;
        secs = secs - (mins * 60);
        return String.format("%d:%02d", mins, secs);
    }
}

As you can see, I've pushed the variable declarations as far down as I could (this is the preferred style in C++ and Java). I've also eliminated ans and have replaced the mix of string concatenation and String.format() with a single call to String.format().

CSS: How to change colour of active navigation page menu

I think you are getting confused about what the a:active CSS selector does. This will only change the colour of your link when you click it (and only for the duration of the click i.e. how long your mouse button stays down). What you need to do is introduce a new class e.g. .selected into your CSS and when you select a link, update the selected menu item with new class e.g.

<div class="menuBar">
    <ul>
        <li class="selected"><a href="index.php">HOME</a></li>
        <li><a href="two.php">PORTFOLIO</a></li>
        ....
    </ul>
</div>

// specific CSS for your menu
div.menuBar li.selected a { color: #FF0000; } 
// more general CSS
li.selected a { color: #FF0000; }

You will need to update your template page to take in a selectedPage parameter.

Android SDK folder taking a lot of disk space. Do we need to keep all of the System Images?

I had 20.8 GB in the C:\Users\ggo\AppData\Local\Android\Sdk\system-images folder (6 android images: - android-10 - android-15 - android-21 - android-23 - android-25 - android-26 ).

I have compressed the C:\Users\ggo\AppData\Local\Android\Sdk\system-images folder.

Now it takes only 4.65 GB.

C:\Users\ggo\AppData\Local\Android\Sdk\system-images

I did not encountered any problem up to now...

Compression seems to vary from 2/3 to 6, sometimes much more:

android-10

android-23

android-25

android-26

Equivalent to 'app.config' for a library (DLL)

You can have separate configuration file, but you'll have to read it "manually", the ConfigurationManager.AppSettings["key"] will read only the config of the running assembly.

Assuming you're using Visual Studio as your IDE, you can right click the desired project ? Add ? New item ? Application Configuration File

This will add App.config to the project folder, put your settings in there under <appSettings> section. In case you're not using Visual Studio and adding the file manually, make sure to give it such name: DllName.dll.config, otherwise the below code won't work properly.

Now to read from this file have such function:

string GetAppSetting(Configuration config, string key)
{
    KeyValueConfigurationElement element = config.AppSettings.Settings[key];
    if (element != null)
    {
        string value = element.Value;
        if (!string.IsNullOrEmpty(value))
            return value;
    }
    return string.Empty;
}

And to use it:

Configuration config = null;
string exeConfigPath = this.GetType().Assembly.Location;
try
{
    config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
}
catch (Exception ex)
{
    //handle errror here.. means DLL has no sattelite configuration file.
}

if (config != null)
{
    string myValue = GetAppSetting(config, "myKey");
    ...
}

You'll also have to add reference to System.Configuration namespace in order to have the ConfigurationManager class available.

When building the project, in addition to the DLL you'll have DllName.dll.config file as well, that's the file you have to publish with the DLL itself.

The above is basic sample code, for those interested in a full scale example, please refer to this other answer.

Getting last month's date in php

echo strtotime("-1 month");

That will output the timestamp for last month exactly. You don't need to reset anything afterwards. If you want it in an English format after that, you can use date() to format the timestamp, ie:

echo date("Y-m-d H:i:s",strtotime("-1 month"));

Django request get parameters

You can use [] to extract values from a QueryDict object like you would any ordinary dictionary.

# HTTP POST variables
request.POST['section'] # => [39]
request.POST['MAINS'] # => [137]

# HTTP GET variables
request.GET['section'] # => [39]
request.GET['MAINS'] # => [137]

# HTTP POST and HTTP GET variables (Deprecated since Django 1.7)
request.REQUEST['section'] # => [39]
request.REQUEST['MAINS'] # => [137]

How can I access Oracle from Python?

Ensure these two and it should work:-

  1. Python, Oracle instantclient and cx_Oracle are 32 bit.
  2. Set the environment variables.

Fixes this issue on windows like a charm.

ssh: check if a tunnel is alive

Autossh is best option - checking process is not working in all cases (e.g. zombie process, network related problems)

example:

autossh -M 2323 -c arcfour -f -N -L 8088:localhost:80 host2

How can I convert an HTML element to a canvas element?

You could spare yourself the transformations, you could use CSS3 Transitions to flip <div>'s and <ol>'s and any HTML tag you want. Here are some demos with source code explain to see and learn: http://www.webdesignerwall.com/trends/47-amazing-css3-animation-demos/

Service vs IntentService in the Android platform

Android IntentService vs Service

1.Service

  • A Service is invoked using startService().
  • A Service can be invoked from any thread.
  • A Service runs background operations on the Main Thread of the Application by default. Hence it can block your Application’s UI.
  • A Service invoked multiple times would create multiple instances.
  • A service needs to be stopped using stopSelf() or stopService().
  • Android service can run parallel operations.

2. IntentService

  • An IntentService is invoked using Intent.
  • An IntentService can in invoked from the Main thread only.
  • An IntentService creates a separate worker thread to run background operations.
  • An IntentService invoked multiple times won’t create multiple instances.
  • An IntentService automatically stops after the queue is completed. No need to trigger stopService() or stopSelf().
  • In an IntentService, multiple intent calls are automatically Queued and they would be executed sequentially.
  • An IntentService cannot run parallel operation like a Service.

Refer from Here

Messagebox with input field

You can reference Microsoft.VisualBasic.dll.

Then using the code below.

Microsoft.VisualBasic.Interaction.InputBox("Question?","Title","Default Text");

Alternatively, by adding a using directive allowing for a shorter syntax in your code (which I'd personally prefer).

using Microsoft.VisualBasic;
...
Interaction.InputBox("Question?","Title","Default Text");

Or you can do what Pranay Rana suggests, that's what I would've done too...

Build unsigned APK file with Android Studio

In Android Studio:

  1. Build

  2. Build APK(s)

  3. Wait and go to the location shown in a pop-up window. On right bottom side

enter image description here

How to get the current time as datetime

Using Date Formatter -Swift 3.0

//Date
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
let dateString = "Current date is: \(dateFormatter.string(from: Date() as Date))"
labelfordate.text = String(dateString)


//Time    
let timeFormatter = DateFormatter()
timeFormatter.timeStyle = .medium
let timeString = "Current time is: \(timeFormatter.string(from: Date() as Date))"
labelfortime.text = String(timeString)

Update Date and Time Every Seconds

override func viewDidLoad() {
super.viewDidLoad()

timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(DateAndTime.action), userInfo: nil, repeats: true)

       }

func action()
    {
    //Date
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .medium
    let dateString = "Current date is: \(dateFormatter.string(from: Date() as Date))"
    labelfordate.text = String(dateString)


    //Time
    let timeFormatter = DateFormatter()
    timeFormatter.timeStyle = .medium
    let timeString = "Current time is: \(timeFormatter.string(from: Date() as Date))"
    labelfortime.text = String(timeString)

    }

Note: DateAndTime in the Timer code is the Class name.

How to delete/remove nodes on Firebase

The problem is that you call remove on the root of your Firebase:

ref = new Firebase("myfirebase.com")
ref.remove();

This will remove the entire Firebase through the API.

You'll typically want to remove specific child nodes under it though, which you do with:

ref.child(key).remove();

How to make HTML open a hyperlink in another window or tab?

use target="_blank"

<a target='_blank' href="http://www.starfall.com/">Starfall</a>

Inverse of a matrix using numpy

Another way to do this is to use the numpy matrix class (rather than a numpy array) and the I attribute. For example:

>>> m = np.matrix([[2,3],[4,5]])
>>> m.I
matrix([[-2.5,  1.5],
       [ 2. , -1. ]])

How does internationalization work in JavaScript?

Localization support in legacy browsers is poor. Originally, this was due to phrases in the ECMAScript language spec that look like this:

Number.prototype.toLocaleString()
Produces a string value that represents the value of the Number formatted according to the conventions of the host environment’s current locale. This function is implementation-dependent, and it is permissible, but not encouraged, for it to return the same thing as toString.

Every localization method defined in the spec is defined as "implementation-dependent", which results in a lot of inconsistencies. In this instance, Chrome Opera and Safari would return the same thing as .toString(). Firefox and IE will return locale formatted strings, and IE even includes a thousand separator (perfect for currency strings). Chrome was recently updated to return a thousands-separated string, though with no fixed decimal.

For modern environments, the ECMAScript Internationalization API spec, a new standard that complements the ECMAScript Language spec, provides much better support for string comparison, number formatting, and the date and time formatting; it also fixes the corresponding functions in the Language Spec. An introduction can be found here. Implementations are available in:

  • Chrome 24
  • Firefox 29
  • Internet Explorer 11
  • Opera 15

There is also a compatibility implementation, Intl.js, which will provide the API in environments where it doesn't already exist.

Determining the user's preferred language remains a problem since there's no specification for obtaining the current language. Each browser implements a method to obtain a language string, but this could be based on the user's operating system language or just the language of the browser:

// navigator.userLanguage for IE, navigator.language for others
var lang = navigator.language || navigator.userLanguage;

A good workaround for this is to dump the Accept-Language header from the server to the client. If formatted as a JavaScript, it can be passed to the Internationalization API constructors, which will automatically pick the best (or first-supported) locale.

In short, you have to put in a lot of the work yourself, or use a framework/library, because you cannot rely on the browser to do it for you.

Various libraries and plugins for localization:

  • Others:

Feel free to add/edit.

How to define Gradle's home in IDEA?

You can write a simple gradle script to print your GRADLE_HOME directory.

task getHomeDir {
    doLast {
        println gradle.gradleHomeDir
    }
}

and name it build.gradle.

Then run it with:

gradle getHomeDir

If you installed with homebrew, use brew info gradle to find the base path (i.e. /usr/local/Cellar/gradle/1.10/), and just append libexec.

The same task in Kotlin in case you use build.gradle.kts:

tasks.register("getHomeDir") {
    println("Gradle home dir: ${gradle.gradleHomeDir}")
}

useState set method not reflecting change immediately

// replace
return <p>hello</p>;
// with
return <p>{JSON.stringify(movies)}</p>;

Now you should see, that your code actually does work. What does not work is the console.log(movies). This is because movies points to the old state. If you move your console.log(movies) outside of useEffect, right above the return, you will see the updated movies object.

How do I add more members to my ENUM-type column in MySQL?

Here is another way...

It adds "others" to the enum definition of the column "rtipo" of the table "firmas".

set @new_enum = 'others';
set @table_name = 'firmas';
set @column_name = 'rtipo';
select column_type into @tmp from information_schema.columns 
  where table_name = @table_name and column_name=@column_name;
set @tmp = insert(@tmp, instr(@tmp,')'), 0, concat(',\'', @new_enum, '\'') );
set @tmp = concat('alter table ', @table_name, ' modify ', @column_name, ' ', @tmp);
prepare stmt from @tmp;
execute stmt;
deallocate prepare stmt;

form confirm before submit

var r = confirm('Want to delete ?'); 

if (r == true) { 
    $('#admin-category-destroy').submit(); 
}

Determine if char is a num or letter

If (theChar >= '0' && theChar <='9') it's a digit. You get the idea.

Convert NaN to 0 in javascript

NaN is the only value in JS which is not equals to itself so we can use this information in our favour

const x = NaN;
let y = x!=x && 0; 
y = Number.isNaN(x) && 0

We can also use Number.isNaN instead of isNaN function as latter coerces its argument to number

isNaN('string')        // true which is incorrect because 'string'=='string'
Number.isNaN('string') // false 

Creating a new column based on if-elif-else condition

enter image description here

Lets say above one is your original dataframe and you want to add a new column 'old'

If age greater than 50 then we consider as older=yes otherwise False

step 1: Get the indexes of rows whose age greater than 50

row_indexes=df[df['age']>=50].index

step 2: Using .loc we can assign a new value to column

df.loc[row_indexes,'elderly']="yes"

same for age below less than 50

row_indexes=df[df['age']<50].index

df[row_indexes,'elderly']="no"

How do I get some variable from another class in Java?

The code that you have is correct. To get a variable from another class you need to create an instance of the class if the variable is not static, and just call the explicit method to get access to that variable. If you put get and set method like the above is the same of declaring that variable public.

Put the method setNum private and inside the getNum assign the value that you want, you will have "get" access to the variable in that case

Set keyboard caret position in html textbox

Excerpted from Josh Stodola's Setting keyboard caret Position in a Textbox or TextArea with Javascript

A generic function that will allow you to insert the caret at any position of a textbox or textarea that you wish:

function setCaretPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}

The first expected parameter is the ID of the element you wish to insert the keyboard caret on. If the element is unable to be found, nothing will happen (obviously). The second parameter is the caret positon index. Zero will put the keyboard caret at the beginning. If you pass a number larger than the number of characters in the elements value, it will put the keyboard caret at the end.

Tested on IE6 and up, Firefox 2, Opera 8, Netscape 9, SeaMonkey, and Safari. Unfortunately on Safari it does not work in combination with the onfocus event).

An example of using the above function to force the keyboard caret to jump to the end of all textareas on the page when they receive focus:

function addLoadEvent(func) {
    if(typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        if(func) {
            var oldLoad = window.onload;

            window.onload = function() {
                if(oldLoad)
                        oldLoad();

                func();
            }
        }
    }
}

// The setCaretPosition function belongs right here!

function setTextAreasOnFocus() {
/***
 * This function will force the keyboard caret to be positioned
 * at the end of all textareas when they receive focus.
 */
    var textAreas = document.getElementsByTagName('textarea');

    for(var i = 0; i < textAreas.length; i++) {
        textAreas[i].onfocus = function() {
            setCaretPosition(this.id, this.value.length);
        }
    }

    textAreas = null;
}

addLoadEvent(setTextAreasOnFocus);

json.net has key method?

JObject.ContainsKey(string propertyName) has been made as public method in 11.0.1 release

Documentation - https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JObject_ContainsKey.htm

Possible to perform cross-database queries with PostgreSQL?

Yes, you can by using DBlink (postgresql only) and DBI-Link (allows foreign cross database queriers) and TDS_LInk which allows queries to be run against MS SQL server.

I have used DB-Link and TDS-link before with great success.

Page Redirect after X seconds wait using JavaScript

It looks you are almost there. Try:

if(error == true){

    // Your application has indicated there's an error
    window.setTimeout(function(){

        // Move to a new location or you can do something else
        window.location.href = "https://www.google.co.in";

    }, 5000);

}

How to initialize std::vector from C-style array?

You use the word initialize so it's unclear if this is one-time assignment or can happen multiple times.

If you just need a one time initialization, you can put it in the constructor and use the two iterator vector constructor:

Foo::Foo(double* w, int len) : w_(w, w + len) { }

Otherwise use assign as previously suggested:

void set_data(double* w, int len)
{
    w_.assign(w, w + len);
}

Is there a way to get a <button> element to link to a location without wrapping it in an <a href ... tag?

<form action="portfolio.html">
 <button type="link" class="btn btn-primary btn-lg">View Work</button>
</form>

I just figured this out, and it links perfectly to another page without having my default link settings over ride my button classes! :)

Prevent WebView from displaying "web page not available"

I've had to face this issue and also tried to solve it from different perspectives. Finally I found a solution by using a single flag to check if an error happened.

... extends WebViewClient {

    boolean error;

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {

        showLoading(true);
        super.onPageStarted(view, url, favicon);

        error  = false; // IMPORTANT
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

        if(!error) {
            Observable.timer(100, TimeUnit.MICROSECONDS, AndroidSchedulers.mainThread())
                    .subscribe((data) -> view.setVisibility(View.VISIBLE) );
        }

        showLoading(false);
    }


    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

        view.stopLoading();

        view.setVisibility(View.INVISIBLE) 
        error  = true;  

        // Handle the error
    }


     @Override
    @TargetApi(android.os.Build.VERSION_CODES.M)
    public void onReceivedError(WebView view,
                                WebResourceRequest request,
                                WebResourceError error) {

        this.onReceivedError(view, error.getErrorCode(),
                error.getDescription().toString(),
                request.getUrl().toString());
    }
 }

This way I hide the page every time there's an error and show it when the page has loaded again properly.

Also added a small delay in case.

I avoided the solution of loading an empty page as it does not allow you to do webview.reload() later on due to it adds that new page in the navigation history.

Lua - Current time in milliseconds

I use LuaSocket to get more precision.

require "socket"
print("Milliseconds: " .. socket.gettime()*1000)

This adds a dependency of course, but works fine for personal use (in benchmarking scripts for example).

Why would Oracle.ManagedDataAccess not work when Oracle.DataAccess does?

Try to add the path to tnsnames.ora to the config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <oracle.manageddataaccess.client>
    <version number="4.112.3.60">
      <settings>
        <setting name="TNS_ADMIN" value="C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN\" />
      </settings>
    </version>
  </oracle.manageddataaccess.client>
</configuration>

Angular: Cannot Get /

Deleting node modules folder worked for me.

  • Delete the node modules folder
  • Run npm install.
  • Re-run the application and it should work.

How does one represent the empty char?

There are two ways to do the same instruction, that is, an empty string. The first way is to allocate an empty string on static memory:

char* my_variable = "";

or, if you want to be explicit:

char my_variable = '\0';

The way posted above is only for a character. And, the second way:

#include <string.h>
char* my_variable = strdup("");

Don't forget to use free() with this one because strdup() use malloc inside.

Regex date validation for yyyy-mm-dd

A simple one would be

\d{4}-\d{2}-\d{2}

Regular expression visualization

Debuggex Demo

but this does not restrict month to 1-12 and days from 1 to 31.

There are more complex checks like in the other answers, by the way pretty clever ones. Nevertheless you have to check for a valid date, because there are no checks for if a month has 28, 30, or 31 days.

Number of elements in a javascript object

The concept of number/length/dimensionality doesn't really make sense for an Object, and needing it suggests you really want an Array to me.

Edit: Pointed out to me that you want an O(1) for this. To the best of my knowledge no such way exists I'm afraid.

Get Hours and Minutes (HH:MM) from date

You can cast datetime to time

select CAST(GETDATE() as time)

If you want a hh:mm format

select cast(CAST(GETDATE() as time) as varchar(5))

Using Colormaps to set color of line in matplotlib

A combination of line styles, markers, and qualitative colors from matplotlib:

import itertools
import matplotlib as mpl
import matplotlib.pyplot as plt
N = 8*4+10
l_styles = ['-','--','-.',':']
m_styles = ['','.','o','^','*']
colormap = mpl.cm.Dark2.colors   # Qualitative colormap
for i,(marker,linestyle,color) in zip(range(N),itertools.product(m_styles,l_styles, colormap)):
    plt.plot([0,1,2],[0,2*i,2*i], color=color, linestyle=linestyle,marker=marker,label=i)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,ncol=4);

enter image description here

UPDATE: Supporting not only ListedColormap, but also LinearSegmentedColormap

import itertools
import matplotlib.pyplot as plt
Ncolors = 8
#colormap = plt.cm.Dark2# ListedColormap
colormap = plt.cm.viridis# LinearSegmentedColormap
Ncolors = min(colormap.N,Ncolors)
mapcolors = [colormap(int(x*colormap.N/Ncolors)) for x in range(Ncolors)]
N = Ncolors*4+10
l_styles = ['-','--','-.',':']
m_styles = ['','.','o','^','*']
fig,ax = plt.subplots(gridspec_kw=dict(right=0.6))
for i,(marker,linestyle,color) in zip(range(N),itertools.product(m_styles,l_styles, mapcolors)):
    ax.plot([0,1,2],[0,2*i,2*i], color=color, linestyle=linestyle,marker=marker,label=i)
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,ncol=3,prop={'size': 8})

enter image description here

Running an outside program (executable) in Python?

If it were me, I'd put the EXE file in the root directory (C:) and see if it works like that. If so, it's probably the (already mentioned) spaces in the directory name. If not, it may be some environment variables.

Also, try to check you stderr (using an earlier answer by int3):

import subprocess
process = subprocess.Popen(["C:/Documents and Settings/flow_model/flow.exe"], \
                           stderr = subprocess.PIPE)
if process.stderr:
    print process.stderr.readlines()

The code might not be entirely correct as I usually don't use Popen or Windows, but should give the idea. It might well be that the error message is on the error stream.

Unable to open debugger port in IntelliJ IDEA

My assumption that this exception usually occurs when Tomcat is improperly closed and still holding the ports. Usually it is enough to kill any process listening to 1099 port. For Window 10:

netstat -aon | find "1099"


taskkill /F /PID $processId

How to know Hive and Hadoop versions from command prompt?

to identify hive version on a EC2 instance use

hive --version

How to detect if javascript files are loaded?

Like T.J. wrote: the order is defined (at least it's sequential when your browser is about to execute any JavaScript, even if it may download the scripts in parallel somehow). However, as apparently you're having trouble, maybe you're using third-party JavaScript libraries that yield some 404 Not Found or timeout? If so, then read Best way to use Google’s hosted jQuery, but fall back to my hosted library on Google fail.

Difference between int32, int, int32_t, int8 and int8_t

Always keep in mind that 'size' is variable if not explicitly specified so if you declare

 int i = 10;

On some systems it may result in 16-bit integer by compiler and on some others it may result in 32-bit integer (or 64-bit integer on newer systems).

In embedded environments this may end up in weird results (especially while handling memory mapped I/O or may be consider a simple array situation), so it is highly recommended to specify fixed size variables. In legacy systems you may come across

 typedef short INT16;
 typedef int INT32;
 typedef long INT64; 

Starting from C99, the designers added stdint.h header file that essentially leverages similar typedefs.

On a windows based system, you may see entries in stdin.h header file as

 typedef signed char       int8_t;
 typedef signed short      int16_t;
 typedef signed int        int32_t;
 typedef unsigned char     uint8_t;

There is quite more to that like minimum width integer or exact width integer types, I think it is not a bad thing to explore stdint.h for a better understanding.

How to check if an Object is a Collection Type in Java?

Java conveniently has the instanceof operator (JLS 15.20.2) to test if a given object is of a given type.

 if (x instanceof List<?>) {   
    List<?> list = (List<?>) x;
    // do something with list
 } else if (x instanceof Collection<?>) {
    Collection<?> col = (Collection<?>) x;
    // do something with col
 }

One thing should be mentioned here: it's important in these kinds of constructs to check in the right order. You will find that if you had swapped the order of the check in the above snippet, the code will still compile, but it will no longer work. That is the following code doesn't work:

 // DOESN'T WORK! Wrong order!
 if (x instanceof Collection<?>) {
    Collection<?> col = (Collection<?>) x;
    // do something with col
 } else if (x instanceof List<?>) { // this will never be reached!
    List<?> list = (List<?>) x;
    // do something with list
 }

The problem is that a List<?> is-a Collection<?>, so it will pass the first test, and the else means that it will never reach the second test. You have to test from the most specific to the most general type.

Is there a command to list all Unix group names?

If you want all groups known to the system, I would recommend using getent group instead of parsing /etc/group:

getent group

The reason is that on networked systems, groups may not only read from /etc/group file, but also obtained through LDAP or Yellow Pages (the list of known groups comes from the local group file plus groups received via LDAP or YP in these cases).

If you want just the group names you can use:

getent group | cut -d: -f1

replace String with another in java

There is a possibility not to use extra variables

String s = "HelloSuresh";
s = s.replace("Hello","");
System.out.println(s);

How do I combine two dataframes?

I believe you can use the append method

bigdata = data1.append(data2, ignore_index=True)

to keep their indexes just dont use the ignore_index keyword ...

Setting the value of checkbox to true or false with jQuery

You can do (jQuery 1.6 onwards):

$('#idCheckbox').prop('checked', true);
$('#idCheckbox').prop('checked', false);

to remove you can also use:

$('#idCheckbox').removeProp('checked');

with jQuery < 1.6 you must do

$('#idCheckbox').attr('checked', true);
$('#idCheckbox').removeAttr('checked');

How to echo xml file in php

This worked for me:

echo(header('content-type: text/xml'));

Update multiple rows with different values in a single SQL query

Use a comma ","

eg: 
UPDATE my_table SET rowOneValue = rowOneValue + 1, rowTwoValue  = rowTwoValue + ( (rowTwoValue / (rowTwoValue) ) + ?) * (v + 1) WHERE value = ?

Passing a varchar full of comma delimited values to a SQL Server IN function

I can suggest using WITH like this:

DECLARE @Delim char(1) = ',';
SET @Ids = @Ids + @Delim;

WITH CTE(i, ls, id) AS (
    SELECT 1, CHARINDEX(@Delim, @Ids, 1), SUBSTRING(@Ids, 1, CHARINDEX(@Delim, @Ids, 1) - 1)
    UNION ALL
    SELECT i + 1, CHARINDEX(@Delim, @Ids, ls + 1), SUBSTRING(@Ids, ls + 1, CHARINDEX(@Delim, @Ids, ls + 1) - CHARINDEX(@Delim, @Ids, ls) - 1)
    FROM CTE
    WHERE  CHARINDEX(@Delim, @Ids, ls + 1) > 1
)
SELECT t.*
FROM yourTable t
    INNER JOIN
    CTE c
    ON t.id = c.id;

How to change root logging level programmatically for logback

using logback 1.1.3 I had to do the following (Scala code):

import ch.qos.logback.classic.Logger
import org.slf4j.LoggerFactory    
...
val root: Logger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME).asInstanceOf[Logger]

Why call git branch --unset-upstream to fixup?

torek's answer is probably perfect, but I just wanted for the record to mention another case which is different than the one described in the original question but the same error may appear (as it may help others with similar problem):

I have created an empty (new) repo using git init --bare on one of my servers. Then I have git cloned it to a local workspace on my PC.

After committing a single version on the local repo I got that error after calling git status.

Following torek's answer, I understand that what happened is that the first commit on local working directory repo created "master" branch. But on the remote repo (on the server) there was never anything, so there was not even a "master" (remotes/origin/master) branch.

After running git push origin master from local repo the remote repo finally had a master branch. This stopped the error from appearing.

So to conclude - one may get such an error for a fresh new remote repo with zero commits since it has no branch, including "master".

how to increase MaxReceivedMessageSize when calling a WCF from C#

Change the customBinding in the web.config to use larger defaults. I picked 2MB as it is a reasonable size. Of course setting it to 2GB (as your code suggests) will work but it does leave you more vulnerable to attacks. Pick a size that is larger than your largest request but isn't overly large.

Check this : Using Large Message Requests in Silverlight with WCF

<system.serviceModel>
   <behaviors>
     <serviceBehaviors>
       <behavior name="TestLargeWCF.Web.MyServiceBehavior">
         <serviceMetadata httpGetEnabled="true"/>
         <serviceDebug includeExceptionDetailInFaults="false"/>
       </behavior>
     </serviceBehaviors>
   </behaviors>
   <bindings>
     <customBinding>
       <binding name="customBinding0">
         <binaryMessageEncoding />
         <!-- Start change -->
         <httpTransport maxReceivedMessageSize="2097152"
                        maxBufferSize="2097152"
                        maxBufferPoolSize="2097152"/>
         <!-- Stop change -->
       </binding>
     </customBinding>
   </bindings>
   <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
   <services>
     <service behaviorConfiguration="Web.MyServiceBehavior" name="TestLargeWCF.Web.MyService">
       <endpoint address=""
                binding="customBinding"
                bindingConfiguration="customBinding0"
                contract="TestLargeWCF.Web.MyService"/>
       <endpoint address="mex"
                binding="mexHttpBinding"
                contract="IMetadataExchange"/>
     </service>
   </services>
 </system.serviceModel> 

What is the best way to uninstall gems from a rails3 project?

I seemed to solve this by manually removing the unicorn gem via bundler ("sudo bundler exec gem uninstall unicorn"), then rebundling ("sudo bundle install").

Not sure why it happened though, although the above fix does seem to work.

How to rename with prefix/suffix?

In my case I have a group of files which needs to be renamed before I can work with them. Each file has its own role in group and has its own pattern.

As result I have a list of rename commands like this:

f=`ls *canctn[0-9]*`   ;  mv $f  CNLC.$f
f=`ls *acustb[0-9]*`   ;  mv $f  CATB.$f
f=`ls *accusgtb[0-9]*` ;  mv $f  CATB.$f
f=`ls *acus[0-9]*`     ;  mv $f  CAUS.$f

Try this also :

f=MyFileName; mv $f {pref1,pref2}$f{suf1,suf2}

This will produce all combinations with prefixes and suffixes:

pref1.MyFileName.suf1
...
pref2.MyFileName.suf2

Another way to solve same problem is to create mapping array and add corespondent prefix for each file type as shown below:

#!/bin/bash
unset masks
typeset -A masks
masks[ip[0-9]]=ip
masks[iaf_usg[0-9]]=ip_usg
masks[ipusg[0-9]]=ip_usg
...
for fileMask in ${!masks[*]}; 
do  
registryEntry="${masks[$fileMask]}";
fileName=*${fileMask}*
[ -e ${fileName} ] &&  mv ${fileName} ${registryEntry}.${fileName}  
done

Variable name as a string in Javascript

In ES6, you could write something like:

let myVar = 'something';
let nameObject = {myVar};
let getVarNameFromObject = (nameObject) => {
  for(let varName in nameObject) {
    return varName;
  }
}
let varName = getVarNameFromObject(nameObject);

Not really the best looking thing, but it gets the job done.

This leverages ES6's object destructuring.

More info here: https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/

how to add picasso library in android studio

easiest way to add dependence

hope this help you or Ctrl + Alt + Shift + S => select Dependencies tab and find what you need ( see my image)

What is *.o file?

A .o object file file (also .obj on Windows) contains compiled object code (that is, machine code produced by your C or C++ compiler), together with the names of the functions and other objects the file contains. Object files are processed by the linker to produce the final executable. If your build process has not produced these files, there is probably something wrong with your makefile/project files.

Change the background color of CardView programmatically

Simplest way for me is this one (Kotlin)

card_item.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#fc4041"))

Linux/Unix command to determine if process is running?

Just a minor addition: if you add the -c flag to ps, you don't need to remove the line containing the grep process with grep -v afterwards. I.e.

ps acux | grep cron

is all the typing you'll need on a bsd-ish system (this includes MacOSX) You can leave the -u away if you need less information.

On a system where the genetics of the native ps command point back to SysV, you'd use

ps -e |grep cron

or

ps -el |grep cron 

for a listing containing more than just pid and process name. Of course you could select the specific fields to print out using the -o <field,field,...> option.

How can I get the root domain URI in ASP.NET?

I know this is older but the correct way to do this now is

string Domain = HttpContext.Current.Request.Url.Authority

That will get the DNS or ip address with port for a server.

Safe width in pixels for printing web pages?

One solution to the problem that I found was to just set the width in inches. So far I've only tested/confirmed this working in Chrome. It worked well for what I was using it for (to print out an 8.5 x 11 sheet)

@media print {
    .printEl { 
        width: 8.5in;
        height: 11in;
    }
}

What are ODEX files in Android?

This Blog article explains the internals of ODEX files:

WHAT IS AN ODEX FILE?

In Android file system, applications come in packages with the extension .apk. These application packages, or APKs contain certain .odex files whose supposed function is to save space. These ‘odex’ files are actually collections of parts of an application that are optimized before booting. Doing so speeds up the boot process, as it preloads part of an application. On the other hand, it also makes hacking those applications difficult because a part of the coding has already been extracted to another location before execution.

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

I had the same issue.

I was adding items to my ArrayList outside the UI thread.

Solution: I have done both, adding the items and called notifyDataSetChanged() in the UI thread.

Dependency Injection vs Factory Pattern

Binoj,

I don't think you have to choose one over the other.

The act of moving a dependent class or interface to a class constructor or setter follows the DI pattern. The object you pass to the constructor or set can be implemented with Factory.

When to use? Use the pattern or patterns that are in your developer wheelhouse. What do they feel the most comfortable with and find easiest to understand.

Apache HttpClient Android (Gradle)

I don't know why but (for now) httpclient can be compiled only as a jar into the libs directory in your project. HttpCore works fine when it is included from mvn like that:

dependencies {
      compile 'org.apache.httpcomponents:httpcore:4.4.3'
}

How to apply Hovering on html area tag?

for complete this script , the function for draw circle ,

    function drawCircle(coordon)
    {
        var coord = coordon.split(',');

        var c = document.getElementById("myCanvas");
        var hdc = c.getContext("2d");
        hdc.beginPath();

        hdc.arc(coord[0], coord[1], coord[2], 0, 2 * Math.PI);
        hdc.stroke();
    }

PHP error: php_network_getaddresses: getaddrinfo failed: (while getting information from other site.)

I faced this issue, while connecting DB, the variable to connect to db was not defined.

Cause: php tried to connect to the db with undefined variable for db host (localhost/127.0.0.1/... any other ip or domain) but failed to trace the domain.

Solution: Make sure the db host is properly defined.