Programs & Examples On #Galileo

Android ADT error, dx.jar was not loaded from the SDK folder

For me, eclipse was looking in the wrong place for the SDK Manager. To fix this I did

  • Window/ Preferences/ Android/ SDK Location

NOTE: The SDK manager tells you what dir it is using near the top of the UI.

I had installed a new version of eclipse that has the ADT bundled up from the Android developer site, but when I opened eclipse it was looking at the old SDK.exe location.

hth

How to uncompress a tar.gz in another directory

You can use the option -C (or --directory if you prefer long options) to give the target directory of your choice in case you are using the Gnu version of tar. The directory should exist:

mkdir foo
tar -xzf bar.tar.gz -C foo

If you are not using a tar capable of extracting to a specific directory, you can simply cd into your target directory prior to calling tar; then you will have to give a complete path to your archive, of course. You can do this in a scoping subshell to avoid influencing the surrounding script:

mkdir foo
(cd foo; tar -xzf ../bar.tar.gz)  # instead of ../ you can use an absolute path as well

Or, if neither an absolute path nor a relative path to the archive file is suitable, you also can use this to name the archive outside of the scoping subshell:

TARGET_PATH=a/very/complex/path/which/might/even/be/absolute
mkdir -p "$TARGET_PATH"
(cd "$TARGET_PATH"; tar -xzf -) < bar.tar.gz

Write values in app.config file

If you are using App.Config to store values in <add Key="" Value="" /> or CustomSections section use ConfigurationManager class, else use XMLDocument class.

For example:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="server" value="192.168.0.1\xxx"/>
    <add key="database" value="DataXXX"/>
    <add key="username" value="userX"/>
    <add key="password" value="passX"/>
  </appSettings>
</configuration>

You could use the code posted on CodeProject

How to setup Tomcat server in Netbeans?

In Netbeans 8 you may have to install the Tomcat plugin manually. After you download and extract Tomcat follow these steps:

  1. Tools -> Plugins -> Available plugins, search for 'tomcat' and install the one named "Java EE Base plugin".
  2. Restart Netbeans
  3. On the project view (default left side of the screen), go to services, right click on Servers and then "Add Server"
  4. Select Apache Tomcat, enter username and password and config the rest and finish

Python name 'os' is not defined

Just add:

import os

in the beginning, before:

from settings import PROJECT_ROOT

This will import the python's module os, which apparently is used later in the code of your module without being imported.

How to make Java work with SQL Server?

Indeed. The thing is that the 2008 R2 version is very tricky. The JTDs driver seems to work on some cases. In a certain server, the jTDS worked fine for an 2008 R2 instance. In another server, though, I had to use Microsoft's JBDC driver sqljdbc4.jar. But then, it would only work after setting the JRE environment to 1.6(or higher).

I used 1.5 for the other server, so I waisted a lot of time on this.

Tricky issue.

PHP Session timeout

<script type="text/javascript">
window.setTimeout("location=('timeout_session.htm');",900000);
</script>

In the header of every page has been working for me during site tests(the site is not yet in production). The HTML page it falls to ends the session and just informs the user of the need to log in again. This seems an easier way than playing with PHP logic. I'd love some comments on the idea. Any traps I havent seen in it ?

WARNING in budgets, maximum exceeded for initial

Open angular.json file and find budgets keyword.

It should look like:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "2mb",
          "maximumError": "5mb"
       }
    ]

As you’ve probably guessed you can increase the maximumWarning value to prevent this warning, i.e.:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "4mb", <===
          "maximumError": "5mb"
       }
    ]

What does budgets mean?

A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.

In our case budget is the limit for bundle sizes.

See also:

HTTP Status 405 - HTTP method POST is not supported by this URL java servlet

If you're still facing the issue even after replacing doGet() with doPost() and changing the form method="post". Try clearing the cache of the browser or hit the URL in another browser or incognito/private mode. It may works!

For best practices, please follow this link. https://www.oracle.com/technetwork/articles/javase/servlets-jsp-140445.html

How do I check if a given Python string is a substring of another one?

string.find("substring") will help you. This function returns -1 when there is no substring.

Copy table without copying data

Only want to clone the structure of table:

CREATE TABLE foo SELECT * FROM bar WHERE 1 = 2;

Also wants to copy the data:

CREATE TABLE foo as SELECT * FROM bar;

Why would you use Expression<Func<T>> rather than Func<T>?

When you want to treat lambda expressions as expression trees and look inside them instead of executing them. For example, LINQ to SQL gets the expression and converts it to the equivalent SQL statement and submits it to server (rather than executing the lambda).

Conceptually, Expression<Func<T>> is completely different from Func<T>. Func<T> denotes a delegate which is pretty much a pointer to a method and Expression<Func<T>> denotes a tree data structure for a lambda expression. This tree structure describes what a lambda expression does rather than doing the actual thing. It basically holds data about the composition of expressions, variables, method calls, ... (for example it holds information such as this lambda is some constant + some parameter). You can use this description to convert it to an actual method (with Expression.Compile) or do other stuff (like the LINQ to SQL example) with it. The act of treating lambdas as anonymous methods and expression trees is purely a compile time thing.

Func<int> myFunc = () => 10; // similar to: int myAnonMethod() { return 10; }

will effectively compile to an IL method that gets nothing and returns 10.

Expression<Func<int>> myExpression = () => 10;

will be converted to a data structure that describes an expression that gets no parameters and returns the value 10:

Expression vs Func larger image

While they both look the same at compile time, what the compiler generates is totally different.

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

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

How to set the background image of a html 5 canvas to .png image

You can draw the image on the canvas and let the user draw on top of that.

The drawImage() function will help you with that, see https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images

Datatable vs Dataset

One feature of the DataSet is that if you can call multiple select statements in your stored procedures, the DataSet will have one DataTable for each.

Windows equivalent of linux cksum command

To avoid annoying non-checksum lines : CertUtil -v -hashfile "your_file" SHA1 | FIND /V "CertUtil" This will display only line(s) NOT contaning CertUtil

jQuery Set Selected Option Using Next

you can use

$('option:selected').next('option')

or

$('option:selected + option')

And set the value:

var nextVal = $('option:selected + option').val();
$('select').val(nextVal);

How to customize <input type="file">?

In webkit you can try this out...

input[type="file"]::-webkit-file-upload-button{
   /* style goes here */
}

JavaScript: What are .extend and .prototype used for?

The extend method for example in jQuery or PrototypeJS, copies all properties from the source to the destination object.

Now about the prototype property, it is a member of function objects, it is part of the language core.

Any function can be used as a constructor, to create new object instances. All functions have this prototype property.

When you use the new operator with on a function object, a new object will be created, and it will inherit from its constructor prototype.

For example:

function Foo () {
}
Foo.prototype.bar = true;

var foo = new Foo();

foo.bar; // true
foo instanceof Foo; // true
Foo.prototype.isPrototypeOf(foo); // true

Unable to establish SSL connection upon wget on Ubuntu 14.04 LTS

you must be using old version of wget i had same issue. i was using wget 1.12.so to solve this issue there are 2 way: Update wget or use curl

curl -LO 'https://example.com/filename.tar.gz'

Using textures in THREE.js

In version r82 of Three.js TextureLoader is the object to use for loading a texture.

Loading one texture (source code, demo)

Extract (test.js):

var scene = new THREE.Scene();
var ratio = window.innerWidth / window.innerHeight;
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight,
  0.1, 50);

var renderer = ...

[...]

/**
 * Will be called when load completes.
 * The argument will be the loaded texture.
 */
var onLoad = function (texture) {
  var objGeometry = new THREE.BoxGeometry(20, 20, 20);
  var objMaterial = new THREE.MeshPhongMaterial({
    map: texture,
    shading: THREE.FlatShading
  });

  var mesh = new THREE.Mesh(objGeometry, objMaterial);

  scene.add(mesh);

  var render = function () {
    requestAnimationFrame(render);

    mesh.rotation.x += 0.010;
    mesh.rotation.y += 0.010;

    renderer.render(scene, camera);
  };

  render();
}

// Function called when download progresses
var onProgress = function (xhr) {
  console.log((xhr.loaded / xhr.total * 100) + '% loaded');
};

// Function called when download errors
var onError = function (xhr) {
  console.log('An error happened');
};

var loader = new THREE.TextureLoader();
loader.load('texture.jpg', onLoad, onProgress, onError);

Loading multiple textures (source code, demo)

In this example the textures are loaded inside the constructor of the mesh, multiple texture are loaded using Promises.

Extract (Globe.js):

Create a new container using Object3D for having two meshes in the same container:

var Globe = function (radius, segments) {

  THREE.Object3D.call(this);

  this.name = "Globe";

  var that = this;

  // instantiate a loader
  var loader = new THREE.TextureLoader();

A map called textures where every object contains the url of a texture file and val for storing the value of a Three.js texture object.

  // earth textures
  var textures = {
    'map': {
      url: 'relief.jpg',
      val: undefined
    },
    'bumpMap': {
      url: 'elev_bump_4k.jpg',
      val: undefined
    },
    'specularMap': {
      url: 'wateretopo.png',
      val: undefined
    }
  };

The array of promises, for each object in the map called textures push a new Promise in the array texturePromises, every Promise will call loader.load. If the value of entry.val is a valid THREE.Texture object, then resolve the promise.

  var texturePromises = [], path = './';

  for (var key in textures) {
    texturePromises.push(new Promise((resolve, reject) => {
      var entry = textures[key]
      var url = path + entry.url

      loader.load(url,
        texture => {
          entry.val = texture;
          if (entry.val instanceof THREE.Texture) resolve(entry);
        },
        xhr => {
          console.log(url + ' ' + (xhr.loaded / xhr.total * 100) +
            '% loaded');
        },
        xhr => {
          reject(new Error(xhr +
            'An error occurred loading while loading: ' +
            entry.url));
        }
      );
    }));
  }

Promise.all takes the promise array texturePromises as argument. Doing so makes the browser wait for all the promises to resolve, when they do we can load the geometry and the material.

  // load the geometry and the textures
  Promise.all(texturePromises).then(loadedTextures => {

    var geometry = new THREE.SphereGeometry(radius, segments, segments);
    var material = new THREE.MeshPhongMaterial({
      map: textures.map.val,
      bumpMap: textures.bumpMap.val,
      bumpScale: 0.005,
      specularMap: textures.specularMap.val,
      specular: new THREE.Color('grey')
    });

    var earth = that.earth = new THREE.Mesh(geometry, material);
    that.add(earth);
  });

For the cloud sphere only one texture is necessary:

  // clouds
  loader.load('n_amer_clouds.png', map => {
    var geometry = new THREE.SphereGeometry(radius + .05, segments, segments);
    var material = new THREE.MeshPhongMaterial({
      map: map,
      transparent: true
    });

    var clouds = that.clouds = new THREE.Mesh(geometry, material);
    that.add(clouds);
  });
}

Globe.prototype = Object.create(THREE.Object3D.prototype);
Globe.prototype.constructor = Globe;

How do I add options to a DropDownList using jQuery?

using jquery you can use

      this.$('select#myid').append('<option>newvalue</option>');

where "myid" is the id of the dropdown list and newvalue is the text that you want to insert..

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

Not a jquery plugin, but the DateJS Library appears to do what you require. The Getting Started page has a number of examples.

Assets file project.assets.json not found. Run a NuGet package restore

To those with the same issue as me in Azure DevOps / VSTS environment encountering a similar message:

C:\Program Files\dotnet\sdk\2.2.104\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets(208,5): Error NETSDK1004: Assets file '...\obj\project.assets.json' not found. Run a NuGet package restore to generate this file

Add /t:Restore to your MSBuild Arguments in Build Solution.

Tuning nginx worker_process to obtain 100k hits per min

Config file:

worker_processes  4;  # 2 * Number of CPUs

events {
    worker_connections  19000;  # It's the key to high performance - have a lot of connections available
}

worker_rlimit_nofile    20000;  # Each connection needs a filehandle (or 2 if you are proxying)


# Total amount of users you can serve = worker_processes * worker_connections

more info: Optimizing nginx for high traffic loads

Getting JSONObject from JSONArray

When using google gson library.

var getRowData =
[{
    "dayOfWeek": "Sun",
    "date": "11-Mar-2012",
    "los": "1",
    "specialEvent": "",
    "lrv": "0"
},
{
    "dayOfWeek": "Mon",
    "date": "",
    "los": "2",
    "specialEvent": "",
    "lrv": "0.16"
}];

    JsonElement root = new JsonParser().parse(request.getParameter("getRowData"));
     JsonArray  jsonArray = root.getAsJsonArray();
     JsonObject  jsonObject1 = jsonArray.get(0).getAsJsonObject();
     String dayOfWeek = jsonObject1.get("dayOfWeek").toString();

// when using jackson library

    JsonFactory f = new JsonFactory();
              ObjectMapper mapper = new ObjectMapper();
          JsonParser jp = f.createJsonParser(getRowData);
          // advance stream to START_ARRAY first:
          jp.nextToken();
          // and then each time, advance to opening START_OBJECT
         while (jp.nextToken() == JsonToken.START_OBJECT) {
            Map<String,Object> userData = mapper.readValue(jp, Map.class);
            userData.get("dayOfWeek");
            // process
           // after binding, stream points to closing END_OBJECT
        }

how to pass variable from shell script to sqlplus

You appear to have a heredoc containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF

or if BUILDING is $2 in your script:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF

If your file.sql had an exit at the end then it would be even simpler as you wouldn't need the heredoc:

sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2

In your SQL you can then refer to the position parameters using substitution variables:

...
}',SEM_Models('&1'),NULL,
...

The &1 will be replaced with the first value passed to the SQL script, BUILDING; because that is a string it still needs to be enclosed in quotes. You might want to set verify off to stop if showing you the substitutions in the output.


You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1, the second is &2, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF

or:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF

If total_count is being passed to your shell script then just use its positional parameter, $4 or whatever. And your SQL would then be:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:

define MY_ALIAS = &1
define MY_MODEL = &2

SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

From your separate question, maybe you just wanted:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

... so the alias will be the same value you're querying on (the value in $2, or BUILDING in the original part of the answer). You can refer to a substitution variable as many times as you want.

That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:

select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT

If you set pages 0 and set heading off, your repeated calls might appear in a neat list. You might also need to set tab off and possibly use rpad('&1', 20) or similar to make that column always the same width. Or get the results as CSV with:

select '&1' ||','|| COUNT(*)

Depends what you're using the results for...

Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection)

I had a similar error with Tomcat 8.0 / MySQL . Changing the jdbc url value from localhost to 127.0.0.1 resolved the issue.

relative path in BAT script

You can get all the required file properties by using the code below:

FOR %%? IN (file_to_be_queried) DO (
    ECHO File Name Only       : %%~n?
    ECHO File Extension       : %%~x?
    ECHO Name in 8.3 notation : %%~sn?
    ECHO File Attributes      : %%~a?
    ECHO Located on Drive     : %%~d?
    ECHO File Size            : %%~z?
    ECHO Last-Modified Date   : %%~t?
    ECHO Parent Folder        : %%~dp?
    ECHO Fully Qualified Path : %%~f?
    ECHO FQP in 8.3 notation  : %%~sf?
    ECHO Location in the PATH : %%~dp$PATH:?
)

Session 'app' error while installing APK

This is a terrible problem, i have facing it so much time, First of all when you run on emulator or real device please make sure that it is not show device is offline in Android monitor, see picture below due to bad cable connection device is showing offline, so make sure first that it is online.

enter image description here

If it's Okay then clean your project and Rebuild your project. You can do it from Build -> clean project / Build-> Rebuild project

Still problem occurs then try to Restart android studio. This is generous error happens due to above cases.But i solve it this way as described.

Create a batch file to copy and rename file

type C:\temp\test.bat>C:\temp\test.log

Choose newline character in Notepad++

on windows 10, Notepad 7.8.5, i found this solution to convert from CRLF to LF.
Edit > Format end of line
and choose either Windows(CR+LF) or Unix(LF)

Global constants file in Swift

Or just in GlobalConstants.swift:

import Foundation

let someNotification = "aaaaNotification"

Touch move getting stuck Ignored attempt to cancel a touchmove

I had this problem and all I had to do is return true from touchend and the warning went away.

Two dimensional array list

A 2d array is simply an array of arrays. The analog for lists is simply a List of Lists.

ArrayList<ArrayList<String>> myList = new ArrayList<ArrayList<String>>();

I'll admit, it's not a pretty solution, especially if you go for a 3 or more dimensional structure.

How to get PHP $_GET array?

Put all the ids into a variable called $ids and separate them with a ",":

$ids = "1,2,3,4,5,6";

Pass them like so:

$url = "?ids={$ids}";

Process them:

$ids = explode(",", $_GET['ids']);

Get CPU Usage from Windows Command Prompt

typeperf "\processor(_total)\% processor time"

does work on Win7, you just need to extract the percent value yourself from the last quoted string.

Detect touch press vs long press vs movement?

I was looking for a similar solution and this is what I would suggest. In the OnTouch method, record the time for MotionEvent.ACTION_DOWN event and then for MotionEvent.ACTION_UP, record the time again. This way you can set your own threshold also. After experimenting few times you will know the max time in millis it would need to record a simple touch and you can use this in move or other method as you like.

Hope this helped. Please comment if you used a different method and solved your problem.

Git 'fatal: Unable to write new index file'

In my case, pausing dropbox sync solved the issue

Call a global variable inside module

For those who didn't know already, you would have to put the declare statement outside your class just like this:

declare var Chart: any;

@Component({
  selector: 'my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss']
})

export class MyComponent {
    //you can use Chart now and compiler wont complain
    private color = Chart.color;
}

In TypeScript the declare keyword is used where you want to define a variable that may not have originated from a TypeScript file.

It is like you tell the compiler that, I know this variable will have a value at runtime, so don't throw a compilation error.

XAMPP Port 80 in use by "Unable to open process" with PID 4

So I have faced the same problem when trying to start apache service and I would like to share my solutions with you. Here is some notes about services or programs that may use port 80:

  1. Skype: skype uses port 80/443 by default. You can change this from tools->options-> advanced->connections and disable checkbox "use port 80 and 443 for addtional incoming connections".
  2. IIS: IIS uses port 80 be default so you need to shut down it. You can use the following two commands net stop w3svc net stop iisadmin
  3. SQL Server Reporting Service: You need to stop this service because it may take port 80 if IIS is not running. Go to local services and stop it.

These options work great with me and I can start apache service without errors.

The other option is to change apache listen port from httpd.conf and set another port number.

Hope this solution helps anyone who face the same problem again.

#1055 - Expression of SELECT list is not in GROUP BY clause and contains nonaggregated column this is incompatible with sql_mode=only_full_group_by

You need to specify all of the columns that you're not using for an aggregation function in your GROUP BY clause like this:

select libelle,credit_initial,disponible_v,sum(montant) as montant 
FROM fiche,annee,type where type.id_type=annee.id_type and annee.id_annee=fiche.id_annee 
and annee = year(current_timestamp) GROUP BY libelle,credit_initial,disponible_v order by libelle asc

The full_group_by mode basically makes you write more idiomatic SQL. You can turn off this setting if you'd like. There are different ways to do this that are outlined in the MySQL Documentation. Here's MySQL's definition of what I said above:

MySQL 5.7.5 and up implements detection of functional dependence. If the ONLY_FULL_GROUP_BY SQL mode is enabled (which it is by default), MySQL rejects queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on them. (Before 5.7.5, MySQL does not detect functional dependency and ONLY_FULL_GROUP_BY is not enabled by default. For a description of pre-5.7.5 behavior, see the MySQL 5.6 Reference Manual.)

You're getting the error because you're on a version < 5.7.5

How to detect Ctrl+V, Ctrl+C using JavaScript?

Important note

I was using e.keyCode for a while and i detected that when i press ctrl + ., This attribute returns a wrong number, 190, while the ascii code of . is 46!

So you should use e.key.toUpperCase().charCodeAt(0) instead of e.keyCode.

Trying to retrieve first 5 characters from string in bash error?

The original syntax will work with BASH but not with DASH. On debian systems you might think you are using bash, but maybe dash instead. If /bin/dash/exist then try temporarily renaming dash to something like no.dash, and then create soft a link, aka ln -s /bin/bash /bin/dash and see if that fixes the problem.

How to send POST request?

If you don't want to use a module you have to install like requests, and your use case is very basic, then you can use urllib2

urllib2.urlopen(url, body)

See the documentation for urllib2 here: https://docs.python.org/2/library/urllib2.html.

Find and replace with a newline in Visual Studio Code

CTRL + H, then select regex (*) and write \n

Shorter version: CTRL+H ALT+R \n

how to query for a list<String> in jdbctemplate

Use following code

List data = getJdbcTemplate().queryForList(query,String.class)

What exactly is a Context in Java?

In programming terms, it's the larger surrounding part which can have any influence on the behaviour of the current unit of work. E.g. the running environment used, the environment variables, instance variables, local variables, state of other classes, state of the current environment, etcetera.

In some API's you see this name back in an interface/class, e.g. Servlet's ServletContext, JSF's FacesContext, Spring's ApplicationContext, Android's Context, JNDI's InitialContext, etc. They all often follow the Facade Pattern which abstracts the environmental details the enduser doesn't need to know about away in a single interface/class.

Sort objects in ArrayList by date?

You can make your object comparable:

public static class MyObject implements Comparable<MyObject> {

  private Date dateTime;

  public Date getDateTime() {
    return dateTime;
  }

  public void setDateTime(Date datetime) {
    this.dateTime = datetime;
  }

  @Override
  public int compareTo(MyObject o) {
    return getDateTime().compareTo(o.getDateTime());
  }
}

And then you sort it by calling:

Collections.sort(myList);

However sometimes you don't want to change your model, like when you want to sort on several different properties. In that case, you can create comparator on the fly:

Collections.sort(myList, new Comparator<MyObject>() {
  public int compare(MyObject o1, MyObject o2) {
      return o1.getDateTime().compareTo(o2.getDateTime());
  }
});

However, the above works only if you're certain that dateTime is not null at the time of comparison. It's wise to handle null as well to avoid NullPointerExceptions:

public static class MyObject implements Comparable<MyObject> {

  private Date dateTime;

  public Date getDateTime() {
    return dateTime;
  }

  public void setDateTime(Date datetime) {
    this.dateTime = datetime;
  }

  @Override
  public int compareTo(MyObject o) {
    if (getDateTime() == null || o.getDateTime() == null)
      return 0;
    return getDateTime().compareTo(o.getDateTime());
  }
}

Or in the second example:

Collections.sort(myList, new Comparator<MyObject>() {
  public int compare(MyObject o1, MyObject o2) {
      if (o1.getDateTime() == null || o2.getDateTime() == null)
        return 0;
      return o1.getDateTime().compareTo(o2.getDateTime());
  }
});

How to configure "Shorten command line" method for whole project in IntelliJ

Intellij 2018.2.5

Run => Edit Configurations => Choose Node on the left hand side => expand Environment => Shorten Command line options => choose Classpath file or JAR manifest

Screen shot of Run/Debug Configuration showing the command line options

Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)

Python datetime objects don't have time zone info by default, and without it, Python actually violates the ISO 8601 specification (if no time zone info is given, assumed to be local time). You can use the pytz package to get some default time zones, or directly subclass tzinfo yourself:

from datetime import datetime, tzinfo, timedelta
class simple_utc(tzinfo):
    def tzname(self,**kwargs):
        return "UTC"
    def utcoffset(self, dt):
        return timedelta(0)

Then you can manually add the time zone info to utcnow():

>>> datetime.utcnow().replace(tzinfo=simple_utc()).isoformat()
'2014-05-16T22:51:53.015001+00:00'

Note that this DOES conform to the ISO 8601 format, which allows for either Z or +00:00 as the suffix for UTC. Note that the latter actually conforms to the standard better, with how time zones are represented in general (UTC is a special case.)

Returning JSON object as response in Spring Boot

use ResponseEntity<ResponseBean>

Here you can use ResponseBean or Any java bean as you like to return your api response and it is the best practice. I have used Enum for response. it will return status code and status message of API.

@GetMapping(path = "/login")
public ResponseEntity<ServiceStatus> restApiExample(HttpServletRequest request,
            HttpServletResponse response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        loginService.login(username, password, request);
        return new ResponseEntity<ServiceStatus>(ServiceStatus.LOGIN_SUCCESS,
                HttpStatus.ACCEPTED);
    }

for response ServiceStatus or(ResponseBody)

    public enum ServiceStatus {

    LOGIN_SUCCESS(0, "Login success"),

    private final int id;
    private final String message;

    //Enum constructor
    ServiceStatus(int id, String message) {
        this.id = id;
        this.message = message;
    }

    public int getId() {
        return id;
    }

    public String getMessage() {
        return message;
    }
}

Spring REST API should have below key in response

  1. Status Code
  2. Message

you will get final response below

{

   "StatusCode" : "0",

   "Message":"Login success"

}

you can use ResponseBody(java POJO, ENUM,etc..) as per your requirement.

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

And why don't you try with this ??? :

var itemsMax = items.Where(x => x.Height == items.Max(y => y.Height));

OR more optimise :

var itemMaxHeight = items.Max(y => y.Height);
var itemsMax = items.Where(x => x.Height == itemMaxHeight);

mmm ?

What is this spring.jpa.open-in-view=true property in Spring Boot?

This property will register an OpenEntityManagerInViewInterceptor, which registers an EntityManager to the current thread, so you will have the same EntityManager until the web request is finished. It has nothing to do with a Hibernate SessionFactory etc.

On duplicate key ignore?

Mysql has this handy UPDATE INTO command ;)

edit Looks like they renamed it to REPLACE

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted

PHP How to find the time elapsed since a date time?

Be warned, the majority of the mathematically calculated examples have a hard limit of 2038-01-18 dates and will not work with fictional dates.

As there was a lack of DateTime and DateInterval based examples, I wanted to provide a multi-purpose function that satisfies the OP's need and others wanting compound elapsed periods, such as 1 month 2 days ago. Along with a bunch of other use cases, such as a limit to display the date instead of the elapsed time, or to filter out portions of the elapsed time result.

Additionally the majority of the examples assume elapsed is from the current time, where the below function allows for it to be overridden with the desired end date.

/**
 * multi-purpose function to calculate the time elapsed between $start and optional $end
 * @param string|null $start the date string to start calculation
 * @param string|null $end the date string to end calculation
 * @param string $suffix the suffix string to include in the calculated string
 * @param string $format the format of the resulting date if limit is reached or no periods were found
 * @param string $separator the separator between periods to use when filter is not true
 * @param null|string $limit date string to stop calculations on and display the date if reached - ex: 1 month
 * @param bool|array $filter false to display all periods, true to display first period matching the minimum, or array of periods to display ['year', 'month']
 * @param int $minimum the minimum value needed to include a period
 * @return string
 */
function elapsedTimeString($start, $end = null, $limit = null, $filter = true, $suffix = 'ago', $format = 'Y-m-d', $separator = ' ', $minimum = 1)
{
    $dates = (object) array(
        'start' => new DateTime($start ? : 'now'),
        'end' => new DateTime($end ? : 'now'),
        'intervals' => array('y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second'),
        'periods' => array()
    );
    $elapsed = (object) array(
        'interval' => $dates->start->diff($dates->end),
        'unknown' => 'unknown'
    );
    if ($elapsed->interval->invert === 1) {
        return trim('0 seconds ' . $suffix);
    }
    if (false === empty($limit)) {
        $dates->limit = new DateTime($limit);
        if (date_create()->add($elapsed->interval) > $dates->limit) {
            return $dates->start->format($format) ? : $elapsed->unknown;
        }
    }
    if (true === is_array($filter)) {
        $dates->intervals = array_intersect($dates->intervals, $filter);
        $filter = false;
    }
    foreach ($dates->intervals as $period => $name) {
        $value = $elapsed->interval->$period;
        if ($value >= $minimum) {
            $dates->periods[] = vsprintf('%1$s %2$s%3$s', array($value, $name, ($value !== 1 ? 's' : '')));
            if (true === $filter) {
                break;
            }
        }
    }
    if (false === empty($dates->periods)) {
        return trim(vsprintf('%1$s %2$s', array(implode($separator, $dates->periods), $suffix)));
    }

    return $dates->start->format($format) ? : $elapsed->unknown;
}

One thing to note - the retrieved intervals for the supplied filter values do not carry over to the next period. The filter merely displays the resulting value of the supplied periods and does not recalculate the periods to display only the desired filter total.


Usage

For the OP's need of displaying the highest period (as of 2015-02-24).

echo elapsedTimeString('2010-04-26');
/** 4 years ago */

To display compound periods and supply a custom end date (note the lack of time supplied and fictional dates).

echo elapsedTimeString('1920-01-01', '2500-02-24', null, false);
/** 580 years 1 month 23 days ago */

To display the result of filtered periods (ordering of array doesn't matter).

echo elapsedTimeString('2010-05-26', '2012-02-24', null, ['month', 'year']);
/** 1 year 8 months ago */

To display the start date in the supplied format (default Y-m-d) if the limit is reached.

echo elapsedTimeString('2010-05-26', '2012-02-24', '1 year');
/** 2010-05-26 */

There are bunch of other use cases. It can also easily be adapted to accept unix timestamps and/or DateInterval objects for the start, end, or limit arguments.

git submodule tracking latest

Edit (2020.12.28): GitHub change default master branch to main branch since October 2020. See https://github.com/github/renaming


Update March 2013

Git 1.8.2 added the possibility to track branches.

"git submodule" started learning a new mode to integrate with the tip of the remote branch (as opposed to integrating with the commit recorded in the superproject's gitlink).

# add submodule to track master branch
git submodule add -b master [URL to Git repo];

# update your submodule
git submodule update --remote 

If you had a submodule already present you now wish would track a branch, see "how to make an existing submodule track a branch".

Also see Vogella's tutorial on submodules for general information on submodules.

Note:

git submodule add -b . [URL to Git repo];
                    ^^^

See git submodule man page:

A special value of . is used to indicate that the name of the branch in the submodule should be the same name as the current branch in the current repository.


See commit b928922727d6691a3bdc28160f93f25712c565f6:

submodule add: If --branch is given, record it in .gitmodules

This allows you to easily record a submodule.<name>.branch option in .gitmodules when you add a new submodule. With this patch,

$ git submodule add -b <branch> <repository> [<path>]
$ git config -f .gitmodules submodule.<path>.branch <branch>

reduces to

$ git submodule add -b <branch> <repository> [<path>]

This means that future calls to

$ git submodule update --remote ...

will get updates from the same branch that you used to initialize the submodule, which is usually what you want.

Signed-off-by: W. Trevor King [email protected]


Original answer (February 2012):

A submodule is a single commit referenced by a parent repo.
Since it is a Git repo on its own, the "history of all commits" is accessible through a git log within that submodule.

So for a parent to track automatically the latest commit of a given branch of a submodule, it would need to:

  • cd in the submodule
  • git fetch/pull to make sure it has the latest commits on the right branch
  • cd back in the parent repo
  • add and commit in order to record the new commit of the submodule.

gitslave (that you already looked at) seems to be the best fit, including for the commit operation.

It is a little annoying to make changes to the submodule due to the requirement to check out onto the correct submodule branch, make the change, commit, and then go into the superproject and commit the commit (or at least record the new location of the submodule).

Other alternatives are detailed here.

SQL - using alias in Group By

Beware of using aliases when grouping the results from a view in SQLite. You will get unexpected results if the alias name is the same as the column name of any underlying tables (to the views.)

Token Authentication vs. Cookies

One of the primary differences is that cookies are subject to Same Origin Policy whereas tokens are not. This creates all kinds of down stream effects.

Since cookies are only sent to and from a particular host that host must bear the burden of authenticating the user and the user must create an account with security data with that host in order to be verifiable.

Tokens on the other hand are issued and are not subject to same origin policy. The issuer can be literally anybody and it is up to the host to decide which issuers to trust. An issuer like Google and Facebook is typically well trusted so a host can shift the burden of authenticating the user (including storing all user security data) to another party and the user can consolidate their personal data under a specific issuer and not have to remember a bunch of different passwords for each host they interact with.

This allows for single sign on scenarios that reduce overall friction in the user experience. In theory the web also becomes more secure as specialised identity providers emerge to provide auth services instead of having every ma and pa website spinning up their own, likely half baked, auth systems. And as these providers emerge the cost of providing secure web resources for even very basic resources trends towards zero.

So in general tokens reduce the friction and costs associated with providing authentication and shifts the burden of the various aspects of a secure web to centralised parties better able to both implement and maintain security systems.

How to connect access database in c#

You are building a DataGridView on the fly and set the DataSource for it. That's good, but then do you add the DataGridView to the Controls collection of the hosting form?

this.Controls.Add(dataGridView1);

By the way the code is a bit confused

String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
string sql  = "SELECT Clients  FROM Tables";
using(OleDbConnection conn = new OleDbConnection(connection))
{
     conn.Open();
     DataSet ds = new DataSet();
     DataGridView dataGridView1 = new DataGridView();
     using(OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn))
     {
         adapter.Fill(ds);
         dataGridView1.DataSource = ds;
         // Of course, before addint the datagrid to the hosting form you need to 
         // set position, location and other useful properties. 
         // Why don't you create the DataGrid with the designer and use that instance instead?
         this.Controls.Add(dataGridView1);
     }
}

EDIT After the comments below it is clear that there is a bit of confusion between the file name (TABLES.ACCDB) and the name of the table CLIENTS.
The SELECT statement is defined (in its basic form) as

 SELECT field_names_list FROM _tablename_

so the correct syntax to use for retrieving all the clients data is

 string sql  = "SELECT * FROM Clients";

where the * means -> all the fields present in the table

How can I develop for iPhone using a Windows development machine?

Hooray! You can now more easily accomplish this with the latest Xamarin.iOS, using a network-linked mac providing the build and deployment capabilities.

See here for more details:

introduction to xamarin ios for visual studio

Jquery: Checking to see if div contains text, then action

Your code contains two problems:

  • The equality operator in JavaScript is ==, not =.
  • jQuery.text() joins all text nodes of matched elements into a single string. If you have two successive elements, of which the first contains 'some' and the second contains 'Text', then your code will incorrectly think that there exists an element that contains 'someText'.

I suggest the following instead:

if ($('#field > div.field-item:contains("someText")').length > 0) {
    $("#somediv").addClass("thisClass");
}

Create request with POST, which response codes 200 or 201 and content

The idea is that the response body gives you a page that links you to the thing:

201 Created

The 201 (Created) status code indicates that the request has been fulfilled and has resulted in one or more new resources being created. The primary resource created by the request is identified by either a Location header field in the response or, if no Location field is received, by the effective request URI.

This means that you would include a Location in the response header that gives the URL of where you can find the newly created thing:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597

Response body

They then go on to mention what you should include in the response body:

The 201 response payload typically describes and links to the resource(s) created.

For the human using the browser, you give them something they can look at, and click, to get to their newly created resource:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: text/html

Your answer has been saved! 
Click <A href="/a/36373586/12597">here</A> to view it.

If the page will only be used by a robot, the it makes sense to have the response be computer readable:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: application/xml

<createdResources>
   <questionID>1860645</questionID>
   <answerID>36373586</answerID>
   <primary>/a/36373586/12597</primary>
   <additional>
      <resource>http://stackoverflow.com/questions/1860645/create-request-with-post-which-response-codes-200-or-201-and-content/36373586#36373586</resource>
      <resource>http://stackoverflow.com/a/1962757/12597</resource>
   </additional>
</createdResource>

Or, if you prefer:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: application/json

{ 
   "questionID": 1860645, 
   "answerID": 36373586,
   "primary": "/a/36373586/12597",
   "additional": [
      "http://stackoverflow.com/questions/1860645/create-request-with-post-which-response-codes-200-or-201-and-content/36373586#36373586",
      "http://stackoverflow.com/a/36373586/12597"
   ]
}

The response is entirely up to you; it's arbitrarily what you'd like.

Cache friendly

Finally there's the optimization that I can pre-cache the created resource (because I already have the content; I just uploaded it). The server can return a date or ETag which I can store with the content I just uploaded:

See Section 7.2 for a discussion of the meaning and purpose of validator header fields, such as ETag and Last-Modified, in a 201 response.

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/23704283/12597
Content-Type: text/html
ETag: JF2CA53BOMQGU5LTOQQGC3RAMV4GC3LQNRSS4
Last-Modified: Sat, 02 Apr 2016 12:22:39 GMT 

Your answer has been saved! 
Click <A href="/a/36373586/12597">here</A> to view it.

And ETag s are purely arbitrary values. Having them be different when a resource changes (and caches need to be updated) is all that matters. The ETag is usually a hash (e.g. SHA2). But it can be a database rowversion, or an incrementing revision number. Anything that will change when the thing changes.

What is __pycache__?

__pycache__ is a folder containing Python 3 bytecode compiled and ready to be executed.

I don't recommend routinely deleting these files or suppressing creation during development as it may hurt performance. Just have a recursive command ready (see below) to clean up when needed as bytecode can become stale in edge cases (see comments).

Python programmers usually ignore bytecode. Indeed __pycache__ and *.pyc are common lines to see in .gitignore files. Bytecode is not meant for distribution and can be disassembled using dis module.


If you are using OS X you can easily hide all of these folders in your project by running following command from the root folder of your project.

find . -name '__pycache__' -exec chflags hidden {} \;

Replace __pycache__ with *.pyc for Python 2.

This sets a flag on all those directories (.pyc files) telling Finder/Textmate 2 to exclude them from listings. Importantly the bytecode is there, it's just hidden.

Rerun the command if you create new modules and wish to hide new bytecode or if you delete the hidden bytecode files.


On Windows the equivalent command might be (not tested, batch script welcome):

dir * /s/b | findstr __pycache__ | attrib +h +s +r

Which is same as going through the project hiding folders using right-click > hide...


Running unit tests is one scenario (more in comments) where deleting the *.pyc files and __pycache__ folders is indeed useful. I use the following lines in my ~/.bash_profile and just run cl to clean up when needed.

alias cpy='find . -name "__pycache__" -delete'
alias cpc='find . -name "*.pyc"       -delete'
...
alias cl='cpy && cpc && ...'

and more lately

# pip install pyclean
pyclean .

How to tell if browser/tab is active

If you are trying to do something similar to the Google search page when open in Chrome, (where certain events are triggered when you 'focus' on the page), then the hover() event may help.

$(window).hover(function() {
  // code here...
});

Re-run Spring Boot Configuration Annotation Processor to update generated metadata

None of these options worked for me. I've found that the auto detection of annotation processors to be pretty flaky. I ended up creating a plugin section in the pom.xml file that explicitly sets the annotation processors that are used for the project. The advantage of this is that you don't need to rely on any IDE settings.

<plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.7.0</version>
            <configuration>
                <compilerVersion>1.8</compilerVersion>
                <source>1.8</source>
                <target>1.8</target>
                <annotationProcessors>
                    <annotationProcessor>org.springframework.boot.configurationprocessor.ConfigurationMetadataAnnotationProcessor</annotationProcessor>
                    <annotationProcessor>lombok.launch.AnnotationProcessorHider$AnnotationProcessor</annotationProcessor>
                    <annotationProcessor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</annotationProcessor>
                </annotationProcessors>
            </configuration>
        </plugin>

Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"

just unpaired your iPhone and reconnected it and make connect via network this not use cable any more.

SQL Server Group by Count of DateTime Per Hour?

You can also achieve this by using following SQL with date and hour in same columns and proper date time format and ordered by date time

SELECT  dateadd(hour, datediff(hour, 0, StartDate), 0) as 'ForDate', 
    COUNT(*) as 'Count' 
FROM #Events
GROUP BY dateadd(hour, datediff(hour, 0, LogTime), 0)
ORDER BY ForDate

Custom Input[type="submit"] style not working with jquerymobile button

I'm assume you cannot get css working for your button using anchor tag. So you need to override the css styles which are being overwritten by other elements using !important property.

HTML

<a href="#" class="selected_btn" data-role="button">Button name</a>

CSS

.selected_btn
{
    border:1px solid red;
    text-decoration:none;
    font-family:helvetica;
    color:red !important;            
    background:url('http://www.lessardstephens.com/layout/images/slideshow_big.png') repeat-x;
}

Here is the demo

How do I put text on ProgressBar?

AVOID FLICKERING TEXT

The solution provided by Barry above is excellent, but there's is the "flicker-problem".

As soon as the Value is above zero the OnPaint will be envoked repeatedly and the text will flicker.

There is a solution to this. We do not need VisualStyles for the object since we will be drawing it with our own code.

Add the following code to the custom object Barry wrote and you will avoid the flicker:

    [DllImportAttribute("uxtheme.dll")]
    private static extern int SetWindowTheme(IntPtr hWnd, string appname, string idlist);

    protected override void OnHandleCreated(EventArgs e)
    {
        SetWindowTheme(this.Handle, "", "");
        base.OnHandleCreated(e);
    }

I did not write this myself. It found it here: https://stackoverflow.com/a/299983/1163954

I've testet it and it works.

Android Studio not showing modules in project structure

As for me issue was that the first line in the build.gradle file of the OpenCV library.

It was something like this: apply plugin: 'com.android.application' This refers to the fact that the imported OpenCV is an application and not a library. It exists for OpenCV above 4.1.0. So change it to: Something like this: apply plugin: 'com.android.library'.

You might get an error in ApplicationId, comment it out in the gradle file.

Issue with virtualenv - cannot activate

  1. For activation you can go to the venv your virtualenv directory by cd venv.

  2. Then on Windows, type dir (on unix, type ls). You will get 5 folders include, Lib, Scripts, tcl and 60

  3. Now type .\Scripts\activate to activate your virtualenv venv.

Your prompt will change to indicate that you are now operating within the virtual environment. It will look something like this (venv)user@host:~/venv$.

And your venv is activated now.

What's the difference between Docker Compose vs. Dockerfile

The answer is neither.

Docker Compose (herein referred to as compose) will use the Dockerfile if you add the build command to your project's docker-compose.yml.

Your Docker workflow should be to build a suitable Dockerfile for each image you wish to create, then use compose to assemble the images using the build command.

You can specify the path to your individual Dockerfiles using build /path/to/dockerfiles/blah where /path/to/dockerfiles/blah is where blah's Dockerfile lives.

Copying and pasting data using VBA code

Use the PasteSpecial method:

sht.Columns("A:G").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues

BUT your big problem is that you're changing your ActiveSheet to "Data" and not changing it back. You don't need to do the Activate and Select, as per my code (this assumes your button is on the sheet you want to copy to).

How to increase number of threads in tomcat thread pool?

Sounds like you should stay with the defaults ;-)

Seriously: The number of maximum parallel connections you should set depends on your expected tomcat usage and also on the number of cores on your server. More cores on your processor => more parallel threads that can be executed.

See here how to configure...

Tomcat 9: https://tomcat.apache.org/tomcat-9.0-doc/config/executor.html

Tomcat 8: https://tomcat.apache.org/tomcat-8.0-doc/config/executor.html

Tomcat 7: https://tomcat.apache.org/tomcat-7.0-doc/config/executor.html

Tomcat 6: https://tomcat.apache.org/tomcat-6.0-doc/config/executor.html

How to get the Enum Index value in C#

Firstly, there could be two values that you're referring to:

Underlying Value

If you are asking about the underlying value, which could be any of these types: byte, sbyte, short, ushort, int, uint, long or ulong

Then you can simply cast it to it's underlying type. Assuming it's an int, you can do it like this:

int eValue = (int)enumValue;

However, also be aware of each items default value (first item is 0, second is 1 and so on) and the fact that each item could have been assigned a new value, which may not necessarily be in any order particular order! (Credit to @JohnStock for the poke to clarify).

This example assigns each a new value, and show the value returned:

public enum MyEnum
{
    MyValue1 = 34,
    MyValue2 = 27
}

(int)MyEnum.MyValue2 == 27; // True

Index Value

The above is generally the most commonly required value, and is what your question detail suggests you need, however each value also has an index value (which you refer to in the title). If you require this then please see other answers below for details.

compare two files in UNIX

Most easy way: sort files with sort(1) and then use diff(1).

What do column flags mean in MySQL Workbench?

This exact question is answered on mySql workbench-faq:

Hover over an acronym to view a description, and see the Section 8.1.11.2, “The Columns Tab” and MySQL CREATE TABLE documentation for additional details.

That means hover over an acronym in the mySql Workbench table editor.

Section 8.1.11.2, “The Columns Tab”

How to wrap text around an image using HTML/CSS

If the image size is variable or the design is responsive, in addition to wrapping the text, you can set a min width for the paragraph to avoid it to become too narrow.
Give an invisible CSS pseudo-element with the desired minimum paragraph width. If there isn't enough space to fit this pseudo-element, then it will be pushed down underneath the image, taking the paragraph with it.

#container:before {
  content: ' ';
  display: table;
  width: 10em;    /* Min width required */
}
#floated{
    float: left;
    width: 150px;
    background: red;
}

Angular 6: saving data to local storage

First you should understand how localStorage works. you are doing wrong way to set/get values in local storage. Please read this for more information : How to Use Local Storage with JavaScript

Import Package Error - Cannot Convert between Unicode and Non Unicode String Data Type

This a solution that uses the IDE to fix:

  1. Add a Data Conversion item to your dataflow as shown below;

enter image description here

  1. Double click on the Data Conversion item, and set it as shown:

enter image description here

  1. Now double click on the DB Destination item, Click on Mapping, and ensure that your input Column is actually the same as coming from the Copy of [your column name], which is in fact the Data Conversion output NOT the DB Source Output (be careful here). Here is a screenshot:

enter image description here

And thats it .. save and run ..

Vertical dividers on horizontal UL menu

A simpler solution would be to just add #navigation ul li~li { border-left: 1px solid #857D7A; }

How to change plot background color?

simpler answer:

ax = plt.axes()
ax.set_facecolor('silver')

Android textview outline text

I've written a class to perform text with outline and still support all the other attributes and drawing of a normal text view.

it basically uses the super.onDraw(Canves canvas) on the TextView but draws twice with different styles.

hope this helps.

public class TextViewOutline extends TextView {

    // constants
    private static final int DEFAULT_OUTLINE_SIZE = 0;
    private static final int DEFAULT_OUTLINE_COLOR = Color.TRANSPARENT;

    // data
    private int mOutlineSize;
    private int mOutlineColor;
    private int mTextColor;
    private float mShadowRadius;
    private float mShadowDx;
    private float mShadowDy;
    private int mShadowColor;

    public TextViewOutline(Context context) {
        this(context, null);
    }

    public TextViewOutline(Context context, AttributeSet attrs) {
        super(context, attrs);
        setAttributes(attrs);
    }

    private void setAttributes(AttributeSet attrs){ 
        // set defaults
        mOutlineSize = DEFAULT_OUTLINE_SIZE;
        mOutlineColor = DEFAULT_OUTLINE_COLOR;   
        // text color   
        mTextColor = getCurrentTextColor();
        if(attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs,R.styleable.TextViewOutline);
            // outline size
            if (a.hasValue(R.styleable.TextViewOutline_outlineSize)) {
                mOutlineSize = (int) a.getDimension(R.styleable.TextViewOutline_outlineSize, DEFAULT_OUTLINE_SIZE);
            }
            // outline color
            if (a.hasValue(R.styleable.TextViewOutline_outlineColor)) {
                mOutlineColor = a.getColor(R.styleable.TextViewOutline_outlineColor, DEFAULT_OUTLINE_COLOR);
            }
            // shadow (the reason we take shadow from attributes is because we use API level 15 and only from 16 we have the get methods for the shadow attributes)
            if (a.hasValue(R.styleable.TextViewOutline_android_shadowRadius) 
                    || a.hasValue(R.styleable.TextViewOutline_android_shadowDx)
                    || a.hasValue(R.styleable.TextViewOutline_android_shadowDy) 
                    || a.hasValue(R.styleable.TextViewOutline_android_shadowColor)) {
                mShadowRadius = a.getFloat(R.styleable.TextViewOutline_android_shadowRadius, 0);
                mShadowDx = a.getFloat(R.styleable.TextViewOutline_android_shadowDx, 0);
                mShadowDy = a.getFloat(R.styleable.TextViewOutline_android_shadowDy, 0);
                mShadowColor = a.getColor(R.styleable.TextViewOutline_android_shadowColor, Color.TRANSPARENT);
            }

            a.recycle();
        }

        PFLog.d("mOutlineSize = " + mOutlineSize);
        PFLog.d("mOutlineColor = " + mOutlineColor);
    }

    private void setPaintToOutline(){
        Paint paint = getPaint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(mOutlineSize);
        super.setTextColor(mOutlineColor);
        super.setShadowLayer(mShadowRadius, mShadowDx, mShadowDy,  mShadowColor);
    }

    private void setPaintToRegular() {
        Paint paint = getPaint();
        paint.setStyle(Paint.Style.FILL);
        paint.setStrokeWidth(0);
        super.setTextColor(mTextColor);
        super.setShadowLayer(0, 0, 0, Color.TRANSPARENT);
    } 

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setPaintToOutline();
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    public void setTextColor(int color) {
        super.setTextColor(color);
        mTextColor = color;
    } 

    @Override
    public void setShadowLayer(float radius, float dx, float dy, int color) {
        super.setShadowLayer(radius, dx, dy, color);
        mShadowRadius = radius;
        mShadowDx = dx;
        mShadowDy = dy;
        mShadowColor = color;
    }

    public void setOutlineSize(int size){
        mOutlineSize = size;
    }

    public void setOutlineColor(int color){
       mOutlineColor = color;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        setPaintToOutline();
        super.onDraw(canvas);
        setPaintToRegular();
        super.onDraw(canvas);
    }

}

attr.xml

<declare-styleable name="TextViewOutline">
    <attr name="outlineSize" format="dimension"/>
    <attr name="outlineColor" format="color|reference"/>
    <attr name="android:shadowRadius"/>
    <attr name="android:shadowDx"/>
    <attr name="android:shadowDy"/>
    <attr name="android:shadowColor"/>
</declare-styleable>

jQuery change input text value

no, you need to do something like:

$('input.sitebg').val('000000');

but you should really be using unique IDs if you can.

You can also get more specific, such as:

$('input[type=text].sitebg').val('000000');

EDIT:

do this to find your input based on the name attribute:

$('input[name=sitebg]').val('000000');

Set a div width, align div center and text align left

Try:

#your_div_id {
  width: 855px;
  margin:0 auto;
  text-align: center;
}

Convert Enumeration to a Set/List

When using guava (See doc) there is Iterators.forEnumeration. Given an Enumeration x you can do the following:

to get a immutable Set:

ImmutableSet.copyOf(Iterators.forEnumeration(x));

to get a immutable List:

ImmutableList.copyOf(Iterators.forEnumeration(x));

to get a hashSet:

Sets.newHashSet(Iterators.forEnumeration(x));

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

I had the same problem and solved it by passing path to a directory where CA keys are stored. On Ubuntu it was:

openssl s_client -CApath /etc/ssl/certs/ -connect address.com:443

How to backup a local Git repository?

Found the simple official way after wading through the walls of text above that would make you think there is none.

Create a complete bundle with:

$ git bundle create <filename> --all

Restore it with:

$ git clone <filename> <folder>

This operation is atomic AFAIK. Check official docs for the gritty details.

Regarding "zip": git bundles are compressed and surprisingly small compared to the .git folder size.

JWT (JSON Web Token) automatic prolongation of expiration

Below are the steps to do revoke your JWT access token:

1) When you do login, send 2 tokens (Access token, Refresh token) in response to client .
2) Access token will have less expiry time and Refresh will have long expiry time .
3) Client (Front end) will store refresh token in his local storage and access token in cookies.
4) Client will use access token for calling apis. But when it expires, pick the refresh token from local storage and call auth server api to get the new token.
5) Your auth server will have an api exposed which will accept refresh token and checks for its validity and return a new access token.
6) Once refresh token is expired, User will be logged out.

Please let me know if you need more details , I can share the code (Java + Spring boot) as well.

How can I output a UTF-8 CSV in PHP that Excel will read properly?

You may append the 3 bytes to the file before exporting, it works for me . Before doing that system only work in Windows and HP -UX but failed in Linux.

FileOutputStream fStream = new FileOutputStream( f );
final byte[] bom = new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF };
OutputStreamWriter writer = new OutputStreamWriter( fStream, "UTF8" );
fStream.write( bom );

Have a UTF-8 BOM (3 bytes, hex EF BB BF) at the start of the file. Otherwise Excel will interpret the data according to your locale's default encoding (e.g. cp1252) instead of utf-8

Generating CSV file for Excel, how to have a newline inside a value

Unable to call the built in mb_internal_encoding method?

For OpenSUse (zypper package manager):

zypper install php5-mbstring

and:

zyper install php7-mbstring

In the other hand, you can search them through YaST Software manager.

Note that, you must restart apache http server:

systemctl restart apache2.service

Java generics - ArrayList initialization

A lot of this has to do with polymorphism. When you assign

X = new Y();

X can be much less 'specific' than Y, but not the other way around. X is just the handle you are accessing Y with, Y is the real instantiated thing,

You get an error here because Integer is a Number, but Number is not an Integer.

ArrayList<Integer> a = new ArrayList<Number>(); // compile-time error

As such, any method of X that you call must be valid for Y. Since X is more generally it probably shares some, but not all of Y's methods. Still, any arguments given must be valid for Y.

In your examples with add, an int (small i) is not a valid Object or Integer.

ArrayList<?> a = new ArrayList<?>();

This is no good because you can't actually instantiate an array list containing ?'s. You can declare one as such, and then damn near anything can follow in new ArrayList<Whatever>();

How do you clone a Git repository into a specific folder?

From some reason this syntax is not standing out:

git clone repo-url [folder]

Here folder is an optional path to the local folder (which will be a local repository).

Git clone will also pull code from remote repository into the local repository. In fact it is true:

git clone repo-url  =  git init + git remote add origin repo-url + git pull

Serving static web resources in Spring Boot & Spring Security application

This may be an answer (for spring boot 2) and a question at the same time. It seems that in spring boot 2 combined with spring security everything (means every route/antmatcher) is protected by default if you use an individual security mechanism extended from

WebSecurityConfigurerAdapter

If you don´t use an individual security mechanism, everything is as it was?

In older spring boot versions (1.5 and below) as Andy Wilkinson states in his above answer places like public/** or static/** are permitted by default.

So to sum this question/answer up - if you are using spring boot 2 with spring security and have an individual security mechanism you have to exclusivley permit access to static contents placed on any route. Like so:

@Configuration
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {

private final ThdAuthenticationProvider thdAuthenticationProvider;

private final ThdAuthenticationDetails thdAuthenticationDetails;

/**
 * Overloaded constructor.
 * Builds up the needed dependencies.
 *
 * @param thdAuthenticationProvider a given authentication provider
 * @param thdAuthenticationDetails  given authentication details
 */
@Autowired
public SpringSecurityConfiguration(@NonNull ThdAuthenticationProvider thdAuthenticationProvider,
                                   @NonNull ThdAuthenticationDetails thdAuthenticationDetails) {
    this.thdAuthenticationProvider = thdAuthenticationProvider;
    this.thdAuthenticationDetails = thdAuthenticationDetails;
}

/**
 * Creates the AuthenticationManager with the given values.
 *
 * @param auth the AuthenticationManagerBuilder
 */
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {

    auth.authenticationProvider(thdAuthenticationProvider);
}

/**
 * Configures the http Security.
 *
 * @param http HttpSecurity
 * @throws Exception a given exception
 */
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
            .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
            .antMatchers("/management/**").hasAnyAuthority(Role.Role_Engineer.getValue(),
            Role.Role_Admin.getValue())
            .antMatchers("/settings/**").hasAnyAuthority(Role.Role_Engineer.getValue(),
            Role.Role_Admin.getValue())

            .anyRequest()
            .fullyAuthenticated()
            .and()
            .formLogin()
            .authenticationDetailsSource(thdAuthenticationDetails)
            .loginPage("/login").permitAll()
            .defaultSuccessUrl("/bundle/index", true)
            .failureUrl("/denied")
            .and()
            .logout()
            .invalidateHttpSession(true)
            .logoutSuccessUrl("/login")
            .logoutUrl("/logout")
            .and()
            .exceptionHandling()
            .accessDeniedHandler(new CustomAccessDeniedHandler());
}

}

Please mind this line of code, which is new:

.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()

If you use spring boot 1.5 and below you don´t need to permit these locations (static/public/webjars etc.) explicitly.

Here is the official note, what has changed in the new security framework as to old versions of itself:

Security changes in Spring Boot 2.0 M4

I hope this helps someone. Thank you! Have a nice day!

new Image(), how to know if image 100% loaded or not?

Use the load event:

img = new Image();

img.onload = function(){
  // image  has been loaded
};

img.src = image_url;

Also have a look at:

Remove NA values from a vector

Use discard from purrr (works with lists and vectors).

discard(v, is.na) 

The benefit is that it is easy to use pipes; alternatively use the built-in subsetting function [:

v %>% discard(is.na)
v %>% `[`(!is.na(.))

Note that na.omit does not work on lists:

> x <- list(a=1, b=2, c=NA)
> na.omit(x)
$a
[1] 1

$b
[1] 2

$c
[1] NA

php date validation

This function working well,

function validateDate($date, $format = 'm/d/Y'){
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) === $date;
}

In excel how do I reference the current row but a specific column?

If you dont want to hard-code the cell addresses you can use the ROW() function.

eg: =AVERAGE(INDIRECT("A" & ROW()), INDIRECT("C" & ROW()))

Its probably not the best way to do it though! Using Auto-Fill and static columns like @JaiGovindani suggests would be much better.

Redirecting from cshtml page

Change to this:

@{ Response.Redirect("~/HOME/NoResults");}

What does ==$0 (double equals dollar zero) mean in Chrome Developer Tools?

The other answers here clearly explained what does it mean.I like to explain its use.

You can select an element in the elements tab and switch to console tab in chrome. Just type $0 or $1 or whatever number and press enter and the element will be displayed in the console for your use.

screenshot of chrome dev tools

"insufficient memory for the Java Runtime Environment " message in eclipse

In your Eclipse installation directory you should be able to find the file eclipse.ini. Open it and find the -vmargs section. Adjust the value of:

-Xmx1024m

In this example it is set to 1GB.

Read XLSX file in Java

You can use Apache Tika for that:

String parse(File xlsxFile) {
    return new Tika().parseToString(xlsxFile);
}

Tika uses Apache POI for parsing XLSX files.

Here are some usage examples for Tiki.

Alternatively, if you want to handle each cell of the spreadsheet individually, here's one way to do this with POI:

void parse(File xlsx) {
    try (XSSFWorkbook workbook = new XSSFWorkbook(xlsx)) {
        // Handle each cell in each sheet
        workbook.forEach(sheet -> sheet.forEach(row -> row.forEach(this::handle)));
    }
    catch (InvalidFormatException | IOException e) {
        System.out.println("Can't parse file " + xlsx);
    }
}

void handle(Cell cell) {
    final String cellContent;
    switch (cell.getCellType()) {
        case Cell.CELL_TYPE_STRING:
            cellContent = cell.getStringCellValue();
            break;
        case Cell.CELL_TYPE_NUMERIC:
            cellContent = String.valueOf(cell.getNumericCellValue());
            break;
        case Cell.CELL_TYPE_BOOLEAN:
            cellContent = String.valueOf(cell.getBooleanCellValue());
            break;
        default:
            cellContent = "Don't know how to handle cell " + cell;
    }
    System.out.println(cellContent);
}

Learning Ruby on Rails

I program with RoR on the Mac OS with textmate, and it's awesome.

I would suggest "Programming Ruby 1.9" (The Pickaxe Book) for Ruby and Agile Web Development with Rails" to learn Rails, both published by the Pragmatic Bookshelf.

Good luck!

How to put a jpg or png image into a button in HTML

<input type= "image" id=" " onclick=" " src=" " />

it works.

How do I filter ForeignKey choices in a Django ModelForm?

To do this with a generic view, like CreateView...

class AddPhotoToProject(CreateView):
    """
    a view where a user can associate a photo with a project
    """
    model = Connection
    form_class = CreateConnectionForm


    def get_context_data(self, **kwargs):
        context = super(AddPhotoToProject, self).get_context_data(**kwargs)
        context['photo'] = self.kwargs['pk']
        context['form'].fields['project'].queryset = Project.objects.for_user(self.request.user)
        return context
    def form_valid(self, form):
        pobj = Photo.objects.get(pk=self.kwargs['pk'])
        obj = form.save(commit=False)
        obj.photo = pobj
        obj.save()

        return_json = {'success': True}

        if self.request.is_ajax():

            final_response = json.dumps(return_json)
            return HttpResponse(final_response)

        else:

            messages.success(self.request, 'photo was added to project!')
            return HttpResponseRedirect(reverse('MyPhotos'))

the most important part of that...

    context['form'].fields['project'].queryset = Project.objects.for_user(self.request.user)

, read my post here

How to use Git Revert

The reason reset and revert tend to come up a lot in the same conversations is because different version control systems use them to mean different things.

In particular, people who are used to SVN or P4 who want to throw away uncommitted changes to a file will often reach for revert before being told that they actually want reset.

Similarly, the revert equivalent in other VCSes is often called rollback or something similar - but "rollback" can also mean "I want to completely discard the last few commits", which is appropriate for reset but not revert. So, there's a lot of confusion where people know what they want to do, but aren't clear on which command they should be using for it.

As for your actual questions about revert...

Okay, you're going to use git revert but how?

git revert first-bad-commit..last-bad-commit

And after running git revert do you have to do something else after? Do you have to commit the changes revert made or does revert directly commit to the repo or what??

By default, git revert prompts you for a commit message and then commits the results. This can be overridden. I quote the man page:

--edit

With this option, git revert will let you edit the commit message prior to committing the revert. This is the default if you run the command from a terminal.

--no-commit

Usually the command automatically creates some commits with commit log messages stating which commits were reverted. This flag applies the changes necessary to revert the named commits to your working tree and the index, but does not make the commits. In addition, when this option is used, your index does not have to match the HEAD commit. The revert is done against the beginning state of your index.

This is useful when reverting more than one commits' effect to your index in a row.

In particular, by default it creates a new commit for each commit you're reverting. You can use revert --no-commit to create changes reverting all of them without committing those changes as individual commits, then commit at your leisure.

How to add a color overlay to a background image?

You can use a pseudo element to create the overlay.

.testclass {
  background-image: url("../img/img.jpg");
  position: relative;
}
.testclass:before {
  content: "";
  position: absolute;
  left: 0; right: 0;
  top: 0; bottom: 0;
  background: rgba(0,0,0,.5);
}

How to get last key in an array?

Try using array_pop and array_keys function as follows:

<?php

$array = array(
    'one' => 1,
    'two' => 2,
    'three' => 3
);

echo array_pop(array_keys($array)); // prints three

?>

Dynamically adding properties to an ExpandoObject

As explained here by Filip - http://www.filipekberg.se/2011/10/02/adding-properties-and-methods-to-an-expandoobject-dynamicly/

You can add a method too at runtime.

x.Add("Shout", new Action(() => { Console.WriteLine("Hellooo!!!"); }));
x.Shout();

What's the meaning of exception code "EXC_I386_GPFLT"?

I'm seeing this error code in rotation crashes on Xcode 12.0 Beta 6, only on the iOS 14 simulator. It doesn't crash on my real device running iOS 13 though! So if you're running beta stuff and seeing rotation crashes in the simulator, maybe you just need to run on a real device with a non-beta iOS version.

Python error: "IndexError: string index out of range"

There were several problems in your code. Here you have a functional version you can analyze (Lets set 'hello' as the target word):

word = 'hello'
so_far = "-" * len(word)       # Create variable so_far to contain the current guess

while word != so_far:          # if still not complete
    print(so_far)
    guess = input('>> ')       # get a char guess

    if guess in word:
        print("\nYes!", guess, "is in the word!")

        new = ""
        for i in range(len(word)):  
            if guess == word[i]:
                new += guess        # fill the position with new value
            else:
                new += so_far[i]    # same value as before
        so_far = new
    else:
        print("try_again")

print('finish')

I tried to write it for py3k with a py2k ide, be careful with errors.

SQL Server - copy stored procedures from one db to another

  • Right click on database
  • Tasks
  • Generate Scripts
  • Select the objects you wish to script
  • Script to File
  • Run generated scripts against target database

Trying to merge 2 dataframes but get ValueError

this simple solution works for me

    final = pd.concat([df, rankingdf], axis=1, sort=False)

but you may need to drop some duplicate column first.

Struct inheritance in C++

Yes. The inheritance is public by default.

Syntax (example):

struct A { };
struct B : A { };
struct C : B { };

Is using 'var' to declare variables optional?

I just found the answer from a forum referred by one of my colleague. If you declare a variable outside a function, it's always global. No matter if you use var keyword or not. But, if you declare the variable inside a function, it has a big difference. Inside a function, if you declare the variable using var keyword, it will be local, but if you declare the variable without var keyword, it will be global. It can overwrite your previously declared variables. - See more at: http://forum.webdeveloperszone.com/question/what-is-the-difference-between-using-var-keyword-or-not-using-var-during-variable-declaration/#sthash.xNnLrwc3.dpuf

How to create a testflight invitation code?

after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.

Authentication issues with WWW-Authenticate: Negotiate

Putting this information here for future readers' benefit.

  • 401 (Unauthorized) response header -> Request authentication header

  • Here are several WWW-Authenticate response headers. (The full list is at IANA: HTTP Authentication Schemes.)

    • WWW-Authenticate: Basic-> Authorization: Basic + token - Use for basic authentication
    • WWW-Authenticate: NTLM-> Authorization: NTLM + token (2 challenges)
    • WWW-Authenticate: Negotiate -> Authorization: Negotiate + token - used for Kerberos authentication
      • By the way: IANA has this angry remark about Negotiate: This authentication scheme violates both HTTP semantics (being connection-oriented) and syntax (use of syntax incompatible with the WWW-Authenticate and Authorization header field syntax).

You can set the Authorization: Basic header only when you also have the WWW-Authenticate: Basic header on your 401 challenge.

But since you have WWW-Authenticate: Negotiate this should be the case for Kerberos based authentication.

how to install apk application from my pc to my mobile android

1.question answer-In your mobile having Developer Option in settings and enable that one. after In android studio project source file in bin--> apk file .just copy the apk file and paste in mobile memory in ur pc.. after all finished .you click that apk file in your mobile is automatically installed.

2.question answer-Your mobile is Samsung are just add Samsung Kies software in your pc..its helps to android code run in your mobile ...

How to append multiple items in one line in Python

mylist = [1,2,3]

def multiple_appends(listname, *element):
    listname.extend(element)

multiple_appends(mylist, 4, 5, "string", False)
print(mylist)

OUTPUT:

[1, 2, 3, 4, 5, 'string', False]

Python iterating through object attributes

You can use the standard Python idiom, vars():

for attr, value in vars(k).items():
    print(attr, '=', value)

Simple pagination in javascript

You can use the code from this minimal plugin. https://www.npmjs.com/package/paginator-js

Array.prototype.paginate = function(pageNumber, itemsPerPage){
  pageNumber   = Number(pageNumber)
  itemsPerPage = Number(itemsPerPage)
  pageNumber   = (pageNumber   < 1 || isNaN(pageNumber))   ? 1 : pageNumber
  itemsPerPage = (itemsPerPage < 1 || isNaN(itemsPerPage)) ? 1 : itemsPerPage

  var start     = ((pageNumber - 1) * itemsPerPage)
  var end       = start + itemsPerPage
  var loopCount = 0
  var result    = {
    data: [],
    end: false
  }

  for(loopCount = start; loopCount < end; loopCount++){
    this[loopCount] && result.data.push(this[loopCount]);
  }

  if(loopCount == this.length){
    result.end = true
  }

  return result
}

How to use multiple conditions (With AND) in IIF expressions in ssrs

You don't need an IIF() at all here. The comparisons return true or false anyway.

Also, since this row visibility is on a group row, make sure you use the same aggregate function on the fields as you use in the fields in the row. So if your group row shows sums, then you'd put this in the Hidden property.

=Sum(Fields!OpeningStock.Value) = 0 And
Sum(Fields!GrossDispatched.Value) = 0 And 
Sum(Fields!TransferOutToMW.Value) = 0 And
Sum(Fields!TransferOutToDW.Value) = 0 And
Sum(Fields!TransferOutToOW.Value) = 0 And
Sum(Fields!NetDispatched.Value) = 0 And
Sum(Fields!QtySold.Value) = 0 And
Sum(Fields!StockAdjustment.Value) = 0 And
Sum(Fields!ClosingStock.Value) = 0

But with the above version, if one record has value 1 and one has value -1 and all others are zero then sum is also zero and the row could be hidden. If that's not what you want you could write a more complex expression:

=Sum(
    IIF(
        Fields!OpeningStock.Value=0 AND
        Fields!GrossDispatched.Value=0 AND
        Fields!TransferOutToMW.Value=0 AND
        Fields!TransferOutToDW.Value=0 AND 
        Fields!TransferOutToOW.Value=0 AND
        Fields!NetDispatched.Value=0 AND
        Fields!QtySold.Value=0 AND
        Fields!StockAdjustment.Value=0 AND
        Fields!ClosingStock.Value=0,
        0,
        1
    )
) = 0

This is essentially a fancy way of counting the number of rows in which any field is not zero. If every field is zero for every row in the group then the expression returns true and the row is hidden.

Bash Templating: How to build configuration files from templates with Bash?

# Usage: template your_file.conf.template > your_file.conf
template() {
        local IFS line
        while IFS=$'\n\r' read -r line ; do
                line=${line//\\/\\\\}         # escape backslashes
                line=${line//\"/\\\"}         # escape "
                line=${line//\`/\\\`}         # escape `
                line=${line//\$/\\\$}         # escape $
                line=${line//\\\${/\${}       # de-escape ${         - allows variable substitution: ${var} ${var:-default_value} etc
                # to allow arithmetic expansion or command substitution uncomment one of following lines:
#               line=${line//\\\$\(/\$\(}     # de-escape $( and $(( - allows $(( 1 + 2 )) or $( command ) - UNSECURE
#               line=${line//\\\$\(\(/\$\(\(} # de-escape $((        - allows $(( 1 + 2 ))
                eval "echo \"${line}\"";
        done < "$1"
}

This is the pure bash function adjustable to your liking, used in production and should not break on any input. If it breaks - let me know.

decompiling DEX into Java sourcecode

You might try JADX (https://bitbucket.org/mstrobel/procyon/wiki/Java%20Decompiler), this is a perfect tool for DEX decompilation.

And yes, it is also available online on (my :0)) new site: http://www.javadecompilers.com/apk/

How to scale a UIImageView proportionally?

Here is how you can scale it easily.

This works in 2.x with the Simulator and the iPhone.

UIImage *thumbnail = [originalImage _imageScaledToSize:CGSizeMake(40.0, 40.0) interpolationQuality:1];

Styling every 3rd item of a list using CSS?

You can use the :nth-child selector for that

li:nth-child(3n) {
 /* your rules here */
}

Where is my m2 folder on Mac OS X Mavericks

On the top of the screen you can find the Finder. Click Go -> Go to Folder -> search ~/.m2

If it is not found, as m2 is a hidden file you need to enable visibility by typing the following command in terminal:

defaults write com.apple.finder AppleShowAllFiles YES

How to use setArguments() and getArguments() methods in Fragments?

Eg: Add data:-

   Bundle bundle = new Bundle();
   bundle.putString("latitude", latitude);
   bundle.putString("longitude", longitude);
   bundle.putString("board_id", board_id);
   MapFragment mapFragment = new MapFragment();
   mapFragment.setArguments(bundle);

Eg: Get data :-

String latitude =  getArguments().getString("latitude")

Eloquent - where not equal to

Use where with a != operator in combination with whereNull

Code::where('to_be_used_by_user_id', '!=' , 2)->orWhereNull('to_be_used_by_user_id')->get()

Changing Background Image with CSS3 Animations

Updated for 2020: Yes, it can be done! Here's how.

Snippet demo:

_x000D_
_x000D_
#mydiv{ animation: changeBg 1s infinite; width:143px; height:100px; }
@keyframes changeBg{
   0%,100%  {background-image: url("https://i.stack.imgur.com/YdrqG.png");}
   25% {background-image: url("https://i.stack.imgur.com/2wKWi.png");}
   50% {background-image: url("https://i.stack.imgur.com/HobHO.png");}
   75% {background-image: url("https://i.stack.imgur.com/3hiHO.png");}
}
_x000D_
<div id='mydiv'></div>
_x000D_
_x000D_
_x000D_


Background image [isn't a property that can be animated][1] - you can't tween the property.

Original Answer: (still a good alternative) Instead, try laying out all the images on top of each other using position:absolute, then animate the opacity of all of them to 0 except the one you want repeatedly.

/usr/bin/codesign failed with exit code 1

It might be strange answer for codesign issue in Xcode 9.0. I was receiving this error too and did not know what to be done, because everything was correct.

I went to the keychain, I had the login option "unlocked". I locked it and compiled my build again. Xcode itself asked me to open access keychain. I gave access and it worked.

Steps were:

  1. Go to keychain
  2. Lock it
  3. Archive the code, build the project again

How to set proper codeigniter base url?

Base url set in CodeIgniter for all url

$config['base_url'] = "http://".$_SERVER['HTTP_HOST']."/";

jQuery 'each' loop with JSON array

This works for me:

$.get("data.php", function(data){
    var expected = ['justIn', 'recent', 'old'];
    var outString = '';
    $.each(expected, function(i, val){
        var contentArray = data[val];
        outString += '<ul><li><b>' + val + '</b>: ';
        $.each(contentArray, function(i1, val2){
            var textID = val2.textId;
            var text = val2.text;
            var textType = val2.textType;
            outString += '<br />('+textID+') '+'<i>'+text+'</i> '+textType;
        });
        outString += '</li></ul>';
    });
    $('#contentHere').append(outString);
}, 'json');

This produces this output:

<div id="contentHere"><ul>
<li><b>justIn</b>:
<br />
(123) <i>Hello</i> Greeting<br>
(514) <i>What's up?</i> Question<br>
(122) <i>Come over here</i> Order</li>
</ul><ul>
<li><b>recent</b>:
<br />
(1255) <i>Hello</i> Greeting<br>
(6564) <i>What's up?</i> Question<br>
(0192) <i>Come over here</i> Order</li>
</ul><ul>
<li><b>old</b>:
<br />
(5213) <i>Hello</i> Greeting<br>
(9758) <i>What's up?</i> Question<br>
(7655) <i>Come over here</i> Order</li>
</ul></div>

And looks like this:

  • justIn:
    (123) Hello Greeting
    (514) What's up? Question
    (122) Come over here Order
  • recent:
    (1255) Hello Greeting
    (6564) What's up? Question
    (0192) Come over here Order
  • old:
    (5213) Hello Greeting
    (9758) What's up? Question
    (7655) Come over here Order

Also, remember to set the contentType as 'json'

event.preventDefault() function not working in IE

return false in your listener should work in all browsers.

$('orderNowForm').addEvent('submit', function () {
    // your code
    return false;
}

Bootstrap 3: how to make head of dropdown link clickable in navbar

This enables the link in the top-level menu of the dropdown when it's opened and disables it when closed, with the only drawback of apparently having to "tap" twice outside of the dropdown to close it in mobile devices.

$(document).on("page:load", function(){
    $('body').on('show.bs.dropdown', function (e) {
        $(e.relatedTarget).addClass('disabled')
    });
    $('body').on('hide.bs.dropdown', function (e) {
        $(e.relatedTarget).removeClass('disabled')
    });
});

Note this assumes the "standard" markup and Turbolinks (Rails). You can try with $(document).ready(...)

How to Change Font Size in drawString Java

Font myFont = new Font ("Courier New", 1, 17);

The 17 represents the font size. Once you have that, you can put:

g.setFont (myFont);
g.drawString ("Hello World", 10, 10);

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

The problem is pyaudio does not have wheels for python 3.7 just try some lower version like 3.6 then install pyaudio

It works

HTML5: Slider with two inputs possible?

Sure you can simply use two sliders overlaying each other and add a bit of javascript (actually not more than 5 lines) that the selectors are not exceeding the min/max values (like in @Garys) solution.

Attached you'll find a short snippet adapted from a current project including some CSS3 styling to show what you can do (webkit only). I also added some labels to display the selected values.

It uses JQuery but a vanillajs version is no magic though.

@Update: The code below was just a proof of concept. Due to many requests I've added a possible solution for Mozilla Firefox (without changing the original code). You may want to refractor the code below before using it.

_x000D_
_x000D_
    (function() {

        function addSeparator(nStr) {
            nStr += '';
            var x = nStr.split('.');
            var x1 = x[0];
            var x2 = x.length > 1 ? '.' + x[1] : '';
            var rgx = /(\d+)(\d{3})/;
            while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + '.' + '$2');
            }
            return x1 + x2;
        }

        function rangeInputChangeEventHandler(e){
            var rangeGroup = $(this).attr('name'),
                minBtn = $(this).parent().children('.min'),
                maxBtn = $(this).parent().children('.max'),
                range_min = $(this).parent().children('.range_min'),
                range_max = $(this).parent().children('.range_max'),
                minVal = parseInt($(minBtn).val()),
                maxVal = parseInt($(maxBtn).val()),
                origin = $(this).context.className;

            if(origin === 'min' && minVal > maxVal-5){
                $(minBtn).val(maxVal-5);
            }
            var minVal = parseInt($(minBtn).val());
            $(range_min).html(addSeparator(minVal*1000) + ' €');


            if(origin === 'max' && maxVal-5 < minVal){
                $(maxBtn).val(5+ minVal);
            }
            var maxVal = parseInt($(maxBtn).val());
            $(range_max).html(addSeparator(maxVal*1000) + ' €');
        }

     $('input[type="range"]').on( 'input', rangeInputChangeEventHandler);
})();
_x000D_
body{
font-family: sans-serif;
font-size:14px;
}
input[type='range'] {
  width: 210px;
  height: 30px;
  overflow: hidden;
  cursor: pointer;
    outline: none;
}
input[type='range'],
input[type='range']::-webkit-slider-runnable-track,
input[type='range']::-webkit-slider-thumb {
  -webkit-appearance: none;
    background: none;
}
input[type='range']::-webkit-slider-runnable-track {
  width: 200px;
  height: 1px;
  background: #003D7C;
}

input[type='range']:nth-child(2)::-webkit-slider-runnable-track{
  background: none;
}

input[type='range']::-webkit-slider-thumb {
  position: relative;
  height: 15px;
  width: 15px;
  margin-top: -7px;
  background: #fff;
  border: 1px solid #003D7C;
  border-radius: 25px;
  z-index: 1;
}


input[type='range']:nth-child(1)::-webkit-slider-thumb{
  z-index: 2;
}

.rangeslider{
    position: relative;
    height: 60px;
    width: 210px;
    display: inline-block;
    margin-top: -5px;
    margin-left: 20px;
}
.rangeslider input{
    position: absolute;
}
.rangeslider{
    position: absolute;
}

.rangeslider span{
    position: absolute;
    margin-top: 30px;
    left: 0;
}

.rangeslider .right{
   position: relative;
   float: right;
   margin-right: -5px;
}


/* Proof of concept for Firefox */
@-moz-document url-prefix() {
  .rangeslider::before{
    content:'';
    width:100%;
    height:2px;
    background: #003D7C;
    display:block;
    position: relative;
    top:16px;
  }

  input[type='range']:nth-child(1){
    position:absolute;
    top:35px !important;
    overflow:visible !important;
    height:0;
  }

  input[type='range']:nth-child(2){
    position:absolute;
    top:35px !important;
    overflow:visible !important;
    height:0;
  }
input[type='range']::-moz-range-thumb {
  position: relative;
  height: 15px;
  width: 15px;
  margin-top: -7px;
  background: #fff;
  border: 1px solid #003D7C;
  border-radius: 25px;
  z-index: 1;
}

  input[type='range']:nth-child(1)::-moz-range-thumb {
      transform: translateY(-20px);    
  }
  input[type='range']:nth-child(2)::-moz-range-thumb {
      transform: translateY(-20px);    
  }
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="rangeslider">
                                <input class="min" name="range_1" type="range" min="1" max="100" value="10" />
                                <input class="max" name="range_1" type="range" min="1" max="100" value="90" />
                                <span class="range_min light left">10.000 €</span>
                                <span class="range_max light right">90.000 €</span>
                            </div>
_x000D_
_x000D_
_x000D_

npm ERR! network getaddrinfo ENOTFOUND

Step 1: Set the proxy npm set proxy http://username:password@companyProxy:8080

npm set https-proxy http://username:password@companyProxy:8080

npm config set strict-ssl false -g

NOTES: No special characters in password except @ allowed.

Right way to reverse a pandas DataFrame?

What is the right way to reverse a pandas DataFrame?

TL;DR: df[::-1]

This is objectively IMO the best method for reversing a DataFrame, because it is a ONE step operation, also very readable (assuming familiarity with slice notation).


Long Version

I've found the ol' slicing trick df[::-1] (or the equivalent df.loc[::-1]1) to be the most concise and idiomatic way of reversing a DataFrame. This mirrors the python list reversal syntax lst[::-1] and is clear in its intent. With the loc syntax, you are also able to slice columns if required, so it is a bit more flexible.

Some points to consider while handling the index:

  • "what if I want to reverse the index as well?"

    • you're already done. df[::-1] reverses both the index and values.
  • "what if I want to drop the index from the result?"

  • "what if I want to keep the index untouched (IOW, only reverse the data, not the index)?"

    • this is somewhat unconventional because it implies the index isn't really relevant to the data. Perhaps consider removing it entirely? Although what you're asking for can technically be achieved using either df[:] = df[::-1] which creates an in-place update to df, or df.loc[::-1].set_index(df.index), which returns a copy.

1: df.loc[::-1] and df.iloc[::-1] are equivalent since the slicing syntax remains the same, whether you're reversing by position (iloc) or label (loc).


The Proof is in the Pudding

enter image description here

X-axis represents the dataset size. Y-axis represents time taken to reverse. No method scales as well as the slicing trick, it's all the way at the bottom of the graph. Benchmarking code for reference, plots generated using perfplot.


Comments on other solutions

  • df.reindex(index=df.index[::-1]) is clearly a popular solution, but on first glance, how obvious is it to an unfamiliar reader that this code is "reversing a DataFrame"? Additionally, this is reversing the index, then using that intermediate result to reindex, so this is essentially a TWO step operation (when it could've been just one).

  • df.sort_index(ascending=False) may work in most cases where you have a simple range index, but this assumes your index was sorted in ascending order and so doesn't generalize well.

  • PLEASE do not use iterrows. I see some options suggesting iterating in reverse. Whatever your use case, there is likely a vectorized method available, but if there isn't then you can use something a little more reasonable such as list comprehensions. See How to iterate over rows in a DataFrame in Pandas for more detail on why iterrows is an antipattern.

Select only rows if its value in a particular column is less than the value in the other column

If you use dplyr package you can do:

library(dplyr)
filter(df, aged <= laclen)

Converting unix timestamp string to readable date

There are two parts:

  1. Convert the unix timestamp ("seconds since epoch") to the local time
  2. Display the local time in the desired format.

A portable way to get the local time that works even if the local time zone had a different utc offset in the past and python has no access to the tz database is to use a pytz timezone:

#!/usr/bin/env python
from datetime import datetime
import tzlocal  # $ pip install tzlocal

unix_timestamp = float("1284101485")
local_timezone = tzlocal.get_localzone() # get pytz timezone
local_time = datetime.fromtimestamp(unix_timestamp, local_timezone)

To display it, you could use any time format that is supported by your system e.g.:

print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))
print(local_time.strftime("%B %d %Y"))  # print date in your format

If you do not need a local time, to get a readable UTC time instead:

utc_time = datetime.utcfromtimestamp(unix_timestamp)
print(utc_time.strftime("%Y-%m-%d %H:%M:%S.%f+00:00 (UTC)"))

If you don't care about the timezone issues that might affect what date is returned or if python has access to the tz database on your system:

local_time = datetime.fromtimestamp(unix_timestamp)
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f"))

On Python 3, you could get a timezone-aware datetime using only stdlib (the UTC offset may be wrong if python has no access to the tz database on your system e.g., on Windows):

#!/usr/bin/env python3
from datetime import datetime, timezone

utc_time = datetime.fromtimestamp(unix_timestamp, timezone.utc)
local_time = utc_time.astimezone()
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))

Functions from the time module are thin wrappers around the corresponding C API and therefore they may be less portable than the corresponding datetime methods otherwise you could use them too:

#!/usr/bin/env python
import time

unix_timestamp  = int("1284101485")
utc_time = time.gmtime(unix_timestamp)
local_time = time.localtime(unix_timestamp)
print(time.strftime("%Y-%m-%d %H:%M:%S", local_time)) 
print(time.strftime("%Y-%m-%d %H:%M:%S+00:00 (UTC)", utc_time))  

Angular directives - when and how to use compile, controller, pre-link and post-link

What else happens between these function calls?

The various directive functions are executed from within two other angular functions called $compile (where the directive's compile is executed) and an internal function called nodeLinkFn (where the directive's controller, preLink and postLink are executed). Various things happen within the angular function before and after the directive functions are called. Perhaps most notably is the child recursion. The following simplified illustration shows key steps within the compile and link phases:

An illustration showing Angular compile and link phases

To demonstrate the these steps, let's use the following HTML markup:

<div ng-repeat="i in [0,1,2]">
    <my-element>
        <div>Inner content</div>
    </my-element>
</div>

With the following directive:

myApp.directive( 'myElement', function() {
    return {
        restrict:   'EA',
        transclude: true,
        template:   '<div>{{label}}<div ng-transclude></div></div>'
    }
});

Compile

The compile API looks like so:

compile: function compile( tElement, tAttributes ) { ... }

Often the parameters are prefixed with t to signify the elements and attributes provided are those of the source template, rather than that of the instance.

Prior to the call to compile transcluded content (if any) is removed, and the template is applied to the markup. Thus, the element provided to the compile function will look like so:

<my-element>
    <div>
        "{{label}}"
        <div ng-transclude></div>
    </div>
</my-element>

Notice that the transcluded content is not re-inserted at this point.

Following the call to the directive's .compile, Angular will traverse all child elements, including those that may have just been introduced by the directive (the template elements, for instance).

Instance creation

In our case, three instances of the source template above will be created (by ng-repeat). Thus, the following sequence will execute three times, once per instance.

Controller

The controller API involves:

controller: function( $scope, $element, $attrs, $transclude ) { ... }

Entering the link phase, the link function returned via $compile is now provided with a scope.

First, the link function create a child scope (scope: true) or an isolated scope (scope: {...}) if requested.

The controller is then executed, provided with the scope of the instance element.

Pre-link

The pre-link API looks like so:

function preLink( scope, element, attributes, controller ) { ... }

Virtually nothing happens between the call to the directive's .controller and the .preLink function. Angular still provide recommendation as to how each should be used.

Following the .preLink call, the link function will traverse each child element - calling the correct link function and attaching to it the current scope (which serves as the parent scope for child elements).

Post-link

The post-link API is similar to that of the pre-link function:

function postLink( scope, element, attributes, controller ) { ... }

Perhaps worth noticing that once a directive's .postLink function is called, the link process of all its children elements has completed, including all the children's .postLink functions.

This means that by the time .postLink is called, the children are 'live' are ready. This includes:

  • data binding
  • transclusion applied
  • scope attached

The template at this stage will thus look like so:

<my-element>
    <div class="ng-binding">
        "{{label}}"
        <div ng-transclude>                
            <div class="ng-scope">Inner content</div>
        </div>
    </div>
</my-element>

How to make execution pause, sleep, wait for X seconds in R?

See help(Sys.sleep).

For example, from ?Sys.sleep

testit <- function(x)
{
    p1 <- proc.time()
    Sys.sleep(x)
    proc.time() - p1 # The cpu usage should be negligible
}
testit(3.7)

Yielding

> testit(3.7)
   user  system elapsed 
  0.000   0.000   3.704 

Uncaught TypeError: data.push is not a function

I think you set it as

var data = []; 

but after some time you made it like:

data = 'some thing which is not an array'; 

then data.push('') will not work as it is not an array anymore.

Remove redundant paths from $PATH variable

If you just want to remove any duplicate paths, I use this script I wrote a while back since I was having trouble with multiple perl5/bin paths:

#!/bin/bash
#
# path-cleanup
#
# This must be run as "source path-cleanup" or ". path-cleanup"
# so the current shell gets the changes.

pathlist=`echo $PATH | sed 's/:/\n/g' | uniq`

# echo "Starting PATH: $PATH"
# echo "pathlist: $pathlist"
unset PATH
# echo "After unset, PATH: $PATH"
for dir in $pathlist
do
    if test -d $dir ; then
        if test -z $PATH; then
            PATH=$dir
        else
            PATH=$PATH:$dir
        fi
    fi
done
export PATH
# echo "After loop, PATH: $PATH"

And I put it in my ~/.profile at the end. Since I use BASH almost exclusively, I haven't tried it in other shells.

How to convert a Binary String to a base 10 integer in Java

This might work:

public int binaryToInteger(String binary) {
    char[] numbers = binary.toCharArray();
    int result = 0;
    for(int i=numbers.length - 1; i>=0; i--)
        if(numbers[i]=='1')
            result += Math.pow(2, (numbers.length-i - 1));
    return result;
}

Difference between window.location.href, window.location.replace and window.location.assign

These do the same thing:

window.location.assign(url);
window.location = url;
window.location.href = url;

They simply navigate to the new URL. The replace method on the other hand navigates to the URL without adding a new record to the history.

So, what you have read in those many forums is not correct. The assign method does add a new record to the history.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/location

Have border wrap around text

This is because h1 is a block element, so it will extend across the line (or the width you give).

You can make the border go only around the text by setting display:inline on the h1

Example: http://jsfiddle.net/jonathon/XGRwy/1/

Java: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

For Windows only, follow these steps:

  1. In Chrome go to settings.
  2. In Settings click show advance settings.
  3. Under HTTPS/SSL Click on Manage Certificates.
  4. Export Your Certificate.
  5. In Windows searchs (Pressing windows key on keyboard) type java.
  6. Select (Configure Java) Option Which will open Java Control Panel
  7. Select Security tab in Java Control Panel
  8. Select Manage Certificates
  9. Click Import
  10. Under (User) tab selected and certificate type as (Trusted Certificates)
  11. Click import button and browse to downloaded certificate and import it.

SQL ORDER BY multiple columns

The results are ordered by the first column, then the second, and so on for as many columns as the ORDER BY clause includes. If you want any results sorted in descending order, your ORDER BY clause must use the DESC keyword directly after the name or the number of the relevant column.

Check out this Example

SELECT first_name, last_name, hire_date, salary 
FROM employee 
ORDER BY hire_date DESC,last_name ASC;

It will order in succession. Order the Hire_Date first, then LAST_NAME it by Hire_Date .

CSS: borders between table columns only

Inside <td>, use style="border-left:1px solid #colour;"

How to synchronize or lock upon variables in Java?

If on another occasion you're synchronising a Collection rather than a String, perhaps you're be iterating over the collection and are worried about it mutating, Java 5 offers:

CRC32 C or C++ implementation

using zlib.h (http://refspecs.linuxbase.org/LSB_3.0.0/LSB-Core-generic/LSB-Core-generic/zlib-crc32-1.html):

#include <zlib.h>
unsigned long  crc = crc32(0L, Z_NULL, 0);
crc = crc32(crc, (const unsigned char*)data_address, data_len);

How to set the environmental variable LD_LIBRARY_PATH in linux

I do the following in Mint 15 through 17, also works on ubuntu server 12.04 and above:

sudo vi /etc/bash.bashrc 

scroll to the bottom, and add:

export LD_LIBRARY_PATH=.

All users have the environment variable added.

Maven compile: package does not exist

the issue happened with me, I resolved by removing the scope tag only and built successfully.

Synchronously waiting for an async operation, and why does Wait() freeze the program here

Calling async code from synchronous code can be quite tricky.

I explain the full reasons for this deadlock on my blog. In short, there's a "context" that is saved by default at the beginning of each await and used to resume the method.

So if this is called in an UI context, when the await completes, the async method tries to re-enter that context to continue executing. Unfortunately, code using Wait (or Result) will block a thread in that context, so the async method cannot complete.

The guidelines to avoid this are:

  1. Use ConfigureAwait(continueOnCapturedContext: false) as much as possible. This enables your async methods to continue executing without having to re-enter the context.
  2. Use async all the way. Use await instead of Result or Wait.

If your method is naturally asynchronous, then you (probably) shouldn't expose a synchronous wrapper.

JavaScript: changing the value of onclick with or without jQuery

BTW, without JQuery this could also be done, but obviously it's pretty ugly as it only considers IE/non-IE:

if(isie)
   tmpobject.setAttribute('onclick',(new Function(tmp.nextSibling.getAttributeNode('onclick').value)));
else
   $(tmpobject).attr('onclick',tmp.nextSibling.attributes[0].value); //this even supposes index

Anyway, just so that people have an overall idea of what can be done, as I'm sure many have stumbled upon this annoyance.

How to add calendar events in Android?

i used the code below, it solves my problem to add event in default device calendar in ICS and also on version less that ICS

    if (Build.VERSION.SDK_INT >= 14) {
        Intent intent = new Intent(Intent.ACTION_INSERT)
        .setData(Events.CONTENT_URI)
        .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis())
        .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis())
        .putExtra(Events.TITLE, "Yoga")
        .putExtra(Events.DESCRIPTION, "Group class")
        .putExtra(Events.EVENT_LOCATION, "The gym")
        .putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY)
        .putExtra(Intent.EXTRA_EMAIL, "[email protected],[email protected]");
         startActivity(intent);
}

    else {
        Calendar cal = Calendar.getInstance();              
        Intent intent = new Intent(Intent.ACTION_EDIT);
        intent.setType("vnd.android.cursor.item/event");
        intent.putExtra("beginTime", cal.getTimeInMillis());
        intent.putExtra("allDay", true);
        intent.putExtra("rrule", "FREQ=YEARLY");
        intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
        intent.putExtra("title", "A Test Event from android app");
        startActivity(intent);
        }

Hope it would help.....

Pass variables by reference in JavaScript

There's actually a pretty sollution:

function updateArray(context, targetName, callback) {
    context[targetName] = context[targetName].map(callback);
}

var myArray = ['a', 'b', 'c'];
updateArray(this, 'myArray', item => {return '_' + item});

console.log(myArray); //(3) ["_a", "_b", "_c"]

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

N=np.floor(np.divide(l,delta))
...
for j in range(N[i]/2):

N[i]/2 will be a float64 but range() expects an integer. Just cast the call to

for j in range(int(N[i]/2)):

SELECTING with multiple WHERE conditions on same column

Consider using INTERSECT like this:

SELECT contactid WHERE flag = 'Volunteer' 
INTERSECT
SELECT contactid WHERE flag = 'Uploaded'

I think it it the most logistic solution.

How to encrypt String in Java

I'd recommend to use some standard symmetric cypher that is widely available like DES, 3DES or AES. While that is not the most secure algorithm, there are loads of implementations and you'd just need to give the key to anyone that is supposed to decrypt the information in the barcode. javax.crypto.Cipher is what you want to work with here.

Let's assume the bytes to encrypt are in

byte[] input;

Next, you'll need the key and initialization vector bytes

byte[] keyBytes;
byte[] ivBytes;

Now you can initialize the Cipher for the algorithm that you select:

// wrap key data in Key/IV specs to pass to cipher
SecretKeySpec key = new SecretKeySpec(keyBytes, "DES");
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
// create the cipher with the algorithm you choose
// see javadoc for Cipher class for more info, e.g.
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

Encryption would go like this:

cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
byte[] encrypted= new byte[cipher.getOutputSize(input.length)];
int enc_len = cipher.update(input, 0, input.length, encrypted, 0);
enc_len += cipher.doFinal(encrypted, enc_len);

And decryption like this:

cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
byte[] decrypted = new byte[cipher.getOutputSize(enc_len)];
int dec_len = cipher.update(encrypted, 0, enc_len, decrypted, 0);
dec_len += cipher.doFinal(decrypted, dec_len);

Swift - encode URL

Swift 4 & 5 (Thanks @sumizome for suggestion. Thanks @FD_ and @derickito for testing)

var allowedQueryParamAndKey = NSCharacterSet.urlQueryAllowed
allowedQueryParamAndKey.remove(charactersIn: ";/?:@&=+$, ")
paramOrKey.addingPercentEncoding(withAllowedCharacters: allowedQueryParamAndKey)

Swift 3

let allowedQueryParamAndKey =  NSCharacterSet.urlQueryAllowed.remove(charactersIn: ";/?:@&=+$, ")
paramOrKey.addingPercentEncoding(withAllowedCharacters: allowedQueryParamAndKey)

Swift 2.2 (Borrowing from Zaph's and correcting for url query key and parameter values)

var allowedQueryParamAndKey =  NSCharacterSet(charactersInString: ";/?:@&=+$, ").invertedSet
paramOrKey.stringByAddingPercentEncodingWithAllowedCharacters(allowedQueryParamAndKey)

Example:

let paramOrKey = "https://some.website.com/path/to/page.srf?a=1&b=2#top"
paramOrKey.addingPercentEncoding(withAllowedCharacters: allowedQueryParamAndKey)
// produces:
"https%3A%2F%2Fsome.website.com%2Fpath%2Fto%2Fpage.srf%3Fa%3D1%26b%3D2%23top"

This is a shorter version of Bryan Chen's answer. I'd guess that urlQueryAllowed is allowing the control characters through which is fine unless they form part of the key or value in your query string at which point they need to be escaped.

How should we manage jdk8 stream for null values

Stuart's answer provides a great explanation, but I'd like to provide another example.

I ran into this issue when attempting to perform a reduce on a Stream containing null values (actually it was LongStream.average(), which is a type of reduction). Since average() returns OptionalDouble, I assumed the Stream could contain nulls but instead a NullPointerException was thrown. This is due to Stuart's explanation of null v. empty.

So, as the OP suggests, I added a filter like so:

list.stream()
    .filter(o -> o != null)
    .reduce(..);

Or as tangens pointed out below, use the predicate provided by the Java API:

list.stream()
    .filter(Objects::nonNull)
    .reduce(..);

From the mailing list discussion Stuart linked: Brian Goetz on nulls in Streams

Modifying the "Path to executable" of a windows service

You can't directly edit your path to execute of a service. For that you can use sc command,

SC CONFIG ServiceName binPath= "Path of your file"

Eg:

sc config MongoDB binPath="I:\Programming\MongoDB\MongoDB\bin\mongod.exe --config I:\Programming\MongoDB\MongoDB\bin\mongod.cfg --service"

Alternative to mysql_real_escape_string without connecting to DB

It is impossible to safely escape a string without a DB connection. mysql_real_escape_string() and prepared statements need a connection to the database so that they can escape the string using the appropriate character set - otherwise SQL injection attacks are still possible using multi-byte characters.

If you are only testing, then you may as well use mysql_escape_string(), it's not 100% guaranteed against SQL injection attacks, but it's impossible to build anything safer without a DB connection.

iOS - Calling App Delegate method from ViewController

If someone need the same in Xamarin (Xamarin.ios / Monotouch), this worked for me:

var myDelegate = UIApplication.SharedApplication.Delegate as AppDelegate;

(Require using UIKit;)

How to use PHP with Visual Studio

By default VS is not made to run PHP, but you can do it with extensions:

You can install an add-on with the extension manager, PHP Tools for Visual Studio.

If you want to install it inside VS, go to Tools > Extension Manager > Online Gallery > Search for PHP where you will find PHP Tools (the link above) for Visual Studio. Also you have VS.Php for Visual Studio. Both are not free.

You have also a cool PHP compiler called Phalanger: Phalanger PHP Compiler

If I'm not mistaken, the code you wrote above is JavaScript (jQuery) and not PHP.

If you want cool standalone IDE's for PHP: (Free)

How to install JQ on Mac by command-line?

On a Mac, the "most efficient" way to install jq would probably be using homebrew, e.g.

brew install jq

If you want the development version, you could try:

brew install --HEAD jq

but this has various pre-requisites.

Detailed instructions are on the "Installation" page of the jq wiki: https://github.com/stedolan/jq/wiki/Installation

The same page also includes details regarding installation from source, and has notes on installing with MacPorts.

How do you move a file?

In TortoiseSVN right click somewhere and go TortoiseSVN > Repo Browser open the repository.

All you then have to do is drag and drop the file from one folder to the where you want it. It'll ask you to add a commit message and it defaults it to "Moved file/folder remotely"

Pdf.js: rendering a pdf file using a base64 file source instead of url

According to the examples base64 encoding is directly supported, although I've not tested it myself. Take your base64 string (derived from a file or loaded with any other method, POST/GET, websockets etc), turn it to a binary with atob, and then parse this to getDocument on the PDFJS API likePDFJS.getDocument({data: base64PdfData}); Codetoffel answer does work just fine for me though.

Inserting code in this LaTeX document with indentation

Specialized packages such as minted, which relies on Pygments to do the formatting, offer various advantages over the listings package. To quote from the minted manual,

Pygments provides far superior syntax highlighting compared to conventional packages. For example, listings basically only highlights strings, comments and keywords. Pygments, on the other hand, can be completely customized to highlight any token kind the source language might support. This might include special formatting sequences inside strings, numbers, different kinds of identifiers and exotic constructs such as HTML tags.

Iterate through a C array

You can store the size somewhere, or you can have a struct with a special value set that you use as a sentinel, the same way that '\0' indicates the end of a string.

What are the -Xms and -Xmx parameters when starting JVM?

-Xms initial heap size for the startup, however, during the working process the heap size can be less than -Xms due to users' inactivity or GC iterations. This is not a minimal required heap size.

-Xmx maximal heap size

Escape @ character in razor view engine

@@ is the escape character for @ in Razor views as stated above.

Razor does however try to work out when an '@' is just an '@' and where it marks C# (or VB.Net) code. One of the main uses for this is to identify email addresses within a Razor view - it should not be necessary to escape the @ character in an email address.

Convert an NSURL to an NSString

I just fought with this very thing and this update didn't work.

This eventually did in Swift:

let myUrlStr : String = myUrl!.relativePath!

javascript clear field value input

This may be what you want:

Working jsFiddle here

  • This code places a default text string Enter your name here inside the <input> textbox, and colorizes the text to light grey.

  • As soon as the box is clicked, the default text is cleared and text color set to black.

  • If text is erased, the default text string is replaced and light grey color reset.


HTML:

<input id="fname" type="text" />

jQuery/javascript:

$(document).ready(function() {

    var curval;
    var fn = $('#fname');
    fn.val('Enter your name here').css({"color":"lightgrey"});

    fn.focus(function() {
        //Upon ENTERING the field
        curval = $(this).val();
        if (curval == 'Enter your name here' || curval == '') {
            $(this).val('');
            $(this).css({"color":"black"});
        }
    }); //END focus()

    fn.blur(function() {
        //Upon LEAVING the field
        curval = $(this).val();
        if (curval != 'Enter your name here' && curval != '') {
            $(this).css({"color":"black"});
        }else{
            fn.val('Enter your name here').css({"color":"lightgrey"});
        }
    }); //END blur()

}); //END document.ready

How do I make a JSON object with multiple arrays?

Enclosed in {} represents an object; enclosed in [] represents an array, there can be multiple objects in the array
example object :

{
    "brand": "bwm", 
    "price": 30000
}


{
    "brand": "benz", 
    "price": 50000
}

example array:

[
    {
        "brand": "bwm", 
        "price": 30000
    }, 
    {
        "brand": "benz", 
        "price": 50000
    }
]

In order to use JSON more beautifully, you can go here JSON Viewer do format

C - split string into an array of strings

Here is an example of how to use strtok borrowed from MSDN.

And the relevant bits, you need to call it multiple times. The token char* is the part you would stuff into an array (you can figure that part out).

char string[] = "A string\tof ,,tokens\nand some  more tokens";
char seps[]   = " ,\t\n";
char *token;

int main( void )
{
    printf( "Tokens:\n" );
    /* Establish string and get the first token: */
    token = strtok( string, seps );
    while( token != NULL )
    {
        /* While there are tokens in "string" */
        printf( " %s\n", token );
        /* Get next token: */
        token = strtok( NULL, seps );
    }
}

Using Powershell to stop a service remotely without WMI or remoting

This worked for me, but I used it as start. powershell outputs, waiting for service to finshing starting a few times then finishes and then a get-service on the remote server shows the service started.

**start**-service -inputobject $(get-service -ComputerName remotePC -Name Spooler)

an attempt was made to access a socket in a way forbbiden by its access permissions. why?

IIS was the main offender for me. My IIS was running and it restrains any new socket connections from opening. The problem resolved for me by stopping IIS by running the command "iisreset -stop"

How to check a string starts with numeric number?

I think you ought to use a regex:


import java.util.regex.*;

public class Test {
  public static void main(String[] args) {
    String neg = "-123abc";
    String pos = "123abc";
    String non = "abc123";
        /* I'm not sure if this regex is too verbose, but it should be
         * clear. It checks that the string starts with either a series
         * of one or more digits... OR a negative sign followed by 1 or
         * more digits. Anything can follow the digits. Update as you need
         * for things that should not follow the digits or for floating
         * point numbers.
         */
    Pattern pattern = Pattern.compile("^(\\d+.*|-\\d+.*)");
    Matcher matcher = pattern.matcher(neg);
    if(matcher.matches()) {
        System.out.println("matches negative number");
    }
    matcher = pattern.matcher(pos);
    if (matcher.matches()) {
        System.out.println("positive matches");
    }
    matcher = pattern.matcher(non);
    if (!matcher.matches()) {
        System.out.println("letters don't match :-)!!!");
    }
  }
}

You may want to adjust this to accept floating point numbers, but this will work for negatives. Other answers won't work for negatives because they only check the first character! Be more specific about your needs and I can help you adjust this approach.

How to Check whether Session is Expired or not in asp.net

this way many people detect session has expired or not. the below code may help u.

protected void Page_Init(object sender, EventArgs e)
    {
        if (Context.Session != null)
        {
            if (Session.IsNewSession)
            {
                HttpCookie newSessionIdCookie = Request.Cookies["ASP.NET_SessionId"];
                if (newSessionIdCookie != null)
                {
                    string newSessionIdCookieValue = newSessionIdCookie.Value;
                    if (newSessionIdCookieValue != string.Empty)
                    {
                        // This means Session was timed Out and New Session was started
                        Response.Redirect("Login.aspx");
                    }
                }
            }
        }
    }

How do I create a round cornered UILabel on the iPhone?

I made a swift UILabel subclass to achieve this effect. In addition I automatically set the text color to either black or white for maximal contrast.

Result

colors-rounded-borders

Used SO-Posts:

Playground

Just paste this into an iOS Playground:

//: Playground - noun: a place where people can play

import UIKit

class PillLabel : UILabel{

    @IBInspectable var color = UIColor.lightGrayColor()
    @IBInspectable var cornerRadius: CGFloat = 8
    @IBInspectable var labelText: String = "None"
    @IBInspectable var fontSize: CGFloat = 10.5

    // This has to be balanced with the number of spaces prefixed to the text
    let borderWidth: CGFloat = 3

    init(text: String, color: UIColor = UIColor.lightGrayColor()) {
        super.init(frame: CGRectMake(0, 0, 1, 1))
        labelText = text
        self.color = color
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    func setup(){
        // This has to be balanced with the borderWidth property
        text = "  \(labelText)".uppercaseString

        // Credits to https://stackoverflow.com/a/33015915/784318
        layer.borderWidth = borderWidth
        layer.cornerRadius = cornerRadius
        backgroundColor = color
        layer.borderColor = color.CGColor
        layer.masksToBounds = true
        font = UIFont.boldSystemFontOfSize(fontSize)
        textColor = color.contrastColor
        sizeToFit()

        // Credits to https://stackoverflow.com/a/15184257/784318
        frame = CGRectInset(self.frame, -borderWidth, -borderWidth)
    }
}


extension UIColor {
    // Credits to https://stackoverflow.com/a/29044899/784318
    func isLight() -> Bool{
        var green: CGFloat = 0.0, red: CGFloat = 0.0, blue: CGFloat = 0.0, alpha: CGFloat = 0.0
        self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
        let brightness = ((red * 299) + (green * 587) + (blue * 114) ) / 1000

        return brightness < 0.5 ? false : true
    }

    var contrastColor: UIColor{
        return self.isLight() ? UIColor.blackColor() : UIColor.whiteColor()
    }
}

var label = PillLabel(text: "yellow", color: .yellowColor())

label = PillLabel(text: "green", color: .greenColor())

label = PillLabel(text: "white", color: .whiteColor())

label = PillLabel(text: "black", color: .blackColor())

"Large data" workflows using pandas

It is worth mentioning here Ray as well,
it's a distributed computation framework, that has it's own implementation for pandas in a distributed way.

Just replace the pandas import, and the code should work as is:

# import pandas as pd
import ray.dataframe as pd

#use pd as usual

can read more details here:

https://rise.cs.berkeley.edu/blog/pandas-on-ray/

Use querystring variables in MVC controller

Here is what I came up with. I was having major problems with this and believe I am in MVC 6 now but this may be helpful to someone even myself in the future..

//The issue was that Reqest.Form Request.Querystring and Request not working in MVC the solution is to use Context.Request.Form and also making sure the form has been submitted otherwise null reference or context issue bug will show up.

     if(Context.Request.ContentLength != null)
     {
         String StartDate = Context.Request.Form["StartMonth"].ToString();
         String EndMonth = Context.Request.Form["EndMonth"].ToString();
        // Vendor

     }

How to find index of an object by key and value in an javascript array

Using jQuery .each()

_x000D_
_x000D_
var peoples = [_x000D_
  { "attr1": "bob", "attr2": "pizza" },_x000D_
  { "attr1": "john", "attr2": "sushi" },_x000D_
  { "attr1": "larry", "attr2": "hummus" }_x000D_
];_x000D_
_x000D_
$.each(peoples, function(index, obj) {_x000D_
   $.each(obj, function(attr, value) {_x000D_
      console.log( attr + ' == ' + value );_x000D_
   });_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Using for-loop:

_x000D_
_x000D_
var peoples = [_x000D_
  { "attr1": "bob", "attr2": "pizza" },_x000D_
  { "attr1": "john", "attr2": "sushi" },_x000D_
  { "attr1": "larry", "attr2": "hummus" }_x000D_
];_x000D_
_x000D_
for (var i = 0; i < peoples.length; i++) {_x000D_
  for (var key in peoples[i]) {_x000D_
    console.log(key + ' == ' + peoples[i][key]);_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

How to import an existing directory into Eclipse?

For Spring Tool Suite I do:

File -> Open projects from File System

Difference between "git add -A" and "git add ."

With Git 2.0, git add -A is default: git add . equals git add -A ..

git add <path> is the same as "git add -A <path>" now, so that "git add dir/" will notice paths you removed from the directory and record the removal.
In older versions of Git, "git add <path>" ignored removals.

You can say "git add --ignore-removal <path>" to add only added or modified paths in <path>, if you really want to.

git add -A is like git add :/ (add everything from top git repo folder).
Note that git 2.7 (Nov. 2015) will allow you to add a folder named ":"!
See commit 29abb33 (25 Oct 2015) by Junio C Hamano (gitster).


Note that starting git 2.0 (Q1 or Q2 2014), when talking about git add . (current path within the working tree), you must use '.' in the other git add commands as well.

That means:

"git add -A ." is equivalent to "git add .; git add -u ."

(Note the extra '.' for git add -A and git add -u)

Because git add -A or git add -u would operate (starting git 2.0 only) on the entire working tree, and not just on the current path.

Those commands will operate on the entire tree in Git 2.0 for consistency with "git commit -a" and other commands. Because there will be no mechanism to make "git add -u" behave as if "git add -u .", it is important for those who are used to "git add -u" (without pathspec) updating the index only for paths in the current subdirectory to start training their fingers to explicitly say "git add -u ." when they mean it before Git 2.0 comes.

A warning is issued when these commands are run without a pathspec and when you have local changes outside the current directory, because the behaviour in Git 2.0 will be different from today's version in such a situation.

How to force maven update?

All the answers here didn't work for me. I used the hammer method:

find ~/.m2/ -name "*.lastUpdated" | xargs rm

That fixed the problem :-)

How to execute cmd commands via Java

Here is a simpler example that does not require multiple threads:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class SimplePty
{
    public SimplePty(Process process) throws IOException
    {
        while (process.isAlive())
        {
            sync(process.getErrorStream(), System.err);
            sync(process.getInputStream(), System.out);
            sync(System.in, process.getOutputStream());
        }
    }
    
    private void sync(InputStream in, OutputStream out) throws IOException
    {
        while (in.available() > 0)
        {
            out.write(in.read());
            out.flush();
        }
    }
    
    public static void main( String[] args ) throws IOException
    {
        String os = System.getProperty("os.name").toLowerCase();
        String shell = os.contains("win") ? "cmd" : "bash";
        Process process = new ProcessBuilder(shell).start();
        new SimplePty(process);
    }
}

Get child node index

ES—Shorter

[...element.parentNode.children].indexOf(element);

The spread Operator is a shortcut for that

Override hosts variable of Ansible playbook from the command line

An other solution is to use the special variable ansible_limit which is the contents of the --limit CLI option for the current execution of Ansible.

- hosts: "{{ ansible_limit | default(omit) }}"

If the --limit option is omitted, then Ansible issues a warning, but does nothing since no host matched.

[WARNING]: Could not match supplied host pattern, ignoring: None

PLAY ****************************************************************
skipping: no hosts matched

How to create a QR code reader in a HTML5 website?

The algorithm that drives http://www.webqr.com is a JavaScript implementation of https://github.com/LazarSoft/jsqrcode. I haven't tried how reliable it is yet, but that's certainly the easier plug-and-play solution (client- or server-side) out of the two.

Remove the last line from a file in Bash

Using GNU sed:

sed -i '$ d' foo.txt

The -i option does not exist in GNU sed versions older than 3.95, so you have to use it as a filter with a temporary file:

cp foo.txt foo.txt.tmp
sed '$ d' foo.txt.tmp > foo.txt
rm -f foo.txt.tmp

Of course, in that case you could also use head -n -1 instead of sed.

MacOS:

On Mac OS X (as of 10.7.4), the equivalent of the sed -i command above is

sed -i '' -e '$ d' foo.txt

How to Code Double Quotes via HTML Codes

There really aren't any differences.

&quot; is processed as &#34; which is the decimal equivalent of &x22; which is the ISO 8859-1 equivalent of ".

The only reason you may be against using &quot; is because it was mistakenly omitted from the HTML 3.2 specification.

Otherwise it all boils down to personal preference.