Programs & Examples On #Text alignment

Most word processing programs give you the capability to change the text alignment of a block of text. This setting determines how the text is displayed horizontally on the page. The four primary types of text alignment include left aligned, right aligned, centered, and justified.

Vertically align text to top within a UILabel

Subclass UILabel and constrain the drawing rectangle, like this:

- (void)drawTextInRect:(CGRect)rect
{
    CGSize sizeThatFits = [self sizeThatFits:rect.size];
    rect.size.height = MIN(rect.size.height, sizeThatFits.height);

    [super drawTextInRect:rect];
}

I tried the solution involving newline padding and ran into incorrect behavior in some cases. In my experience, it's easier to constrain the drawing rect as above than mess with numberOfLines.

P.S. You can imagine easily supporting UIViewContentMode this way:

- (void)drawTextInRect:(CGRect)rect
{
    CGSize sizeThatFits = [self sizeThatFits:rect.size];

    if (self.contentMode == UIViewContentModeTop) {
        rect.size.height = MIN(rect.size.height, sizeThatFits.height);
    }
    else if (self.contentMode == UIViewContentModeBottom) {
        rect.origin.y = MAX(0, rect.size.height - sizeThatFits.height);
        rect.size.height = MIN(rect.size.height, sizeThatFits.height);
    }

    [super drawTextInRect:rect];
}

C++ alignment when printing cout <<

C++20 std::format options <, ^ and >

According to https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification the following should hold:

// left: "42    "
std::cout << std::format("{:<6}", 42);

// right: "    42"
std::cout << std::format("{:>6}", 42);

// center: "  42  "
std::cout << std::format("{:^6}", 42);

More information at: std::string formatting like sprintf

How to set top-left alignment for UILabel for iOS application?

I have this problem to but my label was in UITableViewCell, and in fund that the easiest way to solve the problem was to create an empty UIView and set the label inside it with constraints to the top and to the left side only, on off curse set the number of lines to 0

Difference between <span> and <div> with text-align:center;?

Spans are inline, divs are block elements. i.e. spans are only as wide as their respective content. You can align the span inside the surrounding container (if it's a block container), but you can't align the content.

Span is primarily used for formatting purposes. If you want to arrange or position the contents, use div, p or some other block element.

Under which circumstances textAlign property works in Flutter?

Set alignment: Alignment.centerRight in Container:

Container(
    alignment: Alignment.centerRight,
    child:Text(
       "Hello",
    ),
)

CSS text-align not working

Change the rule on your <a> element from:

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
}?

to

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
    width:100%;
    text-align:center;
}?

Just add two new rules (width:100%; and text-align:center;). You need to make the anchor expand to take up the full width of the list item and then text-align center it.

jsFiddle example

`col-xs-*` not working in Bootstrap 4

you could do this, if you want to use the old syntax (or don't want to rewrite every template)

@for $i from 1 through $grid-columns {
  @include media-breakpoint-up(xs) {
    .col-xs-#{$i} {
      @include make-col-ready();
      @include make-col($i);
    }
  }
}

Align text in JLabel to the right

To me, it seems as if your actual intention is to put different words on different lines. But let me answer your first question:

JLabel lab=new JLabel("text");
lab.setHorizontalAlignment(SwingConstants.LEFT);     

And if you have an image:

JLabel lab=new Jlabel("text");
lab.setIcon(new ImageIcon("path//img.png"));
lab.setHorizontalTextPosition(SwingConstants.LEFT);

But, I believe you want to make the label such that there are only 2 words on 1 line.

In that case try this:

String urText="<html>You can<br>use basic HTML<br>in Swing<br> components," 
   +"Hope<br> I helped!";
JLabel lac=new JLabel(urText);
lac.setAlignmentX(Component.RIGHT_ALIGNMENT);

Purge or recreate a Ruby on Rails database

To drop a particular database, you can do this on rails console:

$rails console
Loading development environment
1.9.3 > ActiveRecord::Migration.drop_table(:<table_name>)
1.9.3 > exit

And then migrate DB again

$bundle exec rake db:migrate 

Return string Input with parse.string

If you're really bent upon converting Integer to String value, I suggest use String.valueOf(YourIntegerVariable). More details can be found at: http://www.tutorialspoint.com/java/java_string_valueof.htm

How do I find an element position in std::vector?

You probably should not use your own function here. Use find() from STL.

Example:

list L;
L.push_back(3);
L.push_back(1);
L.push_back(7);

list::iterator result = find(L.begin(), L.end(), 7); assert(result == L.end() || *result == 7);

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

We can add "AwaitTerminationSeconds" property for both taskExecutor and taskScheduler as below,

<property name="awaitTerminationSeconds" value="${taskExecutor .awaitTerminationSeconds}" />

<property name="awaitTerminationSeconds" value="${taskScheduler .awaitTerminationSeconds}" />

Documentation for "waitForTasksToCompleteOnShutdown" property says, when shutdown is called

"Spring's container shutdown continues while ongoing tasks are being completed. If you want this executor to block and wait for the termination of tasks before the rest of the container continues to shut down - e.g. in order to keep up other resources that your tasks may need -, set the "awaitTerminationSeconds" property instead of or in addition to this property."

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/concurrent/ExecutorConfigurationSupport.html#setWaitForTasksToCompleteOnShutdown-boolean-

So it is always advised to use waitForTasksToCompleteOnShutdown and awaitTerminationSeconds properties together. Value of awaitTerminationSeconds depends on our application.

How to view the Folder and Files in GAC?

Launch the program "Run" (Windows Vista/7/8: type it in the start menu search bar) and type: C:\windows\assembly\GAC_MSIL

Then move to the parent folder (Windows Vista/7/8: by clicking on it in the explorer bar) to see all the GAC files in a normal explorer window. You can now copy, add and remove files as everywhere else.

How to access global variables

I suggest use the common way of import.

First I will explain the way it called "relative import" maybe this way cause of some error

Second I will explain the common way of import.

FIRST:

In go version >= 1.12 there is some new tips about import file and somethings changed.

1- You should put your file in another folder for example I create a file in "model" folder and the file's name is "example.go"

2- You have to use uppercase when you want to import a file!

3- Use Uppercase for variables, structures and functions that you want to import in another files

Notice: There is no way to import the main.go in another file.

file directory is:

root
|_____main.go
|_____model
          |_____example.go

this is a example.go:

package model

import (
    "time"
)

var StartTime = time.Now()

and this is main.go you should use uppercase when you want to import a file. "Mod" started with uppercase

package main

import (
    Mod "./model"
    "fmt"
)

func main() {
    fmt.Println(Mod.StartTime)
}

NOTE!!!

NOTE: I don't recommend this this type of import!

SECOND:

(normal import)

the better way import file is:

your structure should be like this:

root
|_____github.com
         |_________Your-account-name-in-github
         |                |__________Your-project-name
         |                                |________main.go
         |                                |________handlers
         |                                |________models
         |               
         |_________gorilla
                         |__________sessions

and this is a example:

package main

import (
    "github.com/gorilla/sessions"
)

func main(){
     //you can use sessions here
}

so you can import "github.com/gorilla/sessions" in every where that you want...just import it.

How to disable registration new users in Laravel

This might be new in 5.7, but there is now an options array to the auth method. Simply changing

Auth::routes();

to

Auth::routes(['register' => false]);

in your routes file after running php artisan make:auth will disable user registration.

Using jQuery to build table rows from AJAX response(json)

Try this (DEMO link updated):

success: function (response) {
        var trHTML = '';
        $.each(response, function (i, item) {
            trHTML += '<tr><td>' + item.rank + '</td><td>' + item.content + '</td><td>' + item.UID + '</td></tr>';
        });
        $('#records_table').append(trHTML);
    }

Fiddle DEMO WITH AJAX

How good is Java's UUID.randomUUID?

I'm not an expert, but I'd assume that enough smart people looked at Java's random number generator over the years. Hence, I'd also assume that random UUIDs are good. So you should really have the theoretical collision probability (which is about 1 : 3 × 10^38 for all possible UUIDs. Does anybody know how this changes for random UUIDs only? Is it 1/(16*4) of the above?)

From my practical experience, I've never seen any collisions so far. I'll probably have grown an astonishingly long beard the day I get my first one ;)

Func vs. Action vs. Predicate

The difference between Func and Action is simply whether you want the delegate to return a value (use Func) or not (use Action).

Func is probably most commonly used in LINQ - for example in projections:

 list.Select(x => x.SomeProperty)

or filtering:

 list.Where(x => x.SomeValue == someOtherValue)

or key selection:

 list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)

Action is more commonly used for things like List<T>.ForEach: execute the given action for each item in the list. I use this less often than Func, although I do sometimes use the parameterless version for things like Control.BeginInvoke and Dispatcher.BeginInvoke.

Predicate is just a special cased Func<T, bool> really, introduced before all of the Func and most of the Action delegates came along. I suspect that if we'd already had Func and Action in their various guises, Predicate wouldn't have been introduced... although it does impart a certain meaning to the use of the delegate, whereas Func and Action are used for widely disparate purposes.

Predicate is mostly used in List<T> for methods like FindAll and RemoveAll.

Using bootstrap with bower

assuming you have npm installed and bower installed globally

  1. navigate to your project
  2. bower init (this will generate the bower.json file in your directory)
  3. (then keep clicking yes)...
  4. to set the path where bootstrap will be installed:
    manually create a .bowerrc file next to the bower.json file and add the following to it:

    { "directory" : "public/components" }

  5. bower install bootstrap --save

Note: to install other components:

 bower search {component-name-here}

Definition of a Balanced Tree

  1. The height of a node in a tree is the length of the longest path from that node downward to a leaf, counting both the start and end vertices of the path.
  2. A node in a tree is height-balanced if the heights of its subtrees differ by no more than 1.
  3. A tree is height-balanced if all of its nodes are height-balanced.

How to obtain the last path segment of a URI

I know this is old, but the solutions here seem rather verbose. Just an easily readable one-liner if you have a URL or URI:

String filename = new File(url.getPath()).getName();

Or if you have a String:

String filename = new File(new URL(url).getPath()).getName();

Setting href attribute at runtime

In jQuery 1.6+ it's better to use:

$(selector).prop('href',"http://www...") to set the value, and

$(selector).prop('href') to get the value

In short, .prop gets and sets values on the DOM object, and .attr gets and sets values in the HTML. This makes .prop a little faster and possibly more reliable in some contexts.

Tkinter: How to use threads to preventing main event loop from "freezing"

When you join the new thread in the main thread, it will wait until the thread finishes, so the GUI will block even though you are using multithreading.

If you want to place the logic portion in a different class, you can subclass Thread directly, and then start a new object of this class when you press the button. The constructor of this subclass of Thread can receive a Queue object and then you will be able to communicate it with the GUI part. So my suggestion is:

  1. Create a Queue object in the main thread
  2. Create a new thread with access to that queue
  3. Check periodically the queue in the main thread

Then you have to solve the problem of what happens if the user clicks two times the same button (it will spawn a new thread with each click), but you can fix it by disabling the start button and enabling it again after you call self.prog_bar.stop().

import Queue

class GUI:
    # ...

    def tb_click(self):
        self.progress()
        self.prog_bar.start()
        self.queue = Queue.Queue()
        ThreadedTask(self.queue).start()
        self.master.after(100, self.process_queue)

    def process_queue(self):
        try:
            msg = self.queue.get(0)
            # Show result of the task if needed
            self.prog_bar.stop()
        except Queue.Empty:
            self.master.after(100, self.process_queue)

class ThreadedTask(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue
    def run(self):
        time.sleep(5)  # Simulate long running process
        self.queue.put("Task finished")

Remove last character of a StringBuilder?

As of Java 8, the String class has a static method join. The first argument is a string that you want between each pair of strings, and the second is an Iterable<CharSequence> (which are both interfaces, so something like List<String> works. So you can just do this:

String.join(",", serverIds);

Also in Java 8, you could use the new StringJoiner class, for scenarios where you want to start constructing the string before you have the full list of elements to put in it.

how to use ng-option to set default value of select element

Just to add up, I did something like this.

 <select class="form-control" data-ng-model="itemSelect" ng-change="selectedTemplate(itemSelect)" autofocus>
        <option value="undefined" [selected]="itemSelect.Name == undefined" disabled="disabled">Select template...</option>
        <option ng-repeat="itemSelect in templateLists" value="{{itemSelect.ID}}">{{itemSelect.Name}}</option></select>

What's the best way to store co-ordinates (longitude/latitude, from Google Maps) in SQL Server?

SQL Server has support for spatial related information. You can see more at http://www.microsoft.com/sqlserver/2008/en/us/spatial-data.aspx.

Alternativly you can store the information as two basic fields, usually a float is the standard data type reported by most devices and is accurate enough for within an inch or two - more than adequate for Google Maps.

Why is division in Ruby returning an integer instead of decimal value?

You can include the ruby mathn module.

require 'mathn'

This way, you are going to be able to make the division normally.

1/2              #=> (1/2)
(1/2) ** 3       #=> (1/8)
1/3*3            #=> 1
Math.sin(1/2)    #=> 0.479425538604203

This way, you get exact division (class Rational) until you decide to apply an operation that cannot be expressed as a rational, for example Math.sin.

System.Net.WebException HTTP status code

By using the null-conditional operator (?.) you can get the HTTP status code with a single line of code:

 HttpStatusCode? status = (ex.Response as HttpWebResponse)?.StatusCode;

The variable status will contain the HttpStatusCode. When the there is a more general failure like a network error where no HTTP status code is ever sent then status will be null. In that case you can inspect ex.Status to get the WebExceptionStatus.

If you just want a descriptive string to log in case of a failure you can use the null-coalescing operator (??) to get the relevant error:

string status = (ex.Response as HttpWebResponse)?.StatusCode.ToString()
    ?? ex.Status.ToString();

If the exception is thrown as a result of a 404 HTTP status code the string will contain "NotFound". On the other hand, if the server is offline the string will contain "ConnectFailure" and so on.

(And for anybody that wants to know how to get the HTTP substatus code. That is not possible. It is a Microsoft IIS concept that is only logged on the server and never sent to the client.)

Angularjs autocomplete from $http

the easiest way to do that in angular or angularjs without external modules or directives is using list and datalist HTML5. You just get a json and use ng-repeat for feeding the options in datalist. The json you can fetch it from ajax.

in this example:

  • ctrl.query is the query that you enter when you type.
  • ctrl.msg is the message that is showing in the placeholder
  • ctrl.dataList is the json fetched

then you can add filters and orderby in the ng-reapet

!! list and datalist id must have the same name !!

 <input type="text" list="autocompleList" ng-model="ctrl.query" placeholder={{ctrl.msg}}>
<datalist id="autocompleList">
        <option ng-repeat="Ids in ctrl.dataList value={{Ids}}  >
</datalist>

UPDATE : is native HTML5 but be carreful with the type browser and version. check it out : https://caniuse.com/#search=datalist.

R: += (plus equals) and ++ (plus plus) equivalent from c++/c#/java, etc.?

R doesn't have a concept of increment operator (as for example ++ in C). However, it is not difficult to implement one yourself, for example:

inc <- function(x)
{
 eval.parent(substitute(x <- x + 1))
}

In that case you would call

x <- 10
inc(x)

However, it introduces function call overhead, so it's slower than typing x <- x + 1 yourself. If I'm not mistaken increment operator was introduced to make job for compiler easier, as it could convert the code to those machine language instructions directly.

How to center an iframe horizontally?

My simplest solution to this.

iframe {
    margin:auto;
    display:block;
}

sql ORDER BY multiple values in specific order?

The CASE and ORDER BY suggestions should all work, but I'm going to suggest a horse of a different color. Assuming that there are only a reasonable number of values for x_field and you already know what they are, create an enumerated type with F, P, A, and I as the values (plus whatever other possible values apply). Enums will sort in the order implied by their CREATE statement. Also, you can use meaninful value names—your real application probably does and you have just masked them for confidentiality—without wasted space, since only the ordinal position is stored.

How to set xampp open localhost:8080 instead of just localhost

Open XAMPP look below the X to close the program there is a Config option click it then click service and port settings then under Apache change your main port to whatever you changed it to in the config file then click save and your good to go.

Bootstrap 3: Text overlay on image

You need to set the thumbnail class to position relative then the post-content to absolute.

Check this fiddle

.post-content {
    top:0;
    left:0;
    position: absolute;
}

.thumbnail{
    position:relative;

}

Giving it top and left 0 will make it appear in the top left corner.

How to fast get Hardware-ID in C#?

For more details refer to this link

The following code will give you CPU ID:

namespace required System.Management

var mbs = new ManagementObjectSearcher("Select ProcessorId From Win32_processor");
ManagementObjectCollection mbsList = mbs.Get();
string id = "";
foreach (ManagementObject mo in mbsList)
{
    id = mo["ProcessorId"].ToString();
    break;
}

For Hard disk ID and motherboard id details refer this-link

To speed up this procedure, make sure you don't use SELECT *, but only select what you really need. Use SELECT * only during development when you try to find out what you need to use, because then the query will take much longer to complete.

How can I add a custom HTTP header to ajax request with js or jQuery?

Assuming JQuery ajax, you can add custom headers like -

$.ajax({
  url: url,
  beforeSend: function(xhr) {
    xhr.setRequestHeader("custom_header", "value");
  },
  success: function(data) {
  }
});

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

Go to phpMyAdmin/config.inc.php edit the line

$cfg['Servers'][$i]['password'] = '';

to

$cfg['Servers'][$i]['password'] = 'yourpassword';

This problem might occur due to setting of a password to root, thus phpmyadmin is not able to connect to the mysql database.

And the last thing change

$cfg['Servers'][$i]['extension'] = 'mysql';

to

$cfg['Servers'][$i]['extension'] = 'mysqli';

Now restart your server. and see.

How to change background Opacity when bootstrap modal is open

use this code

_x000D_
_x000D_
$("#your_modal_id").on("shown.bs.modal", function(){_x000D_
      $('.modal-backdrop.in').css('opacity', '0.9');_x000D_
});
_x000D_
_x000D_
_x000D_

Get the real width and height of an image with JavaScript? (in Safari/Chrome)

$(document).ready(function(){
                            var image = $("#fix_img");
                            var w = image.width();
                            var h = image.height();
                            var mr = 274/200;
                            var ir = w/h
                            if(ir > mr){
                                image.height(200);
                                image.width(200*ir);
                            } else{
                                image.width(274);
                                image.height(274/ir);
                            }
                        }); 

// This code helps to show image with 200*274 dimention

Filter Pyspark dataframe column with None value

None/Null is a data type of the class NoneType in pyspark/python so, Below will not work as you are trying to compare NoneType object with string object

Wrong way of filreting

df[df.dt_mvmt == None].count() 0 df[df.dt_mvmt != None].count() 0

correct

df=df.where(col("dt_mvmt").isNotNull()) returns all records with dt_mvmt as None/Null

Init function in javascript and how it works

The way I usually explain this to people is to show how it's similar to other JavaScript patterns.

First, you should know that there are two ways to declare a function (actually, there's at least five, but these are the two main culprits):

function foo() {/*code*/}

and

var foo = function() {/*code*/};

Even if this construction looks strange, you probably use it all the time when attaching events:

window.onload=function(){/*code*/};

You should notice that the second form is not much different from a regular variable declaration:

var bar = 5;
var baz = 'some string';
var foo = function() {/*code*/};

But in JavaScript, you always have the choice between using a value directly or through a variable. If bar is 5, then the next two statements are equivalent:

var myVal = bar * 100; // use 'bar'
var myVal = 5 * 100;   // don't use 'bar'

Well, if you can use 5 on its own, why can't you use function() {\*code*\} on its own too? In fact, you can. And that's called an anonymous function. So these two examples are equivalent as well:

var foo = function() {/*code*/}; // use 'foo'
foo();                           

(function(){/*code*/})();        // don't use 'foo' 

The only difference you should see is in the extra brackets. That's simply because if you start a line with the keyword function, the parser will think you are declaring a function using the very first pattern at the top of this answer and throw a syntax error exception. So wrap your entire anonymous function inside a pair of braces and the problem goes away.

In other words, the following three statements are valid:

5;                        // pointless and stupid
'some string';            // pointless and stupid
(function(){/*code*/})(); // wonderfully powerful

[EDIT in 2020]

The previous version of my answer recommended Douglas Crockford's form of parens-wrapping for these "immediately invoked anonymous functions". User @RayLoveless recommended in 2012 to use the version shown now. Back then, before ES6 and arrow functions, there was no obvious idiomatic difference; you simply had to prevent the statement starting with the function keyword. In fact, there were lots of ways to do that. But using parens, these two statements were syntactically and idiomatically equivalent:

( function() { /* code */}() );
( function() { /* code */} )();

But user @zentechinc's comment below reminds me that arrow functions change all this. So now only one of these statements is correct.

( () => { /* code */ }() ); // Syntax error
( () => { /* code */ } )();

Why on earth does this matter? Actually, it's pretty easy to demonstrate. Remember an arrow function can come in two basic forms:

() => { return 5; };       // With a function body
() => { console.log(5); };

() => 5;                   // Or with a single expression
() => console.log(5);

Without parens wrapping this second type of arrow function, you end up with an idiomatic mess:

() => 5();              // How do you invoke a 5?
() => console.log(5)(); // console.log does not return a function!

Find p-value (significance) in scikit-learn LinearRegression

For a one-liner you can use the pingouin.linear_regression function (disclaimer: I am the creator of Pingouin), which works with uni/multi-variate regression using NumPy arrays or Pandas DataFrame, e.g:

import pingouin as pg
# Using a Pandas DataFrame `df`:
lm = pg.linear_regression(df[['x', 'z']], df['y'])
# Using a NumPy array:
lm = pg.linear_regression(X, y)

The output is a dataframe with the beta coefficients, standard errors, T-values, p-values and confidence intervals for each predictor, as well as the R^2 and adjusted R^2 of the fit.

Can I escape a double quote in a verbatim string literal?

For adding some more information, your example will work without the @ symbol (it prevents escaping with \), this way:

string foo = "this \"word\" is escaped!";

It will work both ways but I prefer the double-quote style for it to be easier working, for example, with filenames (with lots of \ in the string).

Remove pattern from string with gsub

Just to point out that there is an approach using functions from the tidyverse, which I find more readable than gsub:

a %>% stringr::str_remove(pattern = ".*_")

Twitter bootstrap modal-backdrop doesn't disappear

If you are using a copy and paste from the getboostrap site itself into an html generated selector, make sure you remove the comment '<!-- /.modal -->'. Bootstrap gets confused and thinks that the comment is a second modal element. It creates another back drop for this "second" element.

How to search multiple columns in MySQL?

Here is a query which you can use to search for anything in from your database as a search result ,

SELECT * FROM tbl_customer 
    WHERE CustomerName LIKE '%".$search."%'
    OR Address LIKE '%".$search."%' 
    OR City LIKE '%".$search."%' 
    OR PostalCode LIKE '%".$search."%' 
    OR Country LIKE '%".$search."%'

Using this code will help you search in for multiple columns easily

How to search by key=>value in a multidimensional array in PHP

$result = array_filter($arr, function ($var) {   
  $found = false;
  array_walk_recursive($var, function ($item, $key) use (&$found) {  
    $found = $found || $key == "name" && $item == "cat 1";
  });
  return $found;
});

Bulk Record Update with SQL

The SQL you posted in your question is one way to do it. Most things in SQL have more than one way to do it.

UPDATE
  [Table1] 
SET
  [Description]=(SELECT [Description] FROM [Table2] t2 WHERE t2.[ID]=Table1.DescriptionID)

If you are planning on running this on a PROD DB, it is best to create a snapshot or mirror of it first and test it out. Verify the data ends up as you expect for a couple records. And if you are satisfied, run it on the real DB.

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

I got the same error but from a backend job (SSIS job). Upon checking the database's Log file growth setting, the log file was limited growth of 1GB. So what happened is when the job ran and it asked SQL server to allocate more log space, but the growth limit of the log declined caused the job to failed. I modified the log growth and set it to grow by 50MB and Unlimited Growth and the error went away.

Hibernate: flush() and commit()

It is usually not recommended to call flush explicitly unless it is necessary. Hibernate usually auto calls Flush at the end of the transaction and we should let it do it's work. Now, there are some cases where you might need to explicitly call flush where a second task depends upon the result of the first Persistence task, both being inside the same transaction.

For example, you might need to persist a new Entity and then use the Id of that Entity to do some other task inside the same transaction, on that case it's required to explicitly flush the entity first.

@Transactional
void someServiceMethod(Entity entity){
    em.persist(entity); 
    em.flush() //need to explicitly flush in order to use id in next statement
    doSomeThingElse(entity.getId());    
}

Also Note that, explicitly flushing does not cause a database commit, a database commit is done only at the end of a transaction, so if any Runtime error occurs after calling flush the changes would still Rollback.

How to configure socket connect timeout

I had the Same problem when connecting to a Socket and I came up with the below solution ,It works Fine for me. `

private bool CheckConnectivityForProxyHost(string hostName, int port)
       {
           if (string.IsNullOrEmpty(hostName))
               return false;

           bool isUp = false;
           Socket testSocket = null;

           try
           {

               testSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
               IPAddress ip = null;
               if (testSocket != null && NetworkingCollaboratorBase.GetResolvedConnecionIPAddress(hostName, out ip))//Use a method to resolve your IP
               {
                   IPEndPoint ipEndPoint = new IPEndPoint(ip, port);

                   isUp = false;
//time out 5 Sec
                  CallWithTimeout(ConnectToProxyServers, 5000, testSocket, ipEndPoint);

                       if (testSocket != null && testSocket.Connected)
                       {
                           isUp = true;
                       }
                   }

               }
           }
           catch (Exception ex)
           {
               isUp = false;
           }
           finally
           {
               try
               {
                   if (testSocket != null)
                   {
                       testSocket.Shutdown(SocketShutdown.Both);
                   }
               }
               catch (Exception ex)
               {

               }
               finally
               {
                   if (testSocket != null)
                       testSocket.Close();
               }

           }

           return isUp;
       }


 private void CallWithTimeout(Action<Socket, IPEndPoint> action, int timeoutMilliseconds, Socket socket, IPEndPoint ipendPoint)
       {
           try
           {
               Action wrappedAction = () =>
               {
                   action(socket, ipendPoint);
               };

               IAsyncResult result = wrappedAction.BeginInvoke(null, null);

               if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
               {
                   wrappedAction.EndInvoke(result);
               }

           }
           catch (Exception ex)
           {

           }
       }

  private void ConnectToProxyServers(Socket testSocket, IPEndPoint ipEndPoint)
       {
           try
           {
               if (testSocket == null || ipEndPoint == null)
                   return;

                   testSocket.Connect(ipEndPoint);

           }
           catch (Exception ex)
           {

           }
       } 

Command for restarting all running docker containers?

To start multiple containers with the only particular container id's $ docker restart contianer-id1 container-id2 container-id3 ...

Programmatically obtain the phone number of the Android phone

Sometimes, below code returns null or blank string.

TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();

With below permission

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

There is another way you will be able to get your phone number, I haven't tested this on multiple devices but above code is not working every time.

Try below code:

String main_data[] = {"data1", "is_primary", "data3", "data2", "data1", "is_primary", "photo_uri", "mimetype"};
Object object = getContentResolver().query(Uri.withAppendedPath(android.provider.ContactsContract.Profile.CONTENT_URI, "data"),
        main_data, "mimetype=?",
        new String[]{"vnd.android.cursor.item/phone_v2"},
        "is_primary DESC");
if (object != null) {
    do {
        if (!((Cursor) (object)).moveToNext())
            break;
        // This is the phoneNumber
        String s1 = ((Cursor) (object)).getString(4);
    } while (true);
    ((Cursor) (object)).close();
}

You will need to add these two permissions.

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />

Hope this helps, Thanks!

Android device chooser - My device seems offline

fastest way is

Settings -> Developer Options -> Android Debugging

turn off and then on again (tested on CyanogenMod 11)

How to send custom headers with requests in Swagger UI?

Golang/go-swagger example: https://github.com/go-swagger/go-swagger/issues/1416

// swagger:parameters opid
type XRequestIdHeader struct {
    // in: header
    // required: true
    XRequestId string `json:"X-Request-Id"`
}

...
    // swagger:operation POST /endpoint/ opid
    // Parameters:
    // - $ref: #/parameters/XRequestIDHeader

How to merge a Series and DataFrame

Update
From v0.24.0 onwards, you can merge on DataFrame and Series as long as the Series is named.

df.merge(s.rename('new'), left_index=True, right_index=True)
# If series is already named,
# df.merge(s, left_index=True, right_index=True)

Nowadays, you can simply convert the Series to a DataFrame with to_frame(). So (if joining on index):

df.merge(s.to_frame(), left_index=True, right_index=True)

Is it possible to include one CSS file in another?

Yes. Importing CSS file into another CSS file is possible.

It must be the first rule in the style sheet using the @import rule.

@import "mystyle.css";
@import url("mystyle.css");

The only caveat is that older web browsers will not support it. In fact, this is one of the CSS 'hack' to hide CSS styles from older browsers.

Refer to this list for browser support.

Greater than and less than in one statement

If this is really bothering you, why not write your own method isBetween(orderBean.getFiles().size(),0,5)?

Another option is to use isEmpty as it is a tad clearer:

if(!orderBean.getFiles().isEmpty() && orderBean.getFiles().size() < 5)

Making text bold using attributed string in swift

You can do this using simple custom method written below. You have give whole string in first parameter and text to be bold in the second parameter. Hope this will help.

func getAttributedBoldString(str : String, boldTxt : String) -> NSMutableAttributedString {
        let attrStr = NSMutableAttributedString.init(string: str)
        let boldedRange = NSRange(str.range(of: boldTxt)!, in: str)
        attrStr.addAttributes([NSAttributedString.Key.font : UIFont.systemFont(ofSize: 17, weight: .bold)], range: boldedRange)
        return attrStr
    }

usage: initalString = I am a Boy

label.attributedText = getAttributedBoldString(str : initalString, boldTxt : "Boy")

resultant string = I am a Boy

Calculate percentage saved between two numbers?

I see that this is a very old question, but this is how I calculate the percentage difference between 2 numbers:

(1 - (oldNumber / newNumber)) * 100

So, the percentage difference from 30 to 40 is:

(1 - (30/40)) * 100 = +25% (meaning, increase by 25%)

The percentage difference from 40 to 30 is:

(1 - (40/30)) * 100 = -33.33% (meaning, decrease by 33%)

In php, I use a function like this:

function calculatePercentage($oldFigure, $newFigure) {
        if (($oldFigure != 0) && ($newFigure != 0)) {
            $percentChange = (1 - $oldFigure / $newFigure) * 100;
        }
        else {
            $percentChange = null;
        }
        return $percentChange;
}

Best practice when adding whitespace in JSX

You can use curly braces like expression with both double quotes and single quotes for space i.e.,

{" "} or {' '}

You can also use ES6 template literals i.e.,

`   <li></li>` or `  ${value}`

You can also use &nbsp like below (inside span)

<span>sample text &nbsp; </span>

You can also use &nbsp in dangerouslySetInnerHTML when printing html content

<div dangerouslySetInnerHTML={{__html: 'sample html text: &nbsp;'}} />

How can one grab a stack trace in C?

For the past few years I have been using Ian Lance Taylor's libbacktrace. It is much cleaner than the functions in the GNU C library which require exporting all the symbols. It provides more utility for the generation of backtraces than libunwind. And last but not least, it is not defeated by ASLR as are approaches requiring external tools such as addr2line.

Libbacktrace was initially part of the GCC distribution, but it is now made available by the author as a standalone library under a BSD license:

https://github.com/ianlancetaylor/libbacktrace

At the time of writing, I would not use anything else unless I need to generate backtraces on a platform which is not supported by libbacktrace.

"Operation must use an updateable query" error in MS Access

I had the same problem exactly, and I can't remember how I fond this solution but simply adding DISTINCTROW solved the problem.

In your code it will look like this:

UPDATE DISTINCTROW [GS] INNER JOIN [Views] ON <- the only change is here
    ([Views].Hostname = [GS].Hostname) 
    AND ([GS].APPID = [Views].APPID) 
 ...

I'm not sure why this works, but for me, it did exactly what I needed.

What is the use of static synchronized method in java?

static methods can be synchronized. But you have one lock per class. when the java class is loaded coresponding java.lang.class class object is there. That object's lock is needed for.static synchronized methods. So when you have a static field which should be restricted to be accessed by multiple threads at once you can set those fields private and create public static synchronized setters or getters to access those fields.

Abstract Class:-Real Time Example

You should be able to cite at least one from the JDK itself. Look in the java.util.collections package. There are several abstract classes. You should fully understand interface, abstract, and concrete for Map and why Joshua Bloch wrote it that way.

The service cannot be started, either because it is disabled or because it has no enabled devices associated with it

Try to open Services Window, by writing services.msc into Start->Run and hit Enter.

When window appears, then find SQL Browser service, right click and choose Properties, and then in dropdown list choose Automatic, or Manual, whatever you want, and click OK. Eventually, if not started immediately, you can again press right click on this service and click Start.

How to convert String to Date value in SAS?

This code helps:

data final; set final;

first_date = INPUT(compress(char_date),date9.); format first_date date9.;

run;

I personally have tried it on SAS

How to adjust the size of y axis labels only in R?

Don't know what you are doing (helpful to show what you tried that didn't work), but your claim that cex.axis only affects the x-axis is not true:

set.seed(123)
foo <- data.frame(X = rnorm(10), Y = rnorm(10))
plot(Y ~ X, data = foo, cex.axis = 3)

at least for me with:

> sessionInfo()
R version 2.11.1 Patched (2010-08-17 r52767)
Platform: x86_64-unknown-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_GB.UTF-8        LC_COLLATE=en_GB.UTF-8    
 [5] LC_MONETARY=C              LC_MESSAGES=en_GB.UTF-8   
 [7] LC_PAPER=en_GB.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods  
[8] base     

other attached packages:
[1] ggplot2_0.8.8 proto_0.3-8   reshape_0.8.3 plyr_1.2.1   

loaded via a namespace (and not attached):
[1] digest_0.4.2 tools_2.11.1

Also, cex.axis affects the labelling of tick marks. cex.lab is used to control what R call the axis labels.

plot(Y ~ X, data = foo, cex.lab = 3)

but even that works for both the x- and y-axis.


Following up Jens' comment about using barplot(). Check out the cex.names argument to barplot(), which allows you to control the bar labels:

dat <- rpois(10, 3) names(dat) <- LETTERS[1:10] barplot(dat, cex.names = 3, cex.axis = 2)

As you mention that cex.axis was only affecting the x-axis I presume you had horiz = TRUE in your barplot() call as well? As the bar labels are not drawn with an axis() call, applying Joris' (otherwise very useful) answer with individual axis() calls won't help in this situation with you using barplot()

HTH

Dataset - Vehicle make/model/year (free)

How about Freebase? I think they have an API available, too.

http://www.freebase.com/

$(document).ready(function(){ Uncaught ReferenceError: $ is not defined

If you are sure jQuery is included try replacing $ with jQuery and try again.

Something like

jQuery(document).ready(function(){..

Still if you are getting error, you haven't included jQuery.

how to change a selections options based on another select option selected?

as a complementary answer to @Navid_pdp11, which will enable to select the first visible item and work on document load as well. put the following below your body tag

<script>
$('#mainCat').on('change', function() {
    let selected = $(this).val();
    $("#expertCat option").each(function(){
        let element =  $(this) ;
        if (element.data("tag") != selected){
            element.removeClass('visible');
            element.addClass('hidden');
            element.hide() ;
        }else{
            element.removeClass('hidden');
            element.addClass('visible');
            element.show();
        }
    });
    let expertCat = $('#expertCat');
    expertCat.prop('selectedIndex',expertCat.find("option.visible:eq(0)").index());
}).triggerHandler('change');
</script>

How to choose the right bean scope?

Introduction

It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.


@Request/View/Flow/Session/ApplicationScoped

A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

See also:


@CustomScoped/NoneScoped/Dependent

It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

See also:


Flash scope

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

See also:

Is it possible to hide/encode/encrypt php source code and let others have the system?

There are many ways for doing that (you might want to obfuscate the source code, you can compress it, ...). Some of these methods need additional code to transform your program in an executable form (compression, for example).

But the thing all methods cannot do, is keeping the source code secret. The other party gets your binary code, which can always be transformed (reverse-engineered) into a human-readable form again, because the binary code contains all functionality information that is provided in your source code.

Is it a good idea to index datetime field in mysql?

MySQL recommends using indexes for a variety of reasons including elimination of rows between conditions: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

This makes your datetime column an excellent candidate for an index if you are going to be using it in conditions frequently in queries. If your only condition is BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) and you have no other index in the condition, MySQL will have to do a full table scan on every query. I'm not sure how many rows are generated in 30 days, but as long as it's less than about 1/3 of the total rows it will be more efficient to use an index on the column.

Your question about creating an efficient database is very broad. I'd say to just make sure that it's normalized and all appropriate columns are indexed (i.e. ones used in joins and where clauses).

How can I set the default value for an HTML <select> element?

I myself use it

<select selected=''>
    <option value=''></option>
    <option value='1'>ccc</option>
    <option value='2'>xxx</option>
    <option value='3'>zzz</option>
    <option value='4'>aaa</option>
    <option value='5'>qqq</option>
    <option value='6'>wwww</option>
</select>

Code Sign error: The identity 'iPhone Developer' doesn't match any valid certificate/private key pair in the default keychain

I 'tripped' across my solution after 2 days...XCODE 4.0

I've just upgraded to XCode 4.0 and this code signing issue has been a stunning frustrastion. And I've been doing this for over a year various versions...so if you are having problems, you are not alone.

I have recertified, reprovisioned, drag and dropped, manually edit the project file, deleted PROVISIIONING paths, stopped/started XCODE, stopped started keychain, checked spelling, checked bundle ID's, check my birth certificate, the phase of the moon, and taught my dog morse code...none of it worked!!!!

--bottom line---

  1. Goto Targets... Build Settings tab
  2. Go to the Code Signing identity block
    • Check Debug AND Distribution have the same code signing information ..in my case "IPhone Distribution:, dont let DEBUG be blank or not filled in.

If the Debug mode was not the same, it failed the Distribution mode as well...go figure. Hope that helps someone...

Figure: This shows how to find the relevant settings in XCode 4.5.

enter image description here

Force youtube embed to start in 720p

You can do this by adding a parameter &hd=1 to the video URL. That forces the video to start in the highest resolution available for the video. However you cannot specifically set it to 720p, because not every video has that hd ish.

http://www.youtube.com/watch?v=VIDEO_ID&hd=1

http://code.google.com/apis/youtube/player_parameters.html

UPDATE: as of 2014, hd is deprecated https://developers.google.com/youtube/player_parameters?csw=1#Deprecated_Parameters

String formatting: % vs. .format vs. string literal

For python version >= 3.6 (see PEP 498)

s1='albha'
s2='beta'

f'{s1}{s2:>10}'

#output
'albha      beta'

What are XAND and XOR

In most cases you won't find an Xand, Xor, nor, nand Logical operator in programming, but fear not in most cases you can simulate it with the other operators.

Since you didn't state any particular language. I won't do any specific language either. For my examples we'll use the following variables.

A = 3
B = 5
C = 7

and for code I'll put it in the code tag to make it easier to see what I did, I'll also follow the logic through the process to show what the end result will be.

NAND

Also known as Not And, can easily be simulated by using a Not operator, (normally indicated as ! )

You can do the following

if(!((A>B) && (B<C)))

if (!(F&&T))
if(!(F))
If(T)

In our example above it will be true, since both sides were not true. Thus giving us the desired result
Nand

NOR

Also known as Not OR, just like NAND we can simulate it with the not operator.
if(!((A>B) || (B<C)))

if (!(F||T))
if(!(T))
if(F)

Again this will give us the desired outcomes
Nor

XOR

Xor or Exlcusive OR only will be true when one is TRUE but the Other is FALSE

If (!(A > C && B > A) && (A > C || B > A) )

If (!(F && T) && (F || T) )
If (!(F) && (T) )
If (T && T )
If (T)

So that is an example of it working for just 1 or the other being true, I'll show if both are true it will be false.

If ( !(A < C && B > A) && (A < C || B > A) )

If ( !(T && T) && (T ||T) )
If ( !(T) && (T) )
If ( F && T )
If (F)

And both false

If (!(A > C && B < A) && (A > C || B < A) )

If (!(F && F) && (F || F) )
If (!(F) && (F) )
If (T && F )
If (F)


And the picture to help
XOR

XAND

And finally our Exclusive And, this will only return true if both are sides are false, or if both are true. Of course You could just call this a Not XOR (NXOR)

Both True If ( (A < C && B > A) || !(A < C || B > A) )

If ((T&&T) || !(T||T))
IF (T || !T)
If (T || F)
IF (T)

Both False If ( (A > C && B < A) || !(A > C || B < A) )

If ( (F && F) || !(F ||F))
If ( F || !F)
If ( F || T)
If (T)

And lastly 1 true and the other one false. If ((A > C && B > A) || !(A > C || B > A) )

If ((F && T) || ! (F || T) )
If (F||!(T))
If (F||F)
If (F)

Or if you want to go the NXOR route...
If (!(!(A > C && B > A) && (A > C || B > A)))

If (!(!(F && T) && (F || T)) )
If (!(!(F) && (T)) )
If (!(T && T) )
If (!(T))
If (F)

enter image description here

Of course everyone else's solutions probably state this as well, I am putting my own answer in here because the top answer didn't seem to understand that not all languages support XOR or XAND for example C uses ^ for XOR and XAND isn't even supported.

So I provided some examples of how to simulate it with the basic operators in the event your language doesn't support XOR or XAND as their own operators like Php if ($a XOR $B).

As for Xnot what is that? Exclusive not? so not not? I don't know how that would look in a logic gate, I think it doesn't exist. Since Not just inverts the output from a 1 to a 0 and 0 to a 1.

Anyway hope that helps.

How to make Java honor the DNS Caching Timeout?

Java has some seriously weird dns caching behavior. Your best bet is to turn off dns caching or set it to some low number like 5 seconds.

networkaddress.cache.ttl (default: -1)
Indicates the caching policy for successful name lookups from the name service. The value is specified as as integer to indicate the number of seconds to cache the successful lookup. A value of -1 indicates "cache forever".

networkaddress.cache.negative.ttl (default: 10)
Indicates the caching policy for un-successful name lookups from the name service. The value is specified as as integer to indicate the number of seconds to cache the failure for un-successful lookups. A value of 0 indicates "never cache". A value of -1 indicates "cache forever".

PowerMockito mock single static method and return object

What you want to do is a combination of part of 1 and all of 2.

You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.

But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.

From the javadoc:

Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.

The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.

Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:

import static org.mockito.Mockito.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

class ClassWithStatics {
  public static String getString() {
    return "String";
  }

  public static int getInt() {
    return 1;
  }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
  @Test
  public void test() {
    PowerMockito.mockStatic(ClassWithStatics.class);

    when(ClassWithStatics.getString()).thenReturn("Hello!");

    System.out.println("String: " + ClassWithStatics.getString());
    System.out.println("Int: " + ClassWithStatics.getInt());
  }
}

The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.

How do I remove a submodule?

You must remove the entry in .gitmodules and .git/config, and remove the directory of the module from the history:

git rm --cached path/to/submodule

If you'll write on git's mailing list probably someone will do a shell script for you.

Error: unable to verify the first certificate in nodejs

I met very rare case, but hopely it could help to someone: made a proxy service, which proxied requests to another service. And every request's error was "unable to verify the first certificate" even when i added all expected certificates.

The reason was pretty simple - i accidently re-sent also the "host" header. Just make sure you don't send "host" header explicitly.

What's the best visual merge tool for Git?

vimdiff

Once you have have learned vim (and IMHO you should), vimdiff is just one more beautiful little orthogonal concept to learn. To get online help in vim:

:help vimdiff 

This question covers how to use it: How do I use vimdiff to resolve a conflict?

enter image description here

If you're stuck in the dark ages of mouse usage, and the files you're merging aren't very large, I recommend meld.

How can I exclude $(this) from a jQuery selector?

You can also use the jQuery .siblings() method:

HTML

<div class="content">
  <a href="#">A</a>
  <a href="#">B</a>
  <a href="#">C</a>
</div>

Javascript

$(".content").on('click', 'a', function(e) {
  e.preventDefault();
  $(this).siblings().hide('slow');
});

Working demo: http://jsfiddle.net/wTm5f/

difference between css height : 100% vs height : auto

height: 100% gives the element 100% height of its parent container.

height: auto means the element height will depend upon the height of its children.

Consider these examples:

height: 100%

<div style="height: 50px">
    <div id="innerDiv" style="height: 100%">
    </div>
</div>

#innerDiv is going to have height: 50px

height: auto

<div style="height: 50px">
    <div id="innerDiv" style="height: auto">
          <div id="evenInner" style="height: 10px">
          </div>
    </div>
</div>

#innerDiv is going to have height: 10px

Android - get children inside a View?

As an update for those who come across this question after 2018, if you are using Kotlin, you can simply use the Android KTX extension property ViewGroup.children to get a sequence of the View's immediate children.

How to initialize an array in angular2 and typescript

I don't fully understand what you really mean by initializing an array?

Here's an example:

class Environment {

    // you can declare private, public and protected variables in constructor signature 
    constructor(
        private id: string,
        private name: string
    ) { 
        alert( this.id );
    }
}


let environments = new Environment('a','b');

// creating and initializing array of Environment objects
let envArr: Array<Environment> = [ 
        new Environment('c','v'), 
        new Environment('c','v'), 
        new Environment('g','g'), 
        new Environment('3','e') 
  ];

Try it here : https://www.typescriptlang.org/play/index.html

How do I convert a byte array to Base64 in Java?

Additionally, for our Android friends (API Level 8):

import android.util.Base64

...

Base64.encodeToString(bytes, Base64.DEFAULT);

jQuery Mobile - back button

try

$(document).ready(function(){
    $('mybutton').click(function(){
        parent.history.back();
        return false;
    });
});

or

$(document).ready(function(){
    $('mybutton').click(function(){
        parent.history.back();

    });
});

Oracle 12c Installation failed to access the temporary location

The main problem in your case would be failure of accessing \\localhost\c$

If you get an error while trying to access the Windows hidden C share (C$):

C:\> net use \\localhost\c$
System error 53 has occurred.

The network path was not found.

You may find the following articles useful: KB254210 and KB951016.

A simple thing is just to make sure your TCP/IP NetBIOS Helper and Server services are running (Start-Run, services.msc) and try again:

C:\> net use \localhost\c$
The command completed successfully.

Of course, your user must be either an administrator or be part of the administrator group.

If it still fails, manually edit the registry (Start-Run, regedit). Browse to:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

and create a new DWORD value LocalAccountTokenFilterPolicy set to 1

After solving this issue and installing Oracle Database Server, you can disable back your TCP/IP NetBIOS Helper service if you don't need it anymore.

References: http://groglogs.blogspot.ro/2013/11/windows-cannot-access-hidden-c-admin.html



For others:
If you don't have the problem with \\localhost\c$, then you might have the other problem with your username as the others stated (e.g. username with '_' in it):
This will get solved by changing TEMP and TMP environment variables from a command line and then running setup.exe from there.

If this still doesn't work:
Try running setup.exe with "-debug" option and see what happens in there.
You may also want to check what's in the .log files created in your %TEMP% folder (e.g. ssproiut_%number%.log)

Where can I find a list of Mac virtual key codes?

Here are the all keycodes.

Here is a table with some keycodes for the three platforms. It is based on a US Extended keyboard layout.

http://web.archive.org/web/20100501161453/http://www.classicteck.com/rbarticles/mackeyboard.php

Or, there is an app in the Mac App Store named "Key Codes". Download it to see the keycodes of the keys you press.

Key Codes:
https://itunes.apple.com/tr/app/key-codes/id414568915?l=tr&mt=12

Multiple GitHub Accounts & SSH Config

I have 2 accounts on github, and here is what I did (on linux) to make it work.

Keys

  • Create 2 pair of rsa keys, via ssh-keygen, name them properly, so that make life easier.
  • Add private keys to local agent via ssh-add path_to_private_key
  • For each github account, upload a (distinct) public key.

Configuration

~/.ssh/config

Host github-kc
    Hostname        github.com
    User git
    IdentityFile    ~/.ssh/github_rsa_kc.pub
    # LogLevel DEBUG3

Host github-abc
    Hostname        github.com
    User git
    IdentityFile    ~/.ssh/github_rsa_abc.pub
    # LogLevel DEBUG3

Set remote url for repo:

  • For repo in Host github-kc:

    git remote set-url origin git@github-kc:kuchaguangjie/pygtrans.git
    
  • For repo in Host github-abc:

    git remote set-url origin git@github-abc:abcdefg/yyy.git
    

Explaination

Options in ~/.ssh/config:

  • Host github-<identify_specific_user>
    Host could be any value that could identify a host plus an account, it don't need to be a real host, e.g github-kc identify one of my account on github for my local laptop,

    When set remote url for a git repo, this is the value to put after git@, that's how a repo maps to a Host, e.g git remote set-url origin git@github-kc:kuchaguangjie/pygtrans.git


  • [Following are sub options of Host]
  • Hostname
    specify the actual hostname, just use github.com for github,
  • User git
    the user is always git for github,
  • IdentityFile
    specify key to use, just put the path the a public key,
  • LogLevel
    specify log level to debug, if any issue, DEBUG3 gives the most detailed info.

What uses are there for "placement new"?

I've used it to create a Variant class (i.e. an object that can represent a single value that can be one of a number of different types).

If all of the value-types supported by the Variant class are POD types (e.g. int, float, double, bool) then a tagged C-style union is sufficient, but if you want some of the value-types to be C++ objects (e.g. std::string), the C union feature won't do, as non-POD datatypes may not be declared as part of a union.

So instead I allocate a byte array that is big enough (e.g. sizeof(the_largest_data_type_I_support)) and use placement new to initialize the appropriate C++ object in that area when the Variant is set to hold a value of that type. (And placement delete beforehand when switching away from a different non-POD data type, of course)

json_encode() escaping forward slashes

is there a way to disable it?

Yes, you only need to use the JSON_UNESCAPED_SLASHES flag.

!important read before: https://stackoverflow.com/a/10210367/367456 (know what you're dealing with - know your enemy)

json_encode($str, JSON_UNESCAPED_SLASHES);

If you don't have PHP 5.4 at hand, pick one of the many existing functions and modify them to your needs, e.g. http://snippets.dzone.com/posts/show/7487 (archived copy).

Example Demo

<?php
/*
 * Escaping the reverse-solidus character ("/", slash) is optional in JSON.
 *
 * This can be controlled with the JSON_UNESCAPED_SLASHES flag constant in PHP.
 *
 * @link http://stackoverflow.com/a/10210433/367456
 */    

$url = 'http://www.example.com/';

echo json_encode($url), "\n";

echo json_encode($url, JSON_UNESCAPED_SLASHES), "\n";

Example Output:

"http:\/\/www.example.com\/"
"http://www.example.com/"

How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?

I usually use some #define and constants to make the calculation easy:

#define NANO_SECOND_MULTIPLIER  1000000  // 1 millisecond = 1,000,000 Nanoseconds
const long INTERVAL_MS = 500 * NANO_SECOND_MULTIPLIER;

Hence my code would look like this:

timespec sleepValue = {0};

sleepValue.tv_nsec = INTERVAL_MS;
nanosleep(&sleepValue, NULL);

C++ error: "Array must be initialized with a brace enclosed initializer"

You can't initialize arrays like this:

int cipher[Array_size][Array_size]=0;

The syntax for 2D arrays is:

int cipher[Array_size][Array_size]={{0}};

Note the curly braces on the right hand side of the initialization statement.

for 1D arrays:

int tomultiply[Array_size]={0};

Cannot push to Git repository on Bitbucket

Just try

git remote add origin <HTTP URL>

How do you change the character encoding of a postgres database?

To change the encoding of your database:

  1. Dump your database
  2. Drop your database,
  3. Create new database with the different encoding
  4. Reload your data.

Make sure the client encoding is set correctly during all this.

Source: http://archives.postgresql.org/pgsql-novice/2006-03/msg00210.php

Upgrading PHP in XAMPP for Windows?

I have upgraded to php7.2 from php5.6

Steps which I followed.

  1. Download PHP binary from here. I have downloaded VC15 x86 Thread Safe Zip file.
  2. Created a backup of xampp/php folder.
  3. Extract all the contents of zip file to xampp/php folder.
  4. Copied php.ini (as I have modified it before and I want my configuration back, if you were using default one then skip this step.)
  5. Edit below file

C:\xampp\apache\conf\extra\http-xampp.conf

5.1. Replace

LoadFile "C:/xampp/php/php5ts.dll"

LoadFile "C:/xampp/php/libpq.dll"

LoadModule php5_module "C:/xampp/php/php5apache2_4.dll"

to

LoadFile "C:/xampp/php/php7ts.dll"

LoadFile "C:/xampp/php/libpq.dll"

LoadModule php7_module "C:/xampp/php/php7apache2_4.dll"

  1. Restart Apache

How to configure XAMPP to send mail from localhost?

I tried many ways to send a mail from XAMPP Localhost, but since XAMPP hasn't SSL Certificate, my email request blocked by Gmail or similar SMTP Service providers.

Then I used MailHog for local smtp server, what you need to do is just run it. localhost:1025 is for smtp server, localhost:8025 is for mail server, where you can check the emails you sent.

here is my code:

    require_once "src/PHPMailer.php";
    require_once "src/SMTP.php";
    require_once "src/Exception.php";

    $mail = new PHPMailer\PHPMailer\PHPMailer();

      //Server settings
    $mail->SMTPDebug = 3;                      // Enable verbose debug output
    $mail->isSMTP();                                            // Send using SMTP
    $mail->Host       = 'localhost';                    // Set the SMTP server to send through
    $mail->Port       = 1025;                                    // TCP port to connect to
    // $mail->Username   = '';                     // SMTP username
    // $mail->Password   = '';                               // SMTP password
    // $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    // $mail->SMTPSecure = 'tls';         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted

    //Recipients
    $mail->setFrom('[email protected]', 'Mailer');
    $mail->addAddress('[email protected]', 'Joe User');     // Add a recipient

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    if(!$mail->Send()) {
        echo "Mailer Error: " . $mail->ErrorInfo;
    } else {
        echo "Message sent!";
    }

MailHog Github Repository link

Create Generic method constraining T to an Enum

The existing answers are true as of C# <=7.2. However, there is a C# language feature request (tied to a corefx feature request) to allow the following;

public class MyGeneric<TEnum> where TEnum : System.Enum
{ }

At time of writing, the feature is "In discussion" at the Language Development Meetings.

EDIT

As per nawfal's info, this is being introduced in C# 7.3.

EDIT 2

This is now in C# 7.3 forward (release notes)

Sample;

public static Dictionary<int, string> EnumNamedValues<T>()
    where T : System.Enum
{
    var result = new Dictionary<int, string>();
    var values = Enum.GetValues(typeof(T));

    foreach (int item in values)
        result.Add(item, Enum.GetName(typeof(T), item));
    return result;
}

Importing CommonCrypto in a Swift framework

I know this is an old question. But I figure out an alternative way to use the library in Swift project, which might be helpful for those who don't want to import framework introduced in these answers.

In Swift project, create a Objective-C bridging header, create NSData category (or custom class that to use the library) in Objective-C. The only drawback would be that you have to write all implementation code in Objective-C. For example:

#import "NSData+NSDataEncryptionExtension.h"
#import <CommonCrypto/CommonCryptor.h>

@implementation NSData (NSDataEncryptionExtension)
- (NSData *)AES256EncryptWithKey:(NSString *)key {
    //do something
}

- (NSData *)AES256DecryptWithKey:(NSString *)key {
//do something
}

And then in your objective-c bridging header, add this

#import "NSData+NSDataEncryptionExtension.h"

And then in Swift class do similar thing:

public extension String {
func encryp(withKey key:String) -> String? {
    if let data = self.data(using: .utf8), let encrypedData = NSData(data: data).aes256Encrypt(withKey: key) {
        return encrypedData.base64EncodedString()
    }
    return nil
}
func decryp(withKey key:String) -> String? {
    if let data = NSData(base64Encoded: self, options: []), let decrypedData = data.aes256Decrypt(withKey: key) {
        return decrypedData.UTF8String
    }
    return nil
}
}

It works as expected.

Intersect Two Lists in C#

public static List<T> ListCompare<T>(List<T> List1 , List<T> List2 , string key )
{
    return List1.Select(t => t.GetType().GetProperty(key).GetValue(t))
                .Intersect(List2.Select(t => t.GetType().GetProperty(key).GetValue(t))).ToList();
}

How can I commit files with git?

It sounds as if the only problem here is that the default editor that is launched is vi or vim, with which you're not familiar. (As quick tip, to exit that editor without saving changes, hit Esc a few times and then type :, q, ! and Enter.)

There are several ways to set up your default editor, and you haven't indicated which operating system you're using, so it's difficult to recommend one in particular. I'd suggest using:

 git config --global core.editor "name-of-your-editor"

... which sets a global git preference for a particular editor. Alternatively you can set the $EDITOR environment variable.

Convert np.array of type float64 to type uint8 scaling values

you can use skimage.img_as_ubyte(yourdata) it will make you numpy array ranges from 0->255

from skimage import img_as_ubyte

img = img_as_ubyte(data)
cv2.imshow("Window", img)

invalid byte sequence for encoding "UTF8"

I got the same error when I was trying to copy a csv generated by Excel to a Postgres table (all on a Mac). This is how I resolved it:

1) Open the File in Atom (the IDE that I use)

2) Make an insignificant change in the file. Save the file. Undo the change. Save again.

Presto! Copy command worked now.

(I think Atom saved it in a format which worked)

Function to check if a string is a date

I found my answer here https://stackoverflow.com/a/19271434/1363220, bassically

$d = DateTime::createFromFormat($format, $date);
// The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
if($d && $d->format($format) === $date) {
    //it's a proper date!
}
else {
    //it's not a proper date
}

What port is a given program using?

netstat -b -a lists the ports in use and gives you the executable that's using each one. I believe you need to be in the administrator group to do this, and I don't know what security implications there are on Vista.

I usually add -n as well to make it a little faster, but adding -b can make it quite slow.

Edit: If you need more functionality than netstat provides, vasac suggests that you try TCPView.

String replacement in java, similar to a velocity template

My preferred way is String.format() because its a oneliner and doesn't require third party libraries:

String message = String.format("Hello! My name is %s, I'm %s.", name, age); 

I use this regularly, e.g. in exception messages like:

throw new Exception(String.format("Unable to login with email: %s", email));

Hint: You can put in as many variables as you like because format() uses Varargs

how to dynamically add options to an existing select in vanilla javascript

Use the document.createElement function and then add it as a child of your select.

var newOption = document.createElement("option");
newOption.text = 'the options text';
newOption.value = 'some value if you want it';
daySelect.appendChild(newOption);

SQL get the last date time record

this working

SELECT distinct filename
,last_value(dates)over (PARTITION BY filename ORDER BY filename)posd
,last_value(status)over (PARTITION BY filename ORDER BY filename )poss
FROM distemp.dbo.Shmy_table

Refresh Excel VBA Function Results

If you include ALL references to the spreadsheet data in the UDF parameter list, Excel will recalculate your function whenever the referenced data changes:

Public Function doubleMe(d As Variant)
    doubleMe = d * 2
End Function

You can also use Application.Volatile, but this has the disadvantage of making your UDF always recalculate - even when it does not need to because the referenced data has not changed.

Public Function doubleMe()
    Application.Volatile
    doubleMe = Worksheets("Fred").Range("A1") * 2
End Function

How to provide password to a command that prompts for one in bash?

Secure commands will not allow this, and rightly so, I'm afraid - it's a security hole you could drive a truck through.

If your command does not allow it using input redirection, or a command-line parameter, or a configuration file, then you're going to have to resort to serious trickery.

Some applications will actually open up /dev/tty to ensure you will have a hard time defeating security. You can get around them by temporarily taking over /dev/tty (creating your own as a pipe, for example) but this requires serious privileges and even it can be defeated.

Is it possible to GROUP BY multiple columns using MySQL?

If you prefer (I need to apply this) group by two columns at same time, I just saw this point:

SELECT CONCAT (col1, '_', col2) AS Group1 ... GROUP BY Group1

What is the difference between public, protected, package-private and private in Java?

Easy rule. Start with declaring everything private. And then progress towards the public as the needs arise and design warrants it.

When exposing members ask yourself if you are exposing representation choices or abstraction choices. The first is something you want to avoid as it will introduce too many dependencies on the actual representation rather than on its observable behavior.

As a general rule I try to avoid overriding method implementations by subclassing; it's too easy to screw up the logic. Declare abstract protected methods if you intend for it to be overridden.

Also, use the @Override annotation when overriding to keep things from breaking when you refactor.

Use placeholders in yaml

I suppose https://get-ytt.io/ would be an acceptable solution to your problem

Regular Expression to reformat a US phone number in Javascript

Assuming you want the format "(123) 456-7890":

function formatPhoneNumber(phoneNumberString) {
  var cleaned = ('' + phoneNumberString).replace(/\D/g, '')
  var match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/)
  if (match) {
    return '(' + match[1] + ') ' + match[2] + '-' + match[3]
  }
  return null
}

Here's a version that allows the optional +1 international code:

function formatPhoneNumber(phoneNumberString) {
  var cleaned = ('' + phoneNumberString).replace(/\D/g, '')
  var match = cleaned.match(/^(1|)?(\d{3})(\d{3})(\d{4})$/)
  if (match) {
    var intlCode = (match[1] ? '+1 ' : '')
    return [intlCode, '(', match[2], ') ', match[3], '-', match[4]].join('')
  }
  return null
}
formatPhoneNumber('+12345678900') // => "+1 (234) 567-8900"
formatPhoneNumber('2345678900')   // => "(234) 567-8900"

Custom sort function in ng-repeat

To include the direction along with the orderBy function:

ng-repeat="card in cards | orderBy:myOrderbyFunction():defaultSortDirection"

where

defaultSortDirection = 0; // 0 = Ascending, 1 = Descending

How to add a new row to an empty numpy array

In this case you might want to use the functions np.hstack and np.vstack

arr = np.array([])
arr = np.hstack((arr, np.array([1,2,3])))
# arr is now [1,2,3]

arr = np.vstack((arr, np.array([4,5,6])))
# arr is now [[1,2,3],[4,5,6]]

You also can use the np.concatenate function.

Cheers

How to run a PowerShell script

An easy way is to use PowerShell ISE, open script, run and invoke your script, function...

Enter image description here

Find all table names with column name?

Please try the below query. Use sys.columns to get the details :-

SELECT c.name AS ColName, t.name AS TableName
FROM sys.columns c
    JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%MyCol%';

check if "it's a number" function in Oracle

You can use the regular expression function 'regexp_like' in ORACLE (10g)as below:

select case
       when regexp_like(myTable.id, '[[:digit:]]') then
        case
       when myTable.id > 0 then
        'Is a number greater than 0'
       else
        'Is a number less than or equal to 0'
     end else 'it is not a number' end as valuetype
from table myTable

TypeScript: Creating an empty typed container array

Okay you got the syntax wrong here, correct way to do this is:

var arr: Criminal[] = [];

I'm assuming you are using var so that means declaring it somewhere inside the func(),my suggestion would be use let instead of var.

If declaring it as c class property usse acces modifiers like private, public, protected.

Node.js Logging

Each answer is 5 6 years old, so bit outdated or depreciated. Let's talk in 2020.

simple-node-logger is simple multi-level logger for console, file, and rolling file appenders. Features include:

  1. levels: trace, debug, info, warn, error and fatal levels (plus all and off)

  2. flexible appender/formatters with default to HH:mm:ss.SSS LEVEL message add appenders to send output to console, file, rolling file, etc

  3. change log levels on the fly

  4. domain and category columns

  5. overridable format methods in base appender

  6. stats that track counts of all log statements including warn, error, etc

You can easily use it in any nodejs web application:

   // create a stdout console logger
  const log = require('simple-node-logger').createSimpleLogger();

or

  // create a stdout and file logger
  const log = require('simple-node-logger').createSimpleLogger('project.log');

or

  // create a custom timestamp format for log statements
  const SimpleNodeLogger = require('simple-node-logger'),
  opts = {
      logFilePath:'mylogfile.log',
      timestampFormat:'YYYY-MM-DD HH:mm:ss.SSS'
   },
  log = SimpleNodeLogger.createSimpleLogger( opts );

or

  // create a file only file logger
  const log = require('simple-node-logger').createSimpleFileLogger('project.log');

or

  // create a rolling file logger based on date/time that fires process events
  const opts = {
      errorEventName:'error',
       logDirectory:'/mylogfiles', // NOTE: folder must exist and be writable...
        fileNamePattern:'roll-<DATE>.log',
         dateFormat:'YYYY.MM.DD'
  };
  const log = require('simple-node-logger').createRollingFileLogger( opts );

Messages can be logged by

  log.info('this is logged info message')
  log.warn('this is logged warn message')//etc..

PLUS POINT: It can send logs to console or socket. You can also append to log levels.

This is the most effective and easy way to handle logs functionality.

How to implement debounce in Vue2?

Option 1: Re-usable, no deps

- Recommended if needed more than once in your project

/helpers.js

export function debounce (fn, delay) {
  var timeoutID = null
  return function () {
    clearTimeout(timeoutID)
    var args = arguments
    var that = this
    timeoutID = setTimeout(function () {
      fn.apply(that, args)
    }, delay)
  }
}

/Component.vue

<script>
  import {debounce} from './helpers'

  export default {
    data () {
      return {
        input: '',
        debouncedInput: ''
      }
    },
    watch: {
      input: debounce(function (newVal) {
        this.debouncedInput = newVal
      }, 500)
    }
  }
</script>

Codepen


Option 2: In-component, also no deps

- Recommended if using once or in small project

/Component.vue

<template>
    <input type="text" v-model="input" />
</template>

<script>
  export default {
    data: {
        timeout: null,
        debouncedInput: ''
    },
    computed: {
     input: {
        get() {
          return this.debouncedInput
        },
        set(val) {
          if (this.timeout) clearTimeout(this.timeout)
          this.timeout = setTimeout(() => {
            this.debouncedInput = val
          }, 300)
        }
      }
    }
  }
</script>

Codepen

Equivalent of explode() to work with strings in MySQL

I'm not sure if this is fully answering the question (it isn't), but it's the solution I came up with for my very similar problem. I know some of the other solutions look shorter but they seem to use SUBSTRING_INDEX() way more than necessary. Here I try to just use LOCATE() just once per delimiter.

-- *****************************************************************************
-- test_PVreplace

DROP FUNCTION IF EXISTS test_PVreplace;

delimiter //
CREATE FUNCTION test_PVreplace (
   str TEXT,   -- String to do search'n'replace on
   pv TEXT     -- Parameter/value pairs 'p1=v1|p2=v2|p3=v3'
   )
   RETURNS TEXT

-- Replace specific tags with specific values.

sproc:BEGIN
   DECLARE idx INT;
   DECLARE idx0 INT DEFAULT 1;   -- 1-origined, not 0-origined
   DECLARE len INT;
   DECLARE sPV TEXT;
   DECLARE iPV INT;
   DECLARE sP TEXT;
   DECLARE sV TEXT;

   -- P/V string *must* end with a delimiter.

   IF (RIGHT (pv, 1) <> '|') THEN
      SET pv = CONCAT (pv, '|');
      END IF;

   -- Find all the P/V pairs.

   SELECT LOCATE ('|', pv, idx0) INTO idx;
   WHILE (idx > 0) DO
      SET len = idx - idx0;
      SELECT SUBSTRING(pv, idx0, len) INTO sPV;

      -- Found a P/V pair.  Break it up.

      SELECT LOCATE ('=', sPV) INTO iPV;
      IF (iPV = 0) THEN
         SET sP = sPV;
         SET sV = '';
      ELSE
         SELECT SUBSTRING(sPV, 1, iPV-1) INTO sP;
         SELECT SUBSTRING(sPV, iPV+1) INTO sV;
         END IF;

      -- Do the substitution(s).

      SELECT REPLACE (str, sP, sV) INTO str;

      -- Do next P/V pair.

      SET idx0 = idx + 1;
      SELECT LOCATE ('|', pv, idx0) INTO idx;
      END WHILE;
   RETURN (str);
END//
delimiter ;

SELECT test_PVreplace ('%one% %two% %three%', '%one%=1|%two%=2|%three%=3');
SELECT test_PVreplace ('%one% %two% %three%', '%one%=I|%two%=II|%three%=III');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', '%one%=I|%two%=II|%three%=III');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', '');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', NULL);
SELECT test_PVreplace ('%one% %two% %three%', '%one%=%two%|%two%=%three%|%three%=III');

jQuery - If element has class do this

First, you're missing some parentheses in your conditional:

if ($("#about").hasClass("opened")) {
  $("#about").animate({right: "-700px"}, 2000);
}

But you can also simplify this to:

$('#about.opened').animate(...);

If #about doesn't have the opened class, it won't animate.

If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)

How to remove focus border (outline) around text/input boxes? (Chrome)

I've found the solution.
I used: outline:none; in the CSS and it seems to have worked. Thanks for the help anyway. :)

How do I copy a string to the clipboard?

The snippet I share here take advantage of the ability to format text files: what if you want to copy a complex output to the clipboard ? (Say a numpy array in column or a list of something)

import subprocess
import os

def cp2clip(clist):

    #create a temporary file
    fi=open("thisTextfileShouldNotExist.txt","w")

    #write in the text file the way you want your data to be
    for m in clist:
        fi.write(m+"\n")

    #close the file
    fi.close()

    #send "clip < file" to the shell
    cmd="clip < thisTextfileShouldNotExist.txt"
    w = subprocess.check_call(cmd,shell=True)

    #delete the temporary text file
    os.remove("thisTextfileShouldNotExist.txt")

    return w

works only for windows, can be adapted for linux or mac I guess. Maybe a bit complicated...

example:

>>>cp2clip(["ET","phone","home"])
>>>0

Ctrl+V in any text editor :

ET
phone
home

Test if a command outputs an empty string

Here's a solution for more extreme cases:

if [ `command | head -c1 | wc -c` -gt 0 ]; then ...; fi

This will work

  • for all Bourne shells;
  • if the command output is all zeroes;
  • efficiently regardless of output size;

however,

  • the command or its subprocesses will be killed once anything is output.

How to Refresh a Component in Angular

constructor(private router:Router, private route:ActivatedRoute ) { 
}

onReload(){
 this.router.navigate(['/servers'],{relativeTo:this.route})
}

How to set cursor to input box in Javascript?

In JavaScript first focus on the control and then select the control to display the cursor on texbox...

document.getElementById(frmObj.id).focus();
document.getElementById(frmObj.id).select();

or by using jQuery

$("#textboxID").focus();

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

Printing all variables value from a class

i will get my answer as follow:

import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class findclass {
    public static void main(String[] args) throws Exception, IllegalAccessException {
        new findclass().findclass(new Object(), "objectName");
        new findclass().findclass(1213, "int");
        new findclass().findclass("ssdfs", "String");
    }


    public Map<String, String>map=new HashMap<String, String>();

    public void findclass(Object c,String name) throws IllegalArgumentException, IllegalAccessException {
        if(map.containsKey(c.getClass().getName() + "@" + Integer.toHexString(c.hashCode()))){
            System.out.println(c.getClass().getSimpleName()+" "+name+" = "+map.get(c.getClass().getName() + "@" + Integer.toHexString(c.hashCode()))+" = "+c);          
            return;}
        map.put(c.getClass().getName() + "@" + Integer.toHexString(c.hashCode()), name);
        Class te=c.getClass();
        if(te.equals(Integer.class)||te.equals(Double.class)||te.equals(Float.class)||te.equals(Boolean.class)||te.equals(Byte.class)||te.equals(Long.class)||te.equals(String.class)||te.equals(Character.class)){
            System.out.println(c.getClass().getSimpleName()+" "+name+" = "+c);
            return; 
        }


        if(te.isArray()){
            if(te==int[].class||te==char[].class||te==double[].class||te==float[].class||te==byte[].class||te==long[].class||te==boolean[].class){
                boolean dotflag=true;
                for (int i = 0; i < Array.getLength(c); i++) {
                    System.out.println(Array.get(c, i).getClass().getSimpleName()+" "+name+"["+i+"] = "+Array.get(c, i));
                }
                return; 
            }
            Object[]arr=(Object[])c;
            for (Object object : arr) {
                if(object==null)    
                    System.out.println(c.getClass().getSimpleName()+" "+name+" = null");
                else {
                    findclass(object, name+"."+object.getClass().getSimpleName());
                }
            }


        }   

        Field[] fields=c.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);

            if(field.get(c)==null){
                System.out.println(field.getType().getSimpleName()+" "+name+"."+field.getName()+" = null");
                continue;
            }

            findclass(field.get(c),name+"."+field.getName());
        }
        if(te.getSuperclass()==Number.class||te.getSuperclass()==Object.class||te.getSuperclass()==null)
            return;
        Field[]faFields=c.getClass().getSuperclass().getDeclaredFields();

        for (Field field : faFields) {
            field.setAccessible(true);
                if(field.get(c)==null){
                    System.out.println(field.getType().getSimpleName()+" "+name+"<"+c.getClass().getSuperclass().getSimpleName()+"."+field.getName()+" = null");
                    continue;
                }
                Object check=field.get(c);
                findclass(field.get(c),name+"<"+c.getClass().getSuperclass().getSimpleName()+"."+field.getName());

        }

    }

    public void findclass(Object c,String name,Writer writer) throws IllegalArgumentException, IllegalAccessException, IOException {
        if(map.containsKey(c.getClass().getName() + "@" + Integer.toHexString(c.hashCode()))){
            writer.append(c.getClass().getSimpleName()+" "+name+" = "+map.get(c.getClass().getName() + "@" + Integer.toHexString(c.hashCode()))+" = "+c+"\n");          
            return;}
        map.put(c.getClass().getName() + "@" + Integer.toHexString(c.hashCode()), name);
        Class te=c.getClass();
        if(te.equals(Integer.class)||te.equals(Double.class)||te.equals(Float.class)||te.equals(Boolean.class)||te.equals(Byte.class)||te.equals(Long.class)||te.equals(String.class)||te.equals(Character.class)){
            writer.append(c.getClass().getSimpleName()+" "+name+" = "+c+"\n");
            return; 
        }


        if(te.isArray()){
            if(te==int[].class||te==char[].class||te==double[].class||te==float[].class||te==byte[].class||te==long[].class||te==boolean[].class){
                boolean dotflag=true;
                for (int i = 0; i < Array.getLength(c); i++) {
                    writer.append(Array.get(c, i).getClass().getSimpleName()+" "+name+"["+i+"] = "+Array.get(c, i)+"\n");
                }
                return; 
            }
            Object[]arr=(Object[])c;
            for (Object object : arr) {
                if(object==null){   
                    writer.append(c.getClass().getSimpleName()+" "+name+" = null"+"\n");
                }else {
                    findclass(object, name+"."+object.getClass().getSimpleName(),writer);
                }
            }


        }   

        Field[] fields=c.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);

            if(field.get(c)==null){
                writer.append(field.getType().getSimpleName()+" "+name+"."+field.getName()+" = null"+"\n");
                continue;
            }

            findclass(field.get(c),name+"."+field.getName(),writer);
        }
        if(te.getSuperclass()==Number.class||te.getSuperclass()==Object.class||te.getSuperclass()==null)
            return;
        Field[]faFields=c.getClass().getSuperclass().getDeclaredFields();

        for (Field field : faFields) {
            field.setAccessible(true);
                if(field.get(c)==null){
                    writer.append(field.getType().getSimpleName()+" "+name+"<"+c.getClass().getSuperclass().getSimpleName()+"."+field.getName()+" = null"+"\n");
                    continue;
                }
                Object check=field.get(c);
                findclass(field.get(c),name+"<"+c.getClass().getSuperclass().getSimpleName()+"."+field.getName(),writer);

        }
    }

}

Round double value to 2 decimal places

I use the solution posted by Umberto Raimondi extending type Double:

extension Double {
    func roundTo(places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor
    }
}

Javascript require() function giving ReferenceError: require is not defined

For me the issue was I did not have my webpack build mode set to production for the package I was referencing in. Explicitly setting it to "build": "webpack --mode production" fixed the issue.

Get text of the selected option with jQuery

You could actually put the value = to the text and then do

$j(document).ready(function(){
    $j("select#select_2").change(function(){
        val = $j("#select_2 option:selected").html();
        alert(val);
    });
});

Or what I did on a similar case was

<select name="options[2]" id="select_2" onChange="JavascriptMethod()">
  with you're options here
</select>

With this second option you should have a undefined. Give me feedback if it worked :)

Patrick

Converting XML to JSON using Python?

Well, probably the simplest way is just parse the XML into dictionaries and then serialize that with simplejson.

What are the differences between "git commit" and "git push"?

Just want to add the following points:

Yon can not push until you commit as we use git push to push commits made on your local branch to a remote repository.

The git push command takes two arguments:

A remote name, for example, origin A branch name, for example, master

For example:

git push  <REMOTENAME> <BRANCHNAME> 
git push  origin       master

How to get temporary folder for current user

DO NOT use this:

System.Environment.GetEnvironmentVariable("TEMP")

Environment variables can be overridden, so the TEMP variable is not necessarily the directory.

The correct way is to use System.IO.Path.GetTempPath() as in the accepted answer.

Java: Replace all ' in a string with \'

You can use apache's commons-text library (instead of commons-lang):

Example code:

org.apache.commons.text.StringEscapeUtils.escapeJava(escapedString);

Dependency:

compile 'org.apache.commons:commons-text:1.8'

OR

<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-text</artifactId>
   <version>1.8</version>
</dependency>

Filter element based on .data() key/value

We can make a plugin pretty easily:

$.fn.filterData = function(key, value) {
    return this.filter(function() {
        return $(this).data(key) == value;
    });
};

Usage (checking a radio button):

$('input[name=location_id]').filterData('my-data','data-val').prop('checked',true);

How can I enable cURL for an installed Ubuntu LAMP stack?

From Install Curl Extension for PHP in Ubuntu:

sudo apt-get install php5-curl

After installing libcurl, you should restart the web server with one of the following commands,

sudo /etc/init.d/apache2 restart

or

sudo service apache2 restart

Thread pooling in C++11

Follwoing [PhD EcE](https://stackoverflow.com/users/3818417/phd-ece) suggestion, I implemented the thread pool:

function_pool.h

#pragma once
#include <queue>
#include <functional>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <cassert>

class Function_pool
{

private:
    std::queue<std::function<void()>> m_function_queue;
    std::mutex m_lock;
    std::condition_variable m_data_condition;
    std::atomic<bool> m_accept_functions;

public:

    Function_pool();
    ~Function_pool();
    void push(std::function<void()> func);
    void done();
    void infinite_loop_func();
};

function_pool.cpp

#include "function_pool.h"

Function_pool::Function_pool() : m_function_queue(), m_lock(), m_data_condition(), m_accept_functions(true)
{
}

Function_pool::~Function_pool()
{
}

void Function_pool::push(std::function<void()> func)
{
    std::unique_lock<std::mutex> lock(m_lock);
    m_function_queue.push(func);
    // when we send the notification immediately, the consumer will try to get the lock , so unlock asap
    lock.unlock();
    m_data_condition.notify_one();
}

void Function_pool::done()
{
    std::unique_lock<std::mutex> lock(m_lock);
    m_accept_functions = false;
    lock.unlock();
    // when we send the notification immediately, the consumer will try to get the lock , so unlock asap
    m_data_condition.notify_all();
    //notify all waiting threads.
}

void Function_pool::infinite_loop_func()
{
    std::function<void()> func;
    while (true)
    {
        {
            std::unique_lock<std::mutex> lock(m_lock);
            m_data_condition.wait(lock, [this]() {return !m_function_queue.empty() || !m_accept_functions; });
            if (!m_accept_functions && m_function_queue.empty())
            {
                //lock will be release automatically.
                //finish the thread loop and let it join in the main thread.
                return;
            }
            func = m_function_queue.front();
            m_function_queue.pop();
            //release the lock
        }
        func();
    }
}

main.cpp

#include "function_pool.h"
#include <string>
#include <iostream>
#include <mutex>
#include <functional>
#include <thread>
#include <vector>

Function_pool func_pool;

class quit_worker_exception : public std::exception {};

void example_function()
{
    std::cout << "bla" << std::endl;
}

int main()
{
    std::cout << "stating operation" << std::endl;
    int num_threads = std::thread::hardware_concurrency();
    std::cout << "number of threads = " << num_threads << std::endl;
    std::vector<std::thread> thread_pool;
    for (int i = 0; i < num_threads; i++)
    {
        thread_pool.push_back(std::thread(&Function_pool::infinite_loop_func, &func_pool));
    }

    //here we should send our functions
    for (int i = 0; i < 50; i++)
    {
        func_pool.push(example_function);
    }
    func_pool.done();
    for (unsigned int i = 0; i < thread_pool.size(); i++)
    {
        thread_pool.at(i).join();
    }
}

How to install SimpleJson Package for Python

If you have Python 2.6 installed then you already have simplejson - just import json; it's the same thing.

How do I get ruby to print a full backtrace instead of a truncated one?

One liner for callstack:

begin; Whatever.you.want; rescue => e; puts e.message; puts; puts e.backtrace; end

One liner for callstack without all the gems's:

begin; Whatever.you.want; rescue => e; puts e.message; puts; puts e.backtrace.grep_v(/\/gems\//); end

One liner for callstack without all the gems's and relative to current directory

begin; Whatever.you.want; rescue => e; puts e.message; puts; puts e.backtrace.grep_v(/\/gems\//).map { |l| l.gsub(`pwd`.strip + '/', '') }; end

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

Laravel back button

You can use {{ URL::previous() }} But it not perfect UX.

For example, when you press F5 button and click again to Back Button with {{ URL::previous() }} you will stay in.

A good way is using {{ route('page.edit', $item->id) }} it always true page you wanna to redirect.

How to use Microsoft.Office.Interop.Excel on a machine without installed MS Office?

you can create a service and generate excel on server and then allow clients download excel. cos buying excel license for 1000 ppl, it is better to have one license for server.

hope that helps.

Creating an empty list in Python

I use [].

  1. It's faster because the list notation is a short circuit.
  2. Creating a list with items should look about the same as creating a list without, why should there be a difference?

How to uninstall Ruby from /usr/local?

Edit: As suggested in comments. This solution is for Linux OS. That too if you have installed ruby manually from package-manager.

If you want to have multiple ruby versions, better to have RVM. In that case you don't need to remove ruby older version.

Still if want to remove then follow the steps below:

First you should find where Ruby is:

whereis ruby

will list all the places where it exists on your system, then you can remove all them explicitly. Or you can use something like this:

rm -rf /usr/local/lib/ruby
rm -rf /usr/lib/ruby
rm -f /usr/local/bin/ruby
rm -f /usr/bin/ruby
rm -f /usr/local/bin/irb
rm -f /usr/bin/irb
rm -f /usr/local/bin/gem
rm -f /usr/bin/gem

Better way to call javascript function in a tag

I’m tempted to say that both are bad practices.

The use of onclick or javascript: should be dismissed in favor of listening to events from outside scripts, allowing for a better separation between markup and logic and thus leading to less repeated code.

Note also that external scripts get cached by the browser.

Have a look at this answer.

Some good ways of implementing cross-browser event listeners here.

Keep the order of the JSON keys during JSON conversion to CSV

Solved.

I used the JSON.simple library from here https://code.google.com/p/json-simple/ to read the JSON string to keep the order of keys and use JavaCSV library from here http://sourceforge.net/projects/javacsv/ to convert to CSV format.

What’s the best way to check if a file exists in C++? (cross platform)

Use stat(), if it is cross-platform enough for your needs. It is not C++ standard though, but POSIX.

On MS Windows there is _stat, _stat64, _stati64, _wstat, _wstat64, _wstati64.

Can't compile C program on a Mac after upgrade to Mojave

TL;DR

Make sure you have downloaded the latest 'Command Line Tools' package and run this from a terminal (command line):

open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

For some information on Catalina, see Can't compile a C program on a Mac after upgrading to Catalina 10.15.


Extracting a semi-coherent answer from rather extensive comments…

Preamble

Very often, xcode-select --install has been the correct solution, but it does not seem to help this time. Have you tried running the main Xcode GUI interface? It may install some extra software for you and clean up. I did that after installing Xcode 10.0, but a week or more ago, long before upgrading to Mojave.

I observe that if your GCC is installed in /usr/local/bin, you probably aren't using the GCC from Xcode; that's normally installed in /usr/bin.

I too have updated to macOS 10.14 Mojave and Xcode 10.0. However, both the system /usr/bin/gcc and system /usr/bin/clang are working for me (Apple LLVM version 10.0.0 (clang-1000.11.45.2) Target: x86_64-apple-darwin18.0.0 for both.) I have a problem with my home-built GCC 8.2.0 not finding headers in /usr/include, which is parallel to your problem with /usr/local/bin/gcc not finding headers either.

I've done a bit of comparison, and my Mojave machine has no /usr/include at all, yet /usr/bin/clang is able to compile OK. A header (_stdio.h, with leading underscore) was in my old /usr/include; it is missing now (hence my problem with GCC 8.2.0). I ran xcode-select --install and it said "xcode-select: note: install requested for command line developer tools" and then ran a GUI installer which showed me a licence which I agreed to, and it downloaded and installed the command line tools — or so it claimed.

I then ran Xcode GUI (command-space, Xcode, return) and it said it needed to install some more software, but still no /usr/include. But I can compile with /usr/bin/clang and /usr/bin/gcc — and the -v option suggests they're using

InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

Working solution

Then Maxxx noted:

I've found a way. If we are using Xcode 10, you will notice that if you navigate to the /usr in the Finder, you will not see a folder called 'include' any more, which is why the terminal complains of the absence of the header files which is contained inside the 'include' folder. In the Xcode 10.0 Release Notes, it says there is a package:

/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg 

and you should install that package to have the /usr/include folder installed. Then you should be good to go.

When all else fails, read the manual or, in this case, the release notes. I'm not dreadfully surprised to find Apple wanting to turn their backs on their Unix heritage, but I am disappointed. If they're careful, they could drive me away. Thank you for the information.

Having installed the package using the following command at the command line, I have /usr/include again, and my GCC 8.2.0 works once more.

open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

Downloading Command Line Tools

As Vesal points out in a valuable comment, you need to download the Command Line Tools package for Xcode 10.1 on Mojave 10.14, and you can do so from:

You need to login with an Apple ID to be able to get the download. When you've done the download, install the Command Line Tools package. Then install the headers as described in the section 'Working Solution'.

This worked for me on Mojave 10.14.1. I must have downloaded this before, but I'd forgotten by the time I was answering this question.

Upgrade to Mojave 10.14.4 and Xcode 10.2

On or about 2019-05-17, I updated to Mojave 10.14.4, and the Xcode 10.2 command line tools were also upgraded (or Xcode 10.1 command line tools were upgraded to 10.2). The open command shown above fixed the missing headers. There may still be adventures to come with upgrading the main Xcode to 10.2 and then re-reinstalling the command line tools and the headers package.

Upgrade to Xcode 10.3 (for Mojave 10.14.6)

On 2019-07-22, I got notice via the App Store that the upgrade to Xcode 10.3 is available and that it includes SDKs for iOS 12.4, tvOS 12.4, watchOS 5.3 and macOS Mojave 10.14.6. I installed it one of my 10.14.5 machines, and ran it, and installed extra components as it suggested, and it seems to have left /usr/include intact.

Later the same day, I discovered that macOS Mojave 10.14.6 was available too (System Preferences ? Software Update), along with a Command Line Utilities package IIRC (it was downloaded and installed automatically). Installing the o/s update did, once more, wipe out /usr/include, but the open command at the top of the answer reinstated it again. The date I had on the file for the open command was 2019-07-15.

Upgrade to XCode 11.0 (for Catalina 10.15)

The upgrade to XCode 11.0 ("includes Swift 5.1 and SDKs for iOS 13, tvOS 13, watchOS 6 and macOS Catalina 10.15") was released 2019-09-21. I was notified of 'updates available', and downloaded and installed it onto machines running macOS Mojave 10.14.6 via the App Store app (updates tab) without problems, and without having to futz with /usr/include. Immediately after installation (before having run the application itself), I tried a recompilation and was told:

Agreeing to the Xcode/iOS license requires admin privileges, please run “sudo xcodebuild -license” and then retry this command.

Running that (sudo xcodebuild -license) allowed me to run the compiler. Since then, I've run the application to install extra components it needs; still no problem. It remains to be seen what happens when I upgrade to Catalina itself — but my macOS Mojave 10.14.6 machines are both OK at the moment (2019-09-24).

Find Oracle JDBC driver in Maven repository

The Oracle JDBC Driver is now available in the Oracle Maven Repository (not in Central).

<dependency>
    <groupId>com.oracle.jdbc</groupId>
    <artifactId>ojdbc7</artifactId>
    <version>12.1.0.2</version>
</dependency>

The Oracle Maven Repository requires a user registration. Instructions can be found in:

https://blogs.oracle.com/dev2dev/get-oracle-jdbc-drivers-and-ucp-from-oracle-maven-repository-without-ides

Update 2019-10-03

I noticed Spring Boot is now using the Oracle JDBC Driver from Maven Central.

<dependency>
    <groupId>com.oracle.ojdbc</groupId>
    <artifactId>ojdbc10</artifactId>
    <version>19.3.0.0</version>
</dependency>

For Gradle users, use:

implementation 'com.oracle.ojdbc:ojdbc10:19.3.0.0'

There is no need for user registration.

Update 2020-03-02

Oracle is now publishing the drivers under the com.oracle.database group id. See Anthony Accioly answer for more information. Thanks Anthony.

Oracle JDBC Driver compatible with JDK6, JDK7, and JDK8

<dependency>
  <groupId>com.oracle.database.jdbc</groupId>
  <artifactId>ojdbc6</artifactId>
  <version>11.2.0.4</version>
</dependency>

Oracle JDBC Driver compatible with JDK8, JDK9, and JDK11

<dependency>
  <groupId>com.oracle.database.jdbc</groupId>
  <artifactId>ojdbc8</artifactId>
  <version>19.3.0.0</version>
</dependency>

Oracle JDBC Driver compatible with JDK10 and JDK11

<dependency>
  <groupId>com.oracle.database.jdbc</groupId>
  <artifactId>ojdbc10</artifactId>
  <version>19.3.0.0</version>
</dependency>

xpath find if node exists

Try the following expression: boolean(path-to-node)

What do the return values of Comparable.compareTo mean in Java?

int x = thisObject.compareTo(anotherObject);

The compareTo() method returns an int with the following characteristics:

  • negative If thisObject < anotherObject
  • zero If thisObject == anotherObject
  • positive If thisObject > anotherObject

SQL Server: Database stuck in "Restoring" state

Ran into a similar issue while restoring the database using SQL server management studio and it got stuck into restoring mode. After several hours of issue tracking, the following query worked for me. The following query restores the database from an existing backup to a previous state. I believe, the catch is the to have the .mdf and .log file in the same directory.

RESTORE DATABASE aqua_lc_availability
FROM DISK = 'path to .bak file'
WITH RECOVERY

Do we need to execute Commit statement after Update in SQL Server

Sql server unlike oracle does not need commits unless you are using transactions.
Immediatly after your update statement the table will be commited, don't use the commit command in this scenario.

How do I merge my local uncommitted changes into another Git branch?

Since your files are not yet committed in branch1:

git stash
git checkout branch2
git stash pop

or

git stash
git checkout branch2
git stash list       # to check the various stash made in different branch
git stash apply x    # to select the right one

As commented by benjohn (see git stash man page):

To also stash currently untracked (newly added) files, add the argument -u, so:

git stash -u

Required maven dependencies for Apache POI to work

For an excel writer you might need the following:

            <dependency>
              <groupId>org.apache.poi</groupId>
              <artifactId>poi</artifactId>
              <version>3.10-FINAL</version>
           </dependency>


        <dependency>
             <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>${apache.poi.version}</version>
       </dependency>

jQuery: get parent, parent id?

 $(this).closest('ul').attr('id');

An error occurred while collecting items to be installed (Access is denied)

I just solved this problem by unchecking Read only checkbox of the Program Files/eclipse folder on win7.

Apply to all files and folders.

In java how to get substring from a string till a character c?

This could help:

public static String getCorporateID(String fileName) {

    String corporateId = null;

    try {
        corporateId = fileName.substring(0, fileName.indexOf("_"));
        // System.out.println(new Date() + ": " + "Corporate:
        // "+corporateId);
        return corporateId;
    } catch (Exception e) {
        corporateId = null;
        e.printStackTrace();
    }

    return corporateId;
}

jQuery AutoComplete Trigger Change Event

The simplest, most robust way is to use the internal ._trigger() to fire the autocomplete change event.

$("#CompanyList").autocomplete({
  source : yourSource,
  change : yourChangeHandler
})

$("#CompanyList").data("ui-autocomplete")._trigger("change");

Note, jQuery UI 1.9 changed from .data("autocomplete") to .data("ui-autocomplete"). You may also see some people using .data("uiAutocomplete") which indeed works in 1.9 and 1.10, but "ui-autocomplete" is the official preferred form. See http://jqueryui.com/upgrade-guide/1.9/#changed-naming-convention-for-data-keys for jQuery UI namespaecing on data keys.

Uncaught SyntaxError: Invalid or unexpected token

The accepted answer work when you have a single line string(the email) but if you have a

multiline string, the error will remain.

Please look into this matter:

<!-- start: definition-->
@{
    dynamic item = new System.Dynamic.ExpandoObject();
    item.MultiLineString = @"a multi-line
                             string";
    item.SingleLineString = "a single-line string";
}
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
<script>
    function Getinfo(text) {
        alert(text);
    }
</script>

Change the single-quote(') to backtick(`) in Getinfo as bellow and error will be fixed:

<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>

How to save Excel Workbook to Desktop regardless of user?

You've mentioned that they each have their own machines, but if they need to log onto a co-workers machine, and then use the file, saving it through "C:\Users\Public\Desktop\" will make it available to different usernames.

Public Sub SaveToDesktop()
    ThisWorkbook.SaveAs Filename:="C:\Users\Public\Desktop\" & ThisWorkbook.Name & "_copy", _ 
    FileFormat:=xlOpenXMLWorkbookMacroEnabled
End Sub

I'm not sure whether this would be a requirement, but may help!

How can I get file extensions with JavaScript?

function file_get_ext(filename)
    {
    return typeof filename != "undefined" ? filename.substring(filename.lastIndexOf(".")+1, filename.length).toLowerCase() : false;
    }

Angular2 *ngIf check object array length in template

You can use

<div class="col-sm-12" *ngIf="event.attendees?.length">

Without event.attendees?.length > 0 or even event.attendees?length != 0

Because ?.length already return boolean value.

If in array will be something it will display it else not.

How to center a WPF app on screen?

There is no WPF equivalent. System.Windows.Forms.Screen is still part of the .NET framework and can be used from WPF though.

See this question for more details, but you can use the calls relating to screens by using the WindowInteropHelper class to wrap your WPF control.

javascript: using a condition in switch case

That's a case where you should use if clauses.

Log.INFO vs. Log.DEBUG

Also remember that all info(), error(), and debug() logging calls provide internal documentation within any application.

How do I automatically play a Youtube video (IFrame API) muted?

Try this its working fine

_x000D_
_x000D_
<html><body style='margin:0px;padding:0px;'>_x000D_
        <script type='text/javascript' src='http://www.youtube.com/iframe_api'></script><script type='text/javascript'>_x000D_
                var player;_x000D_
        function onYouTubeIframeAPIReady()_x000D_
        {player=new YT.Player('playerId',{events:{onReady:onPlayerReady}})}_x000D_
        function onPlayerReady(event){player.mute();player.setVolume(0);player.playVideo();}_x000D_
        </script>_x000D_
        <iframe id='playerId' type='text/html' width='1280' height='720'_x000D_
        src='https://www.youtube.com/embed/R52bof3tvZs?enablejsapi=1&rel=0&playsinline=1&autoplay=1&showinfo=0&autohide=1&controls=0&modestbranding=1' frameborder='0'>_x000D_
        </body></html>
_x000D_
_x000D_
_x000D_

How to store an output of shell script to a variable in Unix?

You need to start the script with a preceding dot, this will put the exported variables in the current environment.

#!/bin/bash
...
export output="SUCCESS"

Then execute it like so

chmod +x /tmp/test.sh
. /tmp/test.sh

When you need the entire output and not just a single value, just put the output in a variable like the other answers indicate

Best way to center a <div> on a page vertically and horizontally?

There is actually a solution, using css3, which can vertically center a div of unknown height. The trick is to move the div down by 50%, then use transformY to get it back up to the middle. The only prerequisite is that the to-be-centered element has a parent. Example:

<div class="parent">
    <div class="center-me">
        Text, images, whatever suits you.
    </div>
</div>

.parent { 
    /* height can be whatever you want, also auto if you want a child 
       div to be responsible for the sizing */ 
    height: 200px;
}

.center-me { 
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    /* prefixes needed for cross-browser support */
    -ms-transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
}

Supported by all major browsers, and IE 9 and up (don't bother about IE 8, as it died together with win xp this autumn. Thank god.)

JS Fiddle Demo

Regular expression for not allowing spaces in the input field

If you're using some plugin which takes string and use construct Regex to create Regex Object i:e new RegExp()

Than Below string will work

'^\\S*$'

It's same regex @Bergi mentioned just the string version for new RegExp constructor

Quick unix command to display specific lines in the middle of a file?

I prefer just going into less and

  • typing 50% to goto halfway the file,
  • 43210G to go to line 43210
  • :43210 to do the same

and stuff like that.

Even better: hit v to start editing (in vim, of course!), at that location. Now, note that vim has the same key bindings!

Get everything after the dash in a string in JavaScript

var testStr = "sometext-20202"
var splitStr = testStr.substring(testStr.indexOf('-') + 1);

Counting repeated elements in an integer array

public class ArrayDuplicate {
private static Scanner sc;
static int totalCount = 0;

    public static void main(String[] args) {
        int n, num;
        sc = new Scanner(System.in);
        System.out.print("Enter the size of array: ");
        n =sc.nextInt();
        int[] a = new int[n];
        for(int i=0;i<n;i++){
            System.out.print("Enter the element at position "+i+": ");
            num = sc.nextInt();
            a[enter image description here][1][i]=num;
        }
        System.out.print("Elements in array are: ");
        for(int i=0;i<a.length;i++)
            System.out.print(a[i]+" ");
        System.out.println();
        duplicate(a);
        System.out.println("There are "+totalCount+" repeated numbers:");
    }

    public static void duplicate(int[] a){
        int j = 0,count, recount, temp;
        for(int i=0; i<a.length;i++){
            count = 0;
            recount = 0;
            j=i+1;
            while(j<a.length){
                if(a[i]==a[j])
                    count++;
                j++;
            }
            if(count>0){
                temp = a[i];
                for(int x=0;x<i;x++){
                    if(a[x]==temp)
                        recount++;
                }
                if(recount==0){                 
                    totalCount++;
                    System.out.println(+a[i]+" : "+count+" times");
                }   
            }

        }
    }

}

When should we use mutex and when should we use semaphore

Trying not to sound zany, but can't help myself.

Your question should be what is the difference between mutex and semaphores ? And to be more precise question should be, 'what is the relationship between mutex and semaphores ?'

(I would have added that question but I'm hundred % sure some overzealous moderator would close it as duplicate without understanding difference between difference and relationship.)

In object terminology we can observe that :

observation.1 Semaphore contains mutex

observation.2 Mutex is not semaphore and semaphore is not mutex.

There are some semaphores that will act as if they are mutex, called binary semaphores, but they are freaking NOT mutex.

There is a special ingredient called Signalling (posix uses condition_variable for that name), required to make a Semaphore out of mutex. Think of it as a notification-source. If two or more threads are subscribed to same notification-source, then it is possible to send them message to either ONE or to ALL, to wakeup.

There could be one or more counters associated with semaphores, which are guarded by mutex. The simple most scenario for semaphore, there is a single counter which can be either 0 or 1.

This is where confusion pours in like monsoon rain.

A semaphore with a counter that can be 0 or 1 is NOT mutex.

Mutex has two states (0,1) and one ownership(task). Semaphore has a mutex, some counters and a condition variable.

Now, use your imagination, and every combination of usage of counter and when to signal can make one kind-of-Semaphore.

  1. Single counter with value 0 or 1 and signaling when value goes to 1 AND then unlocks one of the guy waiting on the signal == Binary semaphore

  2. Single counter with value 0 to N and signaling when value goes to less than N, and locks/waits when values is N == Counting semaphore

  3. Single counter with value 0 to N and signaling when value goes to N, and locks/waits when values is less than N == Barrier semaphore (well if they dont call it, then they should.)

Now to your question, when to use what. (OR rather correct question version.3 when to use mutex and when to use binary-semaphore, since there is no comparison to non-binary-semaphore.) Use mutex when 1. you want a customized behavior, that is not provided by binary semaphore, such are spin-lock or fast-lock or recursive-locks. You can usually customize mutexes with attributes, but customizing semaphore is nothing but writing new semaphore. 2. you want lightweight OR faster primitive

Use semaphores, when what you want is exactly provided by it.

If you dont understand what is being provided by your implementation of binary-semaphore, then IMHO, use mutex.

And lastly read a book rather than relying just on SO.

How can I add a PHP page to WordPress?

You can also directly use the PHP page, like to create the PHP page and run with full path.

Like, http://localhost/path/filename.php

Find intersection of two nested lists?

I was also looking for a way to do it, and eventually it ended up like this:

def compareLists(a,b):
    removed = [x for x in a if x not in b]
    added = [x for x in b if x not in a]
    overlap = [x for x in a if x in b]
    return [removed,added,overlap]

Export data from R to Excel

Here is a way to write data from a dataframe into an excel file by different IDs and into different tabs (sheets) by another ID associated to the first level id. Imagine you have a dataframe that has email_address as one column for a number of different users, but each email has a number of 'sub-ids' that have all the data.

data <- tibble(id = c(1,2,3,4,5,6,7,8,9), email_address = c(rep('[email protected]',3), rep('[email protected]', 3), rep('[email protected]', 3)))

So ids 1,2,3 would be associated with [email protected]. The following code splits the data by email and then puts 1,2,3 into different tabs. The important thing is to set append = True when writing the .xlsx file.


temp_dir <- tempdir()

for(i in unique(data$email_address)){
    
  data %>% 
    filter(email_address == i) %>% 
    arrange(id) -> subset_data
  
  for(j in unique(subset_data$id)){
    write.xlsx(subset_data %>% filter(id == j), 
      file = str_c(temp_dir,"/your_filename_", str_extract(i, pattern = "\\b[A-Za-z0- 
       9._%+-]+"),'_', Sys.Date(), '.xlsx'), 
      sheetName = as.character(j), 
      append = TRUE)}
 
  }

The regex gets the name from the email address and puts it into the file-name.

Hope somebody finds this useful. I'm sure there's more elegant ways of doing this but it works.

Btw, here is a way to then send these individual files to the various email addresses in the data.frame. Code goes into second loop [j]

  send.mail(from = "[email protected]",
            to = i,
          subject = paste("Your report for", str_extract(i, pattern = "\\b[A-Za-z0-9._%+-]+"), 'on', Sys.Date()),
          body = "Your email body",
          authenticate = TRUE,
          smtp = list(host.name = "XXX", port = XXX,
                      user.name = Sys.getenv("XXX"), passwd = Sys.getenv("XXX")),
          attach.files = str_c(temp_dir, "/your_filename_", str_extract(i, pattern = "\\b[A-Za-z0-9._%+-]+"),'_', Sys.Date(), '.xlsx'))


Select multiple value in DropDownList using ASP.NET and C#

In that case you should use ListBox control instead of dropdown and Set the SelectionMode property to Multiple

<asp:ListBox runat="server" SelectionMode="Multiple" >
  <asp:ListItem Text="test1"></asp:ListItem>
  <asp:ListItem Text="test2"></asp:ListItem>
  <asp:ListItem Text="test3"></asp:ListItem>
</asp:ListBox>

How do I find ' % ' with the LIKE operator in SQL Server?

I would use

WHERE columnName LIKE '%[%]%'

SQL Server stores string summary statistics for use in estimating the number of rows that will match a LIKE clause. The cardinality estimates can be better and lead to a more appropriate plan when the square bracket syntax is used.

The response to this Connect Item states

We do not have support for precise cardinality estimation in the presence of user defined escape characters. So we probably get a poor estimate and a poor plan. We'll consider addressing this issue in a future release.

An example

CREATE TABLE T
(
X VARCHAR(50),
Y CHAR(2000) NULL
)

CREATE NONCLUSTERED INDEX IX ON T(X)

INSERT INTO T (X)
SELECT TOP (5) '10% off'
FROM master..spt_values
UNION ALL
SELECT  TOP (100000)  'blah'
FROM master..spt_values v1,  master..spt_values v2


SET STATISTICS IO ON;
SELECT *
FROM T 
WHERE X LIKE '%[%]%'

SELECT *
FROM T
WHERE X LIKE '%\%%' ESCAPE '\'

Shows 457 logical reads for the first query and 33,335 for the second.

How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?

To avoid regex hell you could find your first match, chop off a chunk then attempt to find the next one on the substring. In C# this looks something like this, sorry I've not ported it over to JavaScript for you.

        long count = 0;
        var remainder = data;
        Match match = null;
        do
        {
            match = _rgx.Match(remainder);
            if (match.Success)
            {
                count++;
                remainder = remainder.Substring(match.Index + 1, remainder.Length - (match.Index+1));
            }
        } while (match.Success);
        return count;

jQuery ajax request being block because Cross-Origin

Try to use JSONP in your Ajax call. It will bypass the Same Origin Policy.

http://learn.jquery.com/ajax/working-with-jsonp/

Try example

$.ajax({
    url: "https://api.dailymotion.com/video/x28j5hv?fields=title",

    dataType: "jsonp",
    success: function( response ) {
        console.log( response ); // server response
    }

});

Java regex email

You can use this method for validating email address in java.

public class EmailValidator {
    private Pattern pattern;
    private Matcher matcher;

    private static final String EMAIL_PATTERN = 
        "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
        + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    public EmailValidator() {
        pattern = Pattern.compile(EMAIL_PATTERN);
    }

    /**
    * Validate hex with regular expression
    * 
    * @param hex
    *            hex for validation
    * @return true valid hex, false invalid hex
    */
    public boolean validate(final String hex) {

    matcher = pattern.matcher(hex);
    return matcher.matches();

    }
}

Print a variable in hexadecimal in Python

Convert the string to an integer base 16 then to hexadecimal.

print hex(int(string, base=16))

These are built-in functions.

http://docs.python.org/2/library/functions.html#int

Example

>>> string = 'AA'
>>> _int = int(string, base=16)
>>> _hex = hex(_int)
>>> print _int
170
>>> print _hex
0xaa
>>> 

Getting all request parameters in Symfony 2

With Recent Symfony 2.6+ versions as a best practice Request is passed as an argument with action in that case you won't need to explicitly call $this->getRequest(), but rather call $request->request->all()

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
use Symfony\Component\HttpFoundation\RedirectResponse;

    class SampleController extends Controller
    {


        public function indexAction(Request $request) {

           var_dump($request->request->all());
        }

    }

Shift elements in a numpy array

Benchmarks & introducing Numba

1. Summary

  • The accepted answer (scipy.ndimage.interpolation.shift) is the slowest solution listed in this page.
  • Numba (@numba.njit) gives some performance boost when array size smaller than ~25.000
  • "Any method" equally good when array size large (>250.000).
  • The fastest option really depends on
        (1)  Length of your arrays
        (2)  Amount of shift you need to do.
  • Below is the picture of the timings of all different methods listed on this page (2020-07-11), using constant shift = 10. As one can see, with small array sizes some methods are use more than +2000% time than the best method.

Relative timings, constant shift (10), all methods

2. Detailed benchmarks with the best options

  • Choose shift4_numba (defined below) if you want good all-arounder

Relative timings, best methods (Benchmarks)

3. Code

3.1 shift4_numba

  • Good all-arounder; max 20% wrt. to the best method with any array size
  • Best method with medium array sizes: ~ 500 < N < 20.000.
  • Caveat: Numba jit (just in time compiler) will give performance boost only if you are calling the decorated function more than once. The first call takes usually 3-4 times longer than the subsequent calls.
import numba

@numba.njit
def shift4_numba(arr, num, fill_value=np.nan):
    if num >= 0:
        return np.concatenate((np.full(num, fill_value), arr[:-num]))
    else:
        return np.concatenate((arr[-num:], np.full(-num, fill_value)))

3.2. shift5_numba

  • Best option with small (N <= 300.. 1500) array sizes. Treshold depends on needed amount of shift.
  • Good performance on any array size; max + 50% compared to the fastest solution.
  • Caveat: Numba jit (just in time compiler) will give performance boost only if you are calling the decorated function more than once. The first call takes usually 3-4 times longer than the subsequent calls.
import numba

@numba.njit
def shift5_numba(arr, num, fill_value=np.nan):
    result = np.empty_like(arr)
    if num > 0:
        result[:num] = fill_value
        result[num:] = arr[:-num]
    elif num < 0:
        result[num:] = fill_value
        result[:num] = arr[-num:]
    else:
        result[:] = arr
    return result

3.3. shift5

  • Best method with array sizes ~ 20.000 < N < 250.000
  • Same as shift5_numba, just remove the @numba.njit decorator.

4 Appendix

4.1 Details about used methods

  • shift_scipy: scipy.ndimage.interpolation.shift (scipy 1.4.1) - The option from accepted answer, which is clearly the slowest alternative.
  • shift1: np.roll and out[:num] xnp.nan by IronManMark20 & gzc
  • shift2: np.roll and np.put by IronManMark20
  • shift3: np.pad and slice by gzc
  • shift4: np.concatenate and np.full by chrisaycock
  • shift5: using two times result[slice] = x by chrisaycock
  • shift#_numba: @numba.njit decorated versions of the previous.

The shift2 and shift3 contained functions that were not supported by the current numba (0.50.1).

4.2 Other test results

4.2.1 Relative timings, all methods

4.2.2 Raw timings, all methods

4.2.3 Raw timings, few best methods

Getting the exception value in Python

Another way hasn't been given yet:

try:
    1/0
except Exception, e:
    print e.message

Output:

integer division or modulo by zero

args[0] might actually not be a message.

str(e) might return the string with surrounding quotes and possibly with the leading u if unicode:

'integer division or modulo by zero'

repr(e) gives the full exception representation which is not probably what you want:

"ZeroDivisionError('integer division or modulo by zero',)"

edit

My bad !!! It seems that BaseException.message has been deprecated from 2.6, finally, it definitely seems that there is still not a standardized way to display exception messages. So I guess the best is to do deal with e.args and str(e) depending on your needs (and possibly e.message if the lib you are using is relying on that mechanism).

For instance, with pygraphviz, e.message is the only way to display correctly the exception, using str(e) will surround the message with u''.

But with MySQLdb, the proper way to retrieve the message is e.args[1]: e.message is empty, and str(e) will display '(ERR_CODE, "ERR_MSG")'

How to check the version of scipy

From the python command prompt:

import scipy
print scipy.__version__

In python 3 you'll need to change it to:

print (scipy.__version__)

How to make inactive content inside a div?

Without using an overlay, you can use pointer-events: none on the div in CSS, but this does not work in IE or Opera.

div.disabled
{
  pointer-events: none;

  /* for "disabled" effect */
  opacity: 0.5;
  background: #CCC;
}

Reference

How to determine whether a given Linux is 32 bit or 64 bit?

lscpu will list out these among other information regarding your CPU:

Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
...

Rails: How can I set default values in ActiveRecord?

Here's a solution I've used that I was a little surprised hasn't been added yet.

There are two parts to it. First part is setting the default in the actual migration, and the second part is adding a validation in the model ensuring that the presence is true.

add_column :teams, :new_team_signature, :string, default: 'Welcome to the Team'

So you'll see here that the default is already set. Now in the validation you want to ensure that there is always a value for the string, so just do

 validates :new_team_signature, presence: true

What this will do is set the default value for you. (for me I have "Welcome to the Team"), and then it will go one step further an ensure that there always is a value present for that object.

Hope that helps!

Python re.sub(): how to substitute all 'u' or 'U's with 'you'

Firstly, why doesn't your solution work. You mix up a lot of concepts. Mostly character class with other ones. In the first character class you use | which stems from alternation. In character classes you don't need the pipe. Just list all characters (and character ranges) you want:

[Uu]

Or simply write u if you use the case-insensitive modifier. If you write a pipe there, the character class will actually match pipes in your subject string.

Now in the second character class you use the comma to separate your characters for some odd reason. That does also nothing but include commas into the matchable characters. s and W are probably supposed to be the built-in character classes. Then escape them! Otherwise they will just match literal s and literal W. But then \W already includes everything else you listed there, so a \W alone (without square brackets) would have been enough. And the last part (^a-zA-Z) also doesn't work, because it will simply include ^, (, ) and all letters into the character class. The negation syntax only works for entire character classes like [^a-zA-Z].

What you actually want is to assert that there is no letter in front or after your u. You can use lookarounds for that. The advantage is that they won't be included in the match and thus won't be removed:

r'(?<![a-zA-Z])[uU](?![a-zA-Z])'

Note that I used a raw string. Is generally good practice for regular expressions, to avoid problems with escape sequences.

These are negative lookarounds that make sure that there is no letter character before or after your u. This is an important difference to asserting that there is a non-letter character around (which is similar to what you did), because the latter approach won't work at the beginning or end of the string.

Of course, you can remove the spaces around you from the replacement string.

If you don't want to replace u that are next to digits, you can easily include the digits into the character classes:

r'(?<![a-zA-Z0-9])[uU](?![a-zA-Z0-9])'

And if for some reason an adjacent underscore would also disqualify your u for replacement, you could include that as well. But then the character class coincides with the built-in \w:

r'(?<!\w)[uU](?!\w)'

Which is, in this case, equivalent to EarlGray's r'\b[uU]\b'.

As mentioned above you can shorten all of these, by using the case-insensitive modifier. Taking the first expression as an example:

re.sub(r'(?<![a-z])u(?![a-z])', 'you', text, flags=re.I)

or

re.sub(r'(?<![a-z])u(?![a-z])', 'you', text, flags=re.IGNORECASE)

depending on your preference.

I suggest that you do some reading through the tutorial I linked several times in this answer. The explanations are very comprehensive and should give you a good headstart on regular expressions, which you will probably encounter again sooner or later.

How to efficiently concatenate strings in go

If you have a string slice that you want to efficiently convert to a string then you can use this approach. Otherwise, take a look at the other answers.

There is a library function in the strings package called Join: http://golang.org/pkg/strings/#Join

A look at the code of Join shows a similar approach to Append function Kinopiko wrote: https://golang.org/src/strings/strings.go#L420

Usage:

import (
    "fmt";
    "strings";
)

func main() {
    s := []string{"this", "is", "a", "joined", "string\n"};
    fmt.Printf(strings.Join(s, " "));
}

$ ./test.bin
this is a joined string

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

When you say 2^8 you get 256, but the numbers in computers terms begins from the number 0. So, then you got the 255, you can probe it in a internet mask for the IP or in the IP itself.

255 is the maximum value of a 8 bit integer : 11111111 = 255

Does that help?

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

You need to use @Autowired and @Value. Refer this post for more information on this topic.

Why use deflate instead of gzip for text files served by Apache?

if I remember correctly

  • gzip will compress a little more than deflate
  • deflate is more efficient

How to navigate to a directory in C:\ with Cygwin?

$cd C:\

> (Press enter when you see this line)

You are now in the C drive.