Programs & Examples On #Associations

Associations typically refer to relationships between models in ORMs such as ActiveRecord.

What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations?

In terms of coding, a bidirectional relationship is more complex to implement because the application is responsible for keeping both sides in synch according to JPA specification 5 (on page 42). Unfortunately the example given in the specification does not give more details, so it does not give an idea of the level of complexity.

When not using a second level cache it is usually not a problem to do not have the relationship methods correctly implemented because the instances get discarded at the end of the transaction.

When using second level cache, if anything gets corrupted because of wrongly implemented relationship handling methods, this means that other transactions will also see the corrupted elements (the second level cache is global).

A correctly implemented bi-directional relationship can make queries and the code simpler, but should not be used if it does not really make sense in terms of business logic.

What is the difference between association, aggregation and composition?

Problem with these answers is they are half the story: they explain that aggregation and composition are forms of association, but they don't say if it is possible for an association to be neither of those.

I gather based on some brief readings of many posts on SO and some UML docs that there are 4 main concrete forms of class association:

  1. composition: A is-composed-of-a B; B doesn't exist without A, like a room in a home
  2. aggregation: A has-a B; B can exist without A, like a student in a classroom
  3. dependency: A uses-a B; no lifecycle dependency between A and B, like a method call parameter, return value, or a temporary created during a method call
  4. generalization: A is-a B

When a relationship between two entities isn't one of these, it can just be called "an association" in the generic sense of the term, and further described other ways (note, stereotype, etc).

My guess is that the "generic association" is intended to be used primarily in two circumstances:

  • when the specifics of a relationship are still being worked out; such relationship in a diagram should be converted as soon as possible to what it actually is/will be (one of the other 4).
  • when a relationship doesn't match any of those 4 predetermined by UML; the "generic" association still gives you a way of representing a relationship that is "not one of the other ones", so that you aren't stuck using an incorrect relationship with a note "this is not actually aggregation, it's just that UML doesn't have any other symbol we could use"

Removing specific rows from a dataframe

One simple solution:

cond1 <- df$sub == 1 & df$day == 2

cond2 <- df$sub == 3 & df$day == 4

df <- df[!(cond1 | cond2),]

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

Java Spring - How to use classpath to specify a file location?

From an answer of @NimChimpsky in similar question:

Resource resource = new ClassPathResource("storedProcedures.sql");
InputStream resourceInputStream = resource.getInputStream();

Using ClassPathResource and interface Resource. And make sure you are adding the resources directory correctly (adding /src/main/resources/ into the classpath).

Note that Resource have a method to get a java.io.File so you can also use:

Resource resource = new ClassPathResource("storedProcedures.sql");
FileReader fr = new FileReader(resource.getFile());

Angular 2: Passing Data to Routes?

You can do this:

app-routing-modules.ts:

import { NgModule                  }    from '@angular/core';
import { RouterModule, Routes      }    from '@angular/router';
import { PowerBoosterComponent     }    from './component/power-booster.component';


export const routes: Routes = [
  { path:  'pipeexamples',component: PowerBoosterComponent, 
data:{  name:'shubham' } },
    ];
    @NgModule({
      imports: [ RouterModule.forRoot(routes) ],
      exports: [ RouterModule ]
    })
    export class AppRoutingModule {}

In this above route, I want to send data via a pipeexamples path to PowerBoosterComponent.So now I can receive this data in PowerBoosterComponent like this:

power-booster-component.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params, Data } from '@angular/router';

@Component({
  selector: 'power-booster',
  template: `
    <h2>Power Booster</h2>`
})

export class PowerBoosterComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private router: Router

  ) { }
  ngOnInit() {
    //this.route.snapshot.data['name']
    console.log("Data via params: ",this.route.snapshot.data['name']);
  }
}

So you can get the data by this.route.snapshot.data['name'].

How to force HTTPS using a web.config file

In .Net Core, follow the instructions at https://docs.microsoft.com/en-us/aspnet/core/security/enforcing-ssl

In your startup.cs add the following:

// Requires using Microsoft.AspNetCore.Mvc;
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<MvcOptions>(options =>
    {
        options.Filters.Add(new RequireHttpsAttribute());
    });`enter code here`

To redirect Http to Https, add the following in the startup.cs

// Requires using Microsoft.AspNetCore.Rewrite;
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    var options = new RewriteOptions()
       .AddRedirectToHttps();

    app.UseRewriter(options);

Unsupported operation :not writeable python

You open the variable "file" as a read only then attempt to write to it:

file = open('ValidEmails.txt','r')

Instead, use the 'w' flag.

file = open('ValidEmails.txt','w')
...
file.write(email)

How to declare string constants in JavaScript?

Standard freeze function of built-in Object can be used to freeze an object containing constants.

var obj = {
    constant_1 : 'value_1'
};
Object.freeze(obj);
obj.constant_1 = 'value_2';   //Silently does nothing
obj.constant_2 = 'value_3';   //Silently does nothing

In strict mode, setting values on immutable object throws TypeError. For more details, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

How to get the current user's Active Directory details in C#

Alan already gave you the right answer - use the sAMAccountName to filter your user.

I would add a recommendation on your use of DirectorySearcher - if you only want one or two pieces of information, add them into the "PropertiesToLoad" collection of the DirectorySearcher.

Instead of retrieving the whole big user object and then picking out one or two items, this will just return exactly those bits you need.

Sample:

adSearch.PropertiesToLoad.Add("sn");  // surname = last name
adSearch.PropertiesToLoad.Add("givenName");  // given (or first) name
adSearch.PropertiesToLoad.Add("mail");  // e-mail addresse
adSearch.PropertiesToLoad.Add("telephoneNumber");  // phone number

Those are just the usual AD/LDAP property names you need to specify.

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

import string 

sentence = "I     am having  a   very  nice  23!@$      day. "
# Remove all punctuations
sentence = sentence.translate(str.maketrans('', '', string.punctuation))
# Remove all numbers"
sentence = ''.join([word for word in sentence if not word.isdigit()])
count = 0;
for index in range(len(sentence)-1) :
    if sentence[index+1].isspace() and not sentence[index].isspace():
        count += 1 
print(count)

Is JVM ARGS '-Xms1024m -Xmx2048m' still useful in Java 8?

What I know is one reason when “GC overhead limit exceeded” error is thrown when 2% of the memory is freed after several GC cycles

By this error your JVM is signalling that your application is spending too much time in garbage collection. so the little amount GC was able to clean will be quickly filled again thus forcing GC to restart the cleaning process again.

You should try changing the value of -Xmx and -Xms.

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

Sort list in C# with LINQ

I assume that you want them sorted by something else also, to get a consistent ordering between all items where AVC is the same. For example by name:

var sortedList = list.OrderBy(x => c.AVC).ThenBy(x => x.Name).ToList();

Exception: There is already an open DataReader associated with this Connection which must be closed first

The issue you are running into is that you are starting up a second MySqlCommand while still reading back data with the DataReader. The MySQL connector only allows one concurrent query. You need to read the data into some structure, then close the reader, then process the data. Unfortunately you can't process the data as it is read if your processing involves further SQL queries.

Getting Http Status code number (200, 301, 404, etc.) from HttpWebRequest and HttpWebResponse

Just coerce the StatusCode to int.

var statusNumber;
try {
   response = (HttpWebResponse)request.GetResponse();
   // This will have statii from 200 to 30x
   statusNumber = (int)response.StatusCode;
}
catch (WebException we) {
    // Statii 400 to 50x will be here
    statusNumber = (int)we.Response.StatusCode;
}

Remove a specific character using awk or sed

tr can be more concise for removing characters than sed or awk, especially when you want to remove different characters from a string.

Removing double quotes:

echo '"Hi"' | tr -d \"
# Produces Hi without quotes

Removing different kinds of brackets:

echo '[{Hi}]' | tr -d {}[]
# Produces Hi without brackets

-d stands for "delete".

Insert null/empty value in sql datetime column by default

you can use like this:

string Log_In_Val = (Convert.ToString(attenObj.Log_In) == "" ? "Null" + "," : "'" + Convert.ToString(attenObj.Log_In) + "',");

How to add one day to a date?

best thing to use:

      long currenTime = System.currentTimeMillis();
      long oneHourLater = currentTime + TimeUnit.HOURS.toMillis(1l);

Similarly, you can add MONTHS, DAYS, MINUTES etc

Regex: Use start of line/end of line signs (^ or $) in different context

you just need to use word boundary (\b) instead of ^ and $:

\bgarp\b

Delaying AngularJS route change until model loaded to prevent flicker

$routeProvider resolve property allows delaying of route change until data is loaded.

First define a route with resolve attribute like this.

angular.module('phonecat', ['phonecatFilters', 'phonecatServices', 'phonecatDirectives']).
  config(['$routeProvider', function($routeProvider) {
    $routeProvider.
      when('/phones', {
        templateUrl: 'partials/phone-list.html', 
        controller: PhoneListCtrl, 
        resolve: PhoneListCtrl.resolve}).
      when('/phones/:phoneId', {
        templateUrl: 'partials/phone-detail.html', 
        controller: PhoneDetailCtrl, 
        resolve: PhoneDetailCtrl.resolve}).
      otherwise({redirectTo: '/phones'});
}]);

notice that the resolve property is defined on route.

function PhoneListCtrl($scope, phones) {
  $scope.phones = phones;
  $scope.orderProp = 'age';
}

PhoneListCtrl.resolve = {
  phones: function(Phone, $q) {
    // see: https://groups.google.com/forum/?fromgroups=#!topic/angular/DGf7yyD4Oc4
    var deferred = $q.defer();
    Phone.query(function(successData) {
            deferred.resolve(successData); 
    }, function(errorData) {
            deferred.reject(); // you could optionally pass error data here
    });
    return deferred.promise;
  },
  delay: function($q, $defer) {
    var delay = $q.defer();
    $defer(delay.resolve, 1000);
    return delay.promise;
  }
}

Notice that the controller definition contains a resolve object which declares things which should be available to the controller constructor. Here the phones is injected into the controller and it is defined in the resolve property.

The resolve.phones function is responsible for returning a promise. All of the promises are collected and the route change is delayed until after all of the promises are resolved.

Working demo: http://mhevery.github.com/angular-phonecat/app/#/phones Source: https://github.com/mhevery/angular-phonecat/commit/ba33d3ec2d01b70eb5d3d531619bf90153496831

How to use PHP to connect to sql server

enable mssql in php.ini

;extension=php_mssql.dll

to

extension=php_mssql.dll

Set max-height on inner div so scroll bars appear, but not on parent div

It might be easier to use JavaScript or jquery for this. Assuming that the height of the header and the footer is 200 then the code will be:

function SetHeight(){
    var h = $(window).height();
    $("#inner-right").height(h-200);    
}

$(document).ready(SetHeight);
$(window).resize(SetHeight);

AngularJS $watch window resize inside directive

You shouldn't need a $watch. Just bind to resize event on window:

DEMO

'use strict';

var app = angular.module('plunker', []);

app.directive('myDirective', ['$window', function ($window) {

     return {
        link: link,
        restrict: 'E',
        template: '<div>window size: {{width}}px</div>'
     };

     function link(scope, element, attrs){

       scope.width = $window.innerWidth;

       angular.element($window).bind('resize', function(){

         scope.width = $window.innerWidth;

         // manuall $digest required as resize event
         // is outside of angular
         scope.$digest();
       });

     }

 }]);

How do I prevent site scraping?

Sorry, it's really quite hard to do this...

I would suggest that you politely ask them to not use your content (if your content is copyrighted).

If it is and they don't take it down, then you can take furthur action and send them a cease and desist letter.

Generally, whatever you do to prevent scraping will probably end up with a more negative effect, e.g. accessibility, bots/spiders, etc.

How to add a class to body tag?

Use:

$(document.body).addClass('about');

File upload from <input type="file">

Another way using template reference variable and ViewChild, as proposed by Frelseren:

import { ViewChild } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input type="file" #fileInput/>
    </div>
  `
})  
export class AppComponent {
  @ViewChild("fileInput") fileInputVariable: any;
  randomMethod() {
    const files = this.fileInputVariable.nativeElement.files;
    console.log(files);
  }
}

Also see https://stackoverflow.com/a/40165524/4361955

Array of arrays (Python/NumPy)

You'll have problems creating lists without commas. It shouldn't be too hard to transform your data so that it uses commas as separating character.

Once you have commas in there, it's a relatively simple list creation operations:

array1 = [1,2,3]
array2 = [4,5,6]

array3 = [array1, array2]

array4 = [7,8,9]
array5 = [10,11,12]

array3 = [array3, [array4, array5]]

When testing we get:

print(array3)

[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]

And if we test with indexing it works correctly reading the matrix as made up of 2 rows and 2 columns:

array3[0][1]
[4, 5, 6]

array3[1][1]
[10, 11, 12]

Hope that helps.

Git adding files to repo

This is actually a multi-step process. First you'll need to add all your files to the current stage:

git add .

You can verify that your files will be added when you commit by checking the status of the current stage:

git status

The console should display a message that lists all of the files that are currently staged, like this:

# On branch master
#
# Initial commit
#
# Changes to be committed:
#   (use "git rm --cached <file>..." to unstage)
#
#   new file:   README
#   new file:   src/somefile.js
#

If it all looks good then you're ready to commit. Note that the commit action only commits to your local repository.

git commit -m "some message goes here"

If you haven't connected your local repository to a remote one yet, you'll have to do that now. Assuming your remote repository is hosted on GitHub and named "Some-Awesome-Project", your command is going to look something like this:

git remote add origin [email protected]:username/Some-Awesome-Project

It's a bit confusing, but by convention we refer to the remote repository as 'origin' and the initial local repository as 'master'. When you're ready to push your commits to the remote repository (origin), you'll need to use the 'push' command:

git push origin master

For more information check out the tutorial on GitHub: http://learn.github.com/p/intro.html

CSS last-child(-1)

Unless you can get PHP to label that element with a class you are better to use jQuery.

jQuery(document).ready(function () {
  $count =  jQuery("ul li").size() - 1;
  alert($count);
  jQuery("ul li:nth-child("+$count+")").css("color","red");
});

Windows could not start the Apache2 on Local Computer - problem

I've had this problem twice. The first problem was fixed using the marked answer on this page (thank you for that). However, the second time proved a bit more difficult.

I found that in my httpd-vhosts.conf file that I made a mistake when assigning the document root to a domain name. Fixing this solved my problem. It is well worth checking (or even reverting to a blank copy) your httpd-vhosts.conf file for any errors and typo's.

Slice indices must be integers or None or have __index__ method

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))

How to delete a file from SD card?

Change for Android 4.4+

Apps are not allowed to write (delete, modify ...) to external storage except to their package-specific directories.

As Android documentation states:

"Apps must not be allowed to write to secondary external storage devices, except in their package-specific directories as allowed by synthesized permissions."

However nasty workaround exists (see code below). Tested on Samsung Galaxy S4, but this fix does't work on all devices. Also I wouldn’t count on this workaround being available in future versions of Android.

There is a great article explaining (4.4+) external storage permissions change.

You can read more about workaround here. Workaround source code is from this site.

public class MediaFileFunctions 
{
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static boolean deleteViaContentProvider(Context context, String fullname) 
    { 
      Uri uri=getFileUri(context,fullname); 

      if (uri==null) 
      {
         return false;
      }

      try 
      { 
         ContentResolver resolver=context.getContentResolver(); 

         // change type to image, otherwise nothing will be deleted 
         ContentValues contentValues = new ContentValues(); 
         int media_type = 1; 
         contentValues.put("media_type", media_type); 
         resolver.update(uri, contentValues, null, null); 

         return resolver.delete(uri, null, null) > 0; 
      } 
      catch (Throwable e) 
      { 
         return false; 
      } 
   }

   @TargetApi(Build.VERSION_CODES.HONEYCOMB)
   private static Uri getFileUri(Context context, String fullname) 
   {
      // Note: check outside this class whether the OS version is >= 11 
      Uri uri = null; 
      Cursor cursor = null; 
      ContentResolver contentResolver = null;

      try
      { 
         contentResolver=context.getContentResolver(); 
         if (contentResolver == null)
            return null;

         uri=MediaStore.Files.getContentUri("external"); 
         String[] projection = new String[2]; 
         projection[0] = "_id"; 
         projection[1] = "_data"; 
         String selection = "_data = ? ";    // this avoids SQL injection 
         String[] selectionParams = new String[1]; 
         selectionParams[0] = fullname; 
         String sortOrder = "_id"; 
         cursor=contentResolver.query(uri, projection, selection, selectionParams, sortOrder); 

         if (cursor!=null) 
         { 
            try 
            { 
               if (cursor.getCount() > 0) // file present! 
               {   
                  cursor.moveToFirst(); 
                  int dataColumn=cursor.getColumnIndex("_data"); 
                  String s = cursor.getString(dataColumn); 
                  if (!s.equals(fullname)) 
                     return null; 
                  int idColumn = cursor.getColumnIndex("_id"); 
                  long id = cursor.getLong(idColumn); 
                  uri= MediaStore.Files.getContentUri("external",id); 
               } 
               else // file isn't in the media database! 
               {   
                  ContentValues contentValues=new ContentValues(); 
                  contentValues.put("_data",fullname); 
                  uri = MediaStore.Files.getContentUri("external"); 
                  uri = contentResolver.insert(uri,contentValues); 
               } 
            } 
            catch (Throwable e) 
            { 
               uri = null; 
            }
            finally
            {
                cursor.close();
            }
         } 
      } 
      catch (Throwable e) 
      { 
         uri=null; 
      } 
      return uri; 
   } 
}

How to install pip for Python 3 on Mac OS X?

I had the same problem with python3 and pip3. Decision: solving all conflicts with links and other stuff when do

brew doctor

After that

brew reinstall python3

PHP Get all subdirectories of a given directory

Find all PHP files recursively. The logic should be simple enough to tweak and it aims to be fast(er) by avoiding function calls.

function get_all_php_files($directory) {
    $directory_stack = array($directory);
    $ignored_filename = array(
        '.git' => true,
        '.svn' => true,
        '.hg' => true,
        'index.php' => true,
    );
    $file_list = array();
    while ($directory_stack) {
        $current_directory = array_shift($directory_stack);
        $files = scandir($current_directory);
        foreach ($files as $filename) {
            //  Skip all files/directories with:
            //      - A starting '.'
            //      - A starting '_'
            //      - Ignore 'index.php' files
            $pathname = $current_directory . DIRECTORY_SEPARATOR . $filename;
            if (isset($filename[0]) && (
                $filename[0] === '.' ||
                $filename[0] === '_' ||
                isset($ignored_filename[$filename])
            )) 
            {
                continue;
            }
            else if (is_dir($pathname) === TRUE) {
                $directory_stack[] = $pathname;
            } else if (pathinfo($pathname, PATHINFO_EXTENSION) === 'php') {
                $file_list[] = $pathname;
            }
        }
    }
    return $file_list;
}

Downloading all maven dependencies to a directory NOT in repository?

I found the next command

mvn dependency:copy-dependencies -Dclassifier=sources

here maven.apache.org

Delete all files in directory (but not directory) - one liner solution

package com;
import java.io.File;
public class Delete {
    public static void main(String[] args) {

        String files; 
        File file = new File("D:\\del\\yc\\gh");
        File[] listOfFiles = file.listFiles(); 
        for (int i = 0; i < listOfFiles.length; i++) 
        {
            if (listOfFiles[i].isFile()) 
            {
                files = listOfFiles[i].getName();
                System.out.println(files);
                if(!files.equalsIgnoreCase("Scan.pdf"))
                {
                    boolean issuccess=new File(listOfFiles[i].toString()).delete();
                    System.err.println("Deletion Success "+issuccess);
                }
            }
        }
    }
}

If you want to delete all files remove

if(!files.equalsIgnoreCase("Scan.pdf"))

statement it will work.

AttributeError: 'list' object has no attribute 'encode'

You need to unicode each element of the list individually

[x.encode('utf-8') for x in tmp]

How to call a Python function from Node.js

You can now use RPC libraries that support Python and Javascript such as zerorpc

From their front page:

Node.js Client

var zerorpc = require("zerorpc");

var client = new zerorpc.Client();
client.connect("tcp://127.0.0.1:4242");

client.invoke("hello", "RPC", function(error, res, more) {
    console.log(res);
});

Python Server

import zerorpc

class HelloRPC(object):
    def hello(self, name):
        return "Hello, %s" % name

s = zerorpc.Server(HelloRPC())
s.bind("tcp://0.0.0.0:4242")
s.run()

Make Https call using HttpClient

I had the same problem when connecting to GitHub, which requires a user agent. Thus it is sufficient to provide this rather than generating a certificate

var client = new HttpClient();

client.BaseAddress = new Uri("https://api.github.com");
client.DefaultRequestHeaders.Add(
    "Authorization",
    "token 123456789307d8c1d138ddb0848ede028ed30567");
client.DefaultRequestHeaders.Accept.Add(
    new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add(
    "User-Agent",
    "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");

How to simulate a click by using x,y coordinates in JavaScript?

This is just torazaburo's answer, updated to use a MouseEvent object.

function click(x, y)
{
    var ev = new MouseEvent('click', {
        'view': window,
        'bubbles': true,
        'cancelable': true,
        'screenX': x,
        'screenY': y
    });

    var el = document.elementFromPoint(x, y);

    el.dispatchEvent(ev);
}

Granting DBA privileges to user in Oracle

You need only to write:

GRANT DBA TO NewDBA;

Because this already makes the user a DB Administrator

Installing a pip package from within a Jupyter Notebook not working

! pip install --user <package>

The ! tells the notebook to execute the cell as a shell command.

How can I search (case-insensitive) in a column using LIKE wildcard?

I think this query will do a case insensitive search:

SELECT * FROM trees WHERE trees.`title` ILIKE '%elm%';

Is there a difference between "==" and "is"?

What's the difference between is and ==?

== and is are different comparison! As others already said:

  • == compares the values of the objects.
  • is compares the references of the objects.

In Python names refer to objects, for example in this case value1 and value2 refer to an int instance storing the value 1000:

value1 = 1000
value2 = value1

enter image description here

Because value2 refers to the same object is and == will give True:

>>> value1 == value2
True
>>> value1 is value2
True

In the following example the names value1 and value2 refer to different int instances, even if both store the same integer:

>>> value1 = 1000
>>> value2 = 1000

enter image description here

Because the same value (integer) is stored == will be True, that's why it's often called "value comparison". However is will return False because these are different objects:

>>> value1 == value2
True
>>> value1 is value2
False

When to use which?

Generally is is a much faster comparison. That's why CPython caches (or maybe reuses would be the better term) certain objects like small integers, some strings, etc. But this should be treated as implementation detail that could (even if unlikely) change at any point without warning.

You should only use is if you:

  • want to check if two objects are really the same object (not just the same "value"). One example can be if you use a singleton object as constant.

  • want to compare a value to a Python constant. The constants in Python are:

    • None
    • True1
    • False1
    • NotImplemented
    • Ellipsis
    • __debug__
    • classes (for example int is int or int is float)
    • there could be additional constants in built-in modules or 3rd party modules. For example np.ma.masked from the NumPy module)

In every other case you should use == to check for equality.

Can I customize the behavior?

There is some aspect to == that hasn't been mentioned already in the other answers: It's part of Pythons "Data model". That means its behavior can be customized using the __eq__ method. For example:

class MyClass(object):
    def __init__(self, val):
        self._value = val

    def __eq__(self, other):
        print('__eq__ method called')
        try:
            return self._value == other._value
        except AttributeError:
            raise TypeError('Cannot compare {0} to objects of type {1}'
                            .format(type(self), type(other)))

This is just an artificial example to illustrate that the method is really called:

>>> MyClass(10) == MyClass(10)
__eq__ method called
True

Note that by default (if no other implementation of __eq__ can be found in the class or the superclasses) __eq__ uses is:

class AClass(object):
    def __init__(self, value):
        self._value = value

>>> a = AClass(10)
>>> b = AClass(10)
>>> a == b
False
>>> a == a

So it's actually important to implement __eq__ if you want "more" than just reference-comparison for custom classes!

On the other hand you cannot customize is checks. It will always compare just if you have the same reference.

Will these comparisons always return a boolean?

Because __eq__ can be re-implemented or overridden, it's not limited to return True or False. It could return anything (but in most cases it should return a boolean!).

For example with NumPy arrays the == will return an array:

>>> import numpy as np
>>> np.arange(10) == 2
array([False, False,  True, False, False, False, False, False, False, False], dtype=bool)

But is checks will always return True or False!


1 As Aaron Hall mentioned in the comments:

Generally you shouldn't do any is True or is False checks because one normally uses these "checks" in a context that implicitly converts the condition to a boolean (for example in an if statement). So doing the is True comparison and the implicit boolean cast is doing more work than just doing the boolean cast - and you limit yourself to booleans (which isn't considered pythonic).

Like PEP8 mentions:

Don't compare boolean values to True or False using ==.

Yes:   if greeting:
No:    if greeting == True:
Worse: if greeting is True:

How do I find the number of arguments passed to a Bash script?

Below is the easy one -

cat countvariable.sh

echo "$@" |awk '{for(i=0;i<=NF;i++); print i-1 }'

Output :

#./countvariable.sh 1 2 3 4 5 6
6
#./countvariable.sh 1 2 3 4 5 6 apple orange
8

How to check version of a CocoaPods framework

[CocoaPods]

Cocoapods version

CocoaPods program that is built with Ruby and it will be installable with the default Ruby available on macOS.

pod --version //1.8.0.beta.2
//or
gem which cocoapods //Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.0.beta.2/lib/cocoapods.rb

//install or update
sudo gem install cocoapods

A pod version

Version of pods that is specified in Podfile

Podfile.lock

It is located in the same folder as Podfile. Here you can find a version of a pod which is used

Search for pods

If you are interested in all available version of specific pod you can use

pod search <pod_name>
//or
pod trunk info <pod_name>

Set a pod version in Podfile

//specific version
pod '<framework_name>', "<semantic_versioning>"
// for example
pod 'MyFramework', "1.0"

How can I disable ARC for a single file in a project?

GO to App -> then Targets -> Build Phases -> Compile Source

Now, Select the file in which you want to disable ARC

paste this snippet "-fno-objc-arc" After pasting press ENTER

in each file where you want to disable ARC.

Convert multiple rows into one with comma as separator

A clean and flexible solution in MS SQL Server 2005/2008 is to create a CLR Agregate function.

You'll find quite a few articles (with code) on google.

It looks like this article walks you through the whole process using C#.

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

Your email session should be provided an authenticator instance as below

Session session = Session.getDefaultInstance(props,
    new Authenticator() {
        protected PasswordAuthentication  getPasswordAuthentication() {
        return new PasswordAuthentication(
                    "[email protected]", "password");
                }
    });

a complete example is here http://bharatonjava.wordpress.com/2012/08/27/sending-email-using-java-mail-api/

Shift column in pandas dataframe up by one?

In [44]: df['gdp'] = df['gdp'].shift(-1)

In [45]: df
Out[45]: 
   y  gdp  cap
0  1    3    5
1  2    7    9
2  8    4    2
3  3    7    7
4  6  NaN    7

In [46]: df[:-1]                                                                                                                                                                                                                                                                                                               
Out[46]: 
   y  gdp  cap
0  1    3    5
1  2    7    9
2  8    4    2
3  3    7    7

Error message: "'chromedriver' executable needs to be available in the path"

For Linux and OSX

Step 1: Download chromedriver

# You can find more recent/older versions at http://chromedriver.storage.googleapis.com/
# Also make sure to pick the right driver, based on your Operating System
wget http://chromedriver.storage.googleapis.com/81.0.4044.69/chromedriver_mac64.zip

For debian: wget https://chromedriver.storage.googleapis.com/2.41/chromedriver_linux64.zip

Step 2: Add chromedriver to /usr/local/bin

unzip chromedriver_mac64.zip
sudo mv chromedriver /usr/local/bin
sudo chown root:root /usr/local/bin/chromedriver
sudo chmod +x /usr/local/bin/chromedriver

You should now be able to run

from selenium import webdriver

browser = webdriver.Chrome()
browser.get('http://localhost:8000')

without any issues

What is the difference between null and System.DBNull.Value?

Well, null is not an instance of any type. Rather, it is an invalid reference.

However, System.DbNull.Value, is a valid reference to an instance of System.DbNull (System.DbNull is a singleton and System.DbNull.Value gives you a reference to the single instance of that class) that represents nonexistent* values in the database.

*We would normally say null, but I don't want to confound the issue.

So, there's a big conceptual difference between the two. The keyword null represents an invalid reference. The class System.DbNull represents a nonexistent value in a database field. In general, we should try avoid using the same thing (in this case null) to represent two very different concepts (in this case an invalid reference versus a nonexistent value in a database field).

Keep in mind, this is why a lot of people advocate using the null object pattern in general, which is exactly what System.DbNull is an example of.

How to pass parameter to function using in addEventListener?

No need to pass anything in. The function used for addEventListener will automatically have this bound to the current element. Simply use this in your function:

productLineSelect.addEventListener('change', getSelection, false);

function getSelection() {
    var value = this.options[this.selectedIndex].value;
    alert(value);
}

Here's the fiddle: http://jsfiddle.net/dJ4Wm/


If you want to pass arbitrary data to the function, wrap it in your own anonymous function call:

productLineSelect.addEventListener('change', function() {
    foo('bar');
}, false);

function foo(message) {
    alert(message);
}

Here's the fiddle: http://jsfiddle.net/t4Gun/


If you want to set the value of this manually, you can use the call method to call the function:

var self = this;
productLineSelect.addEventListener('change', function() {
    getSelection.call(self);
    // This'll set the `this` value inside of `getSelection` to `self`
}, false);

function getSelection() {
    var value = this.options[this.selectedIndex].value;
    alert(value);
}

How to get selected value from Dropdown list in JavaScript

I would say change var sv = sel.options[sel.selectedIndex].value; to var sv = sel.options[sel.selectedIndex].text;

It worked for me. Directing you to where I found my solution Getting the selected value dropdown jstl

Simple argparse example wanted: 1 argument, 3 results

Matt is asking about positional parameters in argparse, and I agree that the Python documentation is lacking on this aspect. There's not a single, complete example in the ~20 odd pages that shows both parsing and using positional parameters.

None of the other answers here show a complete example of positional parameters, either, so here's a complete example:

# tested with python 2.7.1
import argparse

parser = argparse.ArgumentParser(description="An argparse example")

parser.add_argument('action', help='The action to take (e.g. install, remove, etc.)')
parser.add_argument('foo-bar', help='Hyphens are cumbersome in positional arguments')

args = parser.parse_args()

if args.action == "install":
    print("You asked for installation")
else:
    print("You asked for something other than installation")

# The following do not work:
# print(args.foo-bar)
# print(args.foo_bar)

# But this works:
print(getattr(args, 'foo-bar'))

The thing that threw me off is that argparse will convert the named argument "--foo-bar" into "foo_bar", but a positional parameter named "foo-bar" stays as "foo-bar", making it less obvious how to use it in your program.

Notice the two lines near the end of my example -- neither of those will work to get the value of the foo-bar positional param. The first one is obviously wrong (it's an arithmetic expression args.foo minus bar), but the second one doesn't work either:

AttributeError: 'Namespace' object has no attribute 'foo_bar'

If you want to use the foo-bar attribute, you must use getattr, as seen in the last line of my example. What's crazy is that if you tried to use dest=foo_bar to change the property name to something that's easier to access, you'd get a really bizarre error message:

ValueError: dest supplied twice for positional argument

Here's how the example above runs:

$ python test.py
usage: test.py [-h] action foo-bar
test.py: error: too few arguments

$ python test.py -h
usage: test.py [-h] action foo-bar

An argparse example

positional arguments:
  action      The action to take (e.g. install, remove, etc.)
  foo-bar     Hyphens are cumbersome in positional arguments

optional arguments:
  -h, --help  show this help message and exit

$ python test.py install foo
You asked for installation
foo

How do you store Java objects in HttpSession?

Here you can do it by using HttpRequest or HttpSession. And think your problem is within the JSP.

If you are going to use the inside servlet do following,

Object obj = new Object();
session.setAttribute("object", obj);

or

HttpSession session = request.getSession();
Object obj = new Object();
session.setAttribute("object", obj);

and after setting your attribute by using request or session, use following to access it in the JSP,

<%= request.getAttribute("object")%>

or

<%= session.getAttribute("object")%>

So seems your problem is in the JSP.

If you want use scriptlets it should be as follows,

<%
Object obj = request.getSession().getAttribute("object");
out.print(obj);
%>

Or can use expressions as follows,

<%= session.getAttribute("object")%>

or can use EL as follows, ${object} or ${sessionScope.object}

How can I beautify JSON programmatically?

Programmatic formatting solution:

The JSON.stringify method supported by many modern browsers (including IE8) can output a beautified JSON string:

JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4);    // stringify with 4 spaces at each level
Demo: http://jsfiddle.net/AndyE/HZPVL/

This method is also included with json2.js, for supporting older browsers.

Manual formatting solution

If you don't need to do it programmatically, Try JSON Lint. Not only will it prettify your JSON, it will validate it at the same time.

How can I see the current value of my $PATH variable on OS X?

Use the command:

 echo $PATH

and you will see all path:

/Users/name/.rvm/gems/ruby-2.5.1@pe/bin:/Users/name/.rvm/gems/ruby-2.5.1@global/bin:/Users/sasha/.rvm/rubies/ruby-2.5.1/bin:/Users/sasha/.rvm/bin:

How can I declare and define multiple variables in one line using C++?

As of C++17, you can use Structured Bindings:

#include <iostream>
#include <tuple>

int main () 
{
    auto [hello, world] = std::make_tuple("Hello ", "world!");
    std::cout << hello << world << std::endl;
    return 0;
}

Demo

Best way to log POST data in Apache?

An easier option may be to log the POST data before it gets to the server. For web applications, I use Burp Proxy and set Firefox to use it as an HTTP/S proxy, and then I can watch (and mangle) data 'on the wire' in real time.

For making API requests without a browser, SoapUI is very useful and may show similar info. I would bet that you could probably configure SoapUI to connect through Burp as well (just a guess though).

How to get std::vector pointer to the raw data?

Take a pointer to the first element instead:

process_data (&something [0]);

Difference between Role and GrantedAuthority in Spring Security

AFAIK GrantedAuthority and roles are same in spring security. GrantedAuthority's getAuthority() string is the role (as per default implementation SimpleGrantedAuthority).

For your case may be you can use Hierarchical Roles

<bean id="roleVoter" class="org.springframework.security.access.vote.RoleHierarchyVoter">
    <constructor-arg ref="roleHierarchy" />
</bean>
<bean id="roleHierarchy"
        class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
    <property name="hierarchy">
        <value>
            ROLE_ADMIN > ROLE_createSubUsers
            ROLE_ADMIN > ROLE_deleteAccounts 
            ROLE_USER > ROLE_viewAccounts
        </value>
    </property>
</bean>

Not the exact sol you looking for, but hope it helps

Edit: Reply to your comment

Role is like a permission in spring-security. using intercept-url with hasRole provides a very fine grained control of what operation is allowed for which role/permission.

The way we handle in our application is, we define permission (i.e. role) for each operation (or rest url) for e.g. view_account, delete_account, add_account etc. Then we create logical profiles for each user like admin, guest_user, normal_user. The profiles are just logical grouping of permissions, independent of spring-security. When a new user is added, a profile is assigned to it (having all permissible permissions). Now when ever user try to perform some action, permission/role for that action is checked against user grantedAuthorities.

Also the defaultn RoleVoter uses prefix ROLE_, so any authority starting with ROLE_ is considered as role, you can change this default behavior by using a custom RolePrefix in role voter and using it in spring security.

JPA or JDBC, how are they different?

JDBC is a much lower-level (and older) specification than JPA. In it's bare essentials, JDBC is an API for interacting with a database using pure SQL - sending queries and retrieving results. It has no notion of objects or hierarchies. When using JDBC, it's up to you to translate a result set (essentially a row/column matrix of values from one or more database tables, returned by your SQL query) into Java objects.

Now, to understand and use JDBC it's essential that you have some understanding and working knowledge of SQL. With that also comes a required insight into what a relational database is, how you work with it and concepts such as tables, columns, keys and relationships. Unless you have at least a basic understanding of databases, SQL and data modelling you will not be able to make much use of JDBC since it's really only a thin abstraction on top of these things.

Error: Argument is not a function, got undefined

I got sane error with LoginController, which I used in main index.html. I found two ways to resolve:

  1. setting $controllerProvider.allowGlobals(), I found that comment in Angular change-list "this option might be handy for migrating old apps, but please don't use it in new ones!" original comment on Angular

    app.config(['$controllerProvider', function($controllerProvider) { $controllerProvider.allowGlobals(); }]);

  2. wrong contructor of registering controller

before

LoginController.$inject = ['$rootScope', '$scope', '$location'];

now

app.controller('LoginController', ['$rootScope', '$scope', '$location', LoginController]);

'app' come from app.js

var MyApp = {};
var app = angular.module('MyApp ', ['app.services']);
var services = angular.module('app.services', ['ngResource', 'ngCookies', 'ngAnimate', 'ngRoute']);

What does it mean when a PostgreSQL process is "idle in transaction"?

As mentioned here: Re: BUG #4243: Idle in transaction it is probably best to check your pg_locks table to see what is being locked and that might give you a better clue where the problem lies.

SQL Server: the maximum number of rows in table

It's hard to give a generic answer to this. It really depends on number of factors:

  • what size your row is
  • what kind of data you store (strings, blobs, numbers)
  • what do you do with your data (just keep it as archive, query it regularly)
  • do you have indexes on your table - how many
  • what's your server specs

etc.

As answered elsewhere here, 100,000 a day and thus per table is overkill - I'd suggest monthly or weekly perhaps even quarterly. The more tables you have the bigger maintenance/query nightmare it will become.

What's the difference between @Component, @Repository & @Service annotations in Spring?

Annotate other components with @Component, for example REST Resource classes.

@Component
public class AdressComp{
    .......
    ...//some code here    
}

@Component is a generic stereotype for any Spring managed component.

@Controller, @Service and @Repository are Specializations of @Component for specific use cases.

@Component in Spring

"Component Specialization"

How can I update the current line in a C# Windows Console App?

i was looking for same solution in vb.net and i found this one and it's great.

however as @JohnOdom suggested a better way to handle the blanks space if previous one is larger than current one..

i make a function in vb.net and thought someone could get helped ..

here is my code:

Private Sub sPrintStatus(strTextToPrint As String, Optional boolIsNewLine As Boolean = False)
    REM intLastLength is declared as public variable on global scope like below
    REM intLastLength As Integer
    If boolIsNewLine = True Then
        intLastLength = 0
    End If
    If intLastLength > strTextToPrint.Length Then
        Console.Write(Convert.ToChar(13) & strTextToPrint.PadRight(strTextToPrint.Length + (intLastLength - strTextToPrint.Length), Convert.ToChar(" ")))
    Else
        Console.Write(Convert.ToChar(13) & strTextToPrint)
    End If
    intLastLength = strTextToPrint.Length
End Sub

Create whole path automatically when writing to a new file

Use FileUtils to handle all these headaches.

Edit: For example, use below code to write to a file, this method will 'checking and creating the parent directory if it does not exist'.

openOutputStream(File file [, boolean append]) 

Call a React component method from outside

With React17 you can use useImperativeHandle hook.

useImperativeHandle customizes the instance value that is exposed to parent components when using ref. As always, imperative code using refs should be avoided in most cases. useImperativeHandle should be used with forwardRef:

function FancyInput(props, ref) {
    const inputRef = useRef();
    useImperativeHandle(ref, () => ({
        focus: () => {
            inputRef.current.focus();
        }
    }));

    return <input ref={inputRef} ... />;
}

FancyInput = forwardRef(FancyInput);

In this example, a parent component that renders would be able to call inputRef.current.focus().

How to select from subquery using Laravel Query Builder?

I like doing something like this:

Message::select('*')
->from(DB::raw("( SELECT * FROM `messages`
                  WHERE `to_id` = ".Auth::id()." AND `isseen` = 0
                  GROUP BY `from_id` asc) as `sub`"))
->count();

It's not very elegant, but it's simple.

Restart android machine

adb reboot should not reboot your linux box.

But in any case, you can redirect the command to a specific adb device using adb -s <device_id> command , where

Device ID can be obtained from the command adb devices
command in this case is reboot

Tuples( or arrays ) as Dictionary keys in C#

The good, clean, fast, easy and readable ways is:

  • generate equality members (Equals() and GetHashCode()) method for the current type. Tools like ReSharper not only creates the methods, but also generates the necessary code for an equality check and/or for calculating hash code. The generated code will be more optimal than Tuple realization.
  • just make a simple key class derived from a tuple.

add something similar like this:

public sealed class myKey : Tuple<TypeA, TypeB, TypeC>
{
    public myKey(TypeA dataA, TypeB dataB, TypeC dataC) : base (dataA, dataB, dataC) { }

    public TypeA DataA => Item1; 

    public TypeB DataB => Item2;

    public TypeC DataC => Item3;
}

So you can use it with dictionary:

var myDictinaryData = new Dictionary<myKey, string>()
{
    {new myKey(1, 2, 3), "data123"},
    {new myKey(4, 5, 6), "data456"},
    {new myKey(7, 8, 9), "data789"}
};
  • You also can use it in contracts
  • as a key for join or groupings in linq
  • going this way you never ever mistype order of Item1, Item2, Item3 ...
  • you no need to remember or look into to code to understand where to go to get something
  • no need to override IStructuralEquatable, IStructuralComparable, IComparable, ITuple they all alredy here

Could not execute menu item (internal error)[Exception] - When changing PHP version from 5.3.1 to 5.2.9

  1. Like you installed older version of PHP do the same with Apache. I picked version 2.0.63 and then I was able to run WAMP Server with PHP 5.2.9 with no problems.

  2. I also read that it's problem with 64-bit version of WAMP.

How to call a REST web service API from JavaScript?

I think add if (this.readyState == 4 && this.status == 200) to wait is better:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // Typical action to be performed when the document is ready:
        var response = xhttp.responseText;
        console.log("ok"+response);
    }
};
xhttp.open("GET", "your url", true);

xhttp.send();

How to move the cursor word by word in the OS X Terminal

If you check Use option as meta key in the keyboard tab of the preferences, then the default emacs style commands for forward- and backward-word and ?F (Alt+F) and ?B (Alt+B) respectively.

I'd recommend reading From Bash to Z-Shell. If you want to increase your bash/zsh prowess!

How to initialize var?

Well, I think you can assign it to a new object. Something like:

var v = new object();

How to call gesture tap on UIView programmatically in swift

I worked out on Xcode 6.4 on swift. See below.

var view1: UIView!

func assignTapToView1() {          
  let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap"))
  //  tap.delegate = self
  view1.addGestureRecognizer(tap)
  self.view .addSubview(view1)

...
}

func handleTap() {
 print("tap working")
 view1.removeFromSuperview()
 // view1.alpha = 0.1
}

Error: Cannot find module 'ejs'

Reinstalling npm, express and ejs fixed my problem

This one worked for me,

  1. On your terminal or cmd -> Go to your apps directory,
  2. cd pathtoyourapp/AppName
  3. rerun your 'npm install'
  4. rerun your 'npm install express'
  5. rerun your 'npm install ejs'

after that, the error was fixed.

Excel to CSV with UTF8 encoding

What about using Powershell.

Get-Content 'C:\my.csv' | Out-File 'C:\my_utf8.csv' -Encoding UTF8

BOOLEAN or TINYINT confusion

The numeric type overview for MySQL states: BOOL, BOOLEAN: These types are synonyms for TINYINT(1). A value of zero is considered false. Nonzero values are considered true.

See here: https://dev.mysql.com/doc/refman/5.7/en/numeric-type-overview.html

Remove or adapt border of frame of legend using matplotlib

One more related question, since it took me forever to find the answer:

How to make the legend background blank (i.e. transparent, not white):

legend = plt.legend()
legend.get_frame().set_facecolor('none')

Warning, you want 'none' (the string). None means the default color instead.

Remove multiple items from a Python list in just one statement

You Can use this -

Suppose we have a list, l = [1,2,3,4,5]

We want to delete last two items in a single statement

del l[3:]

We have output:

l = [1,2,3]

Keep it Simple

Validating Phone Numbers Using Javascript

<!DOCTYPE html>
<html>
    <head>
        <style>
           .container__1{
               max-width: 450px;
               font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
           }
           .container__1 label{
               display: block;
               margin-bottom: 10px;
           }
           .container__1 label > span{
               float: left;
               width: 100px;
               color: #F072A9;
               font-weight: bold;
               font-size: 13px;
               text-shadow: 1px 1px 1px #fff;
           }
           .container__1 fieldset{
               border-radius: 10px;
               -webkit-border-radious:10px;
               -moz-border-radoius: 10px;
               margin: 0px 0px 0px 0px;
               border: 1px solid #FFD2D2;
               padding: 20px;
               background:#FFF4F4 ;
               box-shadow: inset 0px 0px 15px #FFE5E5;


           }
           .container__1 fieldset legend{
               color: #FFA0C9;
               border-top: 1px solid #FFD2D2 ;
               border-left: 1px solid #FFD2D2 ;
               border-right: 1px solid #FFD2D2 ;
               border-radius: 5px 5px 0px 0px;
               background: #FFF4F4;
               padding: 0px 8px 3px 8px;
               box-shadow: -0px -1px 2px #F1F1F1;
               font-weight: normal;
               font-size: 12px;
           }
           .container__1 textarea{
               width: 250px;
               height: 100px;
           }.container__1 input[type=text],
           .container__1 input[type=email],
           .container__1 select{
               border-radius: 3px;
               border: 1px solid #FFC2DC;
               outline: none;
               color: #F072A9;
               padding: 5px 8px 5px 8px;
               box-shadow: inset 1px 1px 4px #FFD5E7;
               background: #FFEFF6;
               

           }
           .container__1 input[type=submit],
           .container__1 input[type=button]{
               background: #EB3B88;
               border: 1px solid #C94A81;
               padding: 5px 15px 5px 15px;
               color: #FFCBE2;
               box-shadow: inset -1px -1px 3px #FF62A7;
               border-radius: 3px;
               font-weight: bold;
           }
           .required{
               color: red;
           }
        </style>
    </head>
    <body>
        <div class="container__1">
            <form name="RegisterForm" onsubmit="return(SubmitClick())">
                <fieldset>
                    <legend>Personal</legend>
                    <label for="field1"><span >Name<span class="required">*</span><input id="name" type="text" class="input-field" name="Name" value=""</label>
                    <label for="field2"><span >Email<span class="required">*</span><input placeholder="Ex: [email protected]" id="email" type="email" class="input-field" name="Email" value=""</label>
                    <label for="field3"><span >Phone<span class="required">*</span><input placeholder="+919853004369" id="mobile" type="text" class="input-field" name="Mobile" value=""</label>
                    <label for="field4">
                        <span>Subject</span>
                        <select name="subject" id="subject" class="select-field">
                            <option value="none">Choose Your Sub..</option>
                            <option value="Appointment">Appiontment</option>
                            <option value="Interview">Interview</option>
                            <option value="Regarding a post">Regarding a post</option>
                        </select>
                    </label>
                    <label><span></span><input type="submit"  ></label>
                </fieldset>
            </form>
        </div>
    </body>
    <script>
        function SubmitClick(){
        _name = document.querySelector('#name').value;
        _email = document.querySelector('#email').value;
        _mobile = document.querySelector('#mobile').value;
        _subject = document.querySelector('#subject').value;
          if(_name == '' || _name == null ){
              alert('Enter Your Name');
              document.RegisterForm.Name.focus();
              return false; 
          } 
          var atPos = _email.indexOf('@');
         var dotPos = _email.lastIndexOf('.');

          if(_email == '' || atPos<1 || (dotPos - atPos)<2){
              alert('Provide Your Correct Email address');
              document.RegisterForm.Email.focus();
              return false;
          }
          var regExp = /^\+91[0-9]{10}$/;
          if(_mobile == '' || !regExp.test(_mobile)){
              alert('Please Provide your Mobile number as Ex:- +919853004369');
              document.RegisterForm.Mobile.focus();
              return false;
          }
          if(_subject == 'none'){
              alert('Please choose a subject');
              document.RegisterForm.subject.focus();
              return false;
          }else{
            alert (`success!!!:--'\n'Name:${_name},'\n' Mobile: ${_mobile},'\n' Email:${_email},'\n' Subject:${_subject},`)
          }
        
          
        }
    </script>
</html>

Convert data.frame column to a vector?

as.vector(unlist(aframe['a2']))

IntelliJ IDEA JDK configuration on Mac OS

On Mac IntelliJ Idea 12 has it's preferences/keymaps placed here: ./Users/viliuskraujutis/Library/Preferences/IdeaIC12/keymaps/

Moving x-axis to the top of a plot in matplotlib

tick_params is very useful for setting tick properties. Labels can be moved to the top with:

    ax.tick_params(labelbottom=False,labeltop=True)

HashMap with multiple values under the same key

Another nice choice is to use MultiValuedMap from Apache Commons. Take a look at the All Known Implementing Classes at the top of the page for specialized implementations.

Example:

HashMap<K, ArrayList<String>> map = new HashMap<K, ArrayList<String>>()

could be replaced with

MultiValuedMap<K, String> map = new MultiValuedHashMap<K, String>();

So,

map.put(key, "A");
map.put(key, "B");
map.put(key, "C");

Collection<String> coll = map.get(key);

would result in collection coll containing "A", "B", and "C".

How do I write dispatch_after GCD in Swift 3, 4, and 5?

try this

let when = DispatchTime.now() + 1.5
    DispatchQueue.main.asyncAfter(deadline: when) {
        //some code
    }

Is there a way to @Autowire a bean that requires constructor arguments?

In this example, how do I specify the value of "constrArg" in MyBeanService with the @Autowire annotation? Is there any way to do this?

No, not in the way that you mean. The bean representing MyConstructorClass must be configurable without requiring any of its client beans, so MyBeanService doesn't get a say in how MyConstructorClass is configured.

This isn't an autowiring problem, the problem here is how does Spring instantiate MyConstructorClass, given that MyConstructorClass is a @Component (and you're using component-scanning, and therefore not specifying a MyConstructorClass explicitly in your config).

As @Sean said, one answer here is to use @Value on the constructor parameter, so that Spring will fetch the constructor value from a system property or properties file. The alternative is for MyBeanService to directly instantiate MyConstructorClass, but if you do that, then MyConstructorClass is no longer a Spring bean.

Box-Shadow on the left side of the element only

You probably need more blur and a little less spread.

box-shadow: -10px 0px 10px 1px #aaaaaa;

Try messing around with the box shadow generator here http://css3generator.com/ until you get your desired effect.

How can I add a .npmrc file?

Assuming you are using VSTS run vsts-npm-auth -config .npmrc to generate new .npmrc file with the auth token

Getting time and date from timestamp with php

If you dont want to change the format of date and time from the timestamp, you can use the explode function in php

$timestamp = "2012-04-02 02:57:54"
$datetime = explode(" ",$timestamp);
$date = $datetime[0];
$time = $datetime[1];

127 Return code from $?

This error is also at times deceiving. It says file is not found even though the files is indeed present. It could be because of invalid unreadable special characters present in the files that could be caused by the editor you are using. This link might help you in such cases.

-bash: ./my_script: /bin/bash^M: bad interpreter: No such file or directory

The best way to find out if it is this issue is to simple place an echo statement in the entire file and verify if the same error is thrown.

How to check if smtp is working from commandline (Linux)

Syntax for establishing a raw network connection using telnet is this:

telnet {domain_name} {port_number}

So telnet to your smtp server like

telnet smtp.mydomain.com 25

And copy and paste the below

helo client.mydomain.com
mail from:<[email protected]>
rcpt to:<[email protected]>
data
From: [email protected]
Subject: test mail from command line

this is test number 1
sent from linux box
.
quit

Note : Do not forgot the "." at the end which represents the end of the message. The "quit" line exits ends the session.

Angular 2 beta.17: Property 'map' does not exist on type 'Observable<Response>'

As Justin Scofield has suggested in his answer, for Angular 5's latest release and for Angular 6, as on 1st June, 2018, just import 'rxjs/add/operator/map'; isn't sufficient to remove the TS error: [ts] Property 'map' does not exist on type 'Observable<Object>'.

Its necessary to run the below command to install the required dependencies: npm install rxjs@6 rxjs-compat@6 --save after which the map import dependency error gets resolved!

JavaScript pattern for multiple constructors

Going further with eruciform's answer, you can chain your new call into your init method.

function Foo () {
    this.bar = 'baz';
}

Foo.prototype.init_1 = function (bar) {
    this.bar = bar;
    return this;
};

Foo.prototype.init_2 = function (baz) {
    this.bar = 'something to do with '+baz;
    return this;
};

var a = new Foo().init_1('constructor 1');
var b = new Foo().init_2('constructor 2');

Trigger a keypress/keydown/keyup event in JS/jQuery?

You can trigger any of the events with a direct call to them, like this:

$(function() {
    $('item').keydown();
    $('item').keypress();
    $('item').keyup();
    $('item').blur();
});

Does that do what you're trying to do?

You should probably also trigger .focus() and potentially .change()

If you want to trigger the key-events with specific keys, you can do so like this:

$(function() {
    var e = $.Event('keypress');
    e.which = 65; // Character 'A'
    $('item').trigger(e);
});

There is some interesting discussion of the keypress events here: jQuery Event Keypress: Which key was pressed?, specifically regarding cross-browser compatability with the .which property.

What GRANT USAGE ON SCHEMA exactly do?

GRANTs on different objects are separate. GRANTing on a database doesn't GRANT rights to the schema within. Similiarly, GRANTing on a schema doesn't grant rights on the tables within.

If you have rights to SELECT from a table, but not the right to see it in the schema that contains it then you can't access the table.

The rights tests are done in order:

Do you have `USAGE` on the schema? 
    No:  Reject access. 
    Yes: Do you also have the appropriate rights on the table? 
        No:  Reject access. 
        Yes: Check column privileges.

Your confusion may arise from the fact that the public schema has a default GRANT of all rights to the role public, which every user/group is a member of. So everyone already has usage on that schema.

The phrase:

(assuming that the objects' own privilege requirements are also met)

Is saying that you must have USAGE on a schema to use objects within it, but having USAGE on a schema is not by itself sufficient to use the objects within the schema, you must also have rights on the objects themselves.

It's like a directory tree. If you create a directory somedir with file somefile within it then set it so that only your own user can access the directory or the file (mode rwx------ on the dir, mode rw------- on the file) then nobody else can list the directory to see that the file exists.

If you were to grant world-read rights on the file (mode rw-r--r--) but not change the directory permissions it'd make no difference. Nobody could see the file in order to read it, because they don't have the rights to list the directory.

If you instead set rwx-r-xr-x on the directory, setting it so people can list and traverse the directory but not changing the file permissions, people could list the file but could not read it because they'd have no access to the file.

You need to set both permissions for people to actually be able to view the file.

Same thing in Pg. You need both schema USAGE rights and object rights to perform an action on an object, like SELECT from a table.

(The analogy falls down a bit in that PostgreSQL doesn't have row-level security yet, so the user can still "see" that the table exists in the schema by SELECTing from pg_class directly. They can't interact with it in any way, though, so it's just the "list" part that isn't quite the same.)

What are the options for (keyup) in Angular2?

you can add keyup event like this

template: `
  <input (keyup)="onKey($event)">
  <p>{{values}}</p>
`

in Component, code some like below

export class KeyUpComponent_v1 {
  values = '';

  onKey(event:any) { // without type info
    this.values += event.target.value + ' | ';
  }
}

Retrieve filename from file descriptor in C

I had this problem on Mac OS X. We don't have a /proc virtual file system, so the accepted solution cannot work.

We do, instead, have a F_GETPATH command for fcntl:

 F_GETPATH          Get the path of the file descriptor Fildes.  The argu-
                    ment must be a buffer of size MAXPATHLEN or greater.

So to get the file associated to a file descriptor, you can use this snippet:

#include <sys/syslimits.h>
#include <fcntl.h>

char filePath[PATH_MAX];
if (fcntl(fd, F_GETPATH, filePath) != -1)
{
    // do something with the file path
}

Since I never remember where MAXPATHLEN is defined, I thought PATH_MAX from syslimits would be fine.

How to iterate over columns of pandas dataframe to run regression

Using list comprehension, you can get all the columns names (header):

[column for column in df]

Nested classes' scope?

Easiest solution:

class OuterClass:
    outer_var = 1
    class InnerClass:
        def __init__(self):
            self.inner_var = OuterClass.outer_var

It requires you to be explicit, but doesn't take much effort.

Getting only hour/minute of datetime

I would recommend keeping the object you have, and just utilizing the properties that you want, rather than removing the resolution you already have.

If you want to print it in a certain format you may want to look at this...That way you can preserve your resolution further down the line.

That being said you can create a new DateTime object using only the properties you want as @romkyns has in his answer.

How do I get a file's directory using the File object?

File API File.getParent or File.getParentFile should return you Directory of file.

Your code should be like :

    File file = new File("c:\\temp\\java\\testfile");
    if(!file.exists()){
        file = file.getParentFile();
    }

You can additionally check your parent file is directory using File.isDirectory API

if(file.isDirectory()){
    System.out.println("file is directory ");
}

Change the mouse pointer using JavaScript

Javascript is pretty good at manipulating css.

 document.body.style.cursor = *cursor-url*;
 //OR
 var elementToChange = document.getElementsByTagName("body")[0];
 elementToChange.style.cursor = "url('cursor url with protocol'), auto";

or with jquery:

$("html").css("cursor: url('cursor url with protocol'), auto");

Firefox will not work unless you specify a default cursor after the imaged one!

other cursor keywords

Also remember that IE6 only supports .cur and .ani cursors.

If cursor doesn't change: In case you are moving the element under the cursor relative to the cursor position (e.g. element dragging) you have to force a redraw on the element:

// in plain js
document.getElementById('parentOfElementToBeRedrawn').style.display = 'none';
document.getElementById('parentOfElementToBeRedrawn').style.display = 'block';
// in jquery
$('#parentOfElementToBeRedrawn').hide().show(0);

working sample:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>First jQuery-Enabled Page</title>
<style type="text/css">

div {
    height: 100px;
    width: 1000px;
    background-color: red;
}

</style>
<script type="text/javascript" src="jquery-1.3.2.js"></script></head>
<body>
<div>
hello with a fancy cursor!
</div>
</body>
<script type="text/javascript">
document.getElementsByTagName("body")[0].style.cursor = "url('http://wiki-devel.sugarlabs.org/images/e/e2/Arrow.cur'), auto";


</script>
</html>

Best way to detect when a user leaves a web page?

Thanks to Service Workers, it is possible to implement a solution similar to Adam's purely on the client-side, granted the browser supports it. Just circumvent heartbeat requests:

// The delay should be longer than the heartbeat by a significant enough amount that there won't be false positives
const liveTimeoutDelay = 10000
let liveTimeout = null

global.self.addEventListener('fetch', event => {
  clearTimeout(liveTimeout)
  liveTimeout = setTimeout(() => {
    console.log('User left page')
    // handle page leave
  }, liveTimeoutDelay)
  // Forward any events except for hearbeat events
  if (event.request.url.endsWith('/heartbeat')) {
    event.respondWith(
      new global.Response('Still here')
    )
  }
})

What's the fastest way in Python to calculate cosine similarity given sparse matrix data?

Hi you can do it this way

    temp = sp.coo_matrix((data, (row, col)), shape=(3, 59))
    temp1 = temp.tocsr()

    #Cosine similarity
    row_sums = ((temp1.multiply(temp1)).sum(axis=1))
    rows_sums_sqrt = np.array(np.sqrt(row_sums))[:,0]
    row_indices, col_indices = temp1.nonzero()
    temp1.data /= rows_sums_sqrt[row_indices]
    temp2 = temp1.transpose()
    temp3 = temp1*temp2

C# list.Orderby descending

look it this piece of code from my project

I'm trying to re-order the list based on a property inside my model,

 allEmployees = new List<Employee>(allEmployees.OrderByDescending(employee => employee.Name));

but I faced a problem when a small and capital letters exist, so to solve it, I used the string comparer.

allEmployees.OrderBy(employee => employee.Name,StringComparer.CurrentCultureIgnoreCase)

Ignore self-signed ssl cert using Jersey Client

Okay, I'd like to just add my class only because there might be some dev out there in the future that wants to connect to a Netbackup server (or something similar) and do stuff from Java while ignoring the SSL cert. This worked for me and we use windows active directory for auth to the Netbackup server.

public static void main(String[] args) throws Exception {
    SSLContext sslcontext = null;
    try {
        sslcontext = SSLContext.getInstance("TLS");
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        sslcontext.init(null, new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
            @Override
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
                //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            @Override
            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
                //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }
        }}, new java.security.SecureRandom());
    } catch (KeyManagementException ex) {
        Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
    }
    //HttpAuthenticationFeature feature = HttpAuthenticationFeature.basicBuilder().credentials(username, password).build();
    ClientConfig clientConfig = new ClientConfig();
    //clientConfig.register(feature);
    Client client = ClientBuilder.newBuilder().withConfig(clientConfig)
            .sslContext(sslcontext)
            .hostnameVerifier((s1, s2) -> true)
            .build();

    //String the_url = "https://the_server:1556/netbackup/security/cacert";
    String the_token;
    {
        String the_url = "https://the_server:1556/netbackup/login";
        WebTarget webTarget = client.target(the_url);

        Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
        String jsonString = new JSONObject()
                .put("domainType", "NT")
                .put("domainName", "XX")
                .put("userName", "the username")
                .put("password", "the password").toString();
        System.out.println(jsonString);
        Response response = invocationBuilder.post(Entity.json(jsonString));
        String data = response.readEntity(String.class);
        JSONObject jo = new JSONObject(data);
        the_token = jo.getString("token");
        System.out.println("token is:" + the_token);

    }
    {
        String the_url = "https://the_server:1556/netbackup/admin/jobs/1122012"; //job id 1122012 is an example
        WebTarget webTarget = client.target(the_url);
        Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, the_token).header(HttpHeaders.ACCEPT, "application/vnd.netbackup+json;version=1.0");
        Response response = invocationBuilder.get();
        System.out.println("response status:" + response.getStatus());
        String data = response.readEntity(String.class);
        //JSONObject jo = new JSONObject(data);
        System.out.println(data);
    }
}

I know it can be considered off-topic, but I bet the dev that tries to connect to a Netbackup server will probably end up here. By the way many thanks to all the answers in this question! The spec I'm talking about is here and their code samples are (currently) missing a Java example.

***This is of course unsafe since we ignore the cert!

Printf width specifier to maintain precision of floating-point value

In one of my comments to an answer I lamented that I've long wanted some way to print all the significant digits in a floating point value in decimal form, in much the same way the as the question asks. Well I finally sat down and wrote it. It's not quite perfect, and this is demo code that prints additional information, but it mostly works for my tests. Please let me know if you (i.e. anyone) would like a copy of the whole wrapper program which drives it for testing.

static unsigned int
ilog10(uintmax_t v);

/*
 * Note:  As presented this demo code prints a whole line including information
 * about how the form was arrived with, as well as in certain cases a couple of
 * interesting details about the number, such as the number of decimal places,
 * and possibley the magnitude of the value and the number of significant
 * digits.
 */
void
print_decimal(double d)
{
        size_t sigdig;
        int dplaces;
        double flintmax;

        /*
         * If we really want to see a plain decimal presentation with all of
         * the possible significant digits of precision for a floating point
         * number, then we must calculate the correct number of decimal places
         * to show with "%.*f" as follows.
         *
         * This is in lieu of always using either full on scientific notation
         * with "%e" (where the presentation is always in decimal format so we
         * can directly print the maximum number of significant digits
         * supported by the representation, taking into acount the one digit
         * represented by by the leading digit)
         *
         *        printf("%1.*e", DBL_DECIMAL_DIG - 1, d)
         *
         * or using the built-in human-friendly formatting with "%g" (where a
         * '*' parameter is used as the number of significant digits to print
         * and so we can just print exactly the maximum number supported by the
         * representation)
         *
         *         printf("%.*g", DBL_DECIMAL_DIG, d)
         *
         *
         * N.B.:  If we want the printed result to again survive a round-trip
         * conversion to binary and back, and to be rounded to a human-friendly
         * number, then we can only print DBL_DIG significant digits (instead
         * of the larger DBL_DECIMAL_DIG digits).
         *
         * Note:  "flintmax" here refers to the largest consecutive integer
         * that can be safely stored in a floating point variable without
         * losing precision.
         */
#ifdef PRINT_ROUND_TRIP_SAFE
# ifdef DBL_DIG
        sigdig = DBL_DIG;
# else
        sigdig = ilog10(uipow(FLT_RADIX, DBL_MANT_DIG - 1));
# endif
#else
# ifdef DBL_DECIMAL_DIG
        sigdig = DBL_DECIMAL_DIG;
# else
        sigdig = (size_t) lrint(ceil(DBL_MANT_DIG * log10((double) FLT_RADIX))) + 1;
# endif
#endif
        flintmax = pow((double) FLT_RADIX, (double) DBL_MANT_DIG); /* xxx use uipow() */
        if (d == 0.0) {
                printf("z = %.*s\n", (int) sigdig + 1, "0.000000000000000000000"); /* 21 */
        } else if (fabs(d) >= 0.1 &&
                   fabs(d) <= flintmax) {
                dplaces = (int) (sigdig - (size_t) lrint(ceil(log10(ceil(fabs(d))))));
                if (dplaces < 0) {
                        /* XXX this is likely never less than -1 */
                        /*
                         * XXX the last digit is not significant!!! XXX
                         *
                         * This should also be printed with sprintf() and edited...
                         */
                        printf("R = %.0f [%d too many significant digits!!!, zero decimal places]\n", d, abs(dplaces));
                } else if (dplaces == 0) {
                        /*
                         * The decimal fraction here is not significant and
                         * should always be zero  (XXX I've never seen this)
                         */
                        printf("R = %.0f [zero decimal places]\n", d);
                } else {
                        if (fabs(d) == 1.0) {
                                /*
                                 * This is a special case where the calculation
                                 * is off by one because log10(1.0) is 0, but
                                 * we still have the leading '1' whole digit to
                                 * count as a significant digit.
                                 */
#if 0
                                printf("ceil(1.0) = %f, log10(ceil(1.0)) = %f, ceil(log10(ceil(1.0))) = %f\n",
                                       ceil(fabs(d)), log10(ceil(fabs(d))), ceil(log10(ceil(fabs(d)))));
#endif
                                dplaces--;
                        }
                        /* this is really the "useful" range of %f */
                        printf("r = %.*f [%d decimal places]\n", dplaces, d, dplaces);
                }
        } else {
                if (fabs(d) < 1.0) {
                        int lz;

                        lz = abs((int) lrint(floor(log10(fabs(d)))));
                        /* i.e. add # of leading zeros to the precision */
                        dplaces = (int) sigdig - 1 + lz;
                        printf("f = %.*f [%d decimal places]\n", dplaces, d, dplaces);
                } else {                /* d > flintmax */
                        size_t n;
                        size_t i;
                        char *df;

                        /*
                         * hmmmm...  the easy way to suppress the "invalid",
                         * i.e. non-significant digits is to do a string
                         * replacement of all dgits after the first
                         * DBL_DECIMAL_DIG to convert them to zeros, and to
                         * round the least significant digit.
                         */
                        df = malloc((size_t) 1);
                        n = (size_t) snprintf(df, (size_t) 1, "%.1f", d);
                        n++;                /* for the NUL */
                        df = realloc(df, n);
                        (void) snprintf(df, n, "%.1f", d);
                        if ((n - 2) > sigdig) {
                                /*
                                 * XXX rounding the integer part here is "hard"
                                 * -- we would have to convert the digits up to
                                 * this point back into a binary format and
                                 * round that value appropriately in order to
                                 * do it correctly.
                                 */
                                if (df[sigdig] >= '5' && df[sigdig] <= '9') {
                                        if (df[sigdig - 1] == '9') {
                                                /*
                                                 * xxx fixing this is left as
                                                 * an exercise to the reader!
                                                 */
                                                printf("F = *** failed to round integer part at the least significant digit!!! ***\n");
                                                free(df);
                                                return;
                                        } else {
                                                df[sigdig - 1]++;
                                        }
                                }
                                for (i = sigdig; df[i] != '.'; i++) {
                                        df[i] = '0';
                                }
                        } else {
                                i = n - 1; /* less the NUL */
                                if (isnan(d) || isinf(d)) {
                                        sigdig = 0; /* "nan" or "inf" */
                                }
                        }
                        printf("F = %.*s. [0 decimal places, %lu digits, %lu digits significant]\n",
                               (int) i, df, (unsigned long int) i, (unsigned long int) sigdig);
                        free(df);
                }
        }

        return;
}


static unsigned int
msb(uintmax_t v)
{
        unsigned int mb = 0;

        while (v >>= 1) { /* unroll for more speed...  (see ilog2()) */
                mb++;
        }

        return mb;
}

static unsigned int
ilog10(uintmax_t v)
{
        unsigned int r;
        static unsigned long long int const PowersOf10[] =
                { 1LLU, 10LLU, 100LLU, 1000LLU, 10000LLU, 100000LLU, 1000000LLU,
                  10000000LLU, 100000000LLU, 1000000000LLU, 10000000000LLU,
                  100000000000LLU, 1000000000000LLU, 10000000000000LLU,
                  100000000000000LLU, 1000000000000000LLU, 10000000000000000LLU,
                  100000000000000000LLU, 1000000000000000000LLU,
                  10000000000000000000LLU };

        if (!v) {
                return ~0U;
        }
        /*
         * By the relationship "log10(v) = log2(v) / log2(10)", we need to
         * multiply "log2(v)" by "1 / log2(10)", which is approximately
         * 1233/4096, or (1233, followed by a right shift of 12).
         *
         * Finally, since the result is only an approximation that may be off
         * by one, the exact value is found by subtracting "v < PowersOf10[r]"
         * from the result.
         */
        r = ((msb(v) * 1233) >> 12) + 1;

        return r - (v < PowersOf10[r]);
}

What is a Maven artifact?

usually we talking Maven Terminology about Group Id , Artifact Id and Snapshot Version

Group Id:identity of the group of the project Artifact Id:identity of the project Snapshot version:the version used by the project.

Artifact is nothing but some resulting file like Jar, War, Ear....

simply says Artifacts are nothing but packages.

HttpListener Access Denied

In case you want to use the flag "user=Everyone" you need to adjust it to your system language. In english it is as mentioned:

netsh http add urlacl url=http://+:80/ user=Everyone

In german it would be:

netsh http add urlacl url=http://+:80/ user=Jeder

C linked list inserting node at the end

This code will work. The answer from samplebias is almost correct, but you need a third change:

int addNodeBottom(int val, node *head){

    //create new node
    node *newNode = (node*)malloc(sizeof(node));

    if(newNode == NULL){
        fprintf(stderr, "Unable to allocate memory for new node\n");
        exit(-1);
    }

    newNode->value = val;
    newNode->next = NULL;  // Change 1

    //check for first insertion
    if(head->next == NULL){
        head->next = newNode;
        printf("added at beginning\n");
    }

    else
    {
        //else loop through the list and find the last
        //node, insert next to it
        node *current = head;
        while (true) { // Change 2
            if(current->next == NULL)
            {
                current->next = newNode;
                printf("added later\n");
                break; // Change 3
            }
            current = current->next;
        };
    }
    return 0;
}

Change 1: newNode->next must be set to NULL so we don't insert invalid pointers at the end of the list.

Change 2/3: The loop is changed to an endless loop that will be jumped out with break; when we found the last element. Note how while(current->next != NULL) contradicted if(current->next == NULL) before.

EDIT: Regarding the while loop, this way it is much better:

  node *current = head;
  while (current->next != NULL) {
    current = current->next;
  }
  current->next = newNode;
  printf("added later\n");

Android Animation Alpha

View.setOnTouchListener { v, event ->
    when (event.action) {
        MotionEvent.ACTION_DOWN -> {
            v.alpha = 0f
            v.invalidate()
        }
        MotionEvent.ACTION_UP -> {
            v.alpha = 1f
            v.invalidate()


        }
    }
    false
}

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

It is not an issue it is because of caching...

To overcome this add a timestamp to your endpoint call, e.g. axios.get('/api/products').

After timestamp it should be axios.get(/api/products?${Date.now()}.

It will resolve your 304 status code.

YYYY-MM-DD format date in shell script

You can do something like this:

$ date +'%Y-%m-%d'

How to parse a string into a nullable int

I've come up with this one, which has satisfied my requirements (I wanted my extension method to emulate as close as possible the return of the framework's TryParse, but without try{} catch{} blocks and without the compiler complaining about inferring a nullable type within the framework method)

private static bool TryParseNullableInt(this string s, out int? result)
{
    int i;
    result = int.TryParse(s, out i) ? (int?)i : null;
    return result != null;
}

What is the difference between compare() and compareTo()?

compareTo() is called on one object, to compare it to another object. compare() is called on some object to compare two other objects.

The difference is where the logic that does actual comparison is defined.

Convert integer to binary in C#

This might be helpful if you want a concise function that you can call from your main method, inside your class. You may still need to call int.Parse(toBinary(someint)) if you require a number instead of a string but I find this method work pretty well. Additionally, this can be adjusted to use a for loop instead of a do-while if you'd prefer.

    public static string toBinary(int base10)
    {
        string binary = "";
        do {
            binary = (base10 % 2) + binary;
            base10 /= 2;
        }
        while (base10 > 0);

        return binary;
    }

toBinary(10) returns the string "1010".

byte[] to hex string

I like using extension methods for conversions like this, even if they just wrap standard library methods. In the case of hexadecimal conversions, I use the following hand-tuned (i.e., fast) algorithms:

public static string ToHex(this byte[] bytes)
{
    char[] c = new char[bytes.Length * 2];

    byte b;

    for(int bx = 0, cx = 0; bx < bytes.Length; ++bx, ++cx) 
    {
        b = ((byte)(bytes[bx] >> 4));
        c[cx] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);

        b = ((byte)(bytes[bx] & 0x0F));
        c[++cx]=(char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);
    }

    return new string(c);
}

public static byte[] HexToBytes(this string str)
{
    if (str.Length == 0 || str.Length % 2 != 0)
        return new byte[0];

    byte[] buffer = new byte[str.Length / 2];
    char c;
    for (int bx = 0, sx = 0; bx < buffer.Length; ++bx, ++sx)
    {
        // Convert first half of byte
        c = str[sx];
        buffer[bx] = (byte)((c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0')) << 4);

        // Convert second half of byte
        c = str[++sx];
        buffer[bx] |= (byte)(c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0'));
    }

    return buffer;
}

How do I assert equality on two classes without an equals method?

Mockito offers a reflection-matcher:

For latest version of Mockito use:

Assert.assertTrue(new ReflectionEquals(expected, excludeFields).matches(actual));

For older versions use:

Assert.assertThat(actual, new ReflectionEquals(expected, excludeFields));

Letsencrypt add domain to existing certificate

Apache on Ubuntu, using the Apache plugin:

sudo certbot certonly --cert-name example.com -d m.example.com,www.m.example.com

The above command is vividly explained in the Certbot user guide on changing a certificate's domain names. Note that the command for changing a certificate's domain names applies to adding new domain names as well.

Edit

If running the above command gives you the error message

Client with the currently selected authenticator does not support any combination of challenges that will satisfy the CA.

follow these instructions from the Let's Encrypt Community

Error: the entity type requires a primary key

This worked for me:

using System.ComponentModel.DataAnnotations;

[Key]
public int ID { get; set; }

Closing pyplot windows

plt.close() will close current instance.

plt.close(2) will close figure 2

plt.close(plot1) will close figure with instance plot1

plt.close('all') will close all fiures

Found here.

Remember that plt.show() is a blocking function, so in the example code you used above, plt.close() isn't being executed until the window is closed, which makes it redundant.

You can use plt.ion() at the beginning of your code to make it non-blocking, although this has other implications.

EXAMPLE

After our discussion in the comments, I've put together a bit of an example just to demonstrate how the plot functionality can be used.

Below I create a plot:

fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
....
par_plot, = plot(x_data,y_data, lw=2, color='red')

In this case, ax above is a handle to a pair of axes. Whenever I want to do something to these axes, I can change my current set of axes to this particular set by calling axes(ax).

par_plot is a handle to the line2D instance. This is called an artist. If I want to change a property of the line, like change the ydata, I can do so by referring to this handle.

I can also create a slider widget by doing the following:

axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)

The first line creates a new axes for the slider (called axsliderA), the second line creates a slider instance sA which is placed in the axes, and the third line specifies a function to call when the slider value changes (update).

My update function could look something like this:

def update(val):
    A = sA.val
    B = sB.val
    C = sC.val
    y_data = A*x_data*x_data + B*x_data + C
    par_plot.set_ydata(y_data)
    draw()

The par_plot.set_ydata(y_data) changes the ydata property of the Line2D object with the handle par_plot.

The draw() function updates the current set of axes.

Putting it all together:

from pylab import *
import matplotlib.pyplot as plt
import numpy

def update(val):
    A = sA.val
    B = sB.val
    C = sC.val
    y_data = A*x_data*x_data + B*x_data + C
    par_plot.set_ydata(y_data)
    draw()


x_data = numpy.arange(-100,100,0.1);

fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
subplots_adjust(top=0.8)

ax.set_xlim(-100, 100);
ax.set_ylim(-100, 100);
ax.set_xlabel('X')
ax.set_ylabel('Y')

axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)

axsliderB = axes([0.43, 0.85, 0.16, 0.075])
sB = Slider(axsliderB, 'B', -30, 30.0, valinit=2)
sB.on_changed(update)

axsliderC = axes([0.74, 0.85, 0.16, 0.075])
sC = Slider(axsliderC, 'C', -30, 30.0, valinit=1)
sC.on_changed(update)

axes(ax)
A = 1;
B = 2;
C = 1;
y_data = A*x_data*x_data + B*x_data + C;

par_plot, = plot(x_data,y_data, lw=2, color='red')

show()

A note about the above: When I run the application, the code runs sequentially right through (it stores the update function in memory, I think), until it hits show(), which is blocking. When you make a change to one of the sliders, it runs the update function from memory (I think?).

This is the reason why show() is implemented in the way it is, so that you can change values in the background by using functions to process the data.

Virtual member call in a constructor

There are well-written answers above for why you wouldn't want to do that. Here's a counter-example where perhaps you would want to do that (translated into C# from Practical Object-Oriented Design in Ruby by Sandi Metz, p. 126).

Note that GetDependency() isn't touching any instance variables. It would be static if static methods could be virtual.

(To be fair, there are probably smarter ways of doing this via dependency injection containers or object initializers...)

public class MyClass
{
    private IDependency _myDependency;

    public MyClass(IDependency someValue = null)
    {
        _myDependency = someValue ?? GetDependency();
    }

    // If this were static, it could not be overridden
    // as static methods cannot be virtual in C#.
    protected virtual IDependency GetDependency() 
    {
        return new SomeDependency();
    }
}

public class MySubClass : MyClass
{
    protected override IDependency GetDependency()
    {
        return new SomeOtherDependency();
    }
}

public interface IDependency  { }
public class SomeDependency : IDependency { }
public class SomeOtherDependency : IDependency { }

What does the explicit keyword mean?

Constructors append implicit conversion. To suppress this implicit conversion it is required to declare a constructor with a parameter explicit.

In C++11 you can also specify an "operator type()" with such keyword http://en.cppreference.com/w/cpp/language/explicit With such specification you can use operator in terms of explicit conversions, and direct initialization of object.

P.S. When using transformations defined BY USER (via constructors and type conversion operator) it is allowed only one level of implicit conversions used. But you can combine this conversions with other language conversions

  • up integral ranks (char to int, float to double);
  • standart conversions (int to double);
  • convert pointers of objects to base class and to void*;

Way to ng-repeat defined number of times instead of repeating over array?

since iterating over a string it will render an item for each char:

<li ng-repeat = "k in 'aaaa' track by $index">
   {{$index}} //THIS DOESN'T ANSWER OP'S QUESTION. Read below.
</li>

we can use this ugly but no-code workaround using the number|n decimal places native filter.

 <li ng-repeat="k in (0|number:mynumber -2 ) track by $index">
    {{$index}}
 </li>

this way we'll have mynumber elements with no extra code. Say '0.000'.
We use mynumber - 2 to compensate 0.
It won't work for numbers below 3, but might be useful in some cases.

SQL Server String or binary data would be truncated

I've built a stored procedure that analyses a source table or query with several characteristics per column among which the minimum length (min_len) and maximum length (max_len).

CREATE PROCEDURE [dbo].[sp_analysetable] (
  @tableName varchar(8000),
  @deep bit = 0
) AS

/*
sp_analysetable 'company'
sp_analysetable 'select * from company where name is not null'
*/

DECLARE @intErrorCode INT, @errorMSG VARCHAR(500), @tmpQ NVARCHAR(2000), @column_name VARCHAR(50), @isQuery bit
SET @intErrorCode=0

IF OBJECT_ID('tempdb..##tmpTableToAnalyse') IS NOT NULL BEGIN
  DROP TABLE ##tmpTableToAnalyse
END
IF OBJECT_ID('tempdb..##tmpColumns') IS NOT NULL BEGIN
  DROP TABLE ##tmpColumns
END

if CHARINDEX('from', @tableName)>0
  set @isQuery=1

IF @intErrorCode=0 BEGIN
  if @isQuery=1 begin
    --set @tableName = 'USE '+@db+';'+replace(@tableName, 'from', 'into ##tmpTableToAnalyse from')
    --replace only first occurance. Now multiple froms may exists, but first from will be replaced with into .. from
    set @tableName=Stuff(@tableName, CharIndex('from', @tableName), Len('from'), 'into ##tmpTableToAnalyse from')
    exec(@tableName)
    IF OBJECT_ID('tempdb..##tmpTableToAnalyse') IS NULL BEGIN
      set @intErrorCode=1
      SET @errorMSG='Error generating temporary table from query.'
    end
    else begin
      set @tableName='##tmpTableToAnalyse'
    end
  end
end

IF @intErrorCode=0 BEGIN
  SET @tmpQ='USE '+DB_NAME()+';'+CHAR(13)+CHAR(10)+'
  select
    c.column_name as [column],
    cast(sp.value as varchar(1000)) as description,
    tc_fk.constraint_type,
    kcu_pk.table_name as fk_table,
    kcu_pk.column_name as fk_column,
    c.ordinal_position as pos,
    c.column_default as [default],
    c.is_nullable as [null],
    c.data_type,
    c.character_maximum_length as length,
    c.numeric_precision as [precision],
    c.numeric_precision_radix as radix,
    cast(null as bit) as [is_unique],
    cast(null as int) as min_len,
    cast(null as int) as max_len,
    cast(null as int) as nulls,
    cast(null as int) as blanks,
    cast(null as int) as numerics,
    cast(null as int) as distincts,
    cast(null as varchar(500)) as distinct_values,
    cast(null as varchar(50)) as remarks
  into ##tmpColumns'
  if @isQuery=1 begin
    SET @tmpQ=@tmpQ+' from tempdb.information_schema.columns c, (select null as value) sp'
  end
  else begin
    SET @tmpQ=@tmpQ+'
      from information_schema.columns c
      left join sysobjects so    on so.name=c.table_name  and so.xtype=''U''
      left join syscolumns sc    on sc.name=c.column_name and sc.id  =so.id 
      left join sys.extended_properties sp on sp.minor_id = sc.colid AND sp.major_id = sc.id and sp.name=''MS_Description''  
      left join information_schema.key_column_usage kcu_fk    on kcu_fk.table_name = c.table_name     and c.column_name = kcu_fk.column_name
      left join information_schema.table_constraints tc_fk    on kcu_fk.table_name = tc_fk.table_name and kcu_fk.constraint_name = tc_fk.constraint_name
      left join information_schema.referential_constraints rc on rc.constraint_name = kcu_fk.constraint_name
      left join information_schema.table_constraints tc_pk    on rc.unique_constraint_name = tc_pk.constraint_name
      left join information_schema.key_column_usage kcu_pk    on tc_pk.constraint_name = kcu_pk.constraint_name
 '
  end
  SET @tmpQ=@tmpQ+' where c.table_name = '''+@tableName+''''

  exec(@tmpQ)
end

IF @intErrorCode=0 AND @deep = 1 BEGIN
  DECLARE
    @count_rows int,
    @count_distinct int,
    @count_nulls int,
    @count_blanks int,
    @count_numerics int,
    @min_len int,
    @max_len int,
    @distinct_values varchar(500)
  DECLARE curTmp CURSOR LOCAL FAST_FORWARD FOR
    select [column] from ##tmpColumns;
  OPEN curTmp
  FETCH NEXT FROM curTmp INTO @column_name
  WHILE @@FETCH_STATUS = 0 and @intErrorCode=0 BEGIN
    set @tmpQ = 'USE '+DB_NAME()+'; SELECT'+
      '  @count_rows=count(0), '+char(13)+char(10)+
      '  @count_distinct=count(distinct ['+@column_name+']),'+char(13)+char(10)+
      '  @count_nulls=sum(case when ['+@column_name+'] is null then 1 else 0 end),'+char(13)+char(10)+
      '  @count_blanks=sum(case when ltrim(['+@column_name+'])='''' then 1 else 0 end),'+char(13)+char(10)+
      '  @count_numerics=sum(isnumeric(['+@column_name+'])),'+char(13)+char(10)+
      '  @min_len=min(len(['+@column_name+'])),'+char(13)+char(10)+
      '  @max_len=max(len(['+@column_name+']))'+char(13)+char(10)+
      ' from ['+@tableName+']'
    exec sp_executesql @tmpQ,
                       N'@count_rows int OUTPUT,
                         @count_distinct int OUTPUT,
                         @count_nulls int OUTPUT,
                         @count_blanks int OUTPUT,
                         @count_numerics int OUTPUT,
                         @min_len int OUTPUT,
                         @max_len int OUTPUT',
                       @count_rows     OUTPUT,
                       @count_distinct OUTPUT,
                       @count_nulls    OUTPUT,
                       @count_blanks    OUTPUT,
                       @count_numerics OUTPUT,
                       @min_len        OUTPUT,
                       @max_len        OUTPUT

    IF (@count_distinct>10) BEGIN
      SET @distinct_values='Many ('+cast(@count_distinct as varchar)+')'
    END ELSE BEGIN
      set @distinct_values=null
      set @tmpQ = N'USE '+DB_NAME()+';'+
        '  select @distinct_values=COALESCE(@distinct_values+'',''+cast(['+@column_name+'] as varchar),  cast(['+@column_name+'] as varchar))'+char(13)+char(10)+
        '  from ('+char(13)+char(10)+
        '    select distinct ['+@column_name+'] from ['+@tableName+'] where ['+@column_name+'] is not null) a'+char(13)+char(10)
      exec sp_executesql @tmpQ,
                         N'@distinct_values varchar(500) OUTPUT',
                         @distinct_values        OUTPUT
    END
    UPDATE ##tmpColumns SET
      is_unique      =case when @count_rows=@count_distinct then 1 else 0 end,
      distincts      =@count_distinct,
      nulls          =@count_nulls,
      blanks         =@count_blanks,
      numerics       =@count_numerics,
      min_len        =@min_len,
      max_len        =@max_len,
      distinct_values=@distinct_values,
      remarks       =
        case when @count_rows=@count_nulls then 'all null,' else '' end+
        case when @count_rows=@count_distinct then 'unique,' else '' end+
        case when @count_distinct=0 then 'empty,' else '' end+
        case when @min_len=@max_len then 'same length,' else '' end+
        case when @count_rows=@count_numerics then 'all numeric,' else '' end
    WHERE [column]=@column_name

    FETCH NEXT FROM curTmp INTO @column_name
  END
  CLOSE curTmp DEALLOCATE curTmp
END

IF @intErrorCode=0 BEGIN
  select * from ##tmpColumns order by pos
end

IF @intErrorCode=0 BEGIN --Clean up temporary tables
  IF OBJECT_ID('tempdb..##tmpTableToAnalyse') IS NOT NULL BEGIN
    DROP TABLE ##tmpTableToAnalyse
  END
  IF OBJECT_ID('tempdb..##tmpColumns') IS NOT NULL BEGIN
    DROP TABLE ##tmpColumns
  END
end

IF @intErrorCode<>0 BEGIN
  RAISERROR(@errorMSG, 12, 1)
END
RETURN @intErrorCode

I store this procedure in the master database so that I can use it in every database like so:

sp_analysetable 'table_name', 1
// deep=1 for doing value analyses

And the output is:

column description constraint_type fk_table fk_column pos default null data_type length precision radix is_unique min_len max_len nulls blanks numerics distincts distinct_values remarks
id_individual NULL PRIMARY KEY NULL NULL 1 NULL NO int NULL 10 10 1 1 2 0 0 70 70 Many (70) unique,all numeric,
id_brand NULL NULL NULL NULL 2 NULL NO int NULL 10 10 0 1 1 0 0 70 2 2,3 same length,all numeric, guid NULL NULL NULL NULL 3 (newid()) NO uniqueidentifier NULL NULL NULL 1 36 36 0 0 0 70 Many (70) unique,same length,
customer_id NULL NULL NULL NULL 4 NULL YES varchar 50 NULL NULL 0 NULL NULL 70 0 0 0 NULL all null,empty,
email NULL NULL NULL NULL 5 NULL YES varchar 100 NULL NULL 0 4 36 0 0 0 31 Many (31)
mobile NULL NULL NULL NULL 6 NULL YES varchar 50 NULL NULL 0 NULL NULL 70 0 0 0 NULL all null,empty,
initials NULL NULL NULL NULL 7 NULL YES varchar 50 NULL NULL 0 NULL NULL 70 0 0 0 NULL all null,empty,
title_short NULL NULL NULL NULL 8 NULL YES varchar 50 NULL NULL 0 NULL NULL 70 0 0 0 NULL all null,empty,
title_long NULL NULL NULL NULL 9 NULL YES varchar 50 NULL NULL 0 NULL NULL 70 0 0 0 NULL all null,empty,
firstname NULL NULL NULL NULL 10 NULL YES varchar 50 NULL NULL 0 NULL NULL 70 0 0 0 NULL all null,empty,
lastname NULL NULL NULL NULL 11 NULL YES varchar 50 NULL NULL 0 NULL NULL 70 0 0 0 NULL all null,empty,
address NULL NULL NULL NULL 12 NULL YES varchar 100 NULL NULL 0 NULL NULL 70 0 0 0 NULL all null,empty,
pc NULL NULL NULL NULL 13 NULL YES varchar 10 NULL NULL 0 NULL NULL 70 0 0 0 NULL all null,empty,
kixcode NULL NULL NULL NULL 14 NULL YES varchar 20 NULL NULL 0 NULL NULL 70 0 0 0 NULL all null,empty,
date_created NULL NULL NULL NULL 15 (getdate()) NO datetime NULL NULL NULL 1 19 19 0 0 0 70 Many (70) unique,same length,
created_by NULL NULL NULL NULL 16 (user_name()) NO varchar 50 NULL NULL 0 13 13 0 0 0 1 loyalz-public same length,
id_location_created NULL FOREIGN KEY location id_location 17 NULL YES int NULL 10 10 0 1 1 0 0 70 2 1,2 same length,all numeric, id_individual_type NULL FOREIGN KEY individual_type id_individual_type 18 NULL YES int NULL 10 10 0 NULL NULL 70 0 0 0 NULL all null,empty,
optin NULL NULL NULL NULL 19 NULL YES int NULL 10 10 0 1 1 39 0 31 2 0,1 same length,

How do I format a string using a dictionary in python-3.x?

To unpack a dictionary into keyword arguments, use **. Also,, new-style formatting supports referring to attributes of objects and items of mappings:

'{0[latitude]} {0[longitude]}'.format(geopoint)
'The title is {0.title}s'.format(a) # the a from your first example

comparing two strings in SQL Server

There is no direct string compare function in SQL Server

CASE
  WHEN str1 = str2 THEN 0
  WHEN str1 < str2 THEN -1
  WHEN str1 > str2 THEN 1
  ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END

Notes

  • you can wraps this via a UDF using CREATE FUNCTION etc
  • you may need NULL handling (in my code above, any NULL will report 1)
  • str1 and str2 will be column names or @variables

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R?

I figured out myself.

cmp calls ComputeBetasAndNuHat which returns a list which has objective as minusloglik

So I can change the function cmp to get this value.

JSON order mixed up

For those who're using maven, please try com.github.tsohr/json

<!-- https://mvnrepository.com/artifact/com.github.tsohr/json -->
<dependency>
    <groupId>com.github.tsohr</groupId>
    <artifactId>json</artifactId>
    <version>0.0.1</version>
</dependency>

It's forked from JSON-java but switch its map implementation with LinkedHashMap which @lemiorhan noted above.

PHP: Split string into array, like explode with no delimiter

Try this:

$str = '123456789';
$char_array = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);

Best way to get value from Collection by index

use for each loop...

ArrayList<Character> al = new ArrayList<>();    
String input="hello";

for (int i = 0; i < input.length(); i++){
    al.add(input.charAt(i));
}

for (Character ch : al) {               
    System.Out.println(ch);             
}

Global Variable in app.js accessible in routes?

I used app.all

The app.all() method is useful for mapping “global” logic for specific path prefixes or arbitrary matches.

In my case, I'm using confit for configuration management,

app.all('*', function (req, res, next) {
    confit(basedir).create(function (err, config) {
        if (err) {
            throw new Error('Failed to load configuration ', err);
        }
        app.set('config', config);
        next();
    });
});

In routes, you simply do req.app.get('config').get('cookie');

Pure css close button

The disappointing thing here is that the "X" isn't transparent (which is how I would likely create a PNG, at least).

I put together this quick test. http://jsfiddle.net/UM3a2/22/embedded/result/ which allows you to color the positive space while leaving the negative space transparent. Since it is made entirely of borders it is easy to color since border-color defaults to the text color.

It doesn't fully support I.E. 8 and earlier (border-radius issues), but it degrades to a square fairly nicely (if you're okay with a square close button).

It also requires two HTML elements since you are only allowed two pseudo elements per selector. I don't know exactly where I learned this, but I think it was in an article by Chris Coyier.

<div id="close" class="arrow-t-b">
  Close
  <div class="arrow-l-r"> </div>
</div>

#close {
  border-width: 4px;
  border-style: solid;
  border-radius: 100%;
  color: #333;
  height: 12px;
  margin:auto;
  position: relative;
  text-indent: -9999px;
  width: 12px;
}
#close:hover {
  color: #39F;
}
.arrow-t-b:after,
.arrow-t-b:before,
.arrow-l-r:after, 
.arrow-l-r:before {
  border-color: transparent;
  border-style: solid;
  border-width: 4px;
  content: "";
  left: 2px;
  top: 0px;
  position: absolute;
}
.arrow-t-b:after {
  border-top-color: inherit;
}
.arrow-l-r:after {
  border-right-color: inherit;
  left: 4px;
  top: 2px;
}
.arrow-t-b:before {
  border-bottom-color: inherit;
  bottom: 0;
}
.arrow-l-r:before {
  border-left-color: inherit;
  left: 0;
  top: 2px;
}

How to to send mail using gmail in Laravel?

you need to enable first the App password of your google account -> security section link

then the app password that will be generated copy it and paste it in to .env file

MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=app_password
MAIL_ENCRYPTION=ssl

Are Git forks actually Git clones?

I keep hearing people say they're forking code in git. Git "fork" sounds suspiciously like git "clone" plus some (meaningless) psychological willingness to forgo future merges. There is no fork command in git, right?

"Forking" is a concept, not a command specifically supported by any version control system.

The simplest kind of forking is synonymous with branching. Every time you create a branch, regardless of your VCS, you've "forked". These forks are usually pretty easy to merge back together.

The kind of fork you're talking about, where a separate party takes a complete copy of the code and walks away, necessarily happens outside the VCS in a centralized system like Subversion. A distributed VCS like Git has much better support for forking the entire codebase and effectively starting a new project.

Git (not GitHub) natively supports "forking" an entire repo (ie, cloning it) in a couple of ways:

  • when you clone, a remote called origin is created for you
  • by default all the branches in the clone will track their origin equivalents
  • fetching and merging changes from the original project you forked from is trivially easy

Git makes contributing changes back to the source of the fork as simple as asking someone from the original project to pull from you, or requesting write access to push changes back yourself. This is the part that GitHub makes easier, and standardizes.

Any angst over Github extending git in this direction? Or any rumors of git absorbing the functionality?

There is no angst because your assumption is wrong. GitHub "extends" the forking functionality of Git with a nice GUI and a standardized way of issuing pull requests, but it doesn't add the functionality to Git. The concept of full-repo-forking is baked right into distributed version control at a fundamental level. You could abandon GitHub at any point and still continue to push/pull projects you've "forked".

Is Java RegEx case-insensitive?

You also can lead your initial string, which you are going to check for pattern matching, to lower case. And use in your pattern lower case symbols respectively.

How to create a readonly textbox in ASP.NET MVC3 Razor

The solution with TextBoxFor is OK, but if you don't want to see the field like EditBox stylish (it might be a little confusing for the user) involve changes as follows:

  1. Razor code before changes

    <div class="editor-field">
         @Html.EditorFor(model => model.Text)
         @Html.ValidationMessageFor(model => model.Text)
    </div>
    
  2. After changes

    <!-- New div display-field (after div editor-label) -->
    <div class="display-field">
        @Html.DisplayFor(model => model.Text)
    </div>
    
    <div class="editor-field">
        <!-- change to HiddenFor in existing div editor-field -->
        @Html.HiddenFor(model => model.Text)
        @Html.ValidationMessageFor(model => model.Text)
    </div>
    

Generally, this solution prevents field from editing, but shows value of it. There is no need for code-behind modifications.

Method to find string inside of the text file. Then getting the following lines up to a certain limit

This will find "Mark Sagal" in Student.txt. Assuming Student.txt contains

Student.txt

Amir Amiri
Mark Sagal
Juan Delacruz

Main.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        final String file = "Student.txt";
        String line = null;
        ArrayList<String> fileContents = new ArrayList<>();

        try {
            FileReader fReader = new FileReader(file);
            BufferedReader fileBuff = new BufferedReader(fReader);
            while ((line = fileBuff.readLine()) != null) {
                fileContents.add(line);
            }
            fileBuff.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        System.out.println(fileContents.contains("Mark Sagal"));
    }
}

How to use a jQuery plugin inside Vue

First install jquery using npm,

npm install jquery --save

I use:

global.jQuery = require('jquery');
var $ = global.jQuery;
window.$ = $;

Are there benefits of passing by pointer over passing by reference in C++?

Not really. Internally, passing by reference is performed by essentially passing the address of the referenced object. So, there really aren't any efficiency gains to be had by passing a pointer.

Passing by reference does have one benefit, however. You are guaranteed to have an instance of whatever object/type that is being passed in. If you pass in a pointer, then you run the risk of receiving a NULL pointer. By using pass-by-reference, you are pushing an implicit NULL-check up one level to the caller of your function.

jQuery onclick event for <li> tags

Typing in $(this) will return the jQuery element instead of the HTML Element. Then it just depends on what you want to do in the click event.

alert($(this));

Regular expression for only characters a-z, A-Z

This /[^a-z]/g solves the problem.

_x000D_
_x000D_
function pangram(str) {
    let regExp = /[^a-z]/g;
    let letters = str.toLowerCase().replace(regExp, '');
    document.getElementById('letters').innerHTML = letters;
}
pangram('GHV 2@# %hfr efg uor7 489(*&^% knt lhtkjj ngnm!@#$%^&*()_');
_x000D_
<h4 id="letters"></h4>
_x000D_
_x000D_
_x000D_

Is there a numpy builtin to reject outliers from a list

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

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

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

PHP's array_map including keys

Not with array_map, as it doesn't handle keys.

array_walk does:

$test_array = array("first_key" => "first_value",
                    "second_key" => "second_value");
array_walk($test_array, function(&$a, $b) { $a = "$b loves $a"; });
var_dump($test_array);

// array(2) {
//   ["first_key"]=>
//   string(27) "first_key loves first_value"
//   ["second_key"]=>
//   string(29) "second_key loves second_value"
// }

It does change the array given as parameter however, so it's not exactly functional programming (as you have the question tagged like that). Also, as pointed out in the comment, this will only change the values of the array, so the keys won't be what you specified in the question.

You could write a function that fixes the points above yourself if you wanted to, like this:

function mymapper($arrayparam, $valuecallback) {
  $resultarr = array();
  foreach ($arrayparam as $key => $value) {
    $resultarr[] = $valuecallback($key, $value);
  }
  return $resultarr;
}

$test_array = array("first_key" => "first_value",
                    "second_key" => "second_value");
$new_array = mymapper($test_array, function($a, $b) { return "$a loves $b"; });
var_dump($new_array);

// array(2) {
//   [0]=>
//   string(27) "first_key loves first_value"
//   [1]=>
//   string(29) "second_key loves second_value"
// }

How do you see the entire command history in interactive Python?

With python 3 interpreter the history is written to
~/.python_history

php error: Class 'Imagick' not found

On an EC2 at AWS, I did this:

 yum list | grep imagick

Then found a list of ones I could install...

 php -v

told me which version of php I had and thus which version of imagick

yum install php56-pecl-imagick.x86_64

Did the trick. Enjoy!

Angular ng-if="" with multiple arguments

For people looking to do if statements with multiple 'or' values.

<div ng-if="::(a || b || c || d || e || f)"><div>

Android Studio AVD - Emulator: Process finished with exit code 1

Check android studio event log as it could be low storage issue.

emulator: ERROR: Not enough disk space to run AVD 'Nexus_5_API_21'. Exiting...

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

Thanks to all for sharing your answers and examples. The same standalone program worked for me by small changes and adding the lines of code below.

In this case, keystore file was given by webservice provider.

// Small changes during connection initiation.. 

// Please add this static block 

      static {

        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()

            {   @Override

        public boolean verify(String hostname, SSLSession arg1) {

        // TODO Auto-generated method stub

                if (hostname.equals("X.X.X.X")) {

                    System.out.println("Return TRUE"+hostname);

                    return true;

                }

                System.out.println("Return FALSE");

                return false;

              }
               });
         }


String xmlServerURL = "https://X.X.X.X:8080/services/EndpointPort";


URL urlXMLServer = new URL(null,xmlServerURL,new sun.net.www.protocol.https.Handler());


HttpsURLConnection httpsURLConnection = (HttpsURLConnection) urlXMLServer               .openConnection();

// Below extra lines are added to the same program

//Keystore file 

 System.setProperty("javax.net.ssl.keyStore", "Drive:/FullPath/keystorefile.store");

 System.setProperty("javax.net.ssl.keyStorePassword", "Password"); // Password given by vendor

//TrustStore file

System.setProperty("javax.net.ssl.trustStore"Drive:/FullPath/keystorefile.store");

System.setProperty("javax.net.ssl.trustStorePassword", "Password");

Changing the text on a label

self.labelText = 'change the value'

The above sentence makes labelText change the value, but not change depositLabel's text.

To change depositLabel's text, use one of following setences:

self.depositLabel['text'] = 'change the value'

OR

self.depositLabel.config(text='change the value')

SonarQube Exclude a directory

You can do the same with build.gradle

sonarqube {
properties {
    property "sonar.exclusions", "**/src/java/test/**/*.java"
  }
}

And if you want to exclude more files/directories then:

sonarqube {
properties {
    property "sonar.exclusions", "**/src/java/test/**/*.java, **/src/java/main/**/*.java"
  }
}

Are PostgreSQL column names case-sensitive?

The column names which are mixed case or uppercase have to be double quoted in PostgresQL. So best convention will be to follow all small case with underscore.

No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes

make sure your package name in "google-services.json" file is same with your apps's package name.

how to read all files inside particular folder

Try this It is working for me..

The syntax is GetFiles(string path, string searchPattern);

var filePath = Server.MapPath("~/App_Data/");
string[] filePaths = Directory.GetFiles(@filePath, "*.*");

This code will return all the files inside App_Data folder.

The second parameter . indicates the searchPattern with File Extension where the first * is for file name and second is for format of the file or File Extension like (*.png - any file name with .png format.

Double decimal formatting in Java

Using String.format, you can do this:

double price = 52000;
String.format("$%,.2f", price);

Notice the comma which makes this different from @Vincent's answer

Output:

$52,000.00

A good resource for formatting is the official java page on the subject

NPM clean modules

In a word no.

In two, not yet.

There is, however, an open issue for a --no-build flag to npm install to perform an installation without building, which could be used to do what you're asking.

See this open issue.

How do I change Bootstrap 3's glyphicons to white?

You can just create your own .white class and add it to the glyphicon element.

.white, .white a {
  color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>

How do I reference a cell within excel named range?

Add a column to the left so that B10 to B20 is your named range Age.

Set A10 to A20 so that A10 = 1, A11= 2,... A20 = 11 and give the range A10 to A20 a name e.g. AgeIndex.

The 5th element can be then found by using an array formula:

=sum( Age * (1 * (AgeIndex = 5) )

As it's an array formula you'll need to press Ctrl + Shift + Return to make it work and not just return. Doing that, the formula will be turned into an array formula:

{=sum( Age * (1 * (AgeIndex = 5) )}

What are the main differences between JWT and OAuth authentication?

Jwt is a strict set of instructions for the issuing and validating of signed access tokens. The tokens contain claims that are used by an app to limit access to a user

OAuth2 on the other hand is not a protocol, its a delegated authorization framework. think very detailed guideline, for letting users and applications authorize specific permissions to other applications in both private and public settings. OpenID Connect which sits on top of OAUTH2 gives you Authentication and Authorization.it details how multiple different roles, users in your system, server side apps like an API, and clients such as websites or native mobile apps, can authenticate with each othe

Note oauth2 can work with jwt , flexible implementation, extandable to different applications

Warning: mysqli_error() expects exactly 1 parameter, 0 given error

mysqli_error function requires $myConnection as parameters, that's why you get the warning

What is the difference between %g and %f in C?

%f and %g does the same thing. Only difference is that %g is the shorter form of %f. That is the precision after decimal point is larger in %f compared to %g

Eclipse error ... cannot be resolved to a type

Solution : 1.Project -> Build Path -> Configure Build Path

2.Select Java Build path on the left menu, and select "Source"

3.Under Project select Include(All) and click OK

Cause : The issue might because u might have deleted the CLASS files or dependencies on the project

Getting index value on razor foreach

All of the above answers require logic in the view. Views should be dumb and contain as little logic as possible. Why not create properties in your view model that correspond to position in the list eg:

public int Position {get; set}

In your view model builder you set the position 1 through 4.

BUT .. there is even a cleaner way. Why not make the CSS class a property of your view model? So instead of the switch statement in your partial, you would just do this:

<div class="@Model.GridCSS">

Move the switch statement to your view model builder and populate the CSS class there.

Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

A simple solution:

original = [1,2,3]
cloned = original.map(x=>x)

Android Studio: Application Installation Failed

I have faced this issue since I have upgraded the build tools from 26.0.2 to 27.0.3. Reverting back, clean and rebuild solve the issue. Also I have degraded the gradle plugin version from 3.1.3 to 3.0.1 as the latest version was overriding the build tools to latest version.

Segmentation Fault - C

Your scanf("%s", s); is commented out. That means s is uninitialized, so when this line ln = strlen(s); executes, you get a seg fault.

It always helps to initialize a pointer to NULL, and then test for null before using the pointer.

How to make a class property?

def _create_type(meta, name, attrs):
    type_name = f'{name}Type'
    type_attrs = {}
    for k, v in attrs.items():
        if type(v) is _ClassPropertyDescriptor:
            type_attrs[k] = v
    return type(type_name, (meta,), type_attrs)


class ClassPropertyType(type):
    def __new__(meta, name, bases, attrs):
        Type = _create_type(meta, name, attrs)
        cls = super().__new__(meta, name, bases, attrs)
        cls.__class__ = Type
        return cls


class _ClassPropertyDescriptor(object):
    def __init__(self, fget, fset=None):
        self.fget = fget
        self.fset = fset

    def __get__(self, obj, owner):
        if self in obj.__dict__.values():
            return self.fget(obj)
        return self.fget(owner)

    def __set__(self, obj, value):
        if not self.fset:
            raise AttributeError("can't set attribute")
        return self.fset(obj, value)

    def setter(self, func):
        self.fset = func
        return self


def classproperty(func):
    return _ClassPropertyDescriptor(func)



class Bar(metaclass=ClassPropertyType):
    __bar = 1

    @classproperty
    def bar(cls):
        return cls.__bar

    @bar.setter
    def bar(cls, value):
        cls.__bar = value

bar = Bar()
assert Bar.bar==1
Bar.bar=2
assert bar.bar==2
nbar = Bar()
assert nbar.bar==2

How to add a new line of text to an existing file in Java?

On line 2 change new FileWriter(my_file_name) to new FileWriter(my_file_name, true) so you're appending to the file rather than overwriting.

File f = new File("/path/of/the/file");
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
            bw.append(line);
            bw.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

Convert iterator to pointer?

That seems not possible in my situation, since the function I mentioned is the find function of unordered_set<std::vector*>.

Are you using custom hash/predicate function objects? If not, then you must pass unordered_set<std::vector<int>*>::find() the pointer to the exact vector that you want to find. A pointer to another vector with the same contents will not work. This is not very useful for lookups, to say the least.

Using unordered_set<std::vector<int> > would be better, because then you could perform lookups by value. I think that would also require a custom hash function object because hash does not to my knowledge have a specialization for vector<int>.

Either way, a pointer into the middle of a vector is not itself a vector, as others have explained. You cannot convert an iterator into a pointer to vector without copying its contents.

Can't use method return value in write context

I'm not sure if this would be a common mistake, but if you do something like:

$var = 'value' .= 'value2';

this will also produce the same error

Can't use method return value in write context

You can't have an = and a .= in the same statement. You can use one or the other, but not both.

Note, I understand this is unrelated to the actual code in the question, however this question is the top result when searching for the error message, so I wanted to post it here for completeness.

How to fix 'sudo: no tty present and no askpass program specified' error?

sudo by default will read the password from the attached terminal. Your problem is that there is no terminal attached when it is run from the netbeans console. So you have to use an alternative way to enter the password: that is called the askpass program.

The askpass program is not a particular program, but any program that can ask for a password. For example in my system x11-ssh-askpass works fine.

In order to do that you have to specify what program to use, either with the environment variable SUDO_ASKPASS or in the sudo.conf file (see man sudo for details).

You can force sudo to use the askpass program by using the option -A. By default it will use it only if there is not an attached terminal.

Search a whole table in mySQL for a string

If you are just looking for some text and don't need a result set for programming purposes, you could install HeidiSQL for free (I'm using v9.2.0.4947).

Right click any database or table and select "Find text on server".

All the matches are shown in a separate tab for each table - very nice.

Frighteningly useful and saved me hours. Forget messing about with lengthy queries!!

JQuery - File attributes

To get the filenames, use:

var files = document.getElementById('inputElementID').files;

Using jQuery (since you already are) you can adapt this to the following:

$('input[type="file"][multiple]').change(
    function(e){
        var files = this.files;
        for (i=0;i<files.length;i++){
            console.log(files[i].fileName + ' (' + files[i].fileSize + ').');
        }
        return false;
    });

JS Fiddle demo.

mongodb/mongoose findMany - find all documents with IDs listed in array

Use this format of querying

let arr = _categories.map(ele => new mongoose.Types.ObjectId(ele.id));

Item.find({ vendorId: mongoose.Types.ObjectId(_vendorId) , status:'Active'})
  .where('category')
  .in(arr)
  .exec();

List of Java processes

pgrep -l java
ps -ef | grep java

fs.writeFile in a promise, asynchronous-synchronous stuff

const util = require('util')
const fs = require('fs');

const fs_writeFile = util.promisify(fs.writeFile)

fs_writeFile('message.txt', 'Hello Node.js')
    .catch((error) => {
        console.log(error)
    });

Python 3 Float Decimal Points/Precision

The comments state the objective is to print to 2 decimal places.

There's a simple answer for Python 3:

>>> num=3.65
>>> "The number is {:.2f}".format(num)
'The number is 3.65'

or equivalently with f-strings (Python 3.6+):

>>> num = 3.65
>>> f"The number is {num:.2f}"
'The number is 3.65'

As always, the float value is an approximation:

>>> "{}".format(num)
'3.65'
>>> "{:.10f}".format(num)
'3.6500000000'
>>> "{:.20f}".format(num)
'3.64999999999999991118'

I think most use cases will want to work with floats and then only print to a specific precision.

Those that want the numbers themselves to be stored to exactly 2 decimal digits of precision, I suggest use the decimal type. More reading on floating point precision for those that are interested.

Change the current directory from a Bash script

I've also created a utility called goat that you can use for easier navigation.

You can view the source code on GitHub.

As of v2.3.1 the usage overview looks like this:

# Create a link (h4xdir) to a directory:
goat h4xdir ~/Documents/dev

# Follow a link to change a directory:
cd h4xdir

# Follow a link (and don't stop there!):
cd h4xdir/awesome-project

# Go up the filesystem tree with '...' (same as `cd ../../`):
cd ...

# List all your links:
goat list

# Delete a link (or more):
goat delete h4xdir lojban

# Delete all the links which point to directories with the given prefix:
goat deleteprefix $HOME/Documents

# Delete all saved links:
goat nuke

# Delete broken links:
goat fix

How to avoid "StaleElementReferenceException" in Selenium?

Try this

while (true) { // loops forever until break
    try { // checks code for exceptions
        WebElement ele=
        (WebElement)wait.until(ExpectedConditions.elementToBeClickable((By.xpath(Xpath))));  
        break; // if no exceptions breaks out of loop
    } 
    catch (org.openqa.selenium.StaleElementReferenceException e1) { 
        Thread.sleep(3000); // you can set your value here maybe 2 secs
        continue; // continues to loop if exception is found
    }
}

How to get the category title in a post in Wordpress?

Use get_the_category() like this:

<?php
foreach((get_the_category()) as $category) { 
    echo $category->cat_name . ' '; 
} 
?>

It returns a list because a post can have more than one category.

The documentation also explains how to do this from outside the loop.

What is Vim recording and how can it be disabled?

As others have said, it's macro recording, and you turn it off with q. Here's a nice article about how-to and why it's useful.

How to achieve function overloading in C?

I hope the below code will help you to understand function overloading

#include <stdio.h>
#include<stdarg.h>

int fun(int a, ...);
int main(int argc, char *argv[]){
   fun(1,10);
   fun(2,"cquestionbank");
   return 0;
}
int fun(int a, ...){
  va_list vl;
  va_start(vl,a);

  if(a==1)
      printf("%d",va_arg(vl,int));
   else
      printf("\n%s",va_arg(vl,char *));
}

CSS media queries for screen sizes

Put it all in one document and use this:

/* Smartphones (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {
  /* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen 
and (min-width : 321px) {
  /* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen 
and (max-width : 320px) {
  /* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) {
  /* Styles */
}

/* iPads (landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) {
  /* Styles */
}

/* iPads (portrait) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) {
  /* Styles */
}

/* Desktops and laptops ----------- */
@media only screen 
and (min-width : 1224px) {
  /* Styles */
}

/* Large screens ----------- */
@media only screen 
and (min-width : 1824px) {
  /* Styles */
}

/* iPhone 4 - 5s ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
  /* Styles */
}

/* iPhone 6 ----------- */
@media
only screen and (max-device-width: 667px) 
only screen and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ ----------- */
@media
only screen and (min-device-width : 414px) 
only screen and (-webkit-device-pixel-ratio: 3) {
  /*** You've spent way too much on a phone ***/
}

/* Samsung Galaxy S7 Edge ----------- */
@media only screen
and (-webkit-min-device-pixel-ratio: 3),
and (min-resolution: 192dpi)and (max-width:640px) {
 /* Styles */
}

Source: http://css-tricks.com/snippets/css/media-queries-for-standard-devices/

At this point, I would definitely consider using em values instead of pixels. For more information, check this post: https://zellwk.com/blog/media-query-units/.

How do I get first name and last name as whole name in a MYSQL query?

When you have three columns : first_name, last_name, mid_name:

SELECT CASE 
    WHEN mid_name IS NULL OR TRIM(mid_name) ='' THEN
        CONCAT_WS( " ", first_name, last_name ) 
    ELSE 
        CONCAT_WS( " ", first_name, mid_name, last_name ) 
    END 
FROM USER;

Calculating average of an array list?

Correct and fast way compute average for List<Integer>:

private double calculateAverage(List<Integer> marks) {
    long sum = 0;
    for (Integer mark : marks) {
        sum += mark;
    }
    return marks.isEmpty()? 0: 1.0*sum/marks.size();
}

This solution take into account:

  • Handle overflow
  • Do not allocate memory like Java8 stream
  • Do not use slow BigDecimal

It works coorectly for List, because any list contains less that 2^31 int, and it is possible to use long as accumulator.

PS

Actually foreach allocate memory - you should use old style for() cycle in mission critical parts

How to use a calculated column to calculate another column in the same view

If you want to refer to calculated column on the "same query level" then you could use CROSS APPLY(Oracle 12c):

--Sample data:
CREATE TABLE tab(ColumnA NUMBER(10,2),ColumnB NUMBER(10,2),ColumnC NUMBER(10,2));

INSERT INTO tab(ColumnA, ColumnB, ColumnC) VALUES (2, 10, 2);
INSERT INTO tab(ColumnA, ColumnB, ColumnC) VALUES (3, 15, 6);
INSERT INTO tab(ColumnA, ColumnB, ColumnC) VALUES (7, 14, 3);
COMMIT;

Query:

SELECT
  ColumnA,
  ColumnB,
  sub.calccolumn1,
  sub.calccolumn1 / ColumnC AS calccolumn2
FROM tab t
CROSS APPLY (SELECT t.ColumnA + t.ColumnB AS calccolumn1 FROM dual) sub;

DBFiddle Demo


Please note that expression from CROSS APPLY/OUTER APPLY is available in other clauses too:

SELECT
  ColumnA,
  ColumnB,
  sub.calccolumn1,
  sub.calccolumn1 / ColumnC AS calccolumn2
FROM tab t
CROSS APPLY (SELECT t.ColumnA + t.ColumnB AS calccolumn1 FROM dual) sub
WHERE sub.calccolumn1 = 12;
-- GROUP BY ...
-- ORDER BY ...;

This approach allows to avoid wrapping entire query with outerquery or copy/paste same expression in multiple places(with complex one it could be hard to maintain).

Related article: The SQL Language’s Most Missing Feature

Mailbox unavailable. The server response was: 5.7.1 Unable to relay for [email protected]

If you have Exchange 2010:

(In my case, the error message didn't contain " for [email protected]")

This shows how to add a receive connector: http://exchangeserverpro.com/how-to-configure-a-relay-connector-for-exchange-server-2010/

But I also needed to perform a step found here: http://recover-email.blogspot.com.au/2013/12/how-to-solve-exchange-smtp-server-error.html

  • Go to Exchange Management Shell and run the command
  • Get-ReceiveConnector "JiraTest" | Add-ADPermission -User "NT AUTHORITY\ANONYMOUS LOGON" -ExtendedRights "ms-Exch-SMTP-Accept-Any-Recipient"

While working on this, I ran the following on the affected server's PowerShell console until the error went away:

Send-MailMessage -From "[email protected]" -To "[email protected]" -Subject "Test Email" -Body "This is a test"

Create an array or List of all dates between two dates

public static IEnumerable<DateTime> GetDateRange(DateTime startDate, DateTime endDate)
{
    if (endDate < startDate)
        throw new ArgumentException("endDate must be greater than or equal to startDate");

    while (startDate <= endDate)
    {
        yield return startDate;
        startDate = startDate.AddDays(1);
    }
}

How to adjust the size of y axis labels only in R?

Don't know what you are doing (helpful to show what you tried that didn't work), but your claim that cex.axis only affects the x-axis is not true:

set.seed(123)
foo <- data.frame(X = rnorm(10), Y = rnorm(10))
plot(Y ~ X, data = foo, cex.axis = 3)

at least for me with:

> sessionInfo()
R version 2.11.1 Patched (2010-08-17 r52767)
Platform: x86_64-unknown-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_GB.UTF-8        LC_COLLATE=en_GB.UTF-8    
 [5] LC_MONETARY=C              LC_MESSAGES=en_GB.UTF-8   
 [7] LC_PAPER=en_GB.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods  
[8] base     

other attached packages:
[1] ggplot2_0.8.8 proto_0.3-8   reshape_0.8.3 plyr_1.2.1   

loaded via a namespace (and not attached):
[1] digest_0.4.2 tools_2.11.1

Also, cex.axis affects the labelling of tick marks. cex.lab is used to control what R call the axis labels.

plot(Y ~ X, data = foo, cex.lab = 3)

but even that works for both the x- and y-axis.


Following up Jens' comment about using barplot(). Check out the cex.names argument to barplot(), which allows you to control the bar labels:

dat <- rpois(10, 3) names(dat) <- LETTERS[1:10] barplot(dat, cex.names = 3, cex.axis = 2)

As you mention that cex.axis was only affecting the x-axis I presume you had horiz = TRUE in your barplot() call as well? As the bar labels are not drawn with an axis() call, applying Joris' (otherwise very useful) answer with individual axis() calls won't help in this situation with you using barplot()

HTH

Difference between VARCHAR and TEXT in MySQL

TL;DR

TEXT

  • fixed max size of 65535 characters (you cannot limit the max size)
  • takes 2 + c bytes of disk space, where c is the length of the stored string.
  • cannot be (fully) part of an index. One would need to specify a prefix length.

VARCHAR(M)

  • variable max size of M characters
  • M needs to be between 1 and 65535
  • takes 1 + c bytes (for M ≤ 255) or 2 + c (for 256 ≤ M ≤ 65535) bytes of disk space where c is the length of the stored string
  • can be part of an index

More Details

TEXT has a fixed max size of 2¹6-1 = 65535 characters.
VARCHAR has a variable max size M up to M = 2¹6-1.
So you cannot choose the size of TEXT but you can for a VARCHAR.

The other difference is, that you cannot put an index (except for a fulltext index) on a TEXT column.
So if you want to have an index on the column, you have to use VARCHAR. But notice that the length of an index is also limited, so if your VARCHAR column is too long you have to use only the first few characters of the VARCHAR column in your index (See the documentation for CREATE INDEX).

But you also want to use VARCHAR, if you know that the maximum length of the possible input string is only M, e.g. a phone number or a name or something like this. Then you can use VARCHAR(30) instead of TINYTEXT or TEXT and if someone tries to save the text of all three "Lord of the Ring" books in your phone number column you only store the first 30 characters :)

Edit: If the text you want to store in the database is longer than 65535 characters, you have to choose MEDIUMTEXT or LONGTEXT, but be careful: MEDIUMTEXT stores strings up to 16 MB, LONGTEXT up to 4 GB. If you use LONGTEXT and get the data via PHP (at least if you use mysqli without store_result), you maybe get a memory allocation error, because PHP tries to allocate 4 GB of memory to be sure the whole string can be buffered. This maybe also happens in other languages than PHP.

However, you should always check the input (Is it too long? Does it contain strange code?) before storing it in the database.

Notice: For both types, the required disk space depends only on the length of the stored string and not on the maximum length.
E.g. if you use the charset latin1 and store the text "Test" in VARCHAR(30), VARCHAR(100) and TINYTEXT, it always requires 5 bytes (1 byte to store the length of the string and 1 byte for each character). If you store the same text in a VARCHAR(2000) or a TEXT column, it would also require the same space, but, in this case, it would be 6 bytes (2 bytes to store the string length and 1 byte for each character).

For more information have a look at the documentation.

Finally, I want to add a notice, that both, TEXT and VARCHAR are variable length data types, and so they most likely minimize the space you need to store the data. But this comes with a trade-off for performance. If you need better performance, you have to use a fixed length type like CHAR. You can read more about this here.

How to assign multiple classes to an HTML container?

To assign multiple classes to an html element, include both class names within the quotations of the class attribute and have them separated by a space:

<article class="column wrapper"> 

In the above example, column and wrapper are two separate css classes, and both of their properties will be applied to the article element.

Where does the @Transactional annotation belong?

Service layer is best place to add @Transactional annotations as most of the business logic present here, it contain detail level use-case behaviour.

Suppose we add it to DAO and from service we are calling 2 DAO classes , one failed and other success , in this case if @Transactional not on service one DB will commit and other will rollback.

Hence my recommendation is use this annotation wisely and use at Service layer only.

Github project- java-algos

Removing double quotes from a string in Java

You can just go for String replace method.-

line1 = line1.replace("\"", "");

Convert String to Calendar Object in Java

Parse a time with timezone, Z in pattern is for time zone

String aTime = "2017-10-25T11:39:00+09:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault());
try {
    Calendar cal = Calendar.getInstance();
    cal.setTime(sdf.parse(aTime));
    Log.i(TAG, "time = " + cal.getTimeInMillis()); 
} catch (ParseException e) {
    e.printStackTrace();
}

Output: it will return the UTC time

1508899140000

enter image description here

If we don't set the time zone in pattern like yyyy-MM-dd'T'HH:mm:ss. SimpleDateFormat will use the time zone which have set in Setting