Programs & Examples On #Postbackurl

return string with first match Regex

You shouldn't be using .findall() at all - .search() is what you want. It finds the leftmost match, which is what you want (or returns None if no match exists).

m = re.search(pattern, text)
result = m.group(0) if m else ""

Whether you want to put that in a function is up to you. It's unusual to want to return an empty string if no match is found, which is why nothing like that is built in. It's impossible to get confused about whether .search() on its own finds a match (it returns None if it didn't, or an SRE_Match object if it did).

How to resolve conflicts in EGit

I know this is an older post, but I just got hit with a similar issue and was able to resolve it, so I thought I'd share.

(Update: As noted in the comments below, this answer was before the inclusion of the "git stash" feature to eGit.)

What I did was:

  1. Copy out the local copy of the conflicting file that may or may not have any changes from the version on the upstream.
  2. Within Eclipse, "Revert" the file to the version right before the conflict.
  3. Run a "Pull" from the remote repository, allowing all changes to be synced to the local work directory. This should clear the updates coming down to your filesystem, leaving only what you have left to push.
  4. Check the current version of the conflicting file in your work directory with the copy you copied out. If there are any differences, do a proper merge of the files and commit that version of the file in the work directory.
  5. Now "Push" your changes up.

Hope that helps.

How to use delimiter for csv in python

CSV Files with Custom Delimiters

By default, a comma is used as a delimiter in a CSV file. However, some CSV files can use delimiters other than a comma. Few popular ones are | and \t.

import csv
data_list = [["SN", "Name", "Contribution"],
             [1, "Linus Torvalds", "Linux Kernel"],
             [2, "Tim Berners-Lee", "World Wide Web"],
             [3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file, delimiter='|')
    writer.writerows(data_list)

output:

SN|Name|Contribution
1|Linus Torvalds|Linux Kernel
2|Tim Berners-Lee|World Wide Web
3|Guido van Rossum|Python Programming

Write CSV files with quotes

import csv

row_list = [["SN", "Name", "Contribution"],
             [1, "Linus Torvalds", "Linux Kernel"],
             [2, "Tim Berners-Lee", "World Wide Web"],
             [3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=';')
    writer.writerows(row_list) 

output:

"SN";"Name";"Contribution"
1;"Linus Torvalds";"Linux Kernel"
2;"Tim Berners-Lee";"World Wide Web"
3;"Guido van Rossum";"Python Programming"

As you can see, we have passed csv.QUOTE_NONNUMERIC to the quoting parameter. It is a constant defined by the csv module.

csv.QUOTE_NONNUMERIC specifies the writer object that quotes should be added around the non-numeric entries.

There are 3 other predefined constants you can pass to the quoting parameter:

  • csv.QUOTE_ALL - Specifies the writer object to write CSV file with quotes around all the entries.
  • csv.QUOTE_MINIMAL - Specifies the writer object to only quote those fields which contain special characters (delimiter, quotechar or any characters in lineterminator)
  • csv.QUOTE_NONE - Specifies the writer object that none of the entries should be quoted. It is the default value.
import csv

row_list = [["SN", "Name", "Contribution"],
             [1, "Linus Torvalds", "Linux Kernel"],
             [2, "Tim Berners-Lee", "World Wide Web"],
             [3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC,
                        delimiter=';', quotechar='*')
    writer.writerows(row_list)

output:

*SN*;*Name*;*Contribution*
1;*Linus Torvalds*;*Linux Kernel*
2;*Tim Berners-Lee*;*World Wide Web*
3;*Guido van Rossum*;*Python Programming*

Here, we can see that quotechar='*' parameter instructs the writer object to use * as quote for all non-numeric values.

Removing duplicate rows from table in Oracle

Check below scripts -

1.

Create table test(id int,sal int); 

2.

    insert into test values(1,100);    
    insert into test values(1,100);    
    insert into test values(2,200);    
    insert into test values(2,200);    
    insert into test values(3,300);    
    insert into test values(3,300);    
    commit;

3.

 select * from test;    

You will see here 6-records.
4.run below query -

delete from 
   test
where rowid in
 (select rowid from 
   (select 
     rowid,
     row_number()
    over 
     (partition by id order by sal) dup
    from test)
  where dup > 1)
  1. select * from test;

You will see that duplicate records have been deleted.
Hope this solves your query. Thanks :)

Build .NET Core console application to output an EXE

UPDATE for .NET 5!

The below applies on/after NOV2020 when .NET 5 is officially out.

(see quick terminology section below, not just the How-to's)

How-To (CLI)

Pre-requisites

  • Download latest version of the .net 5 SDK. Link

Steps

  1. Open a terminal (e.g: bash, command prompt, powershell) and in the same directory as your .csproj file enter the below command:
dotnet publish --output "{any directory}" --runtime {runtime} --configuration {Debug|Release} -p:PublishSingleFile={true|false} -p:PublishTrimmed={true|false} --self-contained {true|false}

example:

dotnet publish --output "c:/temp/myapp" --runtime win-x64 --configuration Release -p:PublishSingleFile=true -p:PublishTrimmed=true --self-contained true

How-To (GUI)

Pre-requisites

  • If reading pre NOV2020: Latest version of Visual Studio Preview*
  • If reading NOV2020+: Latest version of Visual Studio*

*In above 2 cases, the latest .net5 SDK will be automatically installed on your PC.

Steps

  1. Right-Click on Project, and click Publish
    enter image description here

  2. Click Start and choose Folder target, click next and choose Folder Choose Folder Target

  3. Enter any folder location, and click Finish

  4. Click on Edit
    enter image description here

  5. Choose a Target Runtime and tick on Produce Single File and save.* enter image description here

  6. Click Publish

  7. Open a terminal in the location you published your app, and run the .exe. Example: enter image description here

A little bit of terminology

Target Runtime
See the list of RID's

Deployment Mode

  • Framework Dependent means a small .exe file produced but app assumed .Net 5 is installed on the host machine
  • Self contained means a bigger .exe file because the .exe includes the framework but then you can run .exe on any machine, no need for .Net 5 to be pre-installed. NOTE: WHEN USING SELF CONTAINED, ADDITIONAL DEPENDENCIES (.dll's) WILL BE PRODUCED, NOT JUST THE .EXE

Enable ReadyToRun compilation
TLDR: it's .Net5's equivalent of Ahead of Time Compilation (AOT). Pre-compiled to native code, app would usually boot up faster. App more performant (or not!), depending on many factors. More info here

Trim unused assemblies
When set to true, dotnet will generate a very lean and small .exe and only include what it needs. Be careful here. Example: when using reflection in your app you probably don't want to set this flag to true.

Microsoft Doc


Previous Post

UPDATE (31-OCT-2019)

For anyone that wants to do this via a GUI and:

  • Is using Visual Studio 2019
  • Has .NET Core 3.0 installed (included in latest version of Visual Studio 2019)
  • Wants to generate a single file

Enter image description here

Enter image description here

Enter image description here

Enter image description here

Enter image description here

Enter image description here

Enter image description here

enter image description here

Enter image description here

Note

Notice the large file size for such a small application

Enter image description here

You can add the "PublishTrimmed" property. The application will only include components that are used by the application. Caution: don't do this if you are using reflection

Enter image description here

Publish again

Enter image description here

How to declare a global variable in php?

What if you make use of procedural function instead of variable and call them any where as you.

I usually make a collection of configuration values and put them inside a function with return statement. I just include that where I need to make use of global value and call particular function.

function host()
{
   return "localhost";
}

How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session

A common practice is to put a @Transactional above your service class.

@Service
@Transactional
public class MyServiceImpl implements MyService{
...
}

How do I store data in local storage using Angularjs?

If you use $window.localStorage.setItem(key,value) to store,$window.localStorage.getItem(key) to retrieve and $window.localStorage.removeItem(key) to remove, then you can access the values in any page.

You have to pass the $window service to the controller. Though in JavaScript, window object is available globally.

By using $window.localStorage.xxXX() the user has control over the localStorage value. The size of the data depends upon the browser. If you only use $localStorage then value remains as long as you use window.location.href to navigate to other page and if you use <a href="location"></a> to navigate to other page then your $localStorage value is lost in the next page.

Strip out HTML and Special Characters

to allow periods and any other character just add them like so:

change: '#[^a-zA-Z ]#' to:'#[^a-zA-Z .()!]#'

Is Laravel really this slow?

I faced 1.40s while working with a pure laravel in development area!

the problem was using: php artisan serve to run the webserver

when I used apache webserver (or NGINX) instead for the same code I got it down to 153ms

Immediate exit of 'while' loop in C++

Yah Im pretty sure you just put

    break;

right where you want it to exit

like

    if (variable == 1)
    {
    //do something
    }
    else
    {
    //exit
    break;
    }

How to override application.properties during production in Spring-Boot?

I know you asked how to do this, but the answer is you should not do this.

Instead, have a application.properties, application-default.properties application-dev.properties etc., and switch profiles via args to the JVM: e.g. -Dspring.profiles.active=dev

You can also override some things at test time using @TestPropertySource

Ideally everything should be in source control so that there are no surprises e.g. How do you know what properties are sitting there in your server location, and which ones are missing? What happens if developers introduce new things?

Spring Boot is already giving you enough ways to do this right.

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

How to restore SQL Server 2014 backup in SQL Server 2008

No, it is not possible. Stack Overflow wants me to answer with a longer answer, so I will say no again.

Documentation: https://docs.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql#compatibility

Backups that are created by more recent version of SQL Server cannot be restored in earlier versions of SQL Server.

Oracle: How to find out if there is a transaction pending?

Use the query below to find out pending transaction.

If it returns a value, it means there is a pending transaction.

Here is the query:

select dbms_transaction.step_id from dual;

References:
http://www.acehints.com/2011/07/how-to-check-pending-transaction-in.html http://www.acehints.com/p/site-map.html

TypeScript and React - children type?

This is what worked for me:

interface Props {
  children: JSX.Element[] | JSX.Element
}

Edit I would recommend using children: React.ReactNode instead now.

MySQL: @variable vs. variable. What's the difference?

In principle, I use UserDefinedVariables (prepended with @) within Stored Procedures. This makes life easier, especially when I need these variables in two or more Stored Procedures. Just when I need a variable only within ONE Stored Procedure, than I use a System Variable (without prepended @).

@Xybo: I don't understand why using @variables in StoredProcedures should be risky. Could you please explain "scope" and "boundaries" a little bit easier (for me as a newbe)?

Scikit-learn train_test_split with indices

Here's the simplest solution (Jibwa made it seem complicated in another answer), without having to generate indices yourself - just using the ShuffleSplit object to generate 1 split.

import numpy as np 
from sklearn.model_selection import ShuffleSplit # or StratifiedShuffleSplit
sss = ShuffleSplit(n_splits=1, test_size=0.1)

data_size = 100
X = np.reshape(np.random.rand(data_size*2),(data_size,2))
y = np.random.randint(2, size=data_size)

sss.get_n_splits(X, y)
train_index, test_index = next(sss.split(X, y)) 

X_train, X_test = X[train_index], X[test_index] 
y_train, y_test = y[train_index], y[test_index]

Auto-expanding layout with Qt-Designer

Set the horizontalPolicy & VerticalPolicy for the controls/widgets to "Preferred".

Python: Converting from ISO-8859-1/latin1 to UTF-8

concept = concept.encode('ascii', 'ignore') 
concept = MySQLdb.escape_string(concept.decode('latin1').encode('utf8').rstrip())

I do this, I am not sure if that is a good approach but it works everytime !!

What is the equivalent of ngShow and ngHide in Angular 2+?

My issue was displaying/hiding a mat-table on a button click using <ng-container *ngIf="myVar">. The 'loading' of the table was very slow with 300 records at 2-3 seconds.

The data is loaded using a subscribe in ngOnInit(), and is available and ready to be used in the template, however the 'loading' of the table in the template became increasingly slower with the increase in number of rows.

My solution was to replace the *ngIf with:

_x000D_
_x000D_
<div [style.display]="activeSelected ? 'block' : 'none'">
_x000D_
_x000D_
_x000D_

. Now the table loads instantly when the button is clicked.

Maximum length for MD5 input/output

There is no limit to the input of md5 that I know of. Some implementations require the entire input to be loaded into memory before passing it into the md5 function (i.e., the implementation acts on a block of memory, not on a stream), but this is not a limitation of the algorithm itself. The output is always 128 bits. Note that md5 is not an encryption algorithm, but a cryptographic hash. This means that you can use it to verify the integrity of a chunk of data, but you cannot reverse the hashing. Also note that md5 is considered broken, so you shouldn't use it for anything security-related (it's still fine to verify the integrity of downloaded files and such).

How Can I Override Style Info from a CSS Class in the Body of a Page?

Eli, it is important to remember that in css specificity goes a long way. If your inline css is using the !important and isn't overriding the imported stylesheet rules then closely observe the code using a tool such as 'firebug' for firefox. It will show you the css being applied to your element. If there is a syntax error firebug will show you in the warning panel that it has thrown out the declaration.

Also remember that in general an id is more specific than a class is more specific than an element.

Hope that helps.

-Rick

Checking for a null int value from a Java ResultSet

You can call this method using the resultSet and the column name having Number type. It will either return the Integer value, or null. There will be no zeros returned for empty value in the database

private Integer getIntWithNullCheck(ResultSet rset, String columnName) {
    try {
        Integer value = rset.getInt(columnName);
        return rset.wasNull() ? null : value;
    } catch (Exception e) {
        return null;
    }
}

Disable Scrolling on Body

Set height and overflow:

html, body {margin: 0; height: 100%; overflow: hidden}

http://jsfiddle.net/q99hvawt/

Change default timeout for mocha

By default Mocha will read a file named test/mocha.opts that can contain command line arguments. So you could create such a file that contains:

--timeout 5000

Whenever you run Mocha at the command line, it will read this file and set a timeout of 5 seconds by default.

Another way which may be better depending on your situation is to set it like this in a top level describe call in your test file:

describe("something", function () {
    this.timeout(5000); 

    // tests...
});

This would allow you to set a timeout only on a per-file basis.

You could use both methods if you want a global default of 5000 but set something different for some files.


Note that you cannot generally use an arrow function if you are going to call this.timeout (or access any other member of this that Mocha sets for you). For instance, this will usually not work:

describe("something", () => {
    this.timeout(5000); //will not work

    // tests...
});

This is because an arrow function takes this from the scope the function appears in. Mocha will call the function with a good value for this but that value is not passed inside the arrow function. The documentation for Mocha says on this topic:

Passing arrow functions (“lambdas”) to Mocha is discouraged. Due to the lexical binding of this, such functions are unable to access the Mocha context.

Min/Max-value validators in asp.net mvc

jQuery Validation Plugin already implements min and max rules, we just need to create an adapter for our custom attribute:

public class MaxAttribute : ValidationAttribute, IClientValidatable
{
    private readonly int maxValue;

    public MaxAttribute(int maxValue)
    {
        this.maxValue = maxValue;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule();

        rule.ErrorMessage = ErrorMessageString, maxValue;

        rule.ValidationType = "max";
        rule.ValidationParameters.Add("max", maxValue);
        yield return rule;
    }

    public override bool IsValid(object value)
    {
        return (int)value <= maxValue;
    }
}

Adapter:

$.validator.unobtrusive.adapters.add(
   'max',
   ['max'],
   function (options) {
       options.rules['max'] = parseInt(options.params['max'], 10);
       options.messages['max'] = options.message;
   });

Min attribute would be very similar.

Can I get the name of the currently running function in JavaScript?

Information is actual on 2016 year.


Results for function declaration

Result in the Opera

>>> (function func11 (){
...     console.log(
...         'Function name:',
...         arguments.callee.toString().match(/function\s+([_\w]+)/)[1])
... })();
... 
... (function func12 (){
...     console.log('Function name:', arguments.callee.name)
... })();
Function name:, func11
Function name:, func12

Result in the Chrome

(function func11 (){
    console.log(
        'Function name:',
        arguments.callee.toString().match(/function\s+([_\w]+)/)[1])
})();

(function func12 (){
    console.log('Function name:', arguments.callee.name)
})();
Function name: func11
Function name: func12

Result in the NodeJS

> (function func11 (){
...     console.log(
.....         'Function name:',
.....         arguments.callee.toString().match(/function\s+([_\w]+)/)[1])
... })();
Function name: func11
undefined
> (function func12 (){
...     console.log('Function name:', arguments.callee.name)
... })();
Function name: func12

Does not work in the Firefox. Untested on the IE and the Edge.


Results for function expressions

Result in the NodeJS

> var func11 = function(){
...     console.log('Function name:', arguments.callee.name)
... }; func11();
Function name: func11

Result in the Chrome

var func11 = function(){
    console.log('Function name:', arguments.callee.name)
}; func11();
Function name: func11

Does not work in the Firefox, Opera. Untested on the IE and the Edge.

Notes:

  1. Anonymous function does not to make sense to check.
  2. Testing environment

~ $ google-chrome --version
Google Chrome 53.0.2785.116           
~ $ opera --version
Opera 12.16 Build 1860 for Linux x86_64.
~ $ firefox --version
Mozilla Firefox 49.0
~ $ node
node    nodejs  
~ $ nodejs --version
v6.8.1
~ $ uname -a
Linux wlysenko-Aspire 3.13.0-37-generic #64-Ubuntu SMP Mon Sep 22 21:28:38 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

How to Display blob (.pdf) in an AngularJS app

Adding responseType to the request that is made from angular is indeed the solution, but for me it didn't work until I've set responseType to blob, not to arrayBuffer. The code is self explanatory:

    $http({
            method : 'GET',
            url : 'api/paperAttachments/download/' + id,
            responseType: "blob"
        }).then(function successCallback(response) {
            console.log(response);
             var blob = new Blob([response.data]);
             FileSaver.saveAs(blob, getFileNameFromHttpResponse(response));
        }, function errorCallback(response) {   
        });

Convert string to hex-string in C#

few Unicode alternatives

var s = "0";

var s1 = string.Concat(s.Select(c => $"{(int)c:x4}"));  // left padded with 0 - "0030d835dfcfd835dfdad835dfe5d835dff0d835dffb"

var sL = BitConverter.ToString(Encoding.Unicode.GetBytes(s)).Replace("-", "");       // Little Endian "300035D8CFDF35D8DADF35D8E5DF35D8F0DF35D8FBDF"
var sB = BitConverter.ToString(Encoding.BigEndianUnicode.GetBytes(s)).Replace("-", ""); // Big Endian "0030D835DFCFD835DFDAD835DFE5D835DFF0D835DFFB"

// no encodding "300035D8CFDF35D8DADF35D8E5DF35D8F0DF35D8FBDF"
byte[] b = new byte[s.Length * sizeof(char)];
Buffer.BlockCopy(s.ToCharArray(), 0, b, 0, b.Length);
var sb = BitConverter.ToString(b).Replace("-", "");

Rails - Could not find a JavaScript runtime?

On CentOS 6.5, the following worked for me:

sudo yum install -y nodejs

How to 'foreach' a column in a DataTable using C#?

In LINQ you could do something like:

foreach (var data in from DataRow row in dataTable.Rows
                     from DataColumn col in dataTable.Columns
                          where
                              row[col] != null
                          select row[col])
{
    // do something with data
}

How can I print the contents of a hash in Perl?

The easiest way in my experiences is to just use Dumpvalue.

use Dumpvalue;
...
my %hash = { key => "value", foo => "bar" };
my $dumper = new DumpValue();
$dumper->dumpValue(\%hash);

Works like a charm and you don't have to worry about formatting the hash, as it outputs it like the Perl debugger does (great for debugging). Plus, Dumpvalue is included with the stock set of Perl modules, so you don't have to mess with CPAN if you're behind some kind of draconian proxy (like I am at work).

How to create bitmap from byte array?

You'll need to get those bytes into a MemoryStream:

Bitmap bmp;
using (var ms = new MemoryStream(imageData))
{
    bmp = new Bitmap(ms);
}

That uses the Bitmap(Stream stream) constructor overload.

UPDATE: keep in mind that according to the documentation, and the source code I've been reading through, an ArgumentException will be thrown on these conditions:

stream does not contain image data or is null.
-or-
stream contains a PNG image file with a single dimension greater than 65,535 pixels.

When to use EntityManager.find() vs EntityManager.getReference() with JPA

Sssuming you have a parent Post entity and a child PostComment as illustrated in the following diagram:

enter image description here

If you call find when you try to set the @ManyToOne post association:

PostComment comment = new PostComment();
comment.setReview("Just awesome!");
 
Post post = entityManager.find(Post.class, 1L);
comment.setPost(post);
 
entityManager.persist(comment);

Hibernate will execute the following statements:

SELECT p.id AS id1_0_0_,
       p.title AS title2_0_0_
FROM   post p
WHERE p.id = 1
 
INSERT INTO post_comment (post_id, review, id)
VALUES (1, 'Just awesome!', 1)

The SELECT query is useless this time because we don’t need the Post entity to be fetched. We only want to set the underlying post_id Foreign Key column.

Now, if you use getReference instead:

PostComment comment = new PostComment();
comment.setReview("Just awesome!");
 
Post post = entityManager.getReference(Post.class, 1L);
comment.setPost(post);
 
entityManager.persist(comment);

This time, Hibernate will issue just the INSERT statement:

INSERT INTO post_comment (post_id, review, id)
VALUES (1, 'Just awesome!', 1)

Unlike find, the getReference only returns an entity Proxy which only has the identifier set. If you access the Proxy, the associated SQL statement will be triggered as long as the EntityManager is still open.

However, in this case, we don’t need to access the entity Proxy. We only want to propagate the Foreign Key to the underlying table record so loading a Proxy is sufficient for this use case.

When loading a Proxy, you need to be aware that a LazyInitializationException can be thrown if you try to access the Proxy reference after the EntityManager is closed.

How to export MySQL database with triggers and procedures?

May be it's obvious for expert users of MYSQL but I wasted some time while trying to figure out default value would not export functions. So I thought to mention here that --routines param needs to be set to true to make it work.

mysqldump --routines=true -u <user> my_database > my_database.sql

List comprehension with if statement

You got the order wrong. The if should be after the for (unless it is in an if-else ternary operator)

[y for y in a if y not in b]

This would work however:

[y if y not in b else other_value for y in a]

How to get the last element of a slice?

For just reading the last element of a slice:

sl[len(sl)-1]

For removing it:

sl = sl[:len(sl)-1]

See this page about slice tricks

Make $JAVA_HOME easily changable in Ubuntu

Try these steps.

--We are going to edit "etc\profile". The environment variables are to be input at the bottom of the file. Since Ubuntu does not give access to root folder, we will have to use a few commands in the terminal

Step1: Start Terminal. Type in command: gksudo gedit /etc/profile

Step2: The profile text file will open. Enter the environment variables at the bottom of the page........... Eg: export JAVA_HOME=/home/alex/jdk1.6.0_22/bin/java

export PATH=/home/alex/jdk1.6.0_22/bin:$PATH

step3: save and close the file. Check if the environment variables are set by using echo command........ Eg echo $PATH

Class method decorator with self arguments?

You can't. There's no self in the class body, because no instance exists. You'd need to pass it, say, a str containing the attribute name to lookup on the instance, which the returned function can then do, or use a different method entirely.

converting a javascript string to a html object

If the browser that you are planning to use is Mozilla (Addon development) (not sure of chrome) you can use the following method in Javascript

function DOM( string )
{
    var {Cc, Ci} = require("chrome");
    var parser = Cc["@mozilla.org/xmlextras/domparser;1"].createInstance(Ci.nsIDOMParser);
    console.log("PARSING OF DOM COMPLETED ...");
    return (parser.parseFromString(string, "text/html"));
};

Hope this helps

Cannot connect to MySQL 4.1+ using old authentication

If you do not have Administrator access to the MySQL Server configuration (i.e. you are using a hosting service), then there are 2 options to get this to work:

1) Request that the old_passwords option be set to false on the MySQL server

2) Downgrade PHP to 5.2.2 until option 1 occurs.

From what I've been able to find, the issue seems to be with how the MySQL account passwords are stored and if the 'old_passwords' setting is set to true. This causes a compatibility issue between MySQL and newer versions of PHP (5.3+) where PHP attempts to connect using a 41-character hash but the MySQL server is still storing account passwords using a 16-character hash.

This incompatibility was brought about by the changing of the hashing method used in MySQL 4.1 which allows for both short and long hash lengths (Scenario 2 on this page from the MySQL site: http://dev.mysql.com/doc/refman/5.5/en/password-hashing.html) and the inclusion of the MySQL Native Driver in PHP 5.3 (backwards compatibility issue documented on bullet 7 of this page from the PHP documentation: http://www.php.net/manual/en/migration53.incompatible.php).

How to run regasm.exe from command line other than Visual Studio command prompt?

If you created the DLL using .net 4.5 , then copy and paste this command on command prompt.

 %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\regasm.exe MyAssembly.dll

How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?

In JPQL the same is actually true in the spec. The JPA spec does not allow an alias to be given to a fetch join. The issue is that you can easily shoot yourself in the foot with this by restricting the context of the join fetch. It is safer to join twice.

This is normally more an issue with ToMany than ToOnes. For example,

Select e from Employee e 
join fetch e.phones p 
where p.areaCode = '613'

This will incorrectly return all Employees that contain numbers in the '613' area code but will left out phone numbers of other areas in the returned list. This means that an employee that had a phone in the 613 and 416 area codes will loose the 416 phone number, so the object will be corrupted.

Granted, if you know what you are doing, the extra join is not desirable, some JPA providers may allow aliasing the join fetch, and may allow casting the Criteria Fetch to a Join.

Best way to log POST data in Apache?

You can use [ModSecurity][1] to view POST data.

Install on Debian/Ubuntu:

$ sudo apt install libapache2-mod-security2

Use the recommended configuration file:

$ sudo mv /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf

Reload Apache:

$ sudo service apache2 reload

You will now find your data logged under /var/log/apache2/modsec_audit.log

$ tail -f /var/log/apache2/modsec_audit.log
--2222229-A--
[23/Nov/2017:11:36:35 +0000] 
--2222229-B--
POST / HTTP/1.1
Content-Type: application/json
User-Agent: curl
Host: example.com

--2222229-C--
{"test":"modsecurity"}

How to add new activity to existing project in Android Studio?

I think natually do it is straightforward, whether Intellij IDEA or Android Studio, I always click new Java class menu, and then typing the class name, press Enter to create. after that, I manually typing "extends Activity" in the class file, and then import the class by shortcut key. finally, I also manually override the onCreate() method and invoke the setContentView() method.

unary operator expected in shell script when comparing null value with string

Since the value of $var is the empty string, this:

if [ $var == $var1 ]; then

expands to this:

if [ == abcd ]; then

which is a syntax error.

You need to quote the arguments:

if [ "$var" == "$var1" ]; then

You can also use = rather than ==; that's the original syntax, and it's a bit more portable.

If you're using bash, you can use the [[ syntax, which doesn't require the quotes:

if [[ $var = $var1 ]]; then

Even then, it doesn't hurt to quote the variable reference, and adding quotes:

if [[ "$var" = "$var1" ]]; then

might save a future reader a moment trying to remember whether [[ ... ]] requires them.

Hide Text with CSS, Best Practice?

As of September of 2015, the most common practice is to use the following CSS:

.sr-only{
    clip: rect(1px, 1px, 1px, 1px);
    height: 1px;
    overflow: hidden;
    position: absolute !important;
    width: 1px;
}

scroll up and down a div on button click using jquery

Just to add to other comments - it would be worth while to disable scrolling up whilst at the top of the page. If the user accidentally scrolls up whilst already at the top they would have to scroll down twice to start

if(scrolled != 0){
  $("#upClick").on("click" ,function(){
     scrolled=scrolled-300;
        $(".cover").animate({
          scrollTop:  scrolled
     });
  });
}

Android. Fragment getActivity() sometimes returns null

It seems that I found a solution to my problem. Very good explanations are given here and here. Here is my example:

pulic class MyActivity extends FragmentActivity{

private ViewPager pager; 
private TitlePageIndicator indicator;
private TabsAdapter adapter;
private Bundle savedInstanceState;

 @Override
public void onCreate(Bundle savedInstanceState) {

    .... 
    this.savedInstanceState = savedInstanceState;
    pager = (ViewPager) findViewById(R.id.pager);;
    indicator = (TitlePageIndicator) findViewById(R.id.indicator);
    adapter = new TabsAdapter(getSupportFragmentManager(), false);

    if (savedInstanceState == null){    
        adapter.addFragment(new FirstFragment());
        adapter.addFragment(new SecondFragment());
    }else{
        Integer  count  = savedInstanceState.getInt("tabsCount");
        String[] titles = savedInstanceState.getStringArray("titles");
        for (int i = 0; i < count; i++){
            adapter.addFragment(getFragment(i), titles[i]);
        }
    }


    indicator.notifyDataSetChanged();
    adapter.notifyDataSetChanged();

    // push first task
    FirstTask firstTask = new FirstTask(MyActivity.this);
    // set first fragment as listener
    firstTask.setTaskListener((TaskListener) getFragment(0));
    firstTask.execute();

}

private Fragment getFragment(int position){
     return savedInstanceState == null ? adapter.getItem(position) : getSupportFragmentManager().findFragmentByTag(getFragmentTag(position));
}

private String getFragmentTag(int position) {
    return "android:switcher:" + R.id.pager + ":" + position;
}

 @Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("tabsCount",      adapter.getCount());
    outState.putStringArray("titles", adapter.getTitles().toArray(new String[0]));
}

 indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            Fragment currentFragment = adapter.getItem(position);
            ((Taskable) currentFragment).executeTask();
        }

        @Override
        public void onPageScrolled(int i, float v, int i1) {}

        @Override
        public void onPageScrollStateChanged(int i) {}
 });

The main idea in this code is that, while running your application normally, you create new fragments and pass them to the adapter. When you are resuming your application fragment manager already has this fragment's instance and you need to get it from fragment manager and pass it to the adapter.

UPDATE

Also, it is a good practice when using fragments to check isAdded before getActivity() is called. This helps avoid a null pointer exception when the fragment is detached from the activity. For example, an activity could contain a fragment that pushes an async task. When the task is finished, the onTaskComplete listener is called.

@Override
public void onTaskComplete(List<Feed> result) {

    progress.setVisibility(View.GONE);
    progress.setIndeterminate(false);
    list.setVisibility(View.VISIBLE);

    if (isAdded()) {

        adapter = new FeedAdapter(getActivity(), R.layout.feed_item, result);
        list.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

}

If we open the fragment, push a task, and then quickly press back to return to a previous activity, when the task is finished, it will try to access the activity in onPostExecute() by calling the getActivity() method. If the activity is already detached and this check is not there:

if (isAdded()) 

then the application crashes.

How to send email from MySQL 5.1

I agree with Jim Blizard. The database is not the part of your technology stack that should send emails. For example, what if you send an email but then roll back the change that triggered that email? You can't take the email back.

It's better to send the email in your application code layer, after your app has confirmed that the SQL change was made successfully and committed.

How to call multiple functions with @click in vue?

On Vue 2.3 and above you can do this:

<div v-on:click="firstFunction(); secondFunction();"></div>
// or
<div @click="firstFunction(); secondFunction();"></div>

Twitter Bootstrap Modal Form Submit

Updated 2018

Do you want to close the modal after submit? Whether the form in inside the modal or external to it you should be able to use jQuery ajax to submit the form.

Here is an example with the form inside the modal:

<a href="#myModal" role="button" class="btn" data-toggle="modal">Launch demo modal</a>

<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <h3 id="myModalLabel">Modal header</h3>
    </div>
    <div class="modal-body">
        <form id="myForm" method="post">
          <input type="hidden" value="hello" id="myField">
            <button id="myFormSubmit" type="submit">Submit</button>
        </form>
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        <button class="btn btn-primary">Save changes</button>
    </div>
</div>

And the jQuery ajax to get the form fields and submit it..

$('#myFormSubmit').click(function(e){
      e.preventDefault();
      alert($('#myField').val());
      /*
      $.post('http://path/to/post', 
         $('#myForm').serialize(), 
         function(data, status, xhr){
           // do something here with response;
         });
      */
});

Bootstrap 3 example


Bootstrap 4 example

What are all the user accounts for IIS/ASP.NET and how do they differ?

This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....

To cover the identities listed:

IIS_IUSRS:

This is analogous to the old IIS6 IIS_WPG group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.

IUSR:

This account is analogous to the old IUSR_<MACHINE_NAME> local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).

For more information about IIS_IUSRS and IUSR see:

Understanding Built-In User and Group Accounts in IIS 7

DefaultAppPool:

If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name> will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>. You also won't see these pool accounts in your computers User Manager. See the following for more information:

Application Pool Identities

ASP.NET v4.0: -

This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool above.

NETWORK SERVICE: -

The NETWORK SERVICE account is a built-in identity introduced on Windows 2003. NETWORK SERVICE is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).

In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" /> setting in web.config file locally (if that setting is locked then it would need to be done by an admin in the machine.config file).

Setting <identity impersonate="true"> is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).

In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR or a specific custom anonymous account.

LOCAL SERVICE:

The LOCAL SERVICE account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:

LocalService Account

LOCAL SYSTEM:

You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.

LocalSystem Account

In Practice:

In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity:

enter image description here

In the website you should then configure the Authentication feature:

enter image description here

Right click and edit the Anonymous Authentication entry:

enter image description here

Ensure that "Application pool identity" is selected:

enter image description here

When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0 pool permissions then you can either do this via Explorer:

enter image description here

Click the "Check Names" button:

enter image description here

Or you can do this using the ICACLS.EXE utility:

icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)

...or...if you site's application pool is called BobsCatPicBlogthen:

icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)

I hope this helps clear things up.

Update:

I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:

The difference between the 'Local System' account and the 'Network Service' account?

Simple way to get element by id within a div tag?

Unfortunately this is invalid HTML. An ID has to be unique in the whole HTML file.

When you use Javascript's document.getElementById() it depends on the browser, which element it will return, mostly it's the first with a given ID.

You will have no other chance as to re-assign your IDs, or alternatively using the class attribute.

How to order results with findBy() in Doctrine

$cRepo = $em->getRepository('KaleLocationBundle:Country');

// Leave the first array blank
$countries = $cRepo->findBy(array(), array('name'=>'asc'));

Simple if else onclick then do?

you call function on page load time but not call on button event, you will need to call function onclick event, you may add event inline element style or event bining

_x000D_
_x000D_
 function Choice(elem) {_x000D_
   var box = document.getElementById("box");_x000D_
   if (elem.id == "no") {_x000D_
     box.style.backgroundColor = "red";_x000D_
   } else if (elem.id == "yes") {_x000D_
     box.style.backgroundColor = "green";_x000D_
   } else {_x000D_
     box.style.backgroundColor = "purple";_x000D_
   };_x000D_
 };
_x000D_
<div id="box">dd</div>_x000D_
<button id="yes" onclick="Choice(this);">yes</button>_x000D_
<button id="no" onclick="Choice(this);">no</button>_x000D_
<button id="other" onclick="Choice(this);">other</button>
_x000D_
_x000D_
_x000D_

or event binding,

_x000D_
_x000D_
window.onload = function() {_x000D_
  var box = document.getElementById("box");_x000D_
  document.getElementById("yes").onclick = function() {_x000D_
    box.style.backgroundColor = "red";_x000D_
  }_x000D_
  document.getElementById("no").onclick = function() {_x000D_
    box.style.backgroundColor = "green";_x000D_
  }_x000D_
}
_x000D_
<div id="box">dd</div>_x000D_
<button id="yes">yes</button>_x000D_
<button id="no">no</button>
_x000D_
_x000D_
_x000D_

Rails: How to reference images in CSS within Rails 4

None of the answers says about the way, when I'll have .css.erb extension, how to reference images. For me worked both in production and development as well :

2.3.1 CSS and ERB

The asset pipeline automatically evaluates ERB. This means if you add an erb extension to a CSS asset (for example, application.css.erb), then helpers like asset_path are available in your CSS rules:

.class { background-image: url(<%= asset_path 'image.png' %>) }

This writes the path to the particular asset being referenced. In this example, it would make sense to have an image in one of the asset load paths, such as app/assets/images/image.png, which would be referenced here. If this image is already available in public/assets as a fingerprinted file, then that path is referenced.

If you want to use a data URI - a method of embedding the image data directly into the CSS file - you can use the asset_data_uri helper.

.logo { background: url(<%= asset_data_uri 'logo.png' %>) }

This inserts a correctly-formatted data URI into the CSS source.

Note that the closing tag cannot be of the style -%>.

How to select rows from a DataFrame based on column values

To append to this famous question (though a bit too late): You can also do df.groupby('column_name').get_group('column_desired_value').reset_index() to make a new data frame with specified column having a particular value. E.g.

import pandas as pd
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
                   'B': 'one one two three two two one three'.split()})
print("Original dataframe:")
print(df)

b_is_two_dataframe = pd.DataFrame(df.groupby('B').get_group('two').reset_index()).drop('index', axis = 1) 
#NOTE: the final drop is to remove the extra index column returned by groupby object
print('Sub dataframe where B is two:')
print(b_is_two_dataframe)

Run this gives:

Original dataframe:
     A      B
0  foo    one
1  bar    one
2  foo    two
3  bar  three
4  foo    two
5  bar    two
6  foo    one
7  foo  three
Sub dataframe where B is two:
     A    B
0  foo  two
1  foo  two
2  bar  two

Can't push image to Amazon ECR - fails with "no basic auth credentials"

we also encounter this issue today and tried everything mentionned in this post (except generating AWS credentials).

We finally solved the problem by simply upgrading Docker, then the push worked.

The problem was encountered with Docker 1.10.x and was solved with Docker 1.11.x.

Hope this helps

hide div tag on mobile view only?

Set the display property to none as the default, then use a media query to apply the desired styles to the div when the browser reaches a certain width. Replace 768px in the media query with whatever the minimum px value is where your div should be visible.

#title_message {
    display: none;
}

@media screen and (min-width: 768px) {
    #title_message {
        clear: both;
        display: block;
        float: left;
        margin: 10px auto 5px 20px;
        width: 28%;
    }
}

Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

I like to keep is simple when possible. I needed to group by International, filter on all the columns, display the count for each group and hide the group if no items existed.

Plus I did not want to add a custom filter just for something simple like this.

        <tbody>
            <tr ng-show="fusa.length > 0"><td colspan="8"><h3>USA ({{fusa.length}})</h3></td></tr>
            <tr ng-repeat="t in fusa = (usa = (vm.assignmentLookups | filter: {isInternational: false}) | filter: vm.searchResultText)">
                <td>{{$index + 1}}</td>
                <td ng-bind-html="vm.highlight(t.title, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.genericName, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.mechanismsOfAction, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.diseaseStateIndication, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.assignedTo, vm.searchResultText)"></td>
                <td ng-bind-html="t.lastPublished | date:'medium'"></td>
            </tr>
        </tbody>
        <tbody>
            <tr ng-show="fint.length > 0"><td colspan="8"><h3>International ({{fint.length}})</h3></td></tr>
            <tr ng-repeat="t in fint = (int = (vm.assignmentLookups | filter: {isInternational: true}) | filter: vm.searchResultText)">
                <td>{{$index + 1}}</td>
                <td ng-bind-html="vm.highlight(t.title, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.genericName, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.mechanismsOfAction, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.diseaseStateIndication, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.assignedTo, vm.searchResultText)"></td>
                <td ng-bind-html="t.lastPublished | date:'medium'"></td>
            </tr>
        </tbody>

how to get param in method post spring mvc?

When I want to get all the POST params I am using the code below,

@RequestMapping(value = "/", method = RequestMethod.POST)
public ViewForResponseClass update(@RequestBody AClass anObject) {
    // Source..
}

I am using the @RequestBody annotation for post/put/delete http requests instead of the @RequestParam which reads the GET parameters.

Get week of year in JavaScript like in PHP

With Luxon (https://github.com/moment/luxon) :

import { DateTime } from 'luxon';
const week: number = DateTime.fromJSDate(new Date()).weekNumber;

Capture Video of Android's Screen

I guess screencast is no go cause of tegra 2 incompatibility, i already tried it,but no whey! So i tried using Z-ScreeNRecorder from market,installed it on my LG Optimus 2x, but it record's only blank screen,i tried for 5min. and there i get 5min. of blank screen file of 6mb size... so there is no point trying until they release some peace of software that is compatible with tegra2 chipset!

Javascript communication between browser tabs/windows

Communicating between different JavaScript execution context was supported even before HTML5 if the documents was of the same origin. If not or you have no reference to the other Window object, then you could use the new postMessage API introduced with HTML5. I elaborated a bit on both approaches in this stackoverflow answer.

How to serve up images in Angular2?

Just put your images in the assets folder refer them in your html pages or ts files with that link.

How to properly apply a lambda function into a pandas data frame column

You need mask:

sample['PR'] = sample['PR'].mask(sample['PR'] < 90, np.nan)

Another solution with loc and boolean indexing:

sample.loc[sample['PR'] < 90, 'PR'] = np.nan

Sample:

import pandas as pd
import numpy as np

sample = pd.DataFrame({'PR':[10,100,40] })
print (sample)
    PR
0   10
1  100
2   40

sample['PR'] = sample['PR'].mask(sample['PR'] < 90, np.nan)
print (sample)
      PR
0    NaN
1  100.0
2    NaN
sample.loc[sample['PR'] < 90, 'PR'] = np.nan
print (sample)
      PR
0    NaN
1  100.0
2    NaN

EDIT:

Solution with apply:

sample['PR'] = sample['PR'].apply(lambda x: np.nan if x < 90 else x)

Timings len(df)=300k:

sample = pd.concat([sample]*100000).reset_index(drop=True)

In [853]: %timeit sample['PR'].apply(lambda x: np.nan if x < 90 else x)
10 loops, best of 3: 102 ms per loop

In [854]: %timeit sample['PR'].mask(sample['PR'] < 90, np.nan)
The slowest run took 4.28 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 3.71 ms per loop

'if' statement in jinja2 template

Why the loop?

You could simply do this:

{% if 'priority' in data %}
    <p>Priority: {{ data['priority'] }}</p>
{% endif %}

When you were originally doing your string comparison, you should have used == instead.

splitting a string based on tab in the file

You can use regexp to do this:

import re
patt = re.compile("[^\t]+")


s = "a\t\tbcde\t\tef"
patt.findall(s)
['a', 'bcde', 'ef']  

C++ STL Vectors: Get iterator from index?

Also; auto it = std::next(v.begin(), index);

Update: Needs a C++11x compliant compiler

The request failed or the service did not respond in a timely fashion?

I had a similar issue. The next solution is in *case to can't launch the server Locally * and you will see the same error msg.(Image 1)

enter image description here Imagen 1

enter image description here Imagen 2

To solve that and have the server working you must have the next steps.

  1. Go to SQL Server Services
  2. Right click to open properties
  3. Go to LogOn tab (By default you will see something like Image 3)
  4. Select the radio button Built-in account (Image 4)
  5. Click on Ok
  6. Go back to SQL Server Services and launch again the server (Image 5) After that you must be able to see run it.

Image 3 Image 3

enter image description here Image 4

enter image description here Image 5

I hope that works for you or others with similar issues. Follow me for more tips.

tomcat - CATALINA_BASE and CATALINA_HOME variables

CATALINA_HOME vs CATALINA_BASE

If you're running multiple instances, then you need both variables, otherwise only CATALINA_HOME.

In other words: CATALINA_HOME is required and CATALINA_BASE is optional.

CATALINA_HOME represents the root of your Tomcat installation.

Optionally, Tomcat may be configured for multiple instances by defining $CATALINA_BASE for each instance. If multiple instances are not configured, $CATALINA_BASE is the same as $CATALINA_HOME.

See: Apache Tomcat 7 - Introduction

Running with separate CATALINA_HOME and CATALINA_BASE is documented in RUNNING.txt which say:

The CATALINA_HOME and CATALINA_BASE environment variables are used to specify the location of Apache Tomcat and the location of its active configuration, respectively.

You cannot configure CATALINA_HOME and CATALINA_BASE variables in the setenv script, because they are used to find that file.

For example:

(4.1) Tomcat can be started by executing one of the following commands:

  %CATALINA_HOME%\bin\startup.bat         (Windows)

  $CATALINA_HOME/bin/startup.sh           (Unix)

or

  %CATALINA_HOME%\bin\catalina.bat start  (Windows)

  $CATALINA_HOME/bin/catalina.sh start    (Unix)

Multiple Tomcat Instances

In many circumstances, it is desirable to have a single copy of a Tomcat binary distribution shared among multiple users on the same server. To make this possible, you can set the CATALINA_BASE environment variable to the directory that contains the files for your 'personal' Tomcat instance.

When running with a separate CATALINA_HOME and CATALINA_BASE, the files and directories are split as following:

In CATALINA_BASE:

  • bin - Only: setenv.sh (*nix) or setenv.bat (Windows), tomcat-juli.jar
  • conf - Server configuration files (including server.xml)
  • lib - Libraries and classes, as explained below
  • logs - Log and output files
  • webapps - Automatically loaded web applications
  • work - Temporary working directories for web applications
  • temp - Directory used by the JVM for temporary files>

In CATALINA_HOME:

  • bin - Startup and shutdown scripts
  • lib - Libraries and classes, as explained below
  • endorsed - Libraries that override standard "Endorsed Standards". By default it's absent.

How to check

The easiest way to check what's your CATALINA_BASE and CATALINA_HOME is by running startup.sh, for example:

$ /usr/share/tomcat7/bin/startup.sh
Using CATALINA_BASE:   /usr/share/tomcat7
Using CATALINA_HOME:   /usr/share/tomcat7

You may also check where the Tomcat files are installed, by dpkg tool as below (Debian/Ubuntu):

dpkg -L tomcat7-common

Why does ASP.NET webforms need the Runat="Server" attribute?

I think that Microsoft can fix this ambiguity by making the compiler add runat attribute before the page is ever compiled, something like the type-erasure thing that java has with the generics, instead of erasing, it could be writing runat=server wherever it sees asp: prefix for tags, so the developer would not need to worry about it.

How to change the Spyder editor background to dark?

Yes, that's the intuitive answer. Nothing in Spyder is intuitive. Go to Preferences/Editor and select the scheme you want. Then go to Preferences/Syntax Coloring and adjust the colors if you want to. tcebob

What is the function of the push / pop instructions used on registers in x86 assembly?

Almost all CPUs use stack. The program stack is LIFO technique with hardware supported manage.

Stack is amount of program (RAM) memory normally allocated at the top of CPU memory heap and grow (at PUSH instruction the stack pointer is decreased) in opposite direction. A standard term for inserting into stack is PUSH and for remove from stack is POP.

Stack is managed via stack intended CPU register, also called stack pointer, so when CPU perform POP or PUSH the stack pointer will load/store a register or constant into stack memory and the stack pointer will be automatic decreased xor increased according number of words pushed or poped into (from) stack.

Via assembler instructions we can store to stack:

  1. CPU registers and also constants.
  2. Return addresses for functions or procedures
  3. Functions/procedures in/out variables
  4. Functions/procedures local variables.

Clear git local cache

When you think your git is messed up, you can use this command to do everything up-to-date.

git rm -r --cached .
git add .
git commit -am 'git cache cleared'
git push

Also to revert back last commit use this :

git reset HEAD^ --hard

How to read and write into file using JavaScript?

Currently, files can be written and read from the context of a browser tab/window with the File, FileWriter, and FileSystem APIs, though there are caveats to their use (see tail of this answer).

But to answer your question:

Using BakedGoods*

Write file:

bakedGoods.set({
    data: [{key: "testFile", value: "Hello world!", dataFormat: "text/plain"}],
    storageTypes: ["fileSystem"],
    options: {fileSystem:{storageType: Window.PERSISTENT}},
    complete: function(byStorageTypeStoredItemRangeDataObj, byStorageTypeErrorObj){}
});

Read file:

bakedGoods.get({
        data: ["testFile"],
        storageTypes: ["fileSystem"],
        options: {fileSystem:{storageType: Window.PERSISTENT}},
        complete: function(resultDataObj, byStorageTypeErrorObj){}
});

Using the raw File, FileWriter, and FileSystem APIs

Write file:

function onQuotaRequestSuccess(grantedQuota)
{

    function saveFile(directoryEntry)
    {

        function createFileWriter(fileEntry)
        {

            function write(fileWriter)
            {
                var dataBlob = new Blob(["Hello world!"], {type: "text/plain"});
                fileWriter.write(dataBlob);              
            }

            fileEntry.createWriter(write);
        }

        directoryEntry.getFile(
            "testFile", 
            {create: true, exclusive: true},
            createFileWriter
        );
    }

    requestFileSystem(Window.PERSISTENT, grantedQuota, saveFile);
}

var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);

Read file:

function onQuotaRequestSuccess(grantedQuota)
{

    function getfile(directoryEntry)
    {

        function readFile(fileEntry)
        {

            function read(file)
            {
                var fileReader = new FileReader();

                fileReader.onload = function(){var fileData = fileReader.result};
                fileReader.readAsText(file);             
            }

            fileEntry.file(read);
        }

        directoryEntry.getFile(
            "testFile", 
            {create: false},
            readFile
        );
    }

    requestFileSystem(Window.PERSISTENT, grantedQuota, getFile);
}

var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);

Just what you asked for right? Maybe, maybe not. The latter two of the APIs:

  • Are currently only implemented in Chromium-based browsers (Chrome & Opera)
  • Have been taken off the W3C standards track, and as of now are proprietary APIs
  • May be removed from the implementing browsers in the future
  • Constrict the creation of files to a sandbox (a location outside of which the files can produce no effect) on disk

Additionally, the FileSystem spec defines no guidelines on how directory structures are to appear on disk. In Chromium-based browsers for example, the sandbox has a virtual file system (a directory structure which does not necessarily exist on disk in the same form that it does when accessed from within the browser), within which the directories and files created with the APIs are placed.

So though you may be able to write files to a system with the APIs, locating the files without the APIs (well, without the FileSystem API) could be a non-trivial affair.

If you can deal with these issues/limitations, these APIs are pretty much the only native way to do what you've asked.

If you're open to non-native solutions, Silverlight also allows for file i/o from a tab/window contest through IsolatedStorage. However, managed code is required to utilize this facility; a solution which requires writing such code is beyond the scope of this question.

Of course, a solution which makes use of complementary managed code, leaving one with only Javascript to write, is well within the scope of this question ;) :

//Write file to first of either FileSystem or IsolatedStorage
bakedGoods.set({
    data: [{key: "testFile", value: "Hello world!", dataFormat: "text/plain"}],
    storageTypes: ["fileSystem", "silverlight"],
    options: {fileSystem:{storageType: Window.PERSISTENT}},
    complete: function(byStorageTypeStoredItemRangeDataObj, byStorageTypeErrorObj){}
});

* BakedGoods is a Javascript library that establishes a uniform interface that can be used to conduct common storage operations in all native, and some non-native storage facilities. It is maintained by this guy right here : ) .

Object of custom type as dictionary key

You override __hash__ if you want special hash-semantics, and __cmp__ or __eq__ in order to make your class usable as a key. Objects who compare equal need to have the same hash value.

Python expects __hash__ to return an integer, returning Banana() is not recommended :)

User defined classes have __hash__ by default that calls id(self), as you noted.

There is some extra tips from the documentation.:

Classes which inherit a __hash__() method from a parent class but change the meaning of __cmp__() or __eq__() such that the hash value returned is no longer appropriate (e.g. by switching to a value-based concept of equality instead of the default identity based equality) can explicitly flag themselves as being unhashable by setting __hash__ = None in the class definition. Doing so means that not only will instances of the class raise an appropriate TypeError when a program attempts to retrieve their hash value, but they will also be correctly identified as unhashable when checking isinstance(obj, collections.Hashable) (unlike classes which define their own __hash__() to explicitly raise TypeError).

Show week number with Javascript?

It looks like this function I found at weeknumber.net is pretty accurate and easy to use.

// This script is released to the public domain and may be used, modified and
// distributed without restrictions. Attribution not necessary but appreciated.
// Source: http://weeknumber.net/how-to/javascript 

// Returns the ISO week of the date.
Date.prototype.getWeek = function() {
  var date = new Date(this.getTime());
  date.setHours(0, 0, 0, 0);
  // Thursday in current week decides the year.
  date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
  // January 4 is always in week 1.
  var week1 = new Date(date.getFullYear(), 0, 4);
  // Adjust to Thursday in week 1 and count number of weeks from date to week1.
  return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
}

If you're lucky like me and need to find the week number of the month a little adjust will do it:

// Returns the week in the month of the date.
Date.prototype.getWeekOfMonth = function() {
  var date = new Date(this.getTime());
  date.setHours(0, 0, 0, 0);
  // Thursday in current week decides the year.
  date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
  // January 4 is always in week 1.
  var week1 = new Date(date.getFullYear(), date.getMonth(), 4);
  // Adjust to Thursday in week 1 and count number of weeks from date to week1.
  return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
}

Calculating time difference between 2 dates in minutes

I think you could use TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2) something like

select * from MyTab T where
TIMESTAMPDIFF(MINUTE,T.runTime,NOW()) > 20

Enable IIS7 gzip

I only needed to add the feature in windows features as Charlie mentioned.For people who cannot find it on window 10 or server 2012+ find it as below. I struggled a bit

Windows 10

enter image description here

windows server 2012 R2

enter image description here

window server 2016

enter image description here

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JDBC_DBO]]

I guess you are working with a Dynamic Web Project, because you mentioned de folder WEB-INF/lib in a comment; if yes, make sure your not putting any *-servlet jar file inside this folder or other jar already provided by the container, in this case Tomcat. Plus: Once I used jersey-servlet.jar, and I needed to remove it from the lib folder in order to Tomcat start without problems; then I use just jersey-bundle.jar and it works well.

Android studio logcat nothing to show

It's weird to still encounter this problem even on a recent version of Android Studio. I read through the long list of solutions but they did not work for me. The accepted answer worked on an earlier version of Android Studio ( I guess it was v2.3)

I did the following to get Logcat working again:

  1. Logcat > Show only selected application > No filters

enter image description here

  1. Logcat > No filters > Show only selected application

enter image description here

I expected resetting logcat should ideally give me the same effect but it didn't. Manually toggling filter was the only thing that worked.

This is on Android Studio 3.0.1 (stable) (I can't update it before finishing the current project) The issue occurred when I started Android studio in the morning to continue the work I left at night. I hope the devs will look into this. It was painstaking to try over 15 solutions from stackoverflow and still see no result. It's even irritating to reveal another solution for future victims of this issue.

Installation failed with message Invalid File

In my case , there was a single qutation ' in project directory and after removing it resolved

Java character array initializer

Instead of above way u can achieve the solution simply by following method..

public static void main(String args[]) {
    String ini = "Hi there";
    for (int i = 0; i < ini.length(); i++) {
        System.out.print(" " + ini.charAt(i));
    }
}

Refresh a page using PHP

I've found two ways to refresh PHP content:

1. Using the HTML meta tag:

echo("<meta http-equiv='refresh' content='1'>"); //Refresh by HTTP 'meta'

2. Using PHP refresh rate:

$delay = 0; // Where 0 is an example of a time delay. You can use 5 for 5 seconds, for example!
header("Refresh: $delay;"); 

Inverse dictionary lookup in Python

There isn't one as far as I know of, one way however to do it is to create a dict for normal lookup by key and another dict for reverse lookup by value.

There's an example of such an implementation here:

http://code.activestate.com/recipes/415903-two-dict-classes-which-can-lookup-keys-by-value-an/

This does mean that looking up the keys for a value could result in multiple results which can be returned as a simple list.

Cordova : Requirements check failed for JDK 1.8 or greater

Today I also got this error Cordova : Requirements check failed for JDK 1.8 or greater in my Mac OS while build Ionic App when I run command ionic cordova build --release android via terminal.

Below command resolve my issue :-

export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.8.0_231.jdk/Contents/Home"

Hope it will help someone in future!

What's the best way to set a single pixel in an HTML5 canvas?

It seems strange, but nonetheless HTML5 supports drawing lines, circles, rectangles and many other basic shapes, it does not have anything suitable for drawing the basic point. The only way to do so is to simulate point with whatever you have.

So basically there are 3 possible solutions:

  • draw point as a line
  • draw point as a polygon
  • draw point as a circle

Each of them has their drawbacks


Line

function point(x, y, canvas){
  canvas.beginPath();
  canvas.moveTo(x, y);
  canvas.lineTo(x+1, y+1);
  canvas.stroke();
}

Keep in mind that we are drawing to South-East direction, and if this is the edge, there can be a problem. But you can also draw in any other direction.


Rectangle

function point(x, y, canvas){
  canvas.strokeRect(x,y,1,1);
}

or in a faster way using fillRect because render engine will just fill one pixel.

function point(x, y, canvas){
  canvas.fillRect(x,y,1,1);
}

Circle


One of the problems with circles is that it is harder for an engine to render them

function point(x, y, canvas){
  canvas.beginPath();
  canvas.arc(x, y, 1, 0, 2 * Math.PI, true);
  canvas.stroke();
}

the same idea as with rectangle you can achieve with fill.

function point(x, y, canvas){
  canvas.beginPath();
  canvas.arc(x, y, 1, 0, 2 * Math.PI, true);
  canvas.fill();
}

Problems with all these solutions:

  • it is hard to keep track of all the points you are going to draw.
  • when you zoom in, it looks ugly.

If you are wondering, "What is the best way to draw a point?", I would go with filled rectangle. You can see my jsperf here with comparison tests.

How can I use xargs to copy files that have spaces and quotes in their names?

bill_starr's Perl version won't work well for embedded newlines (only copes with spaces). For those on e.g. Solaris where you don't have the GNU tools, a more complete version might be (using sed)...

find -type f | sed 's/./\\&/g' | xargs grep string_to_find

adjust the find and grep arguments or other commands as you require, but the sed will fix your embedded newlines/spaces/tabs.

How to center the text in a JLabel?

myLabel.setHorizontalAlignment(SwingConstants.CENTER);
myLabel.setVerticalAlignment(SwingConstants.CENTER);

If you cannot reconstruct the label for some reason, this is how you edit these properties of a pre-existent JLabel.

@property retain, assign, copy, nonatomic in Objective-C

After reading many articles I decided to put all the attributes information together:

  1. atomic //default
  2. nonatomic
  3. strong=retain //default
  4. weak= unsafe_unretained
  5. retain
  6. assign //default
  7. unsafe_unretained
  8. copy
  9. readonly
  10. readwrite //default

Below is a link to the detailed article where you can find these attributes.

Many thanks to all the people who give best answers here!!

Variable property attributes or Modifiers in iOS

Here is the Sample Description from Article

  1. atomic -Atomic means only one thread access the variable(static type). -Atomic is thread safe. -but it is slow in performance -atomic is default behavior -Atomic accessors in a non garbage collected environment (i.e. when using retain/release/autorelease) will use a lock to ensure that another thread doesn't interfere with the correct setting/getting of the value. -it is not actually a keyword.

Example :

@property (retain) NSString *name;

@synthesize name;
  1. nonatomic -Nonatomic means multiple thread access the variable(dynamic type). -Nonatomic is thread unsafe. -but it is fast in performance -Nonatomic is NOT default behavior,we need to add nonatomic keyword in property attribute. -it may result in unexpected behavior, when two different process (threads) access the same variable at the same time.

Example:

@property (nonatomic, retain) NSString *name;

@synthesize name;

Explain:

Suppose there is an atomic string property called "name", and if you call [self setName:@"A"] from thread A, call [self setName:@"B"] from thread B, and call [self name] from thread C, then all operation on different thread will be performed serially which means if one thread is executing setter or getter, then other threads will wait. This makes property "name" read/write safe but if another thread D calls [name release] simultaneously then this operation might produce a crash because there is no setter/getter call involved here. Which means an object is read/write safe (ATOMIC) but not thread safe as another threads can simultaneously send any type of messages to the object. Developer should ensure thread safety for such objects.

If the property "name" was nonatomic, then all threads in above example - A,B, C and D will execute simultaneously producing any unpredictable result. In case of atomic, Either one of A, B or C will execute first but D can still execute in parallel.

  1. strong (iOS4 = retain ) -it says "keep this in the heap until I don't point to it anymore" -in other words " I'am the owner, you cannot dealloc this before aim fine with that same as retain" -You use strong only if you need to retain the object. -By default all instance variables and local variables are strong pointers. -We generally use strong for UIViewControllers (UI item's parents) -strong is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong means that you own the object.

Example:

@property (strong, nonatomic) ViewController *viewController;

@synthesize viewController;
  1. weak (iOS4 = unsafe_unretained ) -it says "keep this as long as someone else points to it strongly" -the same thing as assign, no retain or release -A "weak" reference is a reference that you do not retain. -We generally use weak for IBOutlets (UIViewController's Childs).This works because the child object only needs to exist as long as the parent object does. -a weak reference is a reference that does not protect the referenced object from collection by a garbage collector. -Weak is essentially assign, a unretained property. Except the when the object is deallocated the weak pointer is automatically set to nil

Example :

@property (weak, nonatomic) IBOutlet UIButton *myButton;

@synthesize myButton;

Strong & Weak Explanation, Thanks to BJ Homer:

Imagine our object is a dog, and that the dog wants to run away (be deallocated). Strong pointers are like a leash on the dog. As long as you have the leash attached to the dog, the dog will not run away. If five people attach their leash to one dog, (five strong pointers to one object), then the dog will not run away until all five leashes are detached. Weak pointers, on the other hand, are like little kids pointing at the dog and saying "Look! A dog!" As long as the dog is still on the leash, the little kids can still see the dog, and they'll still point to it. As soon as all the leashes are detached, though, the dog runs away no matter how many little kids are pointing to it. As soon as the last strong pointer (leash) no longer points to an object, the object will be deallocated, and all weak pointers will be zeroed out. When we use weak? The only time you would want to use weak, is if you wanted to avoid retain cycles (e.g. the parent retains the child and the child retains the parent so neither is ever released).

  1. retain = strong -it is retained, old value is released and it is assigned -retain specifies the new value should be sent -retain on assignment and the old value sent -release -retain is the same as strong. -apple says if you write retain it will auto converted/work like strong only. -methods like "alloc" include an implicit "retain"

Example:

@property (nonatomic, retain) NSString *name;

@synthesize name;
  1. assign -assign is the default and simply performs a variable assignment -assign is a property attribute that tells the compiler how to synthesize the property's setter implementation -I would use assign for C primitive properties and weak for weak references to Objective-C objects.

Example:

@property (nonatomic, assign) NSString *address;

@synthesize address;
  1. unsafe_unretained

    -unsafe_unretained is an ownership qualifier that tells ARC how to insert retain/release calls -unsafe_unretained is the ARC version of assign.

Example:

@property (nonatomic, unsafe_unretained) NSString *nickName;

@synthesize nickName;
  1. copy -copy is required when the object is mutable. -copy specifies the new value should be sent -copy on assignment and the old value sent -release. -copy is like retain returns an object which you must explicitly release (e.g., in dealloc) in non-garbage collected environments. -if you use copy then you still need to release that in dealloc. -Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.

Example:

@property (nonatomic, copy) NSArray *myArray;

@synthesize myArray;

This Row already belongs to another table error when trying to add rows?

Try this:

DataTable dt = (DataTable)Session["dtAllOrders"];
DataTable dtSpecificOrders = dt.Clone();

DataRow[] orderRows = dt.Select("CustomerID = 2");

foreach (DataRow dr in orderRows)
{
    dtSpecificOrders.ImportRow(dr);
}

Convert StreamReader to byte[]

For everyone saying to get the bytes, copy it to MemoryStream, etc. - if the content isn't expected to be larger than computer's memory should be reasonably be expected to allow, why not just use StreamReader's built in ReadLine() or ReadToEnd()? I saw these weren't even mentioned, and they do everything for you.

I had a use-case where I just wanted to store the path of a SQLite file from a FileDialogResult that the user picks during the synching/initialization process. My program then later needs to use this path when it is run for normal application processes. Maybe not the ideal way to capture/re-use the information, but it's not much different than writing to/reading from an .ini file - I just didn't want to set one up for one value. So I just read it from a flat, one-line text file. Here's what I did:

string filePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!filePath.EndsWith(@"\")) temppath += @"\"; // ensures we have a slash on the end
filePath = filePath.Replace(@"\\", @"\"); // Visual Studio escapes slashes by putting double-slashes in their results - this ensures we don't have double-slashes
filePath += "SQLite.txt";

string path = String.Empty;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
path = sr.ReadLine();  // can also use sr.ReadToEnd();
sr.Close();
fs.Close();
fs.Flush();

return path;

If you REALLY need a byte[] instead of a string for some reason, using my example, you can always do:

byte[] toBytes;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
toBytes = Encoding.ASCII.GetBytes(path);
sr.Close();
fs.Close();
fs.Flush();

return toBytes;

(Returning toBytes instead of path.)

If you don't want ASCII you can easily replace that with UTF8, Unicode, etc.

LaTeX beamer: way to change the bullet indentation?

Setting \itemindent for a new itemize environment solves the problem:

\newenvironment{beameritemize}
{ \begin{itemize}
  \setlength{\itemsep}{1.5ex}
  \setlength{\parskip}{0pt}
  \setlength{\parsep}{0pt}   
  \addtolength{\itemindent}{-2em}  }
{ \end{itemize} } 

What does %>% function mean in R?

%...% operators

%>% has no builtin meaning but the user (or a package) is free to define operators of the form %whatever% in any way they like. For example, this function will return a string consisting of its left argument followed by a comma and space and then it's right argument.

"%,%" <- function(x, y) paste0(x, ", ", y)

# test run

"Hello" %,% "World"
## [1] "Hello, World"

The base of R provides %*% (matrix mulitiplication), %/% (integer division), %in% (is lhs a component of the rhs?), %o% (outer product) and %x% (kronecker product). It is not clear whether %% falls in this category or not but it represents modulo.

expm The R package, expm, defines a matrix power operator %^%. For an example see Matrix power in R .

operators The operators R package has defined a large number of such operators such as %!in% (for not %in%). See http://cran.r-project.org/web/packages/operators/operators.pdf

igraph This package defines %--% , %->% and %<-% to select edges.

lubridate This package defines %m+% and %m-% to add and subtract months and %--% to define an interval. igraph also defines %--% .

Pipes

magrittr In the case of %>% the magrittr R package has defined it as discussed in the magrittr vignette. See http://cran.r-project.org/web/packages/magrittr/vignettes/magrittr.html

magittr has also defined a number of other such operators too. See the Additional Pipe Operators section of the prior link which discusses %T>%, %<>% and %$% and http://cran.r-project.org/web/packages/magrittr/magrittr.pdf for even more details.

dplyr The dplyr R package used to define a %.% operator which is similar; however, it has been deprecated and dplyr now recommends that users use %>% which dplyr imports from magrittr and makes available to the dplyr user. As David Arenburg has mentioned in the comments this SO question discusses the differences between it and magrittr's %>% : Differences between %.% (dplyr) and %>% (magrittr)

pipeR The R package, pipeR, defines a %>>% operator that is similar to magrittr's %>% and can be used as an alternative to it. See http://renkun.me/pipeR-tutorial/

The pipeR package also has defined a number of other such operators too. See: http://cran.r-project.org/web/packages/pipeR/pipeR.pdf

postlogic The postlogic package defined %if% and %unless% operators.

wrapr The R package, wrapr, defines a dot pipe %.>% that is an explicit version of %>% in that it does not do implicit insertion of arguments but only substitutes explicit uses of dot on the right hand side. This can be considered as another alternative to %>%. See https://winvector.github.io/wrapr/articles/dot_pipe.html

Bizarro pipe. This is not really a pipe but rather some clever base syntax to work in a way similar to pipes without actually using pipes. It is discussed in http://www.win-vector.com/blog/2017/01/using-the-bizarro-pipe-to-debug-magrittr-pipelines-in-r/ The idea is that instead of writing:

1:8 %>% sum %>% sqrt
## [1] 6

one writes the following. In this case we explicitly use dot rather than eliding the dot argument and end each component of the pipeline with an assignment to the variable whose name is dot (.) . We follow that with a semicolon.

1:8 ->.; sum(.) ->.; sqrt(.)
## [1] 6

Update Added info on expm package and simplified example at top. Added postlogic package.

Exit while loop by user hitting ENTER key

I ran into this page while (no pun) looking for something else. Here is what I use:

while True:
    i = input("Enter text (or Enter to quit): ")
    if not i:
        break
    print("Your input:", i)
print("While loop has exited")

C# Foreach statement does not contain public definition for GetEnumerator

In foreach loop instead of carBootSaleList use carBootSaleList.data.

You probably do not need answer anymore, but it could help someone.

How do I split a string, breaking at a particular character?

This string.split("~")[0]; gets things done.

source: String.prototype.split()


Another functional approach using curry and function composition.

So the first thing would be the split function. We want to make this "john smith~123 Street~Apt 4~New York~NY~12345" into this ["john smith", "123 Street", "Apt 4", "New York", "NY", "12345"]

const split = (separator) => (text) => text.split(separator);
const splitByTilde = split('~');

So now we can use our specialized splitByTilde function. Example:

splitByTilde("john smith~123 Street~Apt 4~New York~NY~12345") // ["john smith", "123 Street", "Apt 4", "New York", "NY", "12345"]

To get the first element we can use the list[0] operator. Let's build a first function:

const first = (list) => list[0];

The algorithm is: split by the colon and then get the first element of the given list. So we can compose those functions to build our final getName function. Building a compose function with reduce:

const compose = (...fns) => (value) => fns.reduceRight((acc, fn) => fn(acc), value);

And now using it to compose splitByTilde and first functions.

const getName = compose(first, splitByTilde);

let string = 'john smith~123 Street~Apt 4~New York~NY~12345';
getName(string); // "john smith"

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

I just found my own solution to this problem, or at least my problem.
I was using justify-content: space-around instead of justify-content: space-between;.

This way the end elements will stick to the top and bottom, and you could have custom margins if you wanted.

How to convert array into comma separated string in javascript

You can simply use JavaScripts join() function for that. This would simply look like a.value.join(','). The output would be a string though.

Using JQuery to check if no radio button in a group has been checked

if ($("input[name='html_elements']:checked").size()==0) {
   alert('Nothing is checked!');
}
else {
  alert('One of the radio buttons is checked!');
}

Set mouse focus and move cursor to end of input using jQuery

It will be different for different browsers:

This works in ff:

    var t =$("#INPUT");
    var l=$("#INPUT").val().length;
    $(t).focus();

    var r = $("#INPUT").get(0).createTextRange();
    r.moveStart("character", l); 
    r.moveEnd("character", l);      
    r.select();

More details are in these articles here at SitePoint, AspAlliance.

Spring Data: "delete by" is supported?

Be carefull when you use derived query for batch delete. It isn't what you expect: DeleteExecution

NHibernate.MappingException: No persister for: XYZ

Spending about 4 hours on googling and stackoverflowing, trying all of stuff around there, i've found my error:

My mapping file was called .nbm.xml instead of .hbm.xml. That was insane.

How do I add one month to current date in Java?

Calendar cal = Calendar.getInstance(); 
cal.add(Calendar.MONTH, 1);

How can we dynamically allocate and grow an array

Take a look at implementation of Java ArrayList. Java ArrayList internally uses a fixed size array and reallocates the array once number of elements exceed current size. You can also implement on similar lines.

calling server side event from html button control

If you are OK with converting the input button to a server side control by specifying runat="server", and you are using asp.net, an option could be using the HtmlButton.OnServerClick property.

<input id="foo "runat="server" type="button" onserverclick="foo_OnClick" />

This should work and call foo_OnClick in your server side code. Also notice that based on Microsoft documentation linked above, you should also be able to use the HTML 4.0 tag.

"Exception has been thrown by the target of an invocation" error (mscorlib)

This is may have 2 reasons

1.I found the connection string error in my web.config file i had changed the connection string and its working.

  1. Connection string is proper then check with the control panel>services> SQL Server Browser > start or not

JavaScript math, round to two decimal places

To get the result with two decimals, you can do like this :

var discount = Math.round((100 - (price / listprice) * 100) * 100) / 100;

The value to be rounded is multiplied by 100 to keep the first two digits, then we divide by 100 to get the actual result.

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

A typical algo for tic-tac-toe should look like this:

Board : A nine-element vector representing the board. We store 2 (indicating Blank), 3 (indicating X), or 5 (indicating O). Turn: An integer indicating which move of the game about to be played. The 1st move will be indicated by 1, last by 9.

The Algorithm

The main algorithm uses three functions.

Make2: returns 5 if the center square of the board is blank i.e. if board[5]=2. Otherwise, this function returns any non-corner square (2, 4, 6 or 8).

Posswin(p): Returns 0 if player p can’t win on his next move; otherwise, it returns the number of the square that constitutes a winning move. This function will enable the program both to win and to block opponents win. This function operates by checking each of the rows, columns, and diagonals. By multiplying the values of each square together for an entire row (or column or diagonal), the possibility of a win can be checked. If the product is 18 (3 x 3 x 2), then X can win. If the product is 50 (5 x 5 x 2), then O can win. If a winning row (column or diagonal) is found, the blank square in it can be determined and the number of that square is returned by this function.

Go (n): makes a move in square n. this procedure sets board [n] to 3 if Turn is odd, or 5 if Turn is even. It also increments turn by one.

The algorithm has a built-in strategy for each move. It makes the odd numbered move if it plays X, the even-numbered move if it plays O.

Turn = 1    Go(1)   (upper left corner).
Turn = 2    If Board[5] is blank, Go(5), else Go(1).
Turn = 3    If Board[9] is blank, Go(9), else Go(3).
Turn = 4    If Posswin(X) is not 0, then Go(Posswin(X)) i.e. [ block opponent’s win], else Go(Make2).
Turn = 5    if Posswin(X) is not 0 then Go(Posswin(X)) [i.e. win], else if Posswin(O) is not 0, then Go(Posswin(O)) [i.e. block win], else if Board[7] is blank, then Go(7), else Go(3). [to explore other possibility if there be any ].
Turn = 6    If Posswin(O) is not 0 then Go(Posswin(O)), else if Posswin(X) is not 0, then Go(Posswin(X)), else Go(Make2).
Turn = 7    If Posswin(X) is not 0 then Go(Posswin(X)), else if Posswin(X) is not 0, then Go(Posswin(O)) else go anywhere that is blank.
Turn = 8    if Posswin(O) is not 0 then Go(Posswin(O)), else if Posswin(X) is not 0, then Go(Posswin(X)), else go anywhere that is blank.
Turn = 9    Same as Turn=7.

I have used it. Let me know how you guys feel.

Number of days between past date and current date in Google spreadsheet

Since this is the top Google answer for this, and it was way easier than I expected, here is the simple answer. Just subtract date1 from date2.

If this is your spreadsheet dates

     A            B
1 10/11/2017  12/1/2017

=(B1)-(A1)

results in 51, which is the number of days between a past date and a current date in Google spreadsheet

As long as it is a date format Google Sheets recognizes, you can directly subtract them and it will be correct.

To do it for a current date, just use the =TODAY() function.

=TODAY()-A1

While today works great, you can't use a date directly in the formula, you should referencing a cell that contains a date.

=(12/1/2017)-(10/1/2017) results in 0.0009915716411, not 61.

new Runnable() but no new thread?

Runnable is often used to provide the code that a thread should run, but Runnable itself has nothing to do with threads. It's just an object with a run() method.

In Android, the Handler class can be used to ask the framework to run some code later on the same thread, rather than on a different one. Runnable is used to provide the code that should run later.

AngularJS : automatically detect change in model

In views with {{}} and/or ng-model, Angular is setting up $watch()es for you behind the scenes.

By default $watch compares by reference. If you set the third parameter to $watch to true, Angular will instead "shallow" watch the object for changes. For arrays this means comparing the array items, for object maps this means watching the properties. So this should do what you want:

$scope.$watch('myModel', function() { ... }, true);

Update: Angular v1.2 added a new method for this, `$watchCollection():

$scope.$watchCollection('myModel', function() { ... });

Note that the word "shallow" is used to describe the comparison rather than "deep" because references are not followed -- e.g., if the watched object contains a property value that is a reference to another object, that reference is not followed to compare the other object.

The requested URL /about was not found on this server

That's not a typical Wordpress rewrite block. This is:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

See http://codex.wordpress.org/Using_Permalinks#Where.27s_my_.htaccess_file.3F

Where's my .htaccess file? WordPress's index.php and .htaccess files should be together in the directory indicated by the Site address (URL) setting on your General Options page. Since the name of the file begins with a dot, the file may not be visible through an FTP client unless you change the preferences of the FTP tool to show all files, including the hidden files. Some hosts (e.g. Godaddy) may not show or allow you to edit .htaccess if you install WordPress through the Godaddy Hosting Connection installation.

Creating and editing (.htaccess) If you do not already have a .htaccess file, create one. If you have shell or ssh access to the server, a simple touch .htaccess command will create the file. If you are using FTP to transfer files, create a file on your local computer, call it 1.htaccess, upload it to the root of your WordPress folder, and then rename it to .htaccess.

You can edit the .htaccess file by FTP, shell, or (possibly) your host's control panel.

The easiest and fastest thing to do it reset your permalinks in Dashboard>>Settings>>Permalinks and make sure .htaccess is writable so WordPress can write the rules itself.

And: are you aware you are calling index.cgi as your default document rather than index.php? That's wrong. Remove index.cgi. Or try removing the whole line, too, because defining a default doc on your server may not be needed.

Which are more performant, CTE or temporary tables?

One use where I found CTE's excelled performance wise was where I needed to join a relatively complex Query on to a few tables which had a few million rows each.

I used the CTE to first select the subset based of the indexed columns to first cut these tables down to a few thousand relevant rows each and then joined the CTE to my main query. This exponentially reduced the runtime of my query.

Whilst results for the CTE are not cached and table variables might have been a better choice I really just wanted to try them out and found the fit the above scenario.

Change value of input onchange?

You can't access your fieldname as a global variable. Use document.getElementById:

function updateInput(ish){
    document.getElementById("fieldname").value = ish;
}

and

onchange="updateInput(this.value)"

Python 2.6: Class inside a Class?

class Second:
    def __init__(self, data):
        self.data = data

class First:
    def SecondClass(self, data):
        return Second(data)

FirstClass = First()
SecondClass = FirstClass.SecondClass('now you see me')
print SecondClass.data

How to find largest objects in a SQL Server database?

In SQL Server 2008, you can also just run the standard report Disk Usage by Top Tables. This can be found by right clicking the DB, selecting Reports->Standard Reports and selecting the report you want.

fastest MD5 Implementation in JavaScript

Just for fun,

this one is 42 lines long, fits in 120 characters horizontally, and looks good. Is it fast? Well - it's fast enough and it's approximately the same as all other JS implementations.

I just wanted something that doesn't look ugly in my helpers.js file and doesn't slow down my SublimeText with 20-mile long minified one-liners.

So here's my favourite md5.

//  A formatted version of a popular md5 implementation.
//  Original copyright (c) Paul Johnston & Greg Holt.
//  The function itself is now 42 lines long.

function md5(inputString) {
    var hc="0123456789abcdef";
    function rh(n) {var j,s="";for(j=0;j<=3;j++) s+=hc.charAt((n>>(j*8+4))&0x0F)+hc.charAt((n>>(j*8))&0x0F);return s;}
    function ad(x,y) {var l=(x&0xFFFF)+(y&0xFFFF);var m=(x>>16)+(y>>16)+(l>>16);return (m<<16)|(l&0xFFFF);}
    function rl(n,c)            {return (n<<c)|(n>>>(32-c));}
    function cm(q,a,b,x,s,t)    {return ad(rl(ad(ad(a,q),ad(x,t)),s),b);}
    function ff(a,b,c,d,x,s,t)  {return cm((b&c)|((~b)&d),a,b,x,s,t);}
    function gg(a,b,c,d,x,s,t)  {return cm((b&d)|(c&(~d)),a,b,x,s,t);}
    function hh(a,b,c,d,x,s,t)  {return cm(b^c^d,a,b,x,s,t);}
    function ii(a,b,c,d,x,s,t)  {return cm(c^(b|(~d)),a,b,x,s,t);}
    function sb(x) {
        var i;var nblk=((x.length+8)>>6)+1;var blks=new Array(nblk*16);for(i=0;i<nblk*16;i++) blks[i]=0;
        for(i=0;i<x.length;i++) blks[i>>2]|=x.charCodeAt(i)<<((i%4)*8);
        blks[i>>2]|=0x80<<((i%4)*8);blks[nblk*16-2]=x.length*8;return blks;
    }
    var i,x=sb(inputString),a=1732584193,b=-271733879,c=-1732584194,d=271733878,olda,oldb,oldc,oldd;
    for(i=0;i<x.length;i+=16) {olda=a;oldb=b;oldc=c;oldd=d;
        a=ff(a,b,c,d,x[i+ 0], 7, -680876936);d=ff(d,a,b,c,x[i+ 1],12, -389564586);c=ff(c,d,a,b,x[i+ 2],17,  606105819);
        b=ff(b,c,d,a,x[i+ 3],22,-1044525330);a=ff(a,b,c,d,x[i+ 4], 7, -176418897);d=ff(d,a,b,c,x[i+ 5],12, 1200080426);
        c=ff(c,d,a,b,x[i+ 6],17,-1473231341);b=ff(b,c,d,a,x[i+ 7],22,  -45705983);a=ff(a,b,c,d,x[i+ 8], 7, 1770035416);
        d=ff(d,a,b,c,x[i+ 9],12,-1958414417);c=ff(c,d,a,b,x[i+10],17,     -42063);b=ff(b,c,d,a,x[i+11],22,-1990404162);
        a=ff(a,b,c,d,x[i+12], 7, 1804603682);d=ff(d,a,b,c,x[i+13],12,  -40341101);c=ff(c,d,a,b,x[i+14],17,-1502002290);
        b=ff(b,c,d,a,x[i+15],22, 1236535329);a=gg(a,b,c,d,x[i+ 1], 5, -165796510);d=gg(d,a,b,c,x[i+ 6], 9,-1069501632);
        c=gg(c,d,a,b,x[i+11],14,  643717713);b=gg(b,c,d,a,x[i+ 0],20, -373897302);a=gg(a,b,c,d,x[i+ 5], 5, -701558691);
        d=gg(d,a,b,c,x[i+10], 9,   38016083);c=gg(c,d,a,b,x[i+15],14, -660478335);b=gg(b,c,d,a,x[i+ 4],20, -405537848);
        a=gg(a,b,c,d,x[i+ 9], 5,  568446438);d=gg(d,a,b,c,x[i+14], 9,-1019803690);c=gg(c,d,a,b,x[i+ 3],14, -187363961);
        b=gg(b,c,d,a,x[i+ 8],20, 1163531501);a=gg(a,b,c,d,x[i+13], 5,-1444681467);d=gg(d,a,b,c,x[i+ 2], 9,  -51403784);
        c=gg(c,d,a,b,x[i+ 7],14, 1735328473);b=gg(b,c,d,a,x[i+12],20,-1926607734);a=hh(a,b,c,d,x[i+ 5], 4,    -378558);
        d=hh(d,a,b,c,x[i+ 8],11,-2022574463);c=hh(c,d,a,b,x[i+11],16, 1839030562);b=hh(b,c,d,a,x[i+14],23,  -35309556);
        a=hh(a,b,c,d,x[i+ 1], 4,-1530992060);d=hh(d,a,b,c,x[i+ 4],11, 1272893353);c=hh(c,d,a,b,x[i+ 7],16, -155497632);
        b=hh(b,c,d,a,x[i+10],23,-1094730640);a=hh(a,b,c,d,x[i+13], 4,  681279174);d=hh(d,a,b,c,x[i+ 0],11, -358537222);
        c=hh(c,d,a,b,x[i+ 3],16, -722521979);b=hh(b,c,d,a,x[i+ 6],23,   76029189);a=hh(a,b,c,d,x[i+ 9], 4, -640364487);
        d=hh(d,a,b,c,x[i+12],11, -421815835);c=hh(c,d,a,b,x[i+15],16,  530742520);b=hh(b,c,d,a,x[i+ 2],23, -995338651);
        a=ii(a,b,c,d,x[i+ 0], 6, -198630844);d=ii(d,a,b,c,x[i+ 7],10, 1126891415);c=ii(c,d,a,b,x[i+14],15,-1416354905);
        b=ii(b,c,d,a,x[i+ 5],21,  -57434055);a=ii(a,b,c,d,x[i+12], 6, 1700485571);d=ii(d,a,b,c,x[i+ 3],10,-1894986606);
        c=ii(c,d,a,b,x[i+10],15,   -1051523);b=ii(b,c,d,a,x[i+ 1],21,-2054922799);a=ii(a,b,c,d,x[i+ 8], 6, 1873313359);
        d=ii(d,a,b,c,x[i+15],10,  -30611744);c=ii(c,d,a,b,x[i+ 6],15,-1560198380);b=ii(b,c,d,a,x[i+13],21, 1309151649);
        a=ii(a,b,c,d,x[i+ 4], 6, -145523070);d=ii(d,a,b,c,x[i+11],10,-1120210379);c=ii(c,d,a,b,x[i+ 2],15,  718787259);
        b=ii(b,c,d,a,x[i+ 9],21, -343485551);a=ad(a,olda);b=ad(b,oldb);c=ad(c,oldc);d=ad(d,oldd);
    }
    return rh(a)+rh(b)+rh(c)+rh(d);
}

But really, I posted it merely out of aesthetic considerations. Also, with the comments it's exactly 4000 bytes. Please don't ask why. I can't come up with a proper explanation for my OCD/rebel behaviour. Also, thank you Paul Johnston, thank you Greg Holt. (Side note: you guys omitted a few var keywords so I took the liberty of adding them.)

Convert ArrayList<String> to String[] array

Try this

String[] arr = list.toArray(new String[list.size()]);

How can I append a string to an existing field in MySQL?

You need to use the CONCAT() function in MySQL for string concatenation:

UPDATE categories SET code = CONCAT(code, '_standard') WHERE id = 1;

Parsing jQuery AJAX response

you must parse JSON string to become object

var dataObject = jQuery.parseJSON(data);

so you can call it like:

success: function (data) {
    var dataObject = jQuery.parseJSON(data);
    if (dataObject.success == 1) {
       var insertedGoalId = dataObject.inserted.goal_id;
       ...
       ...
    }
}

Why dividing two integers doesn't get a float?

Dividing two integers will result in an integer (whole number) result.

You need to cast one number as a float, or add a decimal to one of the numbers, like a/350.0.

How to check if the request is an AJAX request with PHP

From PHP 7 with null coalescing operator it will be shorter:

$is_ajax = 'xmlhttprequest' == strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '' );

Rails server says port already used, how to kill that process?

To kill process on a specific port, you can try this

npx kill-port [port-number]

In Perl, how to remove ^M from a file?

I prefer a more general solution that will work with either DOS or Unix input. Assuming the input is from STDIN:

while (defined(my $ln = <>))
  {
    chomp($ln);
    chop($ln) if ($ln =~ m/\r$/);

    # filter and write
  }

How can I make my custom objects Parcelable?

Here is a website to create a Parcelable Class from your created class:

http://www.parcelabler.com/

Push to GitHub without a password using ssh-key

Additionally for gists, it seems you must leave out the username

git remote set-url origin [email protected]:<Project code>

How to square or raise to a power (elementwise) a 2D numpy array?

The fastest way is to do a*a or a**2 or np.square(a) whereas np.power(a, 2) showed to be considerably slower.

np.power() allows you to use different exponents for each element if instead of 2 you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2 or a*a, which become important in cases where you have small tolerances.

I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:

In [29]: a = np.random.random((1000, 1000))

In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop

In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop

In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop

Python For loop get index

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

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

Convert the values in a column into row names in an existing data frame

in one line

> samp.with.rownames <- data.frame(samp[,-1], row.names=samp[,1])

SQL query to group by day

For oracle you can

group by trunc(created);

as this truncates the created datetime to the previous midnight.

Another option is to

group by to_char(created, 'DD.MM.YYYY');

which achieves the same result, but may be slower as it requires a type conversion.

How to implement "confirmation" dialog in Jquery UI dialog?

Another variation of the above where it checks if the control is either a 'asp:linkbutton' or 'asp:button' which renders as two different html controls. Seems to work just fine for me but haven't tested it extensively.

        $(document).on("click", ".confirm", function (e) {
            e.preventDefault();
            var btn = $(this);
            $("#dialog").dialog('option', 'buttons', {
                "Confirm": function () {
                    if (btn.is("input")) {                            
                        var name = btn.attr("name");
                        __doPostBack(name, '')
                    }
                    else {
                        var href = btn.attr("href");
                        window.location.href = href;
                    }
                    $(this).dialog("close");
                },
                "Cancel": function () {
                    $(this).dialog("close");
                }
            });

            $("#dialog").dialog("open");
        });

Convert pandas.Series from dtype object to float, and errors to nans

Use pd.to_numeric with errors='coerce'

# Setup
s = pd.Series(['1', '2', '3', '4', '.'])
s

0    1
1    2
2    3
3    4
4    .
dtype: object

pd.to_numeric(s, errors='coerce')

0    1.0
1    2.0
2    3.0
3    4.0
4    NaN
dtype: float64

If you need the NaNs filled in, use Series.fillna.

pd.to_numeric(s, errors='coerce').fillna(0, downcast='infer')

0    1
1    2
2    3
3    4
4    0
dtype: float64

Note, downcast='infer' will attempt to downcast floats to integers where possible. Remove the argument if you don't want that.

From v0.24+, pandas introduces a Nullable Integer type, which allows integers to coexist with NaNs. If you have integers in your column, you can use

pd.__version__
# '0.24.1'

pd.to_numeric(s, errors='coerce').astype('Int32')

0      1
1      2
2      3
3      4
4    NaN
dtype: Int32

There are other options to choose from as well, read the docs for more.


Extension for DataFrames

If you need to extend this to DataFrames, you will need to apply it to each row. You can do this using DataFrame.apply.

# Setup.
np.random.seed(0)
df = pd.DataFrame({
    'A' : np.random.choice(10, 5), 
    'C' : np.random.choice(10, 5), 
    'B' : ['1', '###', '...', 50, '234'], 
    'D' : ['23', '1', '...', '268', '$$']}
)[list('ABCD')]
df

   A    B  C    D
0  5    1  9   23
1  0  ###  3    1
2  3  ...  5  ...
3  3   50  2  268
4  7  234  4   $$

df.dtypes

A     int64
B    object
C     int64
D    object
dtype: object

df2 = df.apply(pd.to_numeric, errors='coerce')
df2

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

df2.dtypes

A      int64
B    float64
C      int64
D    float64
dtype: object

You can also do this with DataFrame.transform; although my tests indicate this is marginally slower:

df.transform(pd.to_numeric, errors='coerce')

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

If you have many columns (numeric; non-numeric), you can make this a little more performant by applying pd.to_numeric on the non-numeric columns only.

df.dtypes.eq(object)

A    False
B     True
C    False
D     True
dtype: bool

cols = df.columns[df.dtypes.eq(object)]
# Actually, `cols` can be any list of columns you need to convert.
cols
# Index(['B', 'D'], dtype='object')

df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
# Alternatively,
# for c in cols:
#     df[c] = pd.to_numeric(df[c], errors='coerce')

df

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

Applying pd.to_numeric along the columns (i.e., axis=0, the default) should be slightly faster for long DataFrames.

Allow only numbers to be typed in a textbox

With HTML5 you can do

<input type="number">

You can also use a regex pattern to limit the input text.

<input type="text" pattern="^[0-9]*$" />

How do I decode a URL parameter using C#?

Server.UrlDecode(xxxxxxxx)

Replace text in HTML page with jQuery

var replaced = $("body").html().replace(/-1o9-2202/g,'The ALL new string');
$("body").html(replaced);

for variable:

var replaced = $("body").html().replace(new RegExp("-1o9-2202", "igm"),'The ALL new string');
$("body").html(replaced);

Manually adding a Userscript to Google Chrome

Update 2016: seems to be working again.

Update August 2014: No longer works as of recent Chrome versions.


Yeah, the new state of affairs sucks. Fortunately it's not so hard as the other answers imply.

  1. Browse in Chrome to chrome://extensions
  2. Drag the .user.js file into that page.

Voila. You can also drag files from the downloads footer bar to the extensions tab.

Chrome will automatically create a manifest.json file in the extensions directory that Brock documented.

<3 Freedom.

How to create a stopwatch using JavaScript?

Please see stopwatch.js for a very clean and simple Vanilla Javascript ES6 solution.

Android Studio: Application Installation Failed

if your "versionCode" in build.gradle file is less than the eralier version code then, your app wont install. Try to install with same "version code" or more than that.

Memory address of an object in C#

Switch the alloc type:

GCHandle handle = GCHandle.Alloc(a, GCHandleType.Normal);

Pure Javascript listen to input value change

instead of id use title to identify your element and write the code as below.

$(document).ready(()=>{

 $("input[title='MyObject']").change(()=>{
        console.log("Field has been changed...")
    })  
});

How to install mod_ssl for Apache httpd?

Are any other LoadModule commands referencing modules in the /usr/lib/httpd/modules folder? If so, you should be fine just adding LoadModule ssl_module /usr/lib/httpd/modules/mod_ssl.so to your conf file.

Otherwise, you'll want to copy the mod_ssl.so file to whatever directory the other modules are being loaded from and reference it there.

Operation is not valid due to the current state of the object, when I select a dropdown list

From http://codecorner.galanter.net/2012/06/04/solution-for-operation-is-not-valid-due-to-the-current-state-of-the-object-error/

Issue happens because Microsoft Security Update MS11-100 limits number of keys in Forms collection during HTTP POST request. To alleviate this problem you need to increase that number.

This can be done in your application Web.Config in the <appSettings> section (create the section directly under <configuration> if it doesn’t exist). Add 2 lines similar to the lines below to the section:

<add key="aspnet:MaxHttpCollectionKeys" value="2000" />
<add key="aspnet:MaxJsonDeserializerMembers" value="2000" />

The above example set the limit to 2000 keys. This will lift the limitation and the error should go away.

Uncaught SyntaxError: Unexpected token with JSON.parse

It seems you want to stringify the object. So do this:

JSON.stringify(products);

The reason for the error is that JSON.parse() expects a String value and products is an Array.

Note: I think it attempts json.parse('[object Array]') which complains it didn't expect token o after [.

Batch File; List files in directory, only filenames?

Windows 10:

  1. open cmd

  2. change directory where you want to create text file(movie_list.txt) for the folder (d:\videos\movies)

  3. type following command

    d:\videos\movies> dir /b /a-d > movie_list.txt

How to open an Excel file in C#?

It's easier to help you if you say what's wrong as well, or what fails when you run it.

But from a quick glance you've confused a few things.

The following doesn't work because of a couple of issues.

if (Directory("C:\\csharp\\error report1.xls") = "")

What you are trying to do is creating a new Directory object that should point to a file and then check if there was any errors.

What you are actually doing is trying to call a function named Directory() and then assign a string to the result. This won't work since 1/ you don't have a function named Directory(string str) and you cannot assign to the result from a function (you can only assign a value to a variable).

What you should do (for this line at least) is the following

FileInfo fi = new FileInfo("C:\\csharp\\error report1.xls");
if(!fi.Exists)
{
    // Create the xl file here
}
else
{
    // Open file here
}

As to why the Excel code doesn't work, you have to check the documentation for the Excel library which google should be able to provide for you.

Javascript: how to validate dates in format MM-DD-YYYY?

I would use Moment.js for this task. It makes it very easy to parse dates and it also provides support to detect a an invalid date1 in the correct format. For instance, consider this example:

var formats = ['MM-DD-YYYY', 'MM/DD/YYYY']

moment('11/28/1981', formats).isValid()  // true
moment('2-29-2003', formats).isValid()   // false (not leap year)
moment('2-29-2004', formats).isValid()   // true  (leap year)

First moment(.., formats) is used to parse the input according to the localized format supplied. Then the isValid function is called on the resulting moment object so that we can actually tell if it is a valid date.

This can be used to trivially derive the isValidDate method:

String.prototype.isValidDate = function() {
    var formats = ['MM-DD-YYYY', 'MM/DD/YYYY'];
    return moment("" + this, formats).isValid();
}

1 As I can find scarce little commentary on the matter, I would only use moment.js for dates covered by the Gregorian calendar. There may be plugins for other (including historical or scientific) calendars.

@selector() in Swift?

Swift 4.0

you create the Selector like below.

1.add the event to a button like:

button.addTarget(self, action: #selector(clickedButton(sender:)), for: UIControlEvents.touchUpInside)

and the function will be like below:

@objc func clickedButton(sender: AnyObject) {

}

How many threads can a Java VM support?

After reading Charlie Martin's post, I was curious about whether the heap size makes any difference in the number of threads you can create, and I was totally dumbfounded by the result.

Using JDK 1.6.0_11 on Vista Home Premium SP1, I executed Charlie's test application with different heap sizes, between 2 MB and 1024 MB.

For example, to create a 2 MB heap, I'd invoke the JVM with the arguments -Xms2m -Xmx2m.

Here are my results:

2 mb --> 5744 threads
4 mb --> 5743 threads
8 mb --> 5735 threads
12 mb --> 5724 threads
16 mb --> 5712 threads
24 mb --> 5687 threads
32 mb --> 5662 threads
48 mb --> 5610 threads
64 mb --> 5561 threads
96 mb --> 5457 threads
128 mb --> 5357 threads
192 mb --> 5190 threads
256 mb --> 5014 threads
384 mb --> 4606 threads
512 mb --> 4202 threads
768 mb --> 3388 threads
1024 mb --> 2583 threads

So, yeah, the heap size definitely matters. But the relationship between heap size and maximum thread count is INVERSELY proportional.

Which is weird.

Do I use <img>, <object>, or <embed> for SVG files?

In most circumstances, I recommend using the <object> tag to display SVG images. It feels a little unnatural, but it's the most reliable method if you want to provide dynamic effects.

For images without interaction, the <img> tag or a CSS background can be used.

Inline SVGs or iframes are possible options for some projects, but it's best to avoid <embed>

But if you want to play with SVG stuff like

  • Changing colors
  • Resize path
  • rotate svg

Go with the embedded one

<svg>
    <g> 
        <path> </path>
    </g>
</svg>

How can I strip all punctuation from a string in JavaScript using regex?

As per Wikipedia's list of punctuations I had to build the following regex which detects punctuations :

[\.’'\[\](){}??:,??-–—-…!.‹›«»-\-?‘’“”'";//·\&*@\•^†‡°”¡¿?#?÷׺ª%‰+-=?¶'"?§~_|?¦©?®?™¤???¢¢?$????€ƒ??????M??P??£?????????¥]

Finding the number of days between two dates

If you're using PHP 5.3 >, this is by far the most accurate way of calculating the difference:

$earlier = new DateTime("2010-07-06");
$later = new DateTime("2010-07-09");

$diff = $later->diff($earlier)->format("%a");

How to use OpenFileDialog to select a folder?

this should be the most obvious and straight forward way

using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
{

   System.Windows.Forms.DialogResult result = dialog.ShowDialog();

   if(result == System.Windows.Forms.DialogResult.OK)
   {
      selectedFolder = dialog.SelectedPath;
   }

}

How do I get a div to float to the bottom of its container?

I got this to work on the first try by adding position:absolute; bottom:0; to the div ID inside the CSS. I did not add the parent style position:relative;.

It is working perfect in both Firefox and IE 8, have not tried it in IE 7 yet.

Selenium wait until document is ready

The wait for the document.ready event is not the entire fix to this problem, because this code is still in a race condition: Sometimes this code is fired before the click event is processed so this directly returns, since the browser hasn't started loading the new page yet.

After some searching I found a post on Obay the testing goat, which has a solution for this problem. The c# code for that solution is something like this:

 IWebElement page = null;
 ...
 public void WaitForPageLoad()
 {
    if (page != null)
    {
       var waitForCurrentPageToStale = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
       waitForCurrentPageToStale.Until(ExpectedConditions.StalenessOf(page));
    }

    var waitForDocumentReady = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
    waitForDocumentReady.Until((wdriver) => (driver as IJavaScriptExecutor).ExecuteScript("return document.readyState").Equals("complete"));

    page = driver.FindElement(By.TagName("html"));

}

` I fire this method directly after the driver.navigate.gotourl, so that it gets a reference of the page as soon as possible. Have fun with it!

Custom HTTP headers : naming conventions

Modifying, or more correctly, adding additional HTTP headers is a great code debugging tool if nothing else.

When a URL request returns a redirect or an image there is no html "page" to temporarily write the results of debug code to - at least not one that is visible in a browser.

One approach is to write the data to a local log file and view that file later. Another is to temporarily add HTTP headers reflecting the data and variables being debugged.

I regularly add extra HTTP headers like X-fubar-somevar: or X-testing-someresult: to test things out - and have found a lot of bugs that would have otherwise been very difficult to trace.

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

I benchmarked the suggested with perfplot and found that the good old

temp = x.copy()
temp.update(y)

is the fastest solution together with the new

x | y

enter image description here


Code to reproduce the plot:

from collections import ChainMap
from itertools import chain
import perfplot


def setup(n):
    x = dict(zip(range(n), range(n)))
    y = dict(zip(range(n, 2 * n), range(n, 2 * n)))
    return x, y


def copy_update(data):
    x, y = data
    temp = x.copy()
    temp.update(y)
    return temp


def add_items(data):
    x, y = data
    return dict(list(x.items()) + list(y.items()))


def curly_star(data):
    x, y = data
    return {**x, **y}


def chain_map(data):
    x, y = data
    return dict(ChainMap({}, y, x))


def itertools_chain(data):
    x, y = data
    return dict(chain(x.items(), y.items()))


def python39_concat(data):
    x, y = data
    return x | y


perfplot.show(
    setup=setup,
    kernels=[
        copy_update,
        add_items,
        curly_star,
        chain_map,
        itertools_chain,
        python39_concat,
    ],
    labels=[
        "copy_update",
        "dict(list(x.items()) + list(y.items()))",
        "{**x, **y}",
        "chain_map",
        "itertools.chain",
        "x | y",
    ],
    n_range=[2 ** k for k in range(15)],
    xlabel="len(x), len(y)",
    equality_check=None,
)

How do I POST XML data with curl

You can try the following solution:

curl -v -X POST -d @payload.xml https://<API Path> -k -H "Content-Type: application/xml;charset=utf-8"

DLL Load Library - Error Code 126

This error can happen because some MFC library (eg. mfc120.dll) from which the DLL is dependent is missing in windows/system32 folder.

Convert a String to Modified Camel Case in Java or Title Case as is otherwise called

From commons-lang3

org.apache.commons.lang3.text.WordUtils.capitalizeFully(String str)

Export tables to an excel spreadsheet in same directory

For people who find this via search engines, you do not need VBA. You can just:

1.) select the query or table with your mouse
2.) click export data from the ribbon
3.) click excel from the export subgroup
4.) follow the wizard to select the output file and location.

top nav bar blocking top content of the page

Add this:

.navbar {
  position: relative;
}

PHP passing $_GET in linux command prompt

php -r 'parse_str($argv[2],$_GET);include $argv[1];' index.php 'a=1&b=2'

You could make the first part as an alias:

alias php-get='php -r '\''parse_str($argv[2],$_GET);include $argv[1];'\'

then simply use:

php-get some_script.php 'a=1&b=2&c=3'

How does the "position: sticky;" property work?

if danday74's fix doesn't work, check that the parent element has a height.

In my case I had two childs, one floating left and one floating right. I wanted the right floating one to become sticky but had to add a <div style="clear: both;"></div> at the end of the parent, to give it height.

rename the columns name after cbind the data

you gave the following example in your question:

colnames(merger)[,1]<-"Date"

the problem is the comma: colnames() returns a vector, not a matrix, so the solution is:

colnames(merger)[1]<-"Date"

ResultSet exception - before start of result set

You have to call next() before you can start reading values from the first row. beforeFirst puts the cursor before the first row, so there's no data to read.

Toggle Class in React

You have to use the component's State to update component parameters such as Class Name if you want React to render your DOM correctly and efficiently.

UPDATE: I updated the example to toggle the Sidemenu on a button click. This is not necessary, but you can see how it would work. You might need to use "this.state" vs. "this.props" as I have shown. I'm used to working with Redux components.

constructor(props){
    super(props);
}

getInitialState(){
  return {"showHideSidenav":"hidden"};
}

render() {
    return (
        <div className="header">
            <i className="border hide-on-small-and-down"></i>
            <div className="container">
                <a ref="btn" onClick={this.toggleSidenav.bind(this)} href="#" className="btn-menu show-on-small"><i></i></a>
                <Menu className="menu hide-on-small-and-down"/>
                <Sidenav className={this.props.showHideSidenav}/>
            </div>
        </div>
    )
}

toggleSidenav() {
    var css = (this.props.showHideSidenav === "hidden") ? "show" : "hidden";
    this.setState({"showHideSidenav":css});
}

Now, when you toggle the state, the component will update and change the class name of the sidenav component. You can use CSS to show/hide the sidenav using the class names.

.hidden {
   display:none;
}
.show{
   display:block;
}

Making a POST call instead of GET using urllib2

it should be sending a POST if you provide a data parameter (like you are doing):

from the docs: "the HTTP request will be a POST instead of a GET when the data parameter is provided"

so.. add some debug output to see what's up from the client side.

you can modify your code to this and try again:

import urllib
import urllib2

url = 'http://myserver/post_service'
opener = urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1))
data = urllib.urlencode({'name' : 'joe',
                         'age'  : '10'})
content = opener.open(url, data=data).read()

AES Encryption for an NSString on the iPhone

I have put together a collection of categories for NSData and NSString which uses solutions found on Jeff LaMarche's blog and some hints by Quinn Taylor here on Stack Overflow.

It uses categories to extend NSData to provide AES256 encryption and also offers an extension of NSString to BASE64-encode encrypted data safely to strings.

Here's an example to show the usage for encrypting strings:

NSString *plainString = @"This string will be encrypted";
NSString *key = @"YourEncryptionKey"; // should be provided by a user

NSLog( @"Original String: %@", plainString );

NSString *encryptedString = [plainString AES256EncryptWithKey:key];
NSLog( @"Encrypted String: %@", encryptedString );

NSLog( @"Decrypted String: %@", [encryptedString AES256DecryptWithKey:key] );

Get the full source code here:

https://gist.github.com/838614

Thanks for all the helpful hints!

-- Michael

What are all the different ways to create an object in Java?

Also you can use

 Object myObj = Class.forName("your.cClass").newInstance();

Remove certain characters from a string

One issue with REPLACE will be where city names contain the district name. You can use something like.

SELECT SUBSTRING(O.Ort, LEN(C.CityName) + 2, 8000)
FROM   dbo.tblOrtsteileGeo O
       JOIN dbo.Cities C
         ON C.foo = O.foo
WHERE  O.GKZ = '06440004' 

Nested rows with bootstrap grid system?

Adding to what @KyleMit said, consider using:

  • col-md-* classes for the larger outer columns
  • col-xs-* classes for the smaller inner columns

This will be useful when you view the page on different screen sizes.

On a small screen, the wrapping of larger outer columns will then happen while maintaining the smaller inner columns, if possible

Angular2 Material Dialog css, dialog size

dialog-component.css

This code works perfectly for me, other solutions don't work. Use the ::ng-deep shadow-piercing descendant combinator to force a style down through the child component tree into all the child component views. The ::ng-deep combinator works to any depth of nested components, and it applies to both the view children and content children of the component.

 ::ng-deep .mat-dialog-container {
    height: 400px !important;
    width: 400px !important;
}

When to use in vs ref vs out

You need to use ref if you plan to read and write to the parameter. You need to use out if you only plan to write. In effect, out is for when you'd need more than one return value, or when you don't want to use the normal return mechanism for output (but this should be rare).

There are language mechanics that assist these use cases. Ref parameters must have been initialized before they are passed to a method (putting emphasis on the fact that they are read-write), and out parameters cannot be read before they are assigned a value, and are guaranteed to have been written to at the end of the method (putting emphasis on the fact that they are write only). Contravening to these principles results in a compile-time error.

int x;
Foo(ref x); // error: x is uninitialized

void Bar(out int x) {}  // error: x was not written to

For instance, int.TryParse returns a bool and accepts an out int parameter:

int value;
if (int.TryParse(numericString, out value))
{
    /* numericString was parsed into value, now do stuff */
}
else
{
    /* numericString couldn't be parsed */
}

This is a clear example of a situation where you need to output two values: the numeric result and whether the conversion was successful or not. The authors of the CLR decided to opt for out here since they don't care about what the int could have been before.

For ref, you can look at Interlocked.Increment:

int x = 4;
Interlocked.Increment(ref x);

Interlocked.Increment atomically increments the value of x. Since you need to read x to increment it, this is a situation where ref is more appropriate. You totally care about what x was before it was passed to Increment.

In the next version of C#, it will even be possible to declare variable in out parameters, adding even more emphasis on their output-only nature:

if (int.TryParse(numericString, out int value))
{
    // 'value' exists and was declared in the `if` statement
}
else
{
    // conversion didn't work, 'value' doesn't exist here
}

Typing the Enter/Return key using Python and Selenium

For Ruby:

driver.find_element(:id, "XYZ").send_keys:return

Setting a max character length in CSS

Try this for truncating characters after setting it to max-width. I have used 75ch in this case

_x000D_
_x000D_
p {_x000D_
    white-space: nowrap;_x000D_
    overflow: hidden;_x000D_
    text-overflow: ellipsis;_x000D_
    max-width: 75ch;_x000D_
}
_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisi ligula, dapibus a volutpat sit amet, mattis etc. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisi ligula, dapibus a volutpat sit amet, mattis etc.</p>
_x000D_
_x000D_
_x000D_

For multiline truncating, please follow the link.

An example: https://codepen.io/srekoble/pen/EgmyxV

We will be using webkit css for this. In short WebKit is a HTML/CSS web browser rendering engine for Safari/Chrome. This may be brower specific as every browser is backed by a rendering engine to draw the HTML/CSS web page.

CSS Auto hide elements after 5 seconds

Why not try fadeOut?

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#plsme').fadeOut(5000); // 5 seconds x 1000 milisec = 5000 milisec_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div id='plsme'>Loading... Please Wait</div>
_x000D_
_x000D_
_x000D_

fadeOut (Javascript Pure):

How to make fadeOut effect with pure JavaScript

How to Publish Web with msbuild?

found two different solutions which worked in slightly different way:

1. This solution is inspired by the answer from alexanderb [link]. Unfortunately it did not work for us - some dll's were not copied to the OutDir. We found out that replacing ResolveReferences with Build target solves the problem - now all necessary files are copied into the OutDir location.

msbuild /target:Build;_WPPCopyWebApplication  /p:Configuration=Release;OutDir=C:\Tmp\myApp\ MyApp.csproj
Disadvantage of this solution was the fact that OutDir contained not only files for publish.

2. The first solution works well but not as we expected. We wanted to have the publish functionality as it is in Visual Studio IDE - i.e. only the files which should be published will be copied into the Output directory. As it has been already mentioned first solution copies much more files into the OutDir - the website for publish is then stored in _PublishedWebsites/{ProjectName} subfolder. The following command solves this - only the files for publish will be copied to desired folder. So now you have directory which can be directly published - in comparison with the first solution you will save some space on hard drive.

msbuild /target:Build;PipelinePreDeployCopyAllFilesToOneFolder /p:Configuration=Release;_PackageTempDir=C:\Tmp\myApp\;AutoParameterizationWebConfigConnectionStrings=false MyApp.csproj
AutoParameterizationWebConfigConnectionStrings=false parameter will guarantee that connection strings will not be handled as special artifacts and will be correctly generated - for more information see link.

Get value from hashmap based on key to JSTL

if all you're trying to do is get the value of a single entry in a map, there's no need to loop over any collection at all. simplifying gautum's response slightly, you can get the value of a named map entry as follows:

<c:out value="${map['key']}"/>

where 'map' is the collection and 'key' is the string key for which you're trying to extract the value.

Correct way to select from two tables in SQL Server with no common field to join on

Cross join will help to join multiple tables with no common fields.But be careful while joining as this join will give cartesian resultset of two tables. QUERY:

SELECT 
   table1.columnA
 , table2,columnA
FROM table1 
CROSS JOIN table2

Alternative way to join on some condition that is always true like

SELECT 
   table1.columnA
 , table2,columnA
FROM table1 
INNER JOIN table2 ON 1=1

But this type of query should be avoided for performance as well as coding standards.

How to find which version of TensorFlow is installed in my system?

I installed the Tensorflow 0.12rc from source, and the following command gives me the version info:

python -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 2
python3 -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 3

The following figure shows the output:

enter image description here

Jenkins - passing variables between jobs?

Reading through the answers, I don't see another option that I like so will offer it as well. I love the parameterization of jobs, but it doesn't always scale well. If you have jobs which are not directly downstream of the first job but farther down the pipeline, you don't really want to parameterize every job in the pipeline so as to be able to pass the parameters all the way through. Or if you have a large number of parameters used by a variety of other jobs (especially those not necessarily tied to one parent or master job), again parameterization doesn't work.

In these cases, I favor outputting the values to a properties file and then injecting that in whatever job I need using the EnvInject plugin. This can be done dynamically, which is another way to solve the issue from another answer above where parameterized jobs were still used. This solution scales very well in many scenarios.

Add new value to an existing array in JavaScript

jQuery is an abstraction of JavaScript. Think of jQuery as a sub-set of JavaScript, aimed at working with the DOM. That being said; there are functions for adding item(s) to a collection. I would use basic JavaScript in your case though:

var array;

array[0] = "value1";
array[1] = "value2";
array[2] = "value3";

... Or:

var array = ["value1", "value2", "value3"];

... Or:

var array = [];

array.push("value1");
array.push("value2");
array.push("value3");

DTO and DAO concepts and MVC

DTO is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.

  • DTO should only contain private fields for your data, getters, setters, and constructors.
  • DTO is not recommended to add business logic methods to such classes, but it is OK to add some util methods.

DAO is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).

Here is an example of how the DAO and DTO interfaces would look like:

interface PersonDTO {
    String getName();
    void setName(String name);
    //.....
}

interface PersonDAO {
    PersonDTO findById(long id);
    void save(PersonDTO person);
    //.....
}

The MVC is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.

As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.

minimum double value in C/C++

The original question concerns infinity. So, why not use

#define Infinity  ((double)(42 / 0.0))

according to the IEEE definition? You can negate that of course.

Make a DIV fill an entire table cell

If the positioned element and its father element do not have width and height, then set

padding: 0;

in its father element,

Calculate the date yesterday in JavaScript

This will produce yesterday at 00:00 with minutes precision

var d = new Date();
d.setDate(d.getDate() - 1);
d.setTime(d.getTime()-d.getHours()*3600*1000-d.getMinutes()*60*1000);

How to recover corrupted Eclipse workspace?

I have some experience at recovering from eclipse when it becomes unstartable for whatever reason, could these blog entries help you?

link (archived)

also search for "cannot start eclipse" (I am a new user, I can only post a single hyperlink, so I have to just ask that you search for the second :( sorry)

perhaps those allow you to recover your workspace as well, I hope it helps.

Script for rebuilding and reindexing the fragmented index?

Two solutions: One simple and one more advanced.

Introduction

There are two solutions available to you depending on the severity of your issue

Replace with your own values, as follows:

  • Replace XXXMYINDEXXXX with the name of an index.
  • Replace XXXMYTABLEXXX with the name of a table.
  • Replace XXXDATABASENAMEXXX with the name of a database.

Solution 1. Indexing

Rebuild all indexes for a table in offline mode

ALTER INDEX ALL ON XXXMYTABLEXXX REBUILD

Rebuild one specified index for a table in offline mode

ALTER INDEX XXXMYINDEXXXX ON XXXMYTABLEXXX REBUILD

Solution 2. Fragmentation

Fragmentation is an issue in tables that regularly have entries both added and removed.

Check fragmentation percentage

SELECT  
    ips.[index_id] ,
    idx.[name] ,
    ips.[avg_fragmentation_in_percent]
FROM    
    sys.dm_db_index_physical_stats(DB_ID(N'XXXMYDATABASEXXX'), OBJECT_ID(N'XXXMYTABLEXXX'), NULL, NULL, NULL) AS [ips]
    INNER JOIN sys.indexes AS [idx] ON [ips].[object_id] = [idx].[object_id] AND [ips].[index_id] = [idx].[index_id]

Fragmentation 5..30%

If the fragmentation value is greater than 5%, but less than 30% then it is worth reorganising indexes.

Reorganise all indexes for a table

ALTER INDEX ALL ON XXXMYTABLEXXX REORGANIZE

Reorganise one specified index for a table

ALTER INDEX XXXMYINDEXXXX ON XXXMYTABLEXXX REORGANIZE

Fragmentation 30%+

If the fragmentation value is 30% or greater then it is worth rebuilding then indexes in online mode.

Rebuild all indexes in online mode for a table

ALTER INDEX ALL ON XXXMYTABLEXXX REBUILD WITH (ONLINE = ON)

Rebuild one specified index in online mode for a table

ALTER INDEX XXXMYINDEXXXX ON XXXMYTABLEXXX REBUILD WITH (ONLINE = ON)

Laravel orderBy on a relationship

Using sortBy... could help.

$users = User::all()->with('rated')->get()->sortByDesc('rated.rating');

How do I convert a list into a string with spaces in Python?

So in order to achieve a desired output, we should first know how the function works.

The syntax for join() method as described in the python documentation is as follows:

string_name.join(iterable)

Things to be noted:

  • It returns a string concatenated with the elements of iterable. The separator between the elements being the string_name.
  • Any non-string value in the iterable will raise a TypeError

Now, to add white spaces, we just need to replace the string_name with a " " or a ' ' both of them will work and place the iterable that we want to concatenate.

So, our function will look something like this:

' '.join(my_list)

But, what if we want to add a particular number of white spaces in between our elements in the iterable ?

We need to add this:

str(number*" ").join(iterable)

here, the number will be a user input.

So, for example if number=4.

Then, the output of str(4*" ").join(my_list) will be how are you, so in between every word there are 4 white spaces.

'Best' practice for restful POST response

Returning the whole object on an update would not seem very relevant, but I can hardly see why returning the whole object when it is created would be a bad practice in a normal use case. This would be useful at least to get the ID easily and to get the timestamps when relevant. This is actually the default behavior got when scaffolding with Rails.

I really do not see any advantage to returning only the ID and doing a GET request after, to get the data you could have got with your initial POST.

Anyway as long as your API is consistent I think that you should choose the pattern that fits your needs the best. There is not any correct way of how to build a REST API, imo.