Programs & Examples On #Timefield

Class has no objects member

Just adding on to what @Mallory-Erik said: You can place objects = models.Manager() it in the modals:

class Question(models.Model):
    # ...
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    # ...
    def __str__(self):
        return self.question_text
    question_text = models.CharField(max_length = 200)
    pub_date = models.DateTimeField('date published')
    objects = models.Manager()

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

Since Django 2.x, on_delete is required.

Django Documentation

Deprecated since version 1.9: on_delete will become a required argument in Django 2.0. In older versions it defaults to CASCADE.

OperationalError, no such column. Django

Let's focus on the error:

Exception Value: no such column: snippets_snippet.owner_id

Let's see if that's true...

You can use the manage.py command to access your db shell (this will use the settings.py variables, so you're sure to connect to the right one).

manage.py dbshell

You can now show the details of your table by typing:

.schema TABLE_NAME

Or in your case:

.schema snippets_snippet

More sqlite commands can be found here or by issuing a:

.help

Lastly, end your session by typing:

.quit

This doesn't get you out of the woods, but it helps you know what end of the problem to work on :)

Good luck!

Django: OperationalError No Such Table

I got through the same error when I went on to the admin panel. You ought to run this instead-: python manage.py migrate --run-syncdb. Don't forget to include migrate, I ran:

python manage.py make migrations and then python manage.py migrate

Still when the error persisted I tried it with the above suggested command.

How to convert Django Model object to dict with its fields and values?

Maybe this help you. May this not covert many to many relantionship, but es pretty handy when you want to send your model in json format.

def serial_model(modelobj):
  opts = modelobj._meta.fields
  modeldict = model_to_dict(modelobj)
  for m in opts:
    if m.is_relation:
        foreignkey = getattr(modelobj, m.name)
        if foreignkey:
            try:
                modeldict[m.name] = serial_model(foreignkey)
            except:
                pass
  return modeldict

How do I make an auto increment integer field in Django?

In django with every model you will get the by default id field that is auto increament. But still if you manually want to use auto increment. You just need to specify in your Model AutoField.

class Author(models.Model):
    author_id = models.AutoField(primary_key=True)

you can read more about the auto field in django in Django Documentation for AutoField

RuntimeWarning: DateTimeField received a naive datetime

One can both fix the warning and use the timezone specified in settings.py, which might be different from UTC.

For example in my settings.py I have:

USE_TZ = True
TIME_ZONE = 'Europe/Paris'

Here is a solution; the advantage is that str(mydate) gives the correct time:

>>> from datetime import datetime
>>> from django.utils.timezone import get_current_timezone
>>> mydate = datetime.now(tz=get_current_timezone())
>>> mydate
datetime.datetime(2019, 3, 10, 11, 16, 9, 184106, 
    tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>)
>>> str(mydate)
'2019-03-10 11:16:09.184106+01:00'

Another equivalent method is using make_aware, see dmrz post.

Can't compare naive and aware datetime.now() <= challenge.datetime_end

Disable time zone. Use challenge.datetime_start.replace(tzinfo=None);

You can also use replace(tzinfo=None) for other datetime.

if challenge.datetime_start.replace(tzinfo=None) <= datetime.now().replace(tzinfo=None) <= challenge.datetime_end.replace(tzinfo=None):

How do I get the current date and current time only respectively in Django?

Another way to get datetime UTC with milliseconds.

from datetime import datetime

datetime.utcnow().isoformat(sep='T', timespec='milliseconds') + 'Z'

2020-10-29T14:46:37.655Z

What is the difference between null=True and blank=True in Django?

It's crucial to understand that the options in a Django model field definition serve (at least) two purposes: defining the database tables, and defining the default format and validation of model forms. (I say "default" because the values can always be overridden by providing a custom form.) Some options affect the database, some options affect forms, and some affect both.

When it comes to null and blank, other answers have already made clear that the former affects the database table definition and the latter affects model validation. I think the distinction can be made even clearer by looking at use cases for all four possible configurations:

  • null=False, blank=False: This is the default configuration and means that the value is required in all circumstances.

  • null=True, blank=True: This means that the field is optional in all circumstances. (As noted below, though, this is not the recommended way to make string-based fields optional.)

  • null=False, blank=True: This means that the form doesn't require a value but the database does. There are a number of use cases for this:

    • The most common use is for optional string-based fields. As noted in the documentation, the Django idiom is to use the empty string to indicate a missing value. If NULL was also allowed you would end up with two different ways to indicate a missing value.

    • Another common situation is that you want to calculate one field automatically based on the value of another (in your save() method, say). You don't want the user to provide the value in a form (hence blank=True), but you do want the database to enforce that a value is always provided (null=False).

    • Another use is when you want to indicate that a ManyToManyField is optional. Because this field is implemented as a separate table rather than a database column, null is meaningless. The value of blank will still affect forms, though, controlling whether or not validation will succeed when there are no relations.

  • null=True, blank=False: This means that the form requires a value but the database doesn't. This may be the most infrequently used configuration, but there are some use cases for it:

    • It's perfectly reasonable to require your users to always include a value even if it's not actually required by your business logic. After all, forms are only one way of adding and editing data. You may have code that is generating data which doesn't need the same stringent validation that you want to require of a human editor.

    • Another use case that I've seen is when you have a ForeignKey for which you don't wish to allow cascade deletion. That is, in normal use the relation should always be there (blank=False), but if the thing it points to happens to be deleted, you don't want this object to be deleted too. In that case you can use null=True and on_delete=models.SET_NULL to implement a simple kind of soft deletion.

How to update fields in a model without creating a new record in django?

Django has some documentation about that on their website, see: Saving changes to objects. To summarize:

.. to save changes to an object that's already in the database, use save().

Automatic creation date for Django model form objects?

You can use the auto_now and auto_now_add options for updated_at and created_at respectively.

class MyModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

Django datetime issues (default=datetime.now())

The datetime.now() is evaluated when the class is created, not when new record is being added to the database.

To achieve what you want define this field as:

date = models.DateTimeField(auto_now_add=True)

This way the date field will be set to current date for each new record.

Django auto_now and auto_now_add

Here's the answer if you're using south and you want to default to the date you add the field to the database:

Choose option 2 then: datetime.datetime.now()

Looks like this:

$ ./manage.py schemamigration myapp --auto
 ? The field 'User.created_date' does not have a default specified, yet is NOT NULL.
 ? Since you are adding this field, you MUST specify a default
 ? value to use for existing rows. Would you like to:
 ?  1. Quit now, and add a default to the field in models.py
 ?  2. Specify a one-off value to use for existing columns now
 ? Please select a choice: 2
 ? Please enter Python code for your one-off default value.
 ? The datetime module is available, so you can do e.g. datetime.date.today()
 >>> datetime.datetime.now()
 + Added field created_date on myapp.User

How can I filter a date of a DateTimeField in Django?

Now Django has __date queryset filter to query datetime objects against dates in development version. Thus, it will be available in 1.9 soon.

How to format dateTime in django template?

I suspect wpis.entry.lastChangeDate has been somehow transformed into a string in the view, before arriving to the template.

In order to verify this hypothesis, you may just check in the view if it has some property/method that only strings have - like for instance wpis.entry.lastChangeDate.upper, and then see if the template crashes.

You could also create your own custom filter, and use it for debugging purposes, letting it inspect the object, and writing the results of the inspection on the page, or simply on the console. It would be able to inspect the object, and check if it is really a DateTimeField.

On an unrelated notice, why don't you use models.DateTimeField(auto_now_add=True) to set the datetime on creation?

AttributeError: 'module' object has no attribute 'model'

It's called models.Model and not models.model (case sensitive). Fix your Poll model like this -

class Poll(models.Model):
    question = models.CharField(max_length=200) 
    pub_date = models.DateTimeField('date published')

How to multiply duration by integer?

int32 and time.Duration are different types. You need to convert the int32 to a time.Duration, such as time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond).

How to respond to clicks on a checkbox in an AngularJS directive?

Liviu's answer was extremely helpful for me. Hope this is not bad form but i made a fiddle that may help someone else out in the future.

Two important pieces that are needed are:

    $scope.entities = [{
    "title": "foo",
    "id": 1
}, {
    "title": "bar",
    "id": 2
}, {
    "title": "baz",
    "id": 3
}];
$scope.selected = [];

MVC pattern on Android

After some searching, the most reasonable answer is the following:

MVC is already implemented in Android as:

  1. View = layout, resources and built-in classes like Button derived from android.view.View.
  2. Controller = Activity
  3. Model = the classes that implement the application logic

(This by the way implies no application domain logic in the activity.)

The most reasonable thing for a small developer is to follow this pattern and not to try to do what Google decided not to do.

PS Note that Activity is sometimes restarted, so it's no place for model data (the easiest way to cause a restart is to omit android:configChanges="keyboardHidden|orientation" from the XML and turn your device).

EDIT

We may be talking about MVC, but it will be so to say FMVC, Framework--Model--View--Controller. The Framework (the Android OS) imposes its idea of component life cycle and related events, and in practice the Controller (Activity/Service/BroadcastReceiver) is first of all responsible for coping with these Framework-imposed events (such as onCreate()). Should user input be processed separately? Even if it should, you cannot separate it, user input events also come from Android.

Anyway, the less code that is not Android-specific you put into your Activity/Service/BroadcastReceiver, the better.

How to find whether a number belongs to a particular range in Python?

>>> s = 1.1
>>> 0<= s <=0.2
False
>>> 0<= s <=1.2
True

Google Maps API - how to get latitude and longitude from Autocomplete without showing the map?

Google Places API also provides REST api including Places Autocomplete. https://developers.google.com/places/documentation/autocomplete

But the data retrieve from the service must use for a map.

How to force HTTPS using a web.config file

For those using ASP.NET MVC. You can use the RequireHttpsAttribute to force all responses to be HTTPS:

GlobalFilters.Filters.Add(new RequireHttpsAttribute());

Other things you may also want to do to help secure your site:

  1. Force Anti-Forgery tokens to use SSL/TLS:

    AntiForgeryConfig.RequireSsl = true;
    
  2. Require Cookies to require HTTPS by default by changing the Web.config file:

    <system.web>
        <httpCookies httpOnlyCookies="true" requireSSL="true" />
    </system.web>
    
  3. Use the NWebSec.Owin NuGet package and add the following line of code to enable Strict Transport Security (HSTS) across the site. Don't forget to add the Preload directive below and submit your site to the HSTS Preload site. More information here and here. Note that if you are not using OWIN, there is a Web.config method you can read up on on the NWebSec site.

    // app is your OWIN IAppBuilder app in Startup.cs
    app.UseHsts(options => options.MaxAge(days: 720).Preload());
    
  4. Use the NWebSec.Owin NuGet package and add the following line of code to enable Public Key Pinning (HPKP) across the site. More information here and here.

    // app is your OWIN IAppBuilder app in Startup.cs
    app.UseHpkp(options => options
        .Sha256Pins(
            "Base64 encoded SHA-256 hash of your first certificate e.g. cUPcTAZWKaASuYWhhneDttWpY3oBAkE3h2+soZS7sWs=",
            "Base64 encoded SHA-256 hash of your second backup certificate e.g. M8HztCzM3elUxkcjR2S5P4hhyBNf6lHkmjAHKhpGPWE=")
        .MaxAge(days: 30));
    
  5. Include the https scheme in any URL's used. Content Security Policy (CSP) HTTP header and Subresource Integrity (SRI) do not play nice when you imit the scheme in some browsers. It is better to be explicit about HTTPS. e.g.

    <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.4/bootstrap.min.js">
    </script>
    
  6. Use the ASP.NET MVC Boilerplate Visual Studio project template to generate a project with all of this and much more built in. You can also view the code on GitHub.

Is there a difference between PhoneGap and Cordova commands?

Now a days phonegap and cordova is owned by Adobe. Only name conversation was different. For install plugin functionality , we should use same command for phonegap and cordova too.

Command : cordova plugin add cordova-plugin-photo-library

Here,

  • cordova - keyword for initiator
  • plugin - initialize a plugin
  • cordova plugin photo library - plugin name.

You can also find more plugin from https://cordova.apache.org/docs/en/latest/

Counting Number of Letters in a string variable

myString.Length; //will get you your result
//alternatively, if you only want the count of letters:
myString.Count(char.IsLetter);
//however, if you want to display the words as ***_***** (where _ is a space)
//you can also use this:
//small note: that will fail with a repeated word, so check your repeats!
myString.Split(' ').ToDictionary(n => n, n => n.Length);
//or if you just want the strings and get the counts later:
myString.Split(' ');
//will not fail with repeats
//and neither will this, which will also get you the counts:
myString.Split(' ').Select(n => new KeyValuePair<string, int>(n, n.Length));

How do I change the default port (9000) that Play uses when I execute the "run" command?

Specify Port in Development

By default, SBT runs the application on port 9000:

sbt run

To specify a port add -Dhttp.port flag, for example:

sbt run -Dhttp.port=8080

Using the -Dhttp.port flag, you can debug multiple applications on your development machine. Please note, you can also use the -Dhttp.port flag in test and production environments.

What regular expression will match valid international phone numbers?

I have used this below:

^(\+|00)[0-9]{1,3}[0-9]{4,14}(?:x.+)?$

The format +CCC.NNNNNNNNNNxEEEE or 00CCC.NNNNNNNNNNxEEEE

Phone number must start with '+' or '00' for an international call. where C is the 1–3 digit country code,

N is up to 14 digits,

and E is the (optional) extension.

The leading plus sign and the dot following the country code are required. The literal “x” character is required only if an extension is provided.

Calculate mean and standard deviation from a vector of samples in C++ using Boost

I don't know if Boost has more specific functions, but you can do it with the standard library.

Given std::vector<double> v, this is the naive way:

#include <numeric>

double sum = std::accumulate(v.begin(), v.end(), 0.0);
double mean = sum / v.size();

double sq_sum = std::inner_product(v.begin(), v.end(), v.begin(), 0.0);
double stdev = std::sqrt(sq_sum / v.size() - mean * mean);

This is susceptible to overflow or underflow for huge or tiny values. A slightly better way to calculate the standard deviation is:

double sum = std::accumulate(v.begin(), v.end(), 0.0);
double mean = sum / v.size();

std::vector<double> diff(v.size());
std::transform(v.begin(), v.end(), diff.begin(),
               std::bind2nd(std::minus<double>(), mean));
double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
double stdev = std::sqrt(sq_sum / v.size());

UPDATE for C++11:

The call to std::transform can be written using a lambda function instead of std::minus and std::bind2nd(now deprecated):

std::transform(v.begin(), v.end(), diff.begin(), [mean](double x) { return x - mean; });

Alter and Assign Object Without Side Effects

You will have the same object two times in your array, because object values are passed by reference. You have to create a new object like this

myElement.id = 244;
myElement.value = 3556;
myArray[0] = $.extend({}, myElement); //for shallow copy or
myArray[0] = $.extend(true, {}, myElement); // for deep copy

or

myArray.push({ id: 24, value: 246 });

Overlay normal curve to histogram in R

Here's a nice easy way I found:

h <- hist(g, breaks = 10, density = 10,
          col = "lightgray", xlab = "Accuracy", main = "Overall") 
xfit <- seq(min(g), max(g), length = 40) 
yfit <- dnorm(xfit, mean = mean(g), sd = sd(g)) 
yfit <- yfit * diff(h$mids[1:2]) * length(g) 

lines(xfit, yfit, col = "black", lwd = 2)

How can I find last row that contains data in a specific column?

Last_Row = Range("A1").End(xlDown).Row

Just to verify, let's say you want to print the row number of the last row with the data in cell C1.

Range("C1").Select
Last_Row = Range("A1").End(xlDown).Row
ActiveCell.FormulaR1C1 = Last_Row

SQL Server JOIN missing NULL values

Try using additional condition in join:

SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1 
INNER JOIN Table2
ON (Table1.Col1 = Table2.Col1 
    OR (Table1.Col1 IS NULL AND Table2.Col1 IS NULL)
   )

Get names of all keys in the collection

This works fine for me:

var arrayOfFieldNames = [];

var items = db.NAMECOLLECTION.find();

while(items.hasNext()) {
  var item = items.next();
  for(var index in item) {
    arrayOfFieldNames[index] = index;
   }
}

for (var index in arrayOfFieldNames) {
  print(index);
}

Jenkins returned status code 128 with github

In my case I had to add the public key to my repo (at Bitbucket) AND use git clone once via ssh to answer yes to the "known host" question the first time.

os.path.dirname(__file__) returns empty

import os.path

dirname = os.path.dirname(__file__) or '.'

How do I use jQuery to redirect?

Via Jquery:

$(location).attr('href','http://example.com/Registration/Success/');

Location of hibernate.cfg.xml in project?

Another reason why this exception occurs is if you call the configure method twice on a Configuration or AnnotatedConfiguration object like this -

AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(MyClass.class);
//Use this if config files are in src folder
config.configure();
//Use this if config files are in a subfolder of src, such as "resources"
config.configure("/resources/hibernate.cfg.xml");

Btw, this project structure is inside eclipse.

What is a Java String's default initial value?

There are three types of variables:

  • Instance variables: are always initialized
  • Static variables: are always initialized
  • Local variables: must be initialized before use

The default values for instance and static variables are the same and depends on the type:

  • Object type (String, Integer, Boolean and others): initialized with null
  • Primitive types:
    • byte, short, int, long: 0
    • float, double: 0.0
    • boolean: false
    • char: '\u0000'

An array is an Object. So an array instance variable that is declared but no explicitly initialized will have null value. If you declare an int[] array as instance variable it will have the null value.

Once the array is created all of its elements are assiged with the default type value. For example:

private boolean[] list; // default value is null

private Boolean[] list; // default value is null

once is initialized:

private boolean[] list = new boolean[10]; // all ten elements are assigned to false

private Boolean[] list = new Boolean[10]; // all ten elements are assigned to null (default Object/Boolean value)

Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_151 contains a valid JDK installation

This can occur if your path is too long as well. I solved this by moving my java install to

C:\Java\jdk1.8.0_211

Shuffle an array with python, randomize array item order with python

I don't know I used random.shuffle() but it return 'None' to me, so I wrote this, might helpful to someone

def shuffle(arr):
    for n in range(len(arr) - 1):
        rnd = random.randint(0, (len(arr) - 1))
        val1 = arr[rnd]
        val2 = arr[rnd - 1]

        arr[rnd - 1] = val1
        arr[rnd] = val2

    return arr

How to $http Synchronous call with AngularJS

I have worked with a factory integrated with google maps autocomplete and promises made??, I hope you serve.

http://jsfiddle.net/the_pianist2/vL9nkfe3/1/

you only need to replace the autocompleteService by this request with $ http incuida being before the factory.

app.factory('Autocomplete', function($q, $http) {

and $ http request with

 var deferred = $q.defer();
 $http.get('urlExample').
success(function(data, status, headers, config) {
     deferred.resolve(data);
}).
error(function(data, status, headers, config) {
     deferred.reject(status);
});
 return deferred.promise;

<div ng-app="myApp">
  <div ng-controller="myController">
  <input type="text" ng-model="search"></input>
  <div class="bs-example">
     <table class="table" >
        <thead>
           <tr>
              <th>#</th>
              <th>Description</th>
           </tr>
        </thead>
        <tbody>
           <tr ng-repeat="direction in directions">
              <td>{{$index}}</td>
              <td>{{direction.description}}</td>
           </tr>
        </tbody>
     </table>
  </div>

'use strict';
 var app = angular.module('myApp', []);

  app.factory('Autocomplete', function($q) {
    var get = function(search) {
    var deferred = $q.defer();
    var autocompleteService = new google.maps.places.AutocompleteService();
    autocompleteService.getPlacePredictions({
        input: search,
        types: ['geocode'],
        componentRestrictions: {
            country: 'ES'
        }
    }, function(predictions, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            deferred.resolve(predictions);
        } else {
            deferred.reject(status);
        }
    });
    return deferred.promise;
};

return {
    get: get
};
});

app.controller('myController', function($scope, Autocomplete) {
$scope.$watch('search', function(newValue, oldValue) {
    var promesa = Autocomplete.get(newValue);
    promesa.then(function(value) {
        $scope.directions = value;
    }, function(reason) {
        $scope.error = reason;
    });
 });

});

the question itself is to be made on:

deferred.resolve(varResult); 

when you have done well and the request:

deferred.reject(error); 

when there is an error, and then:

return deferred.promise;

How to delete a selected DataGridViewRow and update a connected database table?

private void btnDelete_Click(object sender, EventArgs e)
{
    dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
                ?BindingSource.EndEdit();
                ?TableAdapter.Update(this.?DataSet.yourTableName);
}

//NOTE:
//? - is your data from database

Exception no need ... or change with your own code.

CODE: enter image description here

DB: enter image description here

Example: prntscr.com/p3208c

DB Set: http://prntscr.com/p321pw

Is there anything like .NET's NotImplementedException in Java?

You could do it yourself (thats what I did) - in order to not be bothered with exception handling, you simply extend the RuntimeException, your class could look something like this:

public class NotImplementedException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    public NotImplementedException(){}
}

You could extend it to take a message - but if you use the method as I do (that is, as a reminder, that there is still something to be implemented), then usually there is no need for additional messages.

I dare say, that I only use this method, while I am in the process of developing a system, makes it easier for me to not lose track of which methods are still not implemented properly :)

Unlink of file Failed. Should I try again?

If closing your IDE and running various git commands listed here won't help, try manually killing all running Java processes. I had a Java process probably left over from eclipse that somehow kept a configuration file open.

Set bootstrap modal body height by percentage

Instead of using a %, the units vh set it to a percent of the viewport (browser window) size.

I was able to set a modal with an image and text beneath to be responsive to the browser window size using vh.

If you just want the content to scroll, you could leave out the part that limits the size of the modal body.

/*When the modal fills the screen it has an even 2.5% on top and bottom*/
/*Centers the modal*/
.modal-dialog {
  margin: 2.5vh auto;
}

/*Sets the maximum height of the entire modal to 95% of the screen height*/
.modal-content {
  max-height: 95vh;
  overflow: scroll;
}

/*Sets the maximum height of the modal body to 90% of the screen height*/
.modal-body {
  max-height: 90vh;
}
/*Sets the maximum height of the modal image to 69% of the screen height*/
.modal-body img {
  max-height: 69vh;
}

jQuery $("#radioButton").change(...) not firing during de-selection

This normally works for me:

if ($("#r1").is(":checked")) {}

Numpy array dimensions

You can use .ndim for dimension and .shape to know the exact dimension

var = np.array([[1,2,3,4,5,6], [1,2,3,4,5,6]])

var.ndim
# displays 2

var.shape
# display 6, 2

You can change the dimension using .reshape function

var = np.array([[1,2,3,4,5,6], [1,2,3,4,5,6]]).reshape(3,4)

var.ndim
#display 2

var.shape
#display 3, 4

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

    //best way to deal with this is sqlbulkcopy 
    //but if you dont like it you can do it like this
    //read current sql table in an adapter
    //add rows of datatable , I have mentioned a simple way of it
    //and finally updating changes

    Dim cnn As New SqlConnection("connection string")        
    cnn.Open()
    Dim cmd As New SqlCommand("select * from  sql_server_table", cnn)
    Dim da As New SqlDataAdapter(cmd)       
    Dim ds As New DataSet()
    da.Fill(ds, "sql_server_table")
    Dim cb As New SqlCommandBuilder(da)        

    //for each datatable row
    ds.Tables("sql_server_table").Rows.Add(COl1, COl2)

    da.Update(ds, "sql_server_table")

Flutter command not found

Just revert to chsh -s /bin/bash from chsh -s /bin/zsh,

Run one command

chsh -s /bin/bash

Your facing this problem just because of you have change shell from /bash to /zsh in macOs. If you run this command again it will change the path again. So just run one command and problem solve.

getting the X/Y coordinates of a mouse click on an image with jQuery

note! there is a difference between e.clientX & e.clientY and e.pageX and e.pageY

try them both out and make sure you are using the proper one. clientX and clientY change based on scrolling position

JPA EntityManager: Why use persist() over merge()?

Some more details about merge which will help you to use merge over persist:

Returning a managed instance other than the original entity is a critical part of the merge process. If an entity instance with the same identifier already exists in the persistence context, the provider will overwrite its state with the state of the entity that is being merged, but the managed version that existed already must be returned to the client so that it can be used. If the provider did not update the Employee instance in the persistence context, any references to that instance will become inconsistent with the new state being merged in.

When merge() is invoked on a new entity, it behaves similarly to the persist() operation. It adds the entity to the persistence context, but instead of adding the original entity instance, it creates a new copy and manages that instance instead. The copy that is created by the merge() operation is persisted as if the persist() method were invoked on it.

In the presence of relationships, the merge() operation will attempt to update the managed entity to point to managed versions of the entities referenced by the detached entity. If the entity has a relationship to an object that has no persistent identity, the outcome of the merge operation is undefined. Some providers might allow the managed copy to point to the non-persistent object, whereas others might throw an exception immediately. The merge() operation can be optionally cascaded in these cases to prevent an exception from occurring. We will cover cascading of the merge() operation later in this section. If an entity being merged points to a removed entity, an IllegalArgumentException exception will be thrown.

Lazy-loading relationships are a special case in the merge operation. If a lazy-loading relationship was not triggered on an entity before it became detached, that relationship will be ignored when the entity is merged. If the relationship was triggered while managed and then set to null while the entity was detached, the managed version of the entity will likewise have the relationship cleared during the merge."

All of the above information was taken from "Pro JPA 2 Mastering the Java™ Persistence API" by Mike Keith and Merrick Schnicariol. Chapter 6. Section detachment and merging. This book is actually a second book devoted to JPA by authors. This new book has many new information then former one. I really recommed to read this book for ones who will be seriously involved with JPA. I am sorry for anonimously posting my first answer.

How can I update window.location.hash without jumping the document?

There is a workaround by using the history API on modern browsers with fallback on old ones:

if(history.pushState) {
    history.pushState(null, null, '#myhash');
}
else {
    location.hash = '#myhash';
}

Credit goes to Lea Verou

Get index of a row of a pandas dataframe as an integer

To answer the original question on how to get the index as an integer for the desired selection, the following will work :

df[df['A']==5].index.item()

Nullable types: better way to check for null or zero in c#

public static bool nz(object obj)
{
    return obj == null || obj.Equals(Activator.CreateInstance(obj.GetType()));
}

How to test a variable is null in python

Testing for name pointing to None and name existing are two semantically different operations.

To check if val is None:

if val is None:
    pass  # val exists and is None

To check if name exists:

try:
    val
except NameError:
    pass  # val does not exist at all

How do you truncate all tables in a database using TSQL?

I do not see why clearing data would be better than a script to drop and re-create each table.

That or keep a back up of your empty DB and restore it over old one

Java switch statement: Constant expression required, but it IS constant

I recommend you to use enums :)

Check this out:

public enum Foo 
{
    BAR("bar"),
    BAZ("baz"),
    BAM("bam");

    private final String description;

    private Foo(String description)
    {
        this.description = description;
    }

    public String getDescription()
    {
        return description;
    }
}

Then you can use it like this:

System.out.println(Foo.BAR.getDescription());

How to get info on sent PHP curl request

The request is printed in a request.txt with details

$ch = curl_init();
$f = fopen('request.txt', 'w');
curl_setopt_array($ch, array(
CURLOPT_URL            => $url, 
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_VERBOSE        => 1,
CURLOPT_STDERR         => $f,
));
$response = curl_exec($ch);
fclose($f);
curl_close($ch);

You can also use curl_getinfo() function.

How to download and save an image in Android

Try this

 try
                {
                    Bitmap bmp = null;
                    URL url = new URL("Your_URL");
                    URLConnection conn = url.openConnection();
                    bmp = BitmapFactory.decodeStream(conn.getInputStream());
                    File f = new File(Environment.getExternalStorageDirectory(),System.currentTimeMillis() + ".jpg");
                    if(f.exists())
                        f.delete();
                    f.createNewFile();
                    Bitmap bitmap = bmp;
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
                    byte[] bitmapdata = bos.toByteArray();
                    FileOutputStream fos = new FileOutputStream(f);
                    fos.write(bitmapdata);
                    fos.flush();
                    fos.close();
                    Log.e(TAG, "imagepath: "+f );
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }

Get UTC time and local time from NSDate object

My Xcode Version 6.1.1 (6A2008a)

In playground, test like this:

// I'm in East Timezone 8
let x = NSDate() //Output:"Dec 29, 2014, 11:37 AM"
let y = NSDate.init() //Output:"Dec 29, 2014, 11:37 AM"
println(x) //Output:"2014-12-29 03:37:24 +0000"


// seconds since 2001
x.hash //Output:441,517,044
x.hashValue //Output:441,517,044
x.timeIntervalSinceReferenceDate //Output:441,517,044.875367

// seconds since 1970
x.timeIntervalSince1970 //Output:1,419,824,244.87537

JQuery show/hide when hover

Since you're using jQuery, you just need to attach to some specific events and some pre defined animations:

$('#cat').hover(function()
{
     // Mouse Over Callback
}, function()
{ 
     // Mouse Leave callback
});

Then, to do the animation, you simply need to call the fadeOut / fadeIn animations:

$('#dog').fadeOut(750 /* Animation Time */, function()
{
    // animation complete callback
     $('#cat').fadeIn(750);
});

Combining the two together, you would simply insert the animations in the hover callbacks (something like so, use this as a reference point):

$('#cat').hover(function()
{
     if($('#dog').is(':visible'))
        $('#dog').fadeOut(750 /* Animation Time */, function()
     {
        // animation complete callback
         $('#cat').fadeIn(750);
     });
}, function()
{ 
     // Mouse Leave callback
});

Google Play app description formatting

Another alternative to cut, copy and paste emojis is:

https://emojicut.com/

Which version of Python do I have installed?

You can get the version of Python by using the following command

python --version

You can even get the version of any package installed in venv using pip freeze as:

pip freeze | grep "package name"

Or using the Python interpreter as:

In [1]: import django
In [2]: django.VERSION
Out[2]: (1, 6, 1, 'final', 0)

A weighted version of random.choice

It depends on how many times you want to sample the distribution.

Suppose you want to sample the distribution K times. Then, the time complexity using np.random.choice() each time is O(K(n + log(n))) when n is the number of items in the distribution.

In my case, I needed to sample the same distribution multiple times of the order of 10^3 where n is of the order of 10^6. I used the below code, which precomputes the cumulative distribution and samples it in O(log(n)). Overall time complexity is O(n+K*log(n)).

import numpy as np

n,k = 10**6,10**3

# Create dummy distribution
a = np.array([i+1 for i in range(n)])
p = np.array([1.0/n]*n)

cfd = p.cumsum()
for _ in range(k):
    x = np.random.uniform()
    idx = cfd.searchsorted(x, side='right')
    sampled_element = a[idx]

How to retrieve SQL result column value using column name in Python?

import pymysql

# Open database connection
db = pymysql.connect("localhost","root","","gkdemo1")

# prepare a cursor object using cursor() method
cursor = db.cursor()

# execute SQL query using execute() method.
cursor.execute("SELECT * from user")

# Get the fields name (only once!)
field_name = [field[0] for field in cursor.description]

# Fetch a single row using fetchone() method.
values = cursor.fetchone()

# create the row dictionary to be able to call row['login']
**row = dict(zip(field_name, values))**

# print the dictionary
print(row)

# print specific field
print(**row['login']**)

# print all field
for key in row:
    print(**key," = ",row[key]**)

# close database connection
db.close()

How do you create a Spring MVC project in Eclipse?

You don't necessarily have to create a Spring project. Almost all Java web applications have he same project structure. In almost every project I create, I automatically add these source folder:

  • src/main/java
  • src/main/resources
  • src/test/java
  • src/test/resources
  • src/main/webapp*

src/main/webapp isn't actually a source folder. The web.xml file under src/main/webapp/WEB-INF will allow you to run your java application on any Java enabled web server (Tomcat, Jetty, etc.). I typically add the Jetty Plugin to my POM (assuming you use Maven), and launch the web app in development using mvn clean jetty:run.

Multiple Cursors in Sublime Text 2 Windows

It's usually just easier to skip the mouse altogether--or it would be if Sublime didn't mess up multiselect when word wrapping. Here's the official documentation on using the keyboard and mouse for multiple selection. Since it's a bit spread out, I'll summarize it:

Where shortcuts are different in Sublime Text 3, I've made a note. For v3, I always test using the latest dev build; if you're using the beta build, your experience may be different.

If you lose your selection when switching tabs or windows (particularly on Linux), try using Ctrl + U to restore it.

Mouse

Windows/Linux

Building blocks:

  • Positive/negative:
    • Add to selection: Ctrl
    • Subtract from selection: Alt In early builds of v3, this didn't work for linear selection.
  • Selection type:
    • Linear selection: Left Click
    • Block selection: Middle Click or Shift + Right Click On Linux, middle click pastes instead by default.

Combine as you see fit. For example:

  • Add to selection: Ctrl + Left Click (and optionally drag)
  • Subtract from selection: Alt + Left Click This didn't work in early builds of v3.
  • Add block selection: Ctrl + Shift + Right Click (and drag)
  • Subtract block selection: Alt + Shift + Right Click (and drag)

Mac OS X

Building blocks:

  • Positive/negative:
    • Add to selection: ?
    • Subtract from selection: ?? (only works with block selection in v3; presumably bug)
  • Selection type:
    • Linear selection: Left Click
    • Block selection: Middle Click or ? + Left Click

Combine as you see fit. For example:

  • Add to selection: ? + Left Click (and optionally drag)
  • Subtract from selection: ?? + Left Click (and drag--this combination doesn't work in Sublime Text 3, but supposedly it works in 2)
  • Add block selection: ?? + Left Click (and drag)
  • Subtract block selection: ??? + Left Click (and drag)

Keyboard

Windows

  • Return to single selection mode: Esc
  • Extend selection upward/downward at all carets: Ctrl + Alt + Up/Down
  • Extend selection leftward/rightward at all carets: Shift + Left/Right
  • Move all carets up/down/left/right, and clear selection: Up/Down/Left/Right
  • Undo the last selection motion: Ctrl + U
  • Add next occurrence of selected text to selection: Ctrl + D
  • Add all occurrences of the selected text to the selection: Alt + F3
  • Rotate between occurrences of selected text (single selection): Ctrl + F3 (reverse: Ctrl + Shift + F3)
  • Turn a single linear selection into a block selection, with a caret at the end of the selected text in each line: Ctrl + Shift + L

Linux

  • Return to single selection mode: Esc
  • Extend selection upward/downward at all carets: Alt + Up/Down Note that you may be able to hold Ctrl as well to get the same shortcuts as Windows, but Linux tends to use Ctrl + Alt combinations for global shortcuts.
  • Extend selection leftward/rightward at all carets: Shift + Left/Right
  • Move all carets up/down/left/right, and clear selection: Up/Down/Left/Right
  • Undo the last selection motion: Ctrl + U
  • Add next occurrence of selected text to selection: Ctrl + D
  • Add all occurrences of the selected text to the selection: Alt + F3
  • Rotate between occurrences of selected text (single selection): Ctrl + F3 (reverse: Ctrl + Shift + F3)
  • Turn a single linear selection into a block selection, with a caret at the end of the selected text in each line: Ctrl + Shift + L

Mac OS X

  • Return to single selection mode: ? (that's the Mac symbol for Escape)
  • Extend selection upward/downward at all carets: ^??, ^?? (See note)
  • Extend selection leftward/rightward at all carets: ??/??
  • Move all carets up/down/left/right and clear selection: ?, ?, ?, ?
  • Undo the last selection motion: ?U
  • Add next occurrence of selected text to selection: ?D
  • Add all occurrences of the selected text to the selection: ^?G
  • Rotate between occurrences of selected text (single selection): ??G (reverse: ???G)
  • Turn a single linear selection into a block selection, with a caret at the end of the selected text in each line: ??L

Notes for Mac users

On Yosemite and El Capitan, ^?? and ^?? are system keyboard shortcuts by default. If you want them to work in Sublime Text, you will need to change them:

  1. Open System Preferences.
  2. Select the Shortcuts tab.
  3. Select Mission Control in the left listbox.
  4. Change the keyboard shortcuts for Mission Control and Application windows (or disable them). I use ^?? and ^??. They defaults are ^? and ^?; adding ^ to those shortcuts triggers the same actions, but slows the animations.

In case you're not familiar with Mac's keyboard symbols:

  • ? is the escape key
  • ^ is the control key
  • ? is the option key
  • ? is the shift key
  • ? is the command key
  • ? et al are the arrow keys, as depicted

SignalR Console app example

The Self-Host now uses Owin. Checkout http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-signalr-20-self-host to setup the server. It's compatible with the client code above.

Visual studio - getting error "Metadata file 'XYZ' could not be found" after edit continue

I had this and managed to fix it using this SO answer: Metadata file '.dll' could not be found

I had to uncheck all of the boxes, click Apply, reenable all of the checkboxes and then click apply again, but it fixed the problem.

Executing another application from Java

I could see that there is a better library than the apache commons exec library. You can execute your job using Java Secure Shell (JSch).

I had the same problem. I used JSch to solve this problem. Apache commons had some issues running commands on a different server. Plus JSch gave me result and errors InputStreams. I found it more elegant. Sample solution can be found here : http://wiki.jsch.org/index.php?Manual%2FExamples%2FJschExecExample

    import java.io.InputStream;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;

    import org.apache.commons.exec.*;

    import com.jcraft.*;
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.Session;
    import com.jcraft.jsch.ChannelExec;

    import java.util.Arrays;
    import java.util.List;
    import java.util.ArrayList;
    import java.util.HashMap;


    public class  exec_linux_cmd {
        public HashMap<String,List<String>> exec_cmd (
                String USERNAME,
                String PASSWORD,
                String host,
                int port,
                String cmd)
        {
            List<String> result = new ArrayList<String>();
            List<String> errors = new ArrayList<String>();
            HashMap<String,List<String>> result_map = new HashMap<String,List<String>>();
        //String line = "echo `eval hostname`";
            try{
            JSch jsch = new JSch();
            /*
            * Open a new session, with your username, host and port
            * Set the password and call connect.
            * session.connect() opens a new connection to remote SSH server.
            * Once the connection is established, you can initiate a new channel.
            * this channel is needed to connect and remotely execute the program
            */

            Session session = jsch.getSession(USERNAME, host, port);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(PASSWORD);
            session.connect();

            //create the excution channel over the session
            ChannelExec channelExec = (ChannelExec)session.openChannel("exec");

            // Gets an InputStream for this channel. All data arriving in as messages from the remote side can be read from this stream.
            InputStream in = channelExec.getInputStream();
            InputStream err = channelExec.getErrStream();

            // Set the command that you want to execute
            // In our case its the remote shell script

            channelExec.setCommand(cmd);

            //Execute the command
            channelExec.connect();

            // read the results stream
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            // read the errors stream. This will be null if no error occured
            BufferedReader err_reader = new BufferedReader(new InputStreamReader(err));
            String line;

            //Read each line from the buffered reader and add it to result list
            // You can also simple print the result here

            while ((line = reader.readLine()) != null)
            {
                result.add(line);
            }

            while ((line = err_reader.readLine()) != null)
            {
                errors.add(line);
            }

            //retrieve the exit status of the remote command corresponding to this channel
            int exitStatus = channelExec.getExitStatus();
            System.out.println(exitStatus);

            //Safely disconnect channel and disconnect session. If not done then it may cause resource leak
            channelExec.disconnect();
            session.disconnect();
            System.out.println(exitStatus);
            result_map.put("result", result);
            result_map.put("error", errors);

            if(exitStatus < 0){
                System.out.println("Done--> " + exitStatus);
                System.out.println(Arrays.asList(result_map));
                //return errors;
            }
            else if(exitStatus > 0){
                System.out.println("Done -->" + exitStatus);
                System.out.println(Arrays.asList(result_map));
                //return errors;
            }
            else{
               System.out.println("Done!");
               System.out.println(Arrays.asList(result_map));
               //return result;
            }

            }
            catch (Exception e)
            {
                System.out.print(e);
            }

            return result_map;
        }



        //CommandLine commandLine = CommandLine.parse(cmd);
        //DefaultExecutor executor = new DefaultExecutor();
        //executor.setExitValue(1);
        //int exitValue = executor.execute(commandLine);

           public static void main(String[] args)
           {
               //String line = args[0];
               final String USERNAME ="abc"; // username for remote host
               final String PASSWORD ="abc"; // password of the remote host
               final String host = "3.98.22.10"; // remote host address
               final int port=22; // remote host port
               HashMap<String,List<String>> result = new HashMap<String,List<String>>();

               //String cmd = "echo `eval hostname`"; // command to execute on remote host
               exec_linux_cmd ex = new exec_linux_cmd();

               result = ex.exec_cmd(USERNAME, PASSWORD , host, port, cmd);
               System.out.println("Result ---> " + result.get("result"));
               System.out.println("Error Msg ---> " +result.get("error"));
               //System.out.println(Arrays.asList(result));

               /*
               for (int i =0; i < result.get("result").size();i++)
               {
                        System.out.println(result.get("result").get(i));
               }
               */

           }
    }

EDIT 1: In order to find your process (if its a long-running one) being executed on Unix, use the ps -aux | grep java. The process ID should be listed alongwith the unix command you are executing.

How can I use an ES6 import in Node.js?

Solution

https://www.npmjs.com/package/babel-register

// This is to allow ES6 export syntax
// to be properly read and processed by node.js application
require('babel-register')({
  presets: [
    'env',
  ],
});

// After that, any line you add below that has typical ES6 export syntax
// will work just fine

const utils = require('../../utils.js');
const availableMixins = require('../../../src/lib/mixins/index.js');

Below is definition of file *mixins/index.js

export { default as FormValidationMixin } from './form-validation'; // eslint-disable-line import/prefer-default-export

That worked just fine inside my Node.js CLI application.

Retrieving the COM class factory for component failed

I have Done the Following Things in IIS 8.5 (Windows Server 2012 R2)Server and its Worked in My Case Without Restart:

  1. Selecting The Application Pool That Connected to The Application in IIS

  2. And Right Click --> Advanced Settings --> Process Model --> Select Local System Instead of Recommended ApplicationPoolIdentity

  3. And Make Sure C:\Windows\SysWOW64\config\systemprofile\desktop Have Enough Access For Users.

  4. Refresh the Website Link that Connected With this Pool


enter image description here

How to force a UIViewController to Portrait orientation in iOS 6

I disagree from @aprato answer, because the UIViewController rotation methods are declared in categories themselves, thus resulting in undefined behavior if you override then in another category. Its safer to override them in a UINavigationController (or UITabBarController) subclass

Also, this does not cover the scenario where you push / present / pop from a Landscape view into a portrait only VC or vice-versa. To solve this tough issue (never addressed by Apple), you should:

In iOS <= 4 and iOS >= 6:

UIViewController *vc = [[UIViewController alloc]init];
[self presentModalViewController:vc animated:NO];
[self dismissModalViewControllerAnimated:NO];
[vc release];

In iOS 5:

UIWindow *window = [[UIApplication sharedApplication] keyWindow];
UIView *view = [window.subviews objectAtIndex:0];
[view removeFromSuperview];
[window addSubview:view];

These will REALLY force UIKit to re-evaluate all your shouldAutorotate , supportedInterfaceOrientations, etc.

How to parse dates in multiple formats using SimpleDateFormat

Using DateTimeFormatter it can be achieved as below:


import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.Date;
import java.util.TimeZone;

public class DateTimeFormatTest {

    public static void main(String[] args) {

        String pattern = "[yyyy-MM-dd[['T'][ ]HH:mm:ss[.SSSSSSSz][.SSS[XXX][X]]]]";
        String timeSample = "2018-05-04T13:49:01.7047141Z";
        SimpleDateFormat simpleDateFormatter = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        TemporalAccessor accessor = formatter.parse(timeSample);
        ZonedDateTime zTime = LocalDateTime.from(accessor).atZone(ZoneOffset.UTC);

        Date date=new Date(zTime.toEpochSecond()*1000);
        simpleDateFormatter.setTimeZone(TimeZone.getTimeZone(ZoneOffset.UTC));
        System.out.println(simpleDateFormatter.format(date));       
    }
}

Pay attention at String pattern, this is the combination of multiple patterns. In open [ and close ] square brackets you can mention any kind of patterns.

General error: 1364 Field 'user_id' doesn't have a default value

Here's how I did it:

This is my PostsController

Post::create([

    'title' => request('title'),
    'body' => request('body'),
    'user_id' => auth()->id() 
]);

And this is my Post Model.

protected $fillable = ['title', 'body','user_id'];

And try refreshing the migration if its just on test instance

$ php artisan migrate:refresh

Note: migrate: refresh will delete all the previous posts, users

How do I efficiently iterate over each entry in a Java Map?

Map<String, String> map = 
for (Map.Entry<String, String> entry : map.entrySet()) {
    MapKey = entry.getKey() 
    MapValue = entry.getValue();
}

How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31')

Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.

I had a opened record set of the post that was created by:

Set RecSet = Conn.Execute()

This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...

RecSet.Close
Set RecSet = Nothing

...everything worked just fine.

So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.

How do you use subprocess.check_output() in Python?

Adding on to the one mentioned by @abarnert

a better one is to catch the exception

import subprocess
try:
    py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'],stderr= subprocess.STDOUT)  
    #print('py2 said:', py2output)
    print "here"
except subprocess.CalledProcessError as e:
    print "Calledprocerr"

this stderr= subprocess.STDOUT is for making sure you dont get the filenotfound error in stderr- which cant be usually caught in filenotfoundexception, else you would end up getting

python: can't open file 'py2.py': [Errno 2] No such file or directory

Infact a better solution to this might be to check, whether the file/scripts exist and then to run the file/script

How can I push a specific commit to a remote, and not previous commits?

I did want to obmit a old big history and start from a fresh commit i choosed to:

rsync -a --exclude '.git' old-repo/ new-repo/
cd new-repo 
git push 

when now old-repo changes i can apply the patches to the new-repo to rebase them on the new-repo.

How to convert string to date to string in Swift iOS?

//String to Date Convert

var dateString = "2014-01-12"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.dateFromString(dateString)
println(s)


//CONVERT FROM NSDate to String  

let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd" 
var dateString = dateFormatter.stringFromDate(date)
println(dateString)  

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

C# - Winforms - Global Variables

The consensus here is to put the global variables in a static class as static members. When you create a new Windows Forms application, it usually comes with a Program class (Program.cs), which is a static class and serves as the main entry point of the application. It lives for the the whole lifetime of the app, so I think it is best to put the global variables there instead of creating a new one.

static class Program
{
    public static string globalString = "This is a global string.";

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

And use it as such:

public partial class Form1 : Form
{
    public Form1()
    {
        Program.globalString = "Accessible in Form1.";

        InitializeComponent();
    }
}

Creating a new directory in C

Look at stat for checking if the directory exists,

And mkdir, to create a directory.

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

struct stat st = {0};

if (stat("/some/directory", &st) == -1) {
    mkdir("/some/directory", 0700);
}

You can see the manual of these functions with the man 2 stat and man 2 mkdir commands.

PHP header(Location: ...): Force URL change in address bar

Do not use any white space. I had the same issue. Then I removed white space like:

header("location:index.php"); or header('location:index.php');

Then it worked.

When should I use cross apply over inner join?

While most queries which employ CROSS APPLY can be rewritten using an INNER JOIN, CROSS APPLY can yield better execution plan and better performance, since it can limit the set being joined yet before the join occurs.

Stolen from Here

How to use if statements in LESS

There is a way to use guards for individual (or multiple) attributes.

@debug: true;

header {
    /* guard for attribute */
    & when (@debug = true) {
        background-color: yellow;
    }
    /* guard for nested class */
    #title when (@debug = true) {
        background-color: orange;
    }
}

/* guard for class */
article when (@debug = true) {
    background-color: red;
}

/* and when debug is off: */
article when not (@debug = true) {
    background-color: green;
}

...and with Less 1.7; compiles to:

header {
    background-color: yellow;
}
header #title {
    background-color: orange;
}
article {
    background-color: red;
}

Excel VBA Check if directory exists error

This is the cleanest way... BY FAR:

Public Function IsDir(s) As Boolean
    IsDir = CreateObject("Scripting.FileSystemObject").FolderExists(s)
End Function

"A referral was returned from the server" exception when accessing AD from C#

In my case I was seeing referrals when I was accessing AD via SSO with an account in a trusted domain. The problem went away when I connected with explicit credentials in the local domain.

i.e. I replaced

DirectoryEntry de = new DirectoryEntry("blah.com");

with

DirectoryEntry de = new DirectoryEntry("blah.com", "[email protected]", "supersecret");

and the problem went away.

Element count of an array in C++

There are no cases where, given an array arr, that the value of sizeof(arr) / sizeof(arr[0]) is not the count of elements, by the definition of array and sizeof.

In fact, it's even directly mentioned (§5.3.3/2):

.... When applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of n elements is n times the size of an element.

Emphasis mine. Divide by the size of an element, sizeof(arr[0]), to obtain n.

In Angular, I need to search objects in an array

Your solutions are correct but unnecessary complicated. You can use pure javascript filter function. This is your model:

     $scope.fishes = [{category:'freshwater', id:'1', name: 'trout', more:'false'},  {category:'freshwater', id:'2', name:'bass', more:'false'}];

And this is your function:

     $scope.showdetails = function(fish_id){
         var found = $scope.fishes.filter({id : fish_id});
         return found;
     };

You can also use expression:

     $scope.showdetails = function(fish_id){
         var found = $scope.fishes.filter(function(fish){ return fish.id === fish_id });
         return found;
     };

More about this function: LINK

Console.WriteLine and generic List

        List<int> a = new List<int>() { 1, 2, 3, 4, 5 };
        a.ForEach(p => Console.WriteLine(p));

edit: ahhh he beat me to it.

What's the best practice for primary keys in tables?

Natural verses artifical keys is a kind of religious debate among the database community - see this article and others it links to. I'm neither in favour of always having artifical keys, nor of never having them. I would decide on a case-by-case basis, for example:

  • US States: I'd go for state_code ('TX' for Texas etc.), rather than state_id=1 for Texas
  • Employees: I'd usually create an artifical employee_id, because it's hard to find anything else that works. SSN or equivalent may work, but there could be issues like a new joiner who hasn't supplied his/her SSN yet.
  • Employee Salary History: (employee_id, start_date). I would not create an artifical employee_salary_history_id. What point would it serve (other than "foolish consistency")

Wherever artificial keys are used, you should always also declare unique constraints on the natural keys. For example, use state_id if you must, but then you'd better declare a unique constraint on state_code, otherwise you are sure to eventually end up with:

state_id    state_code   state_name
137         TX           Texas
...         ...          ...
249         TX           Texas

Statically rotate font-awesome icons

If you want to rotate 45 degrees, you can use the CSS transform property:

.fa-rotate-45 {
    -ms-transform:rotate(45deg);     /* Internet Explorer 9 */
    -webkit-transform:rotate(45deg); /* Chrome, Safari, Opera */
    transform:rotate(45deg);         /* Standard syntax */
}

Explode string by one or more spaces or tabs

The author asked for explode, to you can use explode like this

$resultArray = explode("\t", $inputString);

Note: you must used double quote, not single.

How to check if an integer is within a range?

Most of the given examples assume that for the test range [$a..$b], $a <= $b, i.e. the range extremes are in lower - higher order and most assume that all are integer numbers.
But I needed a function to test if $n was between $a and $b, as described here:

Check if $n is between $a and $b even if:
    $a < $b  
    $a > $b
    $a = $b

All numbers can be real, not only integer.

There is an easy way to test.
I base the test it in the fact that ($n-$a) and ($n-$b) have different signs when $n is between $a and $b, and the same sign when $n is outside the $a..$b range.
This function is valid for testing increasing, decreasing, positive and negative numbers, not limited to test only integer numbers.

function between($n, $a, $b)
{
    return (($a==$n)&&($b==$n))? true : ($n-$a)*($n-$b)<0;
}

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

XCOPY: Overwrite all without prompt in BATCH

The solution is the /Y switch:

xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y

How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?

I have added below code to terminate tasks you can use it. You may change the retry numbers.

package com.xxx.test.schedulers;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import com.xxx.core.XProvLogger;

@Component
class ContextClosedHandler implements ApplicationListener<ContextClosedEvent> , ApplicationContextAware,BeanPostProcessor{


private ApplicationContext context;

public Logger logger = XProvLogger.getInstance().x;

public void onApplicationEvent(ContextClosedEvent event) {


    Map<String, ThreadPoolTaskScheduler> schedulers = context.getBeansOfType(ThreadPoolTaskScheduler.class);

    for (ThreadPoolTaskScheduler scheduler : schedulers.values()) {         
        scheduler.getScheduledExecutor().shutdown();
        try {
            scheduler.getScheduledExecutor().awaitTermination(20000, TimeUnit.MILLISECONDS);
            if(scheduler.getScheduledExecutor().isTerminated() || scheduler.getScheduledExecutor().isShutdown())
                logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has stoped");
            else{
                logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has not stoped normally and will be shut down immediately");
                scheduler.getScheduledExecutor().shutdownNow();
                logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has shut down immediately");
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    Map<String, ThreadPoolTaskExecutor> executers = context.getBeansOfType(ThreadPoolTaskExecutor.class);

    for (ThreadPoolTaskExecutor executor: executers.values()) {
        int retryCount = 0;
        while(executor.getActiveCount()>0 && ++retryCount<51){
            try {
                logger.info("Executer "+executor.getThreadNamePrefix()+" is still working with active " + executor.getActiveCount()+" work. Retry count is "+retryCount);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if(!(retryCount<51))
            logger.info("Executer "+executor.getThreadNamePrefix()+" is still working.Since Retry count exceeded max value "+retryCount+", will be killed immediately");
        executor.shutdown();
        logger.info("Executer "+executor.getThreadNamePrefix()+" with active " + executor.getActiveCount()+" work has killed");
    }
}


@Override
public void setApplicationContext(ApplicationContext context)
        throws BeansException {
    this.context = context;

}


@Override
public Object postProcessAfterInitialization(Object object, String arg1)
        throws BeansException {
    return object;
}


@Override
public Object postProcessBeforeInitialization(Object object, String arg1)
        throws BeansException {
    if(object instanceof ThreadPoolTaskScheduler)
        ((ThreadPoolTaskScheduler)object).setWaitForTasksToCompleteOnShutdown(true);
    if(object instanceof ThreadPoolTaskExecutor)
        ((ThreadPoolTaskExecutor)object).setWaitForTasksToCompleteOnShutdown(true);
    return object;
}

}

How do I call an Angular 2 pipe with multiple arguments?

In your component's template you can use multiple arguments by separating them with colons:

{{ myData | myPipe: 'arg1':'arg2':'arg3'... }}

From your code it will look like this:

new MyPipe().transform(myData, arg1, arg2, arg3)

And in your transform function inside your pipe you can use the arguments like this:

export class MyPipe implements PipeTransform { 
    // specify every argument individually   
    transform(value: any, arg1: any, arg2: any, arg3: any): any { }
    // or use a rest parameter
    transform(value: any, ...args: any[]): any { }
}

Beta 16 and before (2016-04-26)

Pipes take an array that contains all arguments, so you need to call them like this:

new MyPipe().transform(myData, [arg1, arg2, arg3...])

And your transform function will look like this:

export class MyPipe implements PipeTransform {    
    transform(value:any, args:any[]):any {
        var arg1 = args[0];
        var arg2 = args[1];
        ...
    }
}

How to replace blank (null ) values with 0 for all records?

I just had this same problem, and I ended up finding the simplest solution which works for my needs. In the table properties, I set the default value to 0 for the fields that I don't want to show nulls. Super easy.

How to Convert Datetime to Date in dd/MM/yyyy format

You need to use convert in order by as well:

SELECT  Convert(varchar,A.InsertDate,103) as Tran_Date
order by Convert(varchar,A.InsertDate,103)

Make a number a percentage

Most answers suggest appending '%' at the end. I would rather prefer Intl.NumberFormat() with { style: 'percent'}

_x000D_
_x000D_
var num = 25;_x000D_
_x000D_
var option = {_x000D_
  style: 'percent'_x000D_
_x000D_
};_x000D_
var formatter = new Intl.NumberFormat("en-US", option);_x000D_
var percentFormat = formatter.format(num / 100);_x000D_
console.log(percentFormat);
_x000D_
_x000D_
_x000D_

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

If you are installed Skype, Please check this option.

enter image description here

Another case is Windows 10

Check this:

  1. Go to Start, type in services.msc
  2. Scroll down in the Services window to find the World Wide Web Publishing Service.
  3. Right-click on it, and select Stop or Disable it if you just want to use XAMPP only.

enter image description here

View markdown files offline

I like the vertical splitter in Downmarker, you can see the changes as you write!

get and set in TypeScript

You can write this

class Human {
    private firstName : string;
    private lastName : string;

    constructor (
        public FirstName?:string, 
        public LastName?:string) {

    }

    get FirstName() : string {
        console.log("Get FirstName : ", this.firstName);
        return this.firstName;
    }
    set FirstName(value : string) {
        console.log("Set FirstName : ", value);
        this.firstName = value;
    } 

    get LastName() : string {
        console.log("Get LastName : ", this.lastName);
        return this.lastName;
    }
    set LastName(value : string) {
        console.log("Set LastName : ", value);
        this.lastName = value;
    } 

}

How can I call PHP functions by JavaScript?

Void Function

<?php
function printMessage() {
    echo "Hello World!";
}
?>

<script>
    document.write("<?php printMessage() ?>");
</script>

Value Returning Function

<?php
function getMessage() {
    return "Hello World!";
}
?>

<script>
    var text = "<?php echo getMessage() ?>";
</script>

Javascript getElementsByName.value not working

You have mentioned Wrong id

alert(document.getElementById("name").value);

if you want to use name attribute then

alert(document.getElementsByName("username")[0].value);

Updates:

input type="text" id="name" name="username"  

id is different from name

subtract two times in python

You have two datetime.time objects so for that you just create two timedelta using datetime.timedetla and then substract as you do right now using "-" operand. Following is the example way to substract two times without using datetime.

enter = datetime.time(hour=1)  # Example enter time
exit = datetime.time(hour=2)  # Example start time
enter_delta = datetime.timedelta(hours=enter.hour, minutes=enter.minute, seconds=enter.second)
exit_delta = datetime.timedelta(hours=exit.hour, minutes=exit.minute, seconds=exit.second)
difference_delta = exit_delta - enter_delta

difference_delta is your difference which you can use for your reasons.

jQuery Set Cursor Position in Text Area

Here's a jQuery solution:

$.fn.selectRange = function(start, end) {
    if(end === undefined) {
        end = start;
    }
    return this.each(function() {
        if('selectionStart' in this) {
            this.selectionStart = start;
            this.selectionEnd = end;
        } else if(this.setSelectionRange) {
            this.setSelectionRange(start, end);
        } else if(this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    });
};

With this, you can do

$('#elem').selectRange(3,5); // select a range of text
$('#elem').selectRange(3); // set cursor position

Event binding on dynamically created elements?

Here is why dynamically created elements do not respond to clicks :

_x000D_
_x000D_
var body = $("body");_x000D_
var btns = $("button");_x000D_
var btnB = $("<button>B</button>");_x000D_
// `<button>B</button>` is not yet in the document._x000D_
// Thus, `$("button")` gives `[<button>A</button>]`._x000D_
// Only `<button>A</button>` gets a click listener._x000D_
btns.on("click", function () {_x000D_
  console.log(this);_x000D_
});_x000D_
// Too late for `<button>B</button>`..._x000D_
body.append(btnB);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button>A</button>
_x000D_
_x000D_
_x000D_

As a workaround, you have to listen to all clicks and check the source element :

_x000D_
_x000D_
var body = $("body");_x000D_
var btnB = $("<button>B</button>");_x000D_
var btnC = $("<button>C</button>");_x000D_
// Listen to all clicks and_x000D_
// check if the source element_x000D_
// is a `<button></button>`._x000D_
body.on("click", function (ev) {_x000D_
  if ($(ev.target).is("button")) {_x000D_
    console.log(ev.target);_x000D_
  }_x000D_
});_x000D_
// Now you can add any number_x000D_
// of `<button></button>`._x000D_
body.append(btnB);_x000D_
body.append(btnC);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button>A</button>
_x000D_
_x000D_
_x000D_

This is called "Event Delegation". Good news, it's a builtin feature in jQuery :-)

_x000D_
_x000D_
var i = 11;_x000D_
var body = $("body");_x000D_
body.on("click", "button", function () {_x000D_
  var letter = (i++).toString(36).toUpperCase();_x000D_
  body.append($("<button>" + letter + "</button>"));_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button>A</button>
_x000D_
_x000D_
_x000D_

How to access form methods and controls from a class in C#?

JUST YOU CAN SEND FORM TO CLASS LIKE THIS

Class1 excell = new Class1 (); //you must declare this in form as you want to control

excel.get_data_from_excel(this); // And create instance for class and sen this form to another class

INSIDE CLASS AS YOU CREATE CLASS1

class Class1
{
    public void get_data_from_excel (Form1 form) //you getting the form here and you can control as you want
    {
        form.ComboBox1.text = "try it"; //you can chance Form1 UI elements inside the class now
    }
}

IMPORTANT : But you must not forgat you have declare modifier form properties as PUBLIC and you can access other wise you can not see the control in form from class

What is the difference between an int and a long in C++?

The only guarantee you have are:

sizeof(char) == 1
sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) <= sizeof(long long)

// FROM @KTC. The C++ standard also has:
sizeof(signed char)   == 1
sizeof(unsigned char) == 1

// NOTE: These size are not specified explicitly in the standard.
//       They are implied by the minimum/maximum values that MUST be supported
//       for the type. These limits are defined in limits.h
sizeof(short)     * CHAR_BIT >= 16
sizeof(int)       * CHAR_BIT >= 16
sizeof(long)      * CHAR_BIT >= 32
sizeof(long long) * CHAR_BIT >= 64
CHAR_BIT         >= 8   // Number of bits in a byte

Also see: Is long guaranteed to be at least 32 bits?

Android error while retrieving information from server 'RPC:s-5:AEC-0' in Google Play?

Go to "app manager", then go to "all", then click on "Google Services Framework" and then "Clear Data". Reboot and it is done.

Is there a real solution to debug cordova apps

Here's the solution using Phonegap Build. Add the following to your config.xml to be able to inspect with Chrome Remote Webview Debugging.

First, make sure your widget tag contains xmlns:android="http://schemas.android.com/apk/res/android"

<widget 
    xmlns="http://www.w3.org/ns/widgets" 
    xmlns:gap="http://phonegap.com/ns/1.0" 
    xmlns:android="http://schemas.android.com/apk/res/android"
    id="me.app.id" 
    version="1.0.0">

Then add the following

<gap:config-file platform="android" parent="/manifest">
     <application android:debuggable="true" />
</gap:config-file>

It works for me on Nexus 5, Phonegap 3.7.0.

<preference name="phonegap-version" value="3.7.0" />

Build the app in Phonegap Build, install the APK, connect the phone to the USB, enable USB debugging on you phone then visit chrome://inspect.

Source: https://www.genuitec.com/products/gapdebug/learning-center/configuration/

Send POST data via raw json with postman

meda's answer is completely legit, but when I copied the code I got an error!

Somewhere in the "php://input" there's an invalid character (maybe one of the quotes?).

When I typed the "php://input" code manually, it worked. Took me a while to figure out!

Parse usable Street Address, City, State, Zip from a string

RecogniContact is a Windows COM object that parses US and European addresses. You can try it right on http://www.loquisoft.com/index.php?page=8

Disable copy constructor

Make SymbolIndexer( const SymbolIndexer& ) private. If you're assigning to a reference, you're not copying.

Getting pids from ps -ef |grep keyword

I use

ps -C "keyword" -o pid=

This command should give you a PID number.

How to select date from datetime column?

Using WHERE DATE(datetime) = '2009-10-20' has performance issues. As stated here:

  • it will calculate DATE() for all rows, including those that don't match.
  • it will make it impossible to use an index for the query.

Use BETWEEN or >, <, = operators which allow to use an index:

SELECT * FROM data 
WHERE datetime BETWEEN '2009-10-20 00:00:00' AND '2009-10-20 23:59:59'

Update: the impact on using LIKE instead of operators in an indexed column is high. These are some test results on a table with 1,176,000 rows:

  • using datetime LIKE '2009-10-20%' => 2931ms
  • using datetime >= '2009-10-20 00:00:00' AND datetime <= '2009-10-20 23:59:59' => 168ms

When doing a second call over the same query the difference is even higher: 2984ms vs 7ms (yes, just 7 milliseconds!). I found this while rewriting some old code on a project using Hibernate.

How to get the mouse position without events (without moving the mouse)?

I implemented a horizontal/vertical search, (first make a div full of vertical line links arranged horizontally, then make a div full of horizontal line links arranged vertically, and simply see which one has the hover state) like Tim Down's idea above, and it works pretty fast. Sadly, does not work on Chrome 32 on KDE.

jsfiddle.net/5XzeE/4/

How to convert a string to lower case in Bash?

Using GNU sed:

sed 's/.*/\L&/'

Example:

$ foo="Some STRIng";
$ foo=$(echo "$foo" | sed 's/.*/\L&/')
$ echo "$foo"
some string

Multiple conditions in ngClass - Angular 4

you need object notation

<section [ngClass]="{'class1':condition1, 'class2': condition2, 'class3':condition3}" > 

ref: NgClass

Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

I just use contentsMargin to fix the aspect ratio.

#pragma once

#include <QLabel>

class AspectRatioLabel : public QLabel
{
public:
    explicit AspectRatioLabel(QWidget* parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags());
    ~AspectRatioLabel();

public slots:
    void setPixmap(const QPixmap& pm);

protected:
    void resizeEvent(QResizeEvent* event) override;

private:
    void updateMargins();

    int pixmapWidth = 0;
    int pixmapHeight = 0;
};
#include "AspectRatioLabel.h"

AspectRatioLabel::AspectRatioLabel(QWidget* parent, Qt::WindowFlags f) : QLabel(parent, f)
{
}

AspectRatioLabel::~AspectRatioLabel()
{
}

void AspectRatioLabel::setPixmap(const QPixmap& pm)
{
    pixmapWidth = pm.width();
    pixmapHeight = pm.height();

    updateMargins();
    QLabel::setPixmap(pm);
}

void AspectRatioLabel::resizeEvent(QResizeEvent* event)
{
    updateMargins();
    QLabel::resizeEvent(event);
}

void AspectRatioLabel::updateMargins()
{
    if (pixmapWidth <= 0 || pixmapHeight <= 0)
        return;

    int w = this->width();
    int h = this->height();

    if (w <= 0 || h <= 0)
        return;

    if (w * pixmapHeight > h * pixmapWidth)
    {
        int m = (w - (pixmapWidth * h / pixmapHeight)) / 2;
        setContentsMargins(m, 0, m, 0);
    }
    else
    {
        int m = (h - (pixmapHeight * w / pixmapWidth)) / 2;
        setContentsMargins(0, m, 0, m);
    }
}

Works perfectly for me so far. You're welcome.

How to create unit tests easily in eclipse

To create a test case template:

"New" -> "JUnit Test Case" -> Select "Class under test" -> Select "Available methods". I think the wizard is quite easy for you.

HTML 5 Favicon - Support?

No, not all browsers support the sizes attribute:

Note that some platforms define specific sizes:

Gradle store on local file system

On Mac, Linux and Windows i.e. on all 3 of the major platforms, Gradle stores dependencies at:

~/.gradle/caches/modules-2/files-2.1

Unable to load DLL 'SQLite.Interop.dll'

Mine didn't work for unit tests either, and for some reason Michael Bromley's answer involving DeploymentItem attribute didn't work. However, I got it working using test settings. In VS2013, add a new item to your solution and search for "settings" and select the "Test Settings" template file. Name it "SqliteUnitTests" or something and open it. Select "Deployment" off to the right, and add Directory/File. Add paths/directories to your SQLite.Interop.dll file. For me, I added two paths, one each for Project\bin\Debug\x64 and Console\bin\Debug\x86. You may also want to add your Sqlite file, depending on how you expect your unit test/solution to access the file.

What difference does .AsNoTracking() make?

The difference is that in the first case the retrieved user is not tracked by the context so when you are going to save the user back to database you must attach it and set correctly state of the user so that EF knows that it should update existing user instead of inserting a new one. In the second case you don't need to do that if you load and save the user with the same context instance because the tracking mechanism handles that for you.

What's the difference between UTF-8 and UTF-8 without BOM?

I look at this from a different perspective. I think UTF-8 with BOM is better as it provides more information about the file. I use UTF-8 without BOM only if I face problems.

I am using multiple languages (even Cyrillic) on my pages for a long time and when the files are saved without BOM and I re-open them for editing with an editor (as cherouvim also noted), some characters are corrupted.

Note that Windows' classic Notepad automatically saves files with a BOM when you try to save a newly created file with UTF-8 encoding.

I personally save server side scripting files (.asp, .ini, .aspx) with BOM and .html files without BOM.

Align labels in form next to input

WARNING: OUTDATED ANSWER

Nowadays you should definitely avoid using fixed widths. You could use flexbox or CSS grid to come up with a responsive solution. See the other answers.


One possible solution:

  • Give the labels display: inline-block;
  • Give them a fixed width
  • Align text to the right

That is:

_x000D_
_x000D_
label {
  display: inline-block;
  width: 140px;
  text-align: right;
}?
_x000D_
<div class="block">
    <label>Simple label</label>
    <input type="text" />
</div>
<div class="block">
    <label>Label with more text</label>
    <input type="text" />
</div>
<div class="block">
    <label>Short</label>
    <input type="text" />
</div>
_x000D_
_x000D_
_x000D_

JSFiddle

Define global variable with webpack

I solved this issue by setting the global variables as a static properties on the classes to which they are most relevant. In ES5 it looks like this:

var Foo = function(){...};
Foo.globalVar = {};

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

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

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

Procedure or function !!! has too many arguments specified

You invoke the function with 2 parameters (@GenId and @Description):

EXEC etl.etl_M_Update_Promo @GenID, @Description

However you have declared the function to take 1 argument:

ALTER PROCEDURE [etl].[etl_M_Update_Promo]
    @GenId bigint = 0

SQL Server is telling you that [etl_M_Update_Promo] only takes 1 parameter (@GenId)

You can alter the procedure to take two parameters by specifying @Description.

ALTER PROCEDURE [etl].[etl_M_Update_Promo]
    @GenId bigint = 0,
    @Description NVARCHAR(50)
AS 

.... Rest of your code.

How to Apply global font to whole HTML document

Try this:

body
{
    font-family:your font;
    font-size:your value;
    font-weight:your value;
}

Add text at the end of each line

  1. You can also achieve this using the backreference technique

    sed -i.bak 's/\(.*\)/\1:80/' foo.txt
    
  2. You can also use with awk like this

    awk '{print $0":80"}' foo.txt > tmp && mv tmp foo.txt
    

jQuery equivalent of JavaScript's addEventListener method

One thing to note is that jQuery event methods do not fire/trap load on embed tags that contain SVG DOM which loads as a separate document in the embed tag. The only way I found to trap a load event on these were to use raw JavaScript.

This will not work (I've tried on/bind/load methods):

$img.on('load', function () {
    console.log('FOO!');
});

However, this works:

$img[0].addEventListener('load', function () {
    console.log('FOO!');
}, false);

Get current URL with jQuery?

Very Commonly Used top 3 ones are

1. window.location.hostname 
2. window.location.href
3. window.location.pathname

Replacing characters in Ant property

If ant-contrib isn't an option, here's a portable solution for Java 1.6 and later:

<property name="before" value="This is a value"/>
<script language="javascript">
    var before = project.getProperty("before");
    project.setProperty("after", before.replaceAll(" ", "_"));
</script>
<echo>after=${after}</echo>

How do I invoke a Java method when given the method name as a string?

//Step1 - Using string funClass to convert to class
String funClass = "package.myclass";
Class c = Class.forName(funClass);

//Step2 - instantiate an object of the class abov
Object o = c.newInstance();
//Prepare array of the arguments that your function accepts, lets say only one string here
Class[] paramTypes = new Class[1];
paramTypes[0]=String.class;
String methodName = "mymethod";
//Instantiate an object of type method that returns you method name
 Method m = c.getDeclaredMethod(methodName, paramTypes);
//invoke method with actual params
m.invoke(o, "testparam");

ValueError: cannot reshape array of size 30470400 into shape (50,1104,104)

In Matrix terms, the number of elements always has to equal the product of the number of rows and columns. In this particular case, the condition is not matching.

How can I post data as form data instead of a request payload?

You can try with below solution

$http({
        method: 'POST',
        url: url-post,
        data: data-post-object-json,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        transformRequest: function(obj) {
            var str = [];
            for (var key in obj) {
                if (obj[key] instanceof Array) {
                    for(var idx in obj[key]){
                        var subObj = obj[key][idx];
                        for(var subKey in subObj){
                            str.push(encodeURIComponent(key) + "[" + idx + "][" + encodeURIComponent(subKey) + "]=" + encodeURIComponent(subObj[subKey]));
                        }
                    }
                }
                else {
                    str.push(encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]));
                }
            }
            return str.join("&");
        }
    }).success(function(response) {
          /* Do something */
        });

How to use MySQL DECIMAL?

There are correct solutions in the comments, but to summarize them into a single answer:

You have to use DECIMAL(6,4).

Then you can have 6 total number of digits, 2 before and 4 after the decimal point (the scale). At least according to this.

Head and tail in one line

For O(1) complexity of head,tail operation you should use deque however.

Following way:

from collections import deque
l = deque([1,2,3,4,5,6,7,8,9])
head, tail = l.popleft(), l

It's useful when you must iterate through all elements of the list. For example in naive merging 2 partitions in merge sort.

Field 'id' doesn't have a default value?

As id is the primary key, you cannot have different rows with the same value. Try to change your table so that the id is auto incremented:

id int NOT NULL AUTO_INCREMENT

and then set the primary key as follows:

PRIMARY KEY (id)

All together:

CREATE TABLE card_games (
   id int(11) NOT NULL AUTO_INCREMENT,
   nafnleiks varchar(50),
   leiklysing varchar(3000), 
   prentadi varchar(1500), 
   notkunarheimildir varchar(1000),
   upplysingar varchar(1000),
   ymislegt varchar(500),
   PRIMARY KEY (id));

Otherwise, you can indicate the id in every insertion, taking care to set a different value every time:

insert into card_games (id, nafnleiks, leiklysing, prentadi, notkunarheimildir, upplysingar, ymislegt)

values(1, 'Svartipétur', 'Leiklýsingu vantar', 'Er prentað í: Þórarinn Guðmundsson (2010). Spilabókin - Allir helstu spilaleikir og spil.', 'Heimildir um notkun: Árni Sigurðsson (1951). Hátíðir og skemmtanir fyrir hundrað árum', 'Aðrar upplýsingar', 'ekkert hér sem stendur' );

How to compile the finished C# project and then run outside Visual Studio?

On your project folder, open up the bin\Debug subfolder and you'll see the compiled result.

Modulo operation with negative numbers

Can a modulus be negative?

% can be negative as it is the remainder operator, the remainder after division, not after Euclidean_division. Since C99 the result may be 0, negative or positive.

 // a % b
 7 %  3 -->  1  
 7 % -3 -->  1  
-7 %  3 --> -1  
-7 % -3 --> -1  

The modulo OP wanted is a classic Euclidean modulo, not %.

I was expecting a positive result every time.

To perform a Euclidean modulo that is well defined whenever a/b is defined, a,b are of any sign and the result is never negative:

int modulo_Euclidean(int a, int b) {
  int m = a % b;
  if (m < 0) {
    // m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
    m = (b < 0) ? m - b : m + b;
  }
  return m;
}

modulo_Euclidean( 7,  3) -->  1  
modulo_Euclidean( 7, -3) -->  1  
modulo_Euclidean(-7,  3) -->  2  
modulo_Euclidean(-7, -3) -->  2   

PHP: Split a string in to an array foreach char

You can access a string using [], as you do for arrays:

$stringLength = strlen($str);
for ($i = 0; $i < $stringLength; $i++)
    $char = $str[$i];

Command line: search and replace in all filenames matched by grep

Do you mean search and replace a string in all files matched by grep?

perl -p -i -e 's/oldstring/newstring/g' `grep -ril searchpattern *`

Edit

Since this seems to be a fairly popular question thought I'd update.

Nowadays I mostly use ack-grep as it's more user-friendly. So the above command would be:

perl -p -i -e 's/old/new/g' `ack -l searchpattern`

To handle whitespace in file names you can run:

ack --print0 -l searchpattern | xargs -0 perl -p -i -e 's/old/new/g'

you can do more with ack-grep. Say you want to restrict the search to HTML files only:

ack --print0 --html -l searchpattern | xargs -0 perl -p -i -e 's/old/new/g'

And if white space is not an issue it's even shorter:

perl -p -i -e 's/old/new/g' `ack -l --html searchpattern`
perl -p -i -e 's/old/new/g' `ack -f --html` # will match all html files

How to get the sizes of the tables of a MySQL database?

SELECT TABLE_NAME AS table_name, 
table_rows AS QuantofRows, 
ROUND((data_length + index_length) /1024, 2 ) AS total_size_kb 
FROM information_schema.TABLES
WHERE information_schema.TABLES.table_schema = 'db'
ORDER BY (data_length + index_length) DESC; 

all 2 above is tested on mysql

Multiple queries executed in java in single statement

Why dont you try and write a Stored Procedure for this?

You can get the Result Set out and in the same Stored Procedure you can Insert what you want.

The only thing is you might not get the newly inserted rows in the Result Set if you Insert after the Select.

How to add files/folders to .gitignore in IntelliJ IDEA?

You can create file .gitignore and then Idea will suggest you install plugin

Groovy method with optional parameters

You can use arguments with default values.

def someMethod(def mandatory,def optional=null){}

if argument "optional" not exist, it turns to "null".

INSERT with SELECT

We all know this works.

INSERT INTO `TableName`(`col-1`,`col-2`)
SELECT  `col-1`,`col-2` 

===========================
Below method can be used in case of multiple "select" statements. Just for information.

INSERT INTO `TableName`(`col-1`,`col-2`)
 select 1,2  union all
 select 1,2   union all
 select 1,2 ;

"TypeError: (Integer) is not JSON serializable" when serializing JSON in Python?

as @JAC pointed out in the comments of the highest rated answer, the generic solution (for all numpy types) can be found in the thread Converting numpy dtypes to native python types.

Nevertheless, I´ll add my version of the solution below, as my in my case I needed a generic solution that combines these answers and with the answers of the other thread. This should work with almost all numpy types.

def convert(o):
    if isinstance(o, np.generic): return o.item()  
    raise TypeError

json.dumps({'value': numpy.int64(42)}, default=convert)

Change Bootstrap tooltip color

In Bootstrap 3 (not tested in 4) you can override default colors with using a template when creating the tooltip. With this method you can specify tooltip colors runtime:

var bgColor = '#dd0000'; //red
var textColor = '#ffffff'; //white

$('#yourControlId').tooltip({
    placement: "top",
    template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow" style="border-top-color:' + bgColor + ';"></div><div class="tooltip-inner" style="background-color:' + bgColor + ';color:' + textColor + ';"></div></div>'
});

The template is based on original tooltip template. I only added the color styles. The placement must be top, because of arrow styling. (I haven't tried other placement types)

How to check that a JCheckBox is checked?

Use the isSelected method.

You can also use an ItemListener so you'll be notified when it's checked or unchecked.

Path.Combine absolute with relative path strings


Path.GetFullPath(@"c:\windows\temp\..\system32")?

How do you redirect HTTPS to HTTP?

this works for me.

<VirtualHost *:443>
    ServerName www.example.com
    # ... SSL configuration goes here
    Redirect "https://www.example.com/" "http://www.example.com/"
</VirtualHost>

<VirtualHost *:80>
    ServerName www.example.com
    # ... 
</VirtualHost>

be sure to listen to both ports 80 and 443.

Removing elements from an array in C

What solution you need depends on whether you want your array to retain its order, or not.

Generally, you never only have the array pointer, you also have a variable holding its current logical size, as well as a variable holding its allocated size. I'm also assuming that the removeIndex is within the bounds of the array. With that given, the removal is simple:

Order irrelevant

array[removeIndex] = array[--logicalSize];

That's it. You simply copy the last array element over the element that is to be removed, decrementing the logicalSize of the array in the process.

If removeIndex == logicalSize-1, i.e. the last element is to be removed, this degrades into a self-assignment of that last element, but that is not a problem.

Retaining order

memmove(array + removeIndex, array + removeIndex + 1, (--logicalSize - removeIndex)*sizeof(*array));

A bit more complex, because now we need to call memmove() to perform the shifting of elements, but still a one-liner. Again, this also updates the logicalSize of the array in the process.

Store a cmdlet's result value in a variable in Powershell

Use the -ExpandProperty flag of Select-Object

$var=Get-WSManInstance -enumerate wmicimv2/win32_process | select -expand Priority

Update to answer the other question:

Note that you can as well just access the property:

$var=(Get-WSManInstance -enumerate wmicimv2/win32_process).Priority

So to get multiple of these into variables:

$var=Get-WSManInstance -enumerate wmicimv2/win32_process
   $prio = $var.Priority
   $pid = $var.ProcessID

Ideal way to cancel an executing AsyncTask

Our global AsyncTask class variable

LongOperation LongOperationOdeme = new LongOperation();

And KEYCODE_BACK action which interrupt AsyncTask

   @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            LongOperationOdeme.cancel(true);
        }
        return super.onKeyDown(keyCode, event);
    }

It works for me.

How to programmatically tell if a Bluetooth device is connected?

This code is for the headset profiles, probably it will work for other profiles too. First you need to provide profile listener (Kotlin code):

private val mProfileListener = object : BluetoothProfile.ServiceListener {
    override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
        if (profile == BluetoothProfile.HEADSET) 
            mBluetoothHeadset = proxy as BluetoothHeadset            
    }

    override fun onServiceDisconnected(profile: Int) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = null
        }
    }
}

Then while checking bluetooth:

mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET)
if (!mBluetoothAdapter.isEnabled) {
    return Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
}

It takes a bit of time until onSeviceConnected is called. After that you may get the list of the connected headset devices from:

mBluetoothHeadset!!.connectedDevices

How to change line color in EditText

The best approach is to use an AppCompatEditText with backgroundTint attribute of app namespace. i.e.

    <android.support.v7.widget.AppCompatEditText
    android:layout_width="match_parent"      
    app:backgroundTint="YOUR COLOR"
    android:layout_height="wrap_content" />

when we use android:backgroundTint it will only work in API21 or more but app:backgroundTint works on all API levels your app does.

Get image dimensions

Using getimagesize function, we can also get these properties of that specific image-

<?php

list($width, $height, $type, $attr) = getimagesize("image_name.jpg");

echo "Width: " .$width. "<br />";
echo "Height: " .$height. "<br />";
echo "Type: " .$type. "<br />";
echo "Attribute: " .$attr. "<br />";

//Using array
$arr = array('h' => $height, 'w' => $width, 't' => $type, 'a' => $attr);
?>


Result like this -

Width: 200
Height: 100
Type: 2
Attribute: width='200' height='100'


Type of image consider like -

1 = GIF
2 = JPG
3 = PNG
4 = SWF
5 = PSD
6 = BMP
7 = TIFF(intel byte order)
8 = TIFF(motorola byte order)
9 = JPC
10 = JP2
11 = JPX
12 = JB2
13 = SWC
14 = IFF
15 = WBMP
16 = XBM

How to get the Enum Index value in C#

By default the underlying type of each element in the enum is integer.

enum Values
{
   A,
   B,
   C
}

You can also specify custom value for each item:

enum Values
{
   A = 10,
   B = 11,
   C = 12
}
int x = (int)Values.A; // x will be 10;

Note: By default, the first enumerator has the value 0.

extract date only from given timestamp in oracle sql

Convert Timestamp to Date as mentioned below, it will work for sure -

select TO_DATE(TO_CHAR(TO_TIMESTAMP ('2015-04-15 18:00:22.000', 'YYYY-MM-DD HH24:MI:SS.FF'),'MM/DD/YYYY HH24:MI:SS'),'MM/DD/YYYY HH24:MI:SS') dt from dual

Remove '\' char from string c#

You can use String.Replace which basically removes all occurrences

line.Replace(@"\", ""); 

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

I know that I have this problem over and over when I deploy my application on a new server because I'm using this driver to connect to a Excel file. So here it is what I'm doing lately.

There's a Windows Server 2008 R2, I install the Access drivers for a x64 bit machine and I get rid of this message, which makes me very happy just to bump into another.

This one here below works splendidly on my dev machine but on server gives me an error even after installing the latest ODBC drivers, which I think this is the problem, but this is how I solved it.

private const string OledbProviderString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\OlsonWindows.xls;Extended Properties=\"Excel 8.0;HDR=YES\"";

I replace with the new provider like this below:

private const string OledbProviderString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\OlsonWindows.xlsx;Extended Properties='Excel 12.0;HDR=YES;';";

But as I do this, there's one thing you should notice. Using the .xlsx file extension and Excel version is 12.0.

After I get into this error message Error: "Could Not Find Installable ISAM", I decide to change the things a little bit like below:

private const string OledbProviderString =      @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\OlsonWindows.xls;Extended Properties='Excel 8.0;HDR=YES;';"; 

and yes, I'm done with that nasty thing, but here I got another message The Microsoft Access database engine cannot open or write to the file 'time_zone'. It is already opened exclusively by another user, or you need permission to view and write its data. which tells me I'm not far away from solving it.

Maybe there's another process that opened the file meanwhile and all that I have to do is a restart and all will take start smoothly running as expected.

How to loop through all but the last item of a list?

if you meant comparing nth item with n+1 th item in the list you could also do with

>>> for i in range(len(list[:-1])):
...     print list[i]>list[i+1]

note there is no hard coding going on there. This should be ok unless you feel otherwise.

Can a WSDL indicate the SOAP version (1.1 or 1.2) of the web service?

In WSDL, if you look at the Binding section, you will clearly see that soap binding is explicitly mentioned if the service uses soap 1.2. refer the below sample.

<binding name="EmployeeServiceImplPortBinding" type="tns:EmployeeServiceImpl">
<soap12:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
<operation name="findEmployeeById">
    <soap12:operation soapAction=""/>
    <input><soap12:body use="literal"/></input>
    <output><soap12:body use="literal"/></output>
</operation><operation name="create">
    <soap12:operation soapAction=""/>
    <input><soap12:body use="literal"/></input>
    <output><soap12:body use="literal"/></output>
</operation>
</binding>

if the web service use soap 1.1, it will not explicitly define any soap version in the WSDL file under binding section. refer the below sample.

<binding name="EmployeeServiceImplPortBinding" type="tns:EmployeeServiceImpl">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/>
<operation name="findEmployeeById">
    <soap:operation soapAction=""/>
    <input><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></input>
    <output><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></output>
</operation><operation name="create">
    <soap:operation soapAction=""/>
    <input><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></input>
    <output><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></output>
</operation>
</binding>

How to determine the SOAP version of the SOAP message?

but remember that this is not much recommended way to determine the soap version that your web services uses. the version of the soap message can be determined using one of following ways.

1. checking the namespace of the soap message

SOAP 1.1  namespace : http://schemas.xmlsoap.org/soap/envelope

SOAP 1.2 namespace  : http://www.w3.org/2003/05/soap-envelope

2. checking the transport binding information (http header information) of the soap message

SOAP 1.1 : user text/xml for the Context-Type

   POST /MyService HTTP/1.1
   Content-Type: text/xml; charset="utf-8"
   Content-Length: xxx
   SOAPAction: "urn:uuid:myaction"

SOAP 1.2 : user application/soap+xml for the Context-Type

   POST /MyService HTTP/1.1
   Content-Type: application/soap+xml; charset="utf-8"
   Content-Length: xxx
   SOAPAction: "urn:uuid:myaction"

3. using SOAP fault information

The structure of a SOAP fault message between the two versions are different.

Angular: Cannot find a differ supporting object '[object Object]'

Missing square brackets around input property may cause this error. For example:

Component Foo {
    @Input()
    bars: BarType[];
}

Correct:

<app-foo [bars]="smth"></app-foo>

Incorrect (triggering error):

<app-foo bars="smth"></app-foo>

Why does the C++ STL not provide any "tree" containers?

There are two reasons you could want to use a tree:

You want to mirror the problem using a tree-like structure:
For this we have boost graph library

Or you want a container that has tree like access characteristics For this we have

Basically the characteristics of these two containers is such that they practically have to be implemented using trees (though this is not actually a requirement).

See also this question: C tree Implementation

The mysqli extension is missing. Please check your PHP configuration

I encountered this problem today and eventually I realize it was the comment on the line before the mysql dll's that was causing the problem.

This is what you should have in php.ini by default for PHP 5.5.16:

;extension=php_exif.dll       Must be after mbstring as it depends on it
;extension=php_mysql.dll
;extension=php_mysqli.dll

Besides removing the semi-colons, you also need to delete the line of comment that came after php_exif.dll. This leaves you with

extension=php_exif.dll      
extension=php_mysql.dll
extension=php_mysqli.dll

This solves the problem in my case.

Tools for making latex tables in R

... and Trick #3 Multiline entries in an Xtable

Generate some more data

moredata<-data.frame(Nominal=c(1:5), n=rep(5,5), 
        MeanLinBias=signif(rnorm(5, mean=0, sd=10), digits=4), 
        LinCI=paste("(",signif(rnorm(5,mean=-2, sd=5), digits=4),
                ", ", signif(rnorm(5, mean=2, sd=5), digits=4),")",sep=""),
        MeanQuadBias=signif(rnorm(5, mean=0, sd=10), digits=4), 
        QuadCI=paste("(",signif(rnorm(5,mean=-2, sd=5), digits=4),
                ", ", signif(rnorm(5, mean=2, sd=5), digits=4),")",sep=""))

names(moredata)<-c("Nominal", "n","Linear Model \nBias","Linear \nCI", "Quadratic Model \nBias", "Quadratic \nCI")

Now produce our xtable, using the sanitize function to replace column names with the correct Latex newline commands (including double backslashes so R is happy)

<<label=multilinetable, results=tex, echo=FALSE>>=
foo<-xtable(moredata)
align(foo) <- c( rep('c',3),'p{1.8in}','p{2in}','p{1.8in}','p{2in}' )
print(foo, 
            floating=FALSE, 
            include.rownames=FALSE,
            sanitize.text.function = function(str) {
                str<-gsub("\n","\\\\", str, fixed=TRUE)

                return(str)
            }, 
            sanitize.colnames.function = function(str) {
                str<-c("Nominal", "n","\\centering Linear Model\\\\ \\% Bias","\\centering Linear \\\\ 95\\%CI", "\\centering Quadratic Model\\\\ \\%Bias", "\\centering Quadratic \\\\ 95\\%CI \\tabularnewline")
                return(str)
            })
@  

(although this isn't perfect, as we need \tabularnewline so the table is formatted correctly, and Xtable still puts in a final \, so we end up with a blank line below the table header.)

Get the index of the object inside an array, matching a condition

var CarId = 23;

//x.VehicleId property to match in the object array
var carIndex = CarsList.map(function (x) { return x.VehicleId; }).indexOf(CarId);

And for basic array numbers you can also do this:

var numberList = [100,200,300,400,500];
var index = numberList.indexOf(200); // 1

You will get -1 if it cannot find a value in the array.

Eliminate extra separators below UITableView

You may find lots of answers to this question. Most of them around manipulation with UITableView's tableFooterView attribute and this is proper way to hide empty rows. For the conveniency I've created simple extension which allows to turn on/off empty rows from Interface Builder. You can check it out from this gist file. I hope it could save a little of your time.

extension UITableView {

  @IBInspectable
  var isEmptyRowsHidden: Bool {
        get {
          return tableFooterView != nil
        }
        set {
          if newValue {
              tableFooterView = UIView(frame: .zero)
          } else {
              tableFooterView = nil
          }
       }
    }
}

Usage:

tableView.isEmptyRowsHidden = true

enter image description here

How to make Git "forget" about a file that was tracked but is now in .gitignore?

Use this when:

1. You want to untrack a lot of files, or

2. You updated your gitignore file

Source link: http://www.codeblocq.com/2016/01/Untrack-files-already-added-to-git-repository-based-on-gitignore/

Let’s say you have already added/committed some files to your git repository and you then add them to your .gitignore; these files will still be present in your repository index. This article we will see how to get rid of them.

Step 1: Commit all your changes

Before proceeding, make sure all your changes are committed, including your .gitignore file.

Step 2: Remove everything from the repository

To clear your repo, use:

git rm -r --cached .
  • rm is the remove command
  • -r will allow recursive removal
  • –cached will only remove files from the index. Your files will still be there.

The rm command can be unforgiving. If you wish to try what it does beforehand, add the -n or --dry-run flag to test things out.

Step 3: Re add everything

git add .

Step 4: Commit

git commit -m ".gitignore fix"

Your repository is clean :)

Push the changes to your remote to see the changes effective there as well.

Github permission denied: ssh add agent has no identities

One additional element that I realized is that typically .ssh folder is created in your root folder in Mac OS X /Users/. If you try to use ssh -vT [email protected] from another folder it will give you an error even if you had added the correct key.

You need to add the key again (ssh-add 'correct path to id_rsa') from the current folder to authenticate successfully (assuming that you have already uploaded the key to your profile in Git)

How do I get the base URL with PHP?

The following code will reduce the problem to check the protocol. The $_SERVER['APP_URL'] will display the domain name with the protocol

$_SERVER['APP_URL'] will return protocol://domain ( eg:-http://localhost)

$_SERVER['REQUEST_URI'] for remaining parts of the url such as /directory/subdirectory/something/else

 $url = $_SERVER['APP_URL'].$_SERVER['REQUEST_URI'];

The output would be like this

http://localhost/directory/subdirectory/something/else

"Post Image data using POSTMAN"

Now you can hover the key input and select "file", which will give you a file selector in the value column:

enter image description here

Colorplot of 2D array matplotlib

I'm afraid your posted example is not working, since X and Y aren't defined. So instead of pcolormesh let's use imshow:

import numpy as np
import matplotlib.pyplot as plt

H = np.array([[1, 2, 3, 4],
              [5, 6, 7, 8],
              [9, 10, 11, 12],
              [13, 14, 15, 16]])  # added some commas and array creation code

fig = plt.figure(figsize=(6, 3.2))

ax = fig.add_subplot(111)
ax.set_title('colorMap')
plt.imshow(H)
ax.set_aspect('equal')

cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical')
plt.show()

Side-by-side list items as icons within a div (css)

I would recommend that you use display: inline;. float is screwed up in IE. Here is an example of how I would approach it:

<ul class="side-by-side">
  <li>item 1<li>
  <li>item 2<li>
  <li>item 3<li>
</ul>

and here's the css:

.side-by-side {
  width: 100%;
  border: 1px solid black;

}
.side-by-side li {
  display: inline;
}

Also, if you use floats the ul will not wrap around the li's and will instead have a hight of 0 in this example:

.side-by-side li {
  float: left;
}

Business logic in MVC

Q1:

Business logics can be considered in two categories:

  1. Domain logics like controls on an email address (uniqueness, constraints, etc.), obtaining the price of a product for invoice, or, calculating the shoppingCart's total price based of its product objects.

  2. More broad and complicated workflows which are called business processes, like controlling the registration process for the student (which usually includes several steps and needs different checks and has more complicated constraints).

The first category goes into model and the second one belongs to controller. This is because the cases in the second category are broad application logics and putting them in the model may mix the model's abstraction (for example, it is not clear if we need to put those decisions in one model class or another, since they are related to both!).

See this answer for a specific distinction between model and controller, this link for very exact definitions and also this link for a nice Android example.

The point is that the notes mentioned by "Mud" and "Frank" above both can be true as well as "Pete"'s (business logic can be put in model, or controller, according to the type of business logic).

Finally, note that MVC differs from context to context. For example, in Android applications, some alternative definitions are suggested that differs from web-based ones (see this post for example).


Q2:

Business logic is more general and (as "decyclone" mentioned above) we have the following relation between them:

business rules ? business logics

Disable submit button when form invalid with AngularJS

We can create a simple directive and disable the button until all the mandatory fields are filled.

angular.module('sampleapp').directive('disableBtn',
function() {
 return {
  restrict : 'A',
  link : function(scope, element, attrs) {
   var $el = $(element);
   var submitBtn = $el.find('button[type="submit"]');
   var _name = attrs.name;
   scope.$watch(_name + '.$valid', function(val) {
    if (val) {
     submitBtn.removeAttr('disabled');
    } else {
     submitBtn.attr('disabled', 'disabled');
    }
   });
  }
 };
}
);

For More Info click here

How can you run a Java program without main method?

Up until JDK6, you could use a static initializer block to print the message. This way, as soon as your class is loaded the message will be printed. The trick then becomes using another program to load your class.

public class Hello {
  static {
    System.out.println("Hello, World!");
  }
}

Of course, you can run the program as java Hello and you will see the message; however, the command will also fail with a message stating:

Exception in thread "main" java.lang.NoSuchMethodError: main

[Edit] as noted by others, you can avoid the NoSuchmethodError by simply calling System.exit(0) immediately after printing the message.

As of JDK6 onward, you no longer see the message from the static initializer block; details here.

How to select rows for a specific date, ignoring time in SQL Server

Try this:

true
select cast(salesDate as date) [date] from sales where salesDate = '2010/11/11'
false
select cast(salesDate as date) [date] from sales where salesDate = '11/11/2010'

How to increase the max upload file size in ASP.NET?

If you are using Framework 4.6

<httpRuntime targetFramework="4.6.1" requestValidationMode="2.0" maxRequestLength="10485760"  />

How to correctly catch change/focusOut event on text input in React.js?

You'd need to be careful as onBlur has some caveats in IE11 (How to use relatedTarget (or equivalent) in IE?, https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget).

There is, however, no way to use onFocusOut in React as far as I can tell. See the issue on their github https://github.com/facebook/react/issues/6410 if you need more information.

ReferenceError: Invalid left-hand side in assignment

Common reasons for the error:

  • use of assignment (=) instead of equality (==/===)
  • assigning to result of function foo() = 42 instead of passing arguments (foo(42))
  • simply missing member names (i.e. assuming some default selection) : getFoo() = 42 instead of getFoo().theAnswer = 42 or array indexing getArray() = 42 instead of getArray()[0]= 42

In this particular case you want to use == (or better === - What exactly is Type Coercion in Javascript?) to check for equality (like if(one === "rock" && two === "rock"), but it the actual reason you are getting the error is trickier.

The reason for the error is Operator precedence. In particular we are looking for && (precedence 6) and = (precedence 3).

Let's put braces in the expression according to priority - && is higher than = so it is executed first similar how one would do 3+4*5+6 as 3+(4*5)+6:

 if(one= ("rock" && two) = "rock"){...

Now we have expression similar to multiple assignments like a = b = 42 which due to right-to-left associativity executed as a = (b = 42). So adding more braces:

 if(one= (  ("rock" && two) = "rock" )  ){...

Finally we arrived to actual problem: ("rock" && two) can't be evaluated to l-value that can be assigned to (in this particular case it will be value of two as truthy).

Note that if you'd use braces to match perceived priority surrounding each "equality" with braces you get no errors. Obviously that also producing different result than you'd expect - changes value of both variables and than do && on two strings "rock" && "rock" resulting in "rock" (which in turn is truthy) all the time due to behavior of logial &&:

if((one = "rock") && (two = "rock"))
{
   // always executed, both one and two are set to "rock"
   ...
}

For even more details on the error and other cases when it can happen - see specification:

Assignment

LeftHandSideExpression = AssignmentExpression
...
Throw a SyntaxError exception if the following conditions are all true:
...
IsStrictReference(lref) is true

Left-Hand-Side Expressions

and The Reference Specification Type explaining IsStrictReference:

... function calls are permitted to return references. This possibility is admitted purely for the sake of host objects. No built-in ECMAScript function defined by this specification returns a reference and there is no provision for a user-defined function to return a reference...

Why are empty catch blocks a bad idea?

There are rare instances where it can be justified. In Python you often see this kind of construction:

try:
    result = foo()
except ValueError:
    result = None

So it might be OK (depending on your application) to do:

result = bar()
if result == None:
    try:
        result = foo()
    except ValueError:
        pass # Python pass is equivalent to { } in curly-brace languages
 # Now result == None if bar() returned None *and* foo() failed

In a recent .NET project, I had to write code to enumerate plugin DLLs to find classes that implement a certain interface. The relevant bit of code (in VB.NET, sorry) is:

    For Each dllFile As String In dllFiles
        Try
            ' Try to load the DLL as a .NET Assembly
            Dim dll As Assembly = Assembly.LoadFile(dllFile)
            ' Loop through the classes in the DLL
            For Each cls As Type In dll.GetExportedTypes()
                ' Does this class implement the interface?
                If interfaceType.IsAssignableFrom(cls) Then

                    ' ... more code here ...

                End If
            Next
        Catch ex As Exception
            ' Unable to load the Assembly or enumerate types -- just ignore
        End Try
    Next

Although even in this case, I'd admit that logging the failure somewhere would probably be an improvement.

How to bind inverse boolean properties in WPF?

Add one more property in your view model, which will return reverse value. And bind that to button. Like;

in view model:

public bool IsNotReadOnly{get{return !IsReadOnly;}}

in xaml:

IsEnabled="{Binding IsNotReadOnly"}

JavaScript file upload size validation

Even though the question is answered, I wanted to post my answer. Might come handy to future viewers.You can use it like in the following code.

<input type="file" id="fileinput" />
<script type="text/javascript">
  function readSingleFile(evt) {
    //Retrieve the first (and only!) File from the FileList object
    var f = evt.target.files[0]; 
    if (f) {
      var r = new FileReader();
      r.onload = function(e) { 
          var contents = e.target.result;
        alert( "Got the file.n" 
              +"name: " + f.name + "n"
              +"type: " + f.type + "n"
              +"size: " + f.size + " bytesn"
              + "starts with: " + contents.substr(1, contents.indexOf("n"))
        ); 
        if(f.size > 5242880) {
               alert('File size Greater then 5MiB!');
                }

         
      }
      r.readAsText(f);
    } else { 
      alert("Failed to load file");
    }
  }

How to remove new line characters from data rows in mysql?

UPDATE mytable SET title=TRIM(REPLACE(REPLACE(title, "\n", ""), "\t", ""));

Twitter Bootstrap hide css class and jQuery

If an element has bootstrap's "hide" class and you want to display it with some sliding effect such as .slideDown(), you can cheat bootstrap like:

$('#hiddenElement').hide().removeClass('hide').slideDown('fast')

Java Spring Boot: How to map my app root (“/”) to index.html?

I had the same problem. Spring boot knows where static html files are located.

  1. Add index.html into resources/static folder
  2. Then delete full controller method for root path like @RequestMapping("/") etc
  3. Run app and check http://localhost:8080 (Should work)

window.onload vs $(document).ready()

The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.

The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.

Embedding DLLs in a compiled executable

Another product that can handle this elegantly is SmartAssembly, at SmartAssembly.com. This product will, in addition to merging all dependencies into a single DLL, (optionally) obfuscate your code, remove extra meta-data to reduce the resulting file size, and can also actually optimize the IL to increase runtime performance.

There is also some kind of global exception handling/reporting feature it adds to your software (if desired) that could be useful. I believe it also has a command-line API so you can make it part of your build process.

jquery: animate scrollLeft

First off I should point out that css animations would probably work best if you are doing this a lot but I ended getting the desired effect by wrapping .scrollLeft inside .animate

$('.swipeRight').click(function()
{

    $('.swipeBox').animate( { scrollLeft: '+=460' }, 1000);
});

$('.swipeLeft').click(function()
{
    $('.swipeBox').animate( { scrollLeft: '-=460' }, 1000);
});

The second parameter is speed, and you can also add a third parameter if you are using smooth scrolling of some sort.

Google Maps API warning: NoApiKeys

Creating and using the key is the way to go. The usage is free until your application reaches 25.000 calls per day on 90 consecutive days.

BTW.: In the google Developer documentation it says you shall add the api key as option {key:yourKey} when calling the API to create new instances. This however doesn't shush the console warning. You have to add the key as a parameter when including the api.

<script src="https://maps.googleapis.com/maps/api/js?key=yourKEYhere"></script>

Get the key here: GoogleApiKey Generation site

What is JavaScript garbage collection?

Good quote taken from a blog

The DOM component is "garbage collected", as is the JScript component, which means that if you create an object within either component, and then lose track of that object, it will eventually be cleaned up.

For example:

function makeABigObject() {
var bigArray = new Array(20000);
}

When you call that function, the JScript component creates an object (named bigArray) that is accessible within the function. As soon as the function returns, though, you "lose track" of bigArray because there's no way to refer to it anymore. Well, the JScript component realizes that you've lost track of it, and so bigArray is cleaned up--its memory is reclaimed. The same sort of thing works in the DOM component. If you say document.createElement('div'), or something similar, then the DOM component creates an object for you. Once you lose track of that object somehow, the DOM component will clean up the related.

Xcode iOS 8 Keyboard types not supported

I too had this problem after updating to the latest Xcode Beta. The settings on the simulator are refreshed, so the laptop (external) keyboard was being detected. If you simply press:

 iOS Simulator -> Hardware -> Keyboard -> Connect Hardware Keyboard

then the software keyboard will be displayed once again.

JQuery Event for user pressing enter in a textbox?

If your input is search, you also can use on 'search' event. Example

<input type="search" placeholder="Search" id="searchTextBox">

.

$("#searchPostTextBox").on('search', function () {
    alert("search value: "+$(this).val());
});

Create aar file in Android Studio

Retrieve exported .aar file from local builds

If you have a module defined as an android library project you'll get .aar files for all build flavors (debug and release by default) in the build/outputs/aar/ directory of that project.

your-library-project
    |- build
        |- outputs
            |- aar
                |- appframework-debug.aar
                 - appframework-release.aar

If these files don't exist start a build with

gradlew assemble

for macOS users

./gradlew assemble

Library project details

A library project has a build.gradle file containing apply plugin: com.android.library. For reference of this library packaged as an .aar file you'll have to define some properties like package and version.

Example build.gradle file for library (this example includes obfuscation in release):

apply plugin: 'com.android.library'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.0"

    defaultConfig {
        minSdkVersion 9
        targetSdkVersion 21
        versionCode 1
        versionName "0.1.0"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

Reference .aar file in your project

In your app project you can drop this .aar file in the libs folder and update the build.gradle file to reference this library using the below example:

apply plugin: 'com.android.application'

repositories {
    mavenCentral()
    flatDir {
        dirs 'libs' //this way we can find the .aar file in libs folder
    }
}

android {
    compileSdkVersion 21
    buildToolsVersion "21.0.0"

    defaultConfig {

        minSdkVersion 14
        targetSdkVersion 20
        versionCode 4
        versionName "0.4.0"

        applicationId "yourdomain.yourpackage"
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            minifyEnabled false
        }
    }
}

dependencies {
    compile 'be.hcpl.android.appframework:appframework:0.1.0@aar'
}

Alternative options for referencing local dependency files in gradle can be found at: http://kevinpelgrims.com/blog/2014/05/18/reference-a-local-aar-in-your-android-project

Sharing dependencies using maven

If you need to share these .aar files within your organization check out maven. A nice write up on this topic can be found at: https://web.archive.org/web/20141002122437/http://blog.glassdiary.com/post/67134169807/how-to-share-android-archive-library-aar-across

About the .aar file format

An aar file is just a .zip with an alternative extension and specific content. For details check this link about the aar format.

How to subtract a day from a date?

You can use a timedelta object:

from datetime import datetime, timedelta
    
d = datetime.today() - timedelta(days=days_to_subtract)

How do I resolve a path relative to an ASP.NET MVC 4 application root?

In your controller use:

var path = HttpContext.Server.MapPath("~/Data/data.html");

This allows you to test the controller with Moq like so:

var queryString = new NameValueCollection();
var mockRequest = new Mock<HttpRequestBase>();
mockRequest.Setup(r => r.QueryString).Returns(queryString);
var mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Setup(c => c.Request).Returns(mockRequest.Object);
var server = new Mock<HttpServerUtilityBase>();
server.Setup(m => m.MapPath("~/Data/data.html")).Returns("path/to/test/data");
mockHttpContext.Setup(m => m.Server).Returns(server.Object);
var mockControllerContext = new Mock<ControllerContext>();
mockControllerContext.Setup(c => c.HttpContext).Returns(mockHttpContext.Object);
var controller = new MyTestController();
controller.ControllerContext = mockControllerContext.Object;

What are the differences between B trees and B+ trees?

  1. In a B tree search keys and data are stored in internal or leaf nodes. But in a B+-tree data is stored only in leaf nodes.
  2. Full scan of a B+ tree is very easy because all data are found in leaf nodes. Full scan of a B tree requires a full traversal.
  3. In a B tree, data may be found in leaf nodes or internal nodes. Deletion of internal nodes is very complicated. In a B+ tree, data is only found in leaf nodes. Deletion of leaf nodes is easy.
  4. Insertion in B tree is more complicated than B+ tree.
  5. B+ trees store redundant search keys but B tree has no redundant value.
  6. In a B+ tree, leaf node data is ordered as a sequential linked list but in a B tree the leaf node cannot be stored using a linked list. Many database systems' implementations prefer the structural simplicity of a B+ tree.

mailto link multiple body lines

This is what I do, just add \n and use encodeURIComponent

Example

var emailBody = "1st line.\n 2nd line \n 3rd line";

emailBody = encodeURIComponent(emailBody);

href = "mailto:[email protected]?body=" + emailBody;

Check encodeURIComponent docs

How can I scroll up more (increase the scroll buffer) in iTerm2?

Solution: In order to increase your buffer history on iterm bash terminal you've got two options:

Go to iterm -> Preferences -> Profiles -> Terminal Tab -> Scrollback Buffer (section)

Option 1. select the checkbox Unlimited scrollback

Option 2. type the selected Scrollback lines numbers you'd like your terminal buffer to cache (See image below)

enter image description here

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

Your question almost spells the SQL for this:

DELETE FROM table WHERE id IN (1, 4, 6, 7)

Different color for each bar in a bar chart; ChartJS

This works for me in the current version 2.7.1:

function colorizePercentageChart(myObjBar) {

var bars = myObjBar.data.datasets[0].data;
console.log(myObjBar.data.datasets[0]);
for (i = 0; i < bars.length; i++) {

    var color = "green";

    if(parseFloat(bars[i])  < 95){
        color = "yellow";
    }
    if(parseFloat(bars[i])  < 50){
         color = "red";
    }

    console.log(color);
    myObjBar.data.datasets[0].backgroundColor[i] = color;

}
myObjBar.update(); 

}

How to style components using makeStyles and still have lifecycle methods in Material UI?

Another one solution can be used for class components - just override default MUI Theme properties with MuiThemeProvider. This will give more flexibility in comparison with other methods - you can use more than one MuiThemeProvider inside your parent component.

simple steps:

  1. import MuiThemeProvider to your class component
  2. import createMuiTheme to your class component
  3. create new theme
  4. wrap target MUI component you want to style with MuiThemeProvider and your custom theme

please, check this doc for more details: https://material-ui.com/customization/theming/

_x000D_
_x000D_
import React from 'react';
import PropTypes from 'prop-types';
import Button from '@material-ui/core/Button';

import { MuiThemeProvider } from '@material-ui/core/styles';
import { createMuiTheme } from '@material-ui/core/styles';

const InputTheme = createMuiTheme({
    overrides: {
        root: {
            background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
            border: 0,
            borderRadius: 3,
            boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
            color: 'white',
            height: 48,
            padding: '0 30px',
        },
    }
});

class HigherOrderComponent extends React.Component {

    render(){
        const { classes } = this.props;
        return (
            <MuiThemeProvider theme={InputTheme}>
                <Button className={classes.root}>Higher-order component</Button>
            </MuiThemeProvider>
        );
    }
}

HigherOrderComponent.propTypes = {
    classes: PropTypes.object.isRequired,
};

export default HigherOrderComponent;
_x000D_
_x000D_
_x000D_

How to create border in UIButton?

To change button Radius, Color and Width I set like this:

self.myBtn.layer.cornerRadius = 10;
self.myBtn.layer.borderWidth = 1;
self.myBtn.layer.borderColor =[UIColor colorWithRed:189.0/255.0f green:189.0/255.0f blue:189.0/255.0f alpha:1.0].CGColor;

onKeyPress Vs. onKeyUp and onKeyDown

A few practical facts that might be useful to decide which event to handle (run the script below and focus on the input box):

_x000D_
_x000D_
$('input').on('keyup keydown keypress',e=>console.log(e.type, e.keyCode, e.which, e.key))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input/>
_x000D_
_x000D_
_x000D_

Pressing:

  • non inserting/typing keys (e.g. Shift, Ctrl) will not trigger a keypress. Press Ctrl and release it:

    keydown 17 17 Control

    keyup 17 17 Control

  • keys from keyboards that apply characters transformations to other characters may lead to Dead and duplicate "keys" (e.g. ~, ´) on keydown. Press ´ and release it in order to display a double ´´:

    keydown 192 192 Dead

    keydown 192 192 ´´

    keypress 180 180 ´

    keypress 180 180 ´

    keyup 192 192 Dead

Additionally, non typing inputs (e.g. ranged <input type="range">) will still trigger all keyup, keydown and keypress events according to the pressed keys.

How to check if a symlink exists

How about using readlink?

# if symlink, readlink returns not empty string (the symlink target)
# if string is not empty, test exits w/ 0 (normal)
#
# if non symlink, readlink returns empty string
# if string is empty, test exits w/ 1 (error)
simlink? () {
  test "$(readlink "${1}")";
}

FILE=/usr/mda

if simlink? "${FILE}"; then
  echo $FILE is a symlink
else
  echo $FILE is not a symlink
fi

Excel Looping through rows and copy cell values to another worksheet

Private Sub CommandButton1_Click() 

Dim Z As Long 
Dim Cellidx As Range 
Dim NextRow As Long 
Dim Rng As Range 
Dim SrcWks As Worksheet 
Dim DataWks As Worksheet 
Z = 1 
Set SrcWks = Worksheets("Sheet1") 
Set DataWks = Worksheets("Sheet2") 
Set Rng = EntryWks.Range("B6:ad6") 

NextRow = DataWks.UsedRange.Rows.Count 
NextRow = IIf(NextRow = 1, 1, NextRow + 1) 

For Each RA In Rng.Areas 
    For Each Cellidx In RA 
        Z = Z + 1 
        DataWks.Cells(NextRow, Z) = Cellidx 
    Next Cellidx 
Next RA 
End Sub

Alternatively

Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10") 

This is a CopynPaste - Method

Sub CopyDataToPlan()

Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean

On Error GoTo Err_Execute

'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value

Sheets("Plan").Select

'Start at column B
LColumn = 2
LFound = False

While LFound = False

  'Encountered blank cell in row 2, terminate search
  If Len(Cells(2, LColumn)) = 0 Then
     MsgBox "No matching date was found."
     Exit Sub

  'Found match in row 2
  ElseIf Cells(2, LColumn) = LDate Then

     'Select values to copy from "Rolling Plan" sheet
     Sheets("Rolling Plan").Select
     Range("B5:H6").Select
     Selection.Copy

     'Paste onto "Plan" sheet
     Sheets("Plan").Select
     Cells(3, LColumn).Select
     Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
     False, Transpose:=False

     LFound = True
     MsgBox "The data has been successfully copied."

     'Continue searching
      Else
         LColumn = LColumn + 1
      End If

   Wend

   Exit Sub

Err_Execute:
  MsgBox "An error occurred."

End Sub

And there might be some methods doing that in Excel.