Programs & Examples On #Textblock

TextBlock is a UI control for displaying small amounts of text in WPF (.NET Framework).

Text vertical alignment in WPF TextBlock

TextBlock doesn't support vertical alignment of its content. If you must use TextBlock then you have to align it with respect to its parent.

However if you can use Label instead (and they do have very similar functionality) then you can position the text content:

<Label VerticalContentAlignment="Center" HorizontalContentAlignment="Center">
   I am centred text!
</Label>

The Label will stretch to fill its bounds by default, meaning the label's text will be centred.

Automatic vertical scroll bar in WPF TextBlock?

You can use

ScrollViewer.HorizontalScrollBarVisibility="Visible"
ScrollViewer.VerticalScrollBarVisibility="Visible"

These are attached property of wpf. For more information

http://wpfbugs.blogspot.in/2014/02/wpf-layout-controls-scrollviewer.html

Programmatically set TextBlock Foreground Color

Foreground needs a Brush, so you can use

textBlock.Foreground = Brushes.Navy;

If you want to use the color from RGB or ARGB then

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 255, 125, 35)); 

or

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(Colors.Navy); 

To get the Color from Hex

textBlock.Foreground = new System.Windows.Media.SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFDFD991")); 

How to put a new line into a wpf TextBlock control?

Even though this is an old question, I've just come across the problem and solved it differently from the given answers. Maybe it could be helpful to others.

I noticed that even though my XML files looked like:

<tag>
 <subTag>content with newline.\r\nto display</subTag>
</tag>

When it was read into my C# code the string had double backslashes.

\\r\\n

To fix this I wrote a ValueConverter to strip the extra backslash.

public class XmlStringConverter : IValueConverter
{
    public object Convert(
        object value,
        Type targetType,
        object parameter,
        CultureInfo culture)
    {
        string valueAsString = value as string;
        if (string.IsNullOrEmpty(valueAsString))
        {
            return value;
        }

        valueAsString = valueAsString.Replace("\\r\\n", "\r\n");
        return valueAsString;
    }

    public object ConvertBack(
        object value,
        Type targetType,
        object parameter,
        CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

How to bind multiple values to a single WPF TextBlock?

If these are just going to be textblocks (and thus one way binding), and you just want to concatenate values, just bind two textblocks and put them in a horizontal stackpanel.

    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Name}"/>
        <TextBlock Text="{Binding ID}"/>
    </StackPanel>

That will display the text (which is all Textblocks do) without having to do any more coding. You might put a small margin on them to make them look right though.

Any way to make a WPF textblock selectable?

public MainPage()
{
    this.InitializeComponent();
    ...
    ...
    ...
    //Make Start result text copiable
    TextBlockStatusStart.IsTextSelectionEnabled = true;
}

What Are Some Good .NET Profilers?

I would add that dotTrace's ability to diff memory and performance trace sessions is absolutely invaluable (ANTS may also have a memory diff feature, but I didn't see a performance diff).

Being able to run a profiling session before and after a bug fix or enhancement, then compare the results is incredibly valuable, especially with a mammoth legacy .NET application (as in my case) where performance was never a priority and where finding bottlenecks could be VERY tedious. Doing a before-and-after diff allows you to see the change in call count for each method and the change in duration for each method.

This is helpful not only during code changes, but also if you have an application that uses a different database, say, for each client/customer. If one customer complains of slowness, you can run a profiling session using their database and compare the results with a "fast" database to determine which operations are contributing to the slowness. Of course there are many database-side performance tools, but sometimes I really helps to see the performance metrics from the application side (since that's closer to what the user's actually seeing).

Bottom line: dotTrace works great, and the diff is invaluable.

how to get the host url using javascript from the current page

To get the hostname: location.hostname

But your example is looking for the scheme as well, so location.origin appears to do what you want in Chrome, but gets not mention in the Mozdev docs. You can construct it with

location.protocol + '//' + location.hostname

If you want the port number as well (for when it isn't 80) then:

location.protocol + '//' + location.host

How to go from one page to another page using javascript?

hope this would help:

window.location.href = '/url_after_domain';

Characters allowed in a URL

EDIT: As @Jukka K. Korpela correctly points out, RFC 1738 was updated by RFC 3986. This has expanded and clarified the characters valid for host, unfortunately it's not easily copied and pasted, but I'll do my best.

In first matched order:

host        = IP-literal / IPv4address / reg-name

IP-literal  = "[" ( IPv6address / IPvFuture  ) "]"

IPvFuture   = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )

IPv6address =         6( h16 ":" ) ls32
                  /                       "::" 5( h16 ":" ) ls32
                  / [               h16 ] "::" 4( h16 ":" ) ls32
                  / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32
                  / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32
                  / [ *3( h16 ":" ) h16 ] "::"    h16 ":"   ls32
                  / [ *4( h16 ":" ) h16 ] "::"              ls32
                  / [ *5( h16 ":" ) h16 ] "::"              h16
                  / [ *6( h16 ":" ) h16 ] "::"

ls32        = ( h16 ":" h16 ) / IPv4address
                  ; least-significant 32 bits of address

h16         = 1*4HEXDIG 
               ; 16 bits of address represented in hexadecimal

IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet

dec-octet   = DIGIT                 ; 0-9
              / %x31-39 DIGIT         ; 10-99
              / "1" 2DIGIT            ; 100-199
              / "2" %x30-34 DIGIT     ; 200-249
              / "25" %x30-35          ; 250-255

reg-name    = *( unreserved / pct-encoded / sub-delims )

unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~"     <---This seems like a practical shortcut, most closely resembling original answer

reserved    = gen-delims / sub-delims

gen-delims  = ":" / "/" / "?" / "#" / "[" / "]" / "@"

sub-delims  = "!" / "$" / "&" / "'" / "(" / ")"
              / "*" / "+" / "," / ";" / "="

pct-encoded = "%" HEXDIG HEXDIG

Original answer from RFC 1738 specification:

Thus, only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL.

^ obsolete since 1998.

how to add button click event in android studio

package com.mani.smsdetect;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements View.OnClickListener {

    //Declaration Button
    Button btnClickMe;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Intialization Button

        btnClickMe = (Button) findViewById(R.id.btnClickMe);

        btnClickMe.setOnClickListener(MainActivity.this);
        //Here MainActivity.this is a Current Class Reference (context)
    }

    @Override
    public void onClick(View v) {

        //Your Logic
    }
}

Checking something isEmpty in Javascript?

just put the variable inside the if condition, if variable has any value it will return true else false.

if (response.photo){ // if you are checking for string use this if(response.photo == "") condition
 alert("Has Value");
}
else
{
 alert("No Value");
};

How to Store Historical Data

I don't think there is a particular standard way of doing it but I thought I would throw in a possible method. I work in Oracle and our in-house web application framework that utilizes XML for storing application data.

We use something called a Master - Detail model that at it's simplest consists of:

Master Table for example calledWidgets often just containing an ID. Will often contain data that won't change over time / isn't historical.

Detail / History Table for example called Widget_Details containing at least:

  • ID - primary key. Detail/historical ID
  • MASTER_ID - for example in this case called 'WIDGET_ID', this is the FK to the Master record
  • START_DATETIME - timestamp indicating the start of that database row
  • END_DATETIME - timestamp indicating the end of that database row
  • STATUS_CONTROL - single char column indicated status of the row. 'C' indicates current, NULL or 'A' would be historical/archived. We only use this because we can't index on END_DATETIME being NULL
  • CREATED_BY_WUA_ID - stores the ID of the account that caused the row to be created
  • XMLDATA - stores the actual data

So essentially, a entity starts by having 1 row in the master and 1 row in the detail. The detail having a NULL end date and STATUS_CONTROL of 'C'. When an update occurs, the current row is updated to have END_DATETIME of the current time and status_control is set to NULL (or 'A' if preferred). A new row is created in the detail table, still linked to the same master, with status_control 'C', the id of the person making the update and the new data stored in the XMLDATA column.

This is the basis of our historical model. The Create / Update logic is handled in an Oracle PL/SQL package so you simply pass the function the current ID, your user ID and the new XML data and internally it does all the updating / inserting of rows to represent that in the historical model. The start and end times indicate when that row in the table is active for.

Storage is cheap, we don't generally DELETE data and prefer to keep an audit trail. This allows us to see what our data looked like at any given time. By indexing status_control = 'C' or using a View, cluttering isn't exactly a problem. Obviously your queries need to take into account you should always use the current (NULL end_datetime and status_control = 'C') version of a record.

C++ string to double conversion

The problem is that C++ is a statically-typed language, meaning that if something is declared as a string, it's a string, and if something is declared as a double, it's a double. Unlike other languages like JavaScript or PHP, there is no way to automatically convert from a string to a numeric value because the conversion might not be well-defined. For example, if you try converting the string "Hi there!" to a double, there's no meaningful conversion. Sure, you could just set the double to 0.0 or NaN, but this would almost certainly be masking the fact that there's a problem in the code.

To fix this, don't buffer the file contents into a string. Instead, just read directly into the double:

double lol;
openfile >> lol;

This reads the value directly as a real number, and if an error occurs will cause the stream's .fail() method to return true. For example:

double lol;
openfile >> lol;

if (openfile.fail()) {
    cout << "Couldn't read a double from the file." << endl;
}

casting Object array to Integer array error

Or do the following:

...

  Integer[] integerArray = new Integer[integerList.size()];
  integerList.toArray(integerArray);

  return integerArray;

}

How do I see what character set a MySQL database / table / column is?

show global variables where variable_name like 'character_set_%' or variable_name like 'collation%'

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

While writing this question, I discovered the answer. Installing a CA from Safari no longer automatically trusts it. I had to manually trust it from the Certificate Trust Settings panel (also mentioned in this question).

enter image description here

I debated canceling the question, but I thought it might be helpful to have some of the relevant code and log details someone might be looking for. Also, I never encountered the issue until iOS 11. I even went back and reconfirmed that it automatically works up through iOS 10.

I've never needed to touch that settings panel before, because any installed certificates were automatically trusted. Maybe it will change by the time iOS 11 ships, but I doubt it. Hopefully this helps save someone the time I wasted.

If anyone knows why this behaves differently for some people on different versions of iOS, I'd love to know in comments.

Update 1: Checking out the first iOS 12 beta, it looks like things remain the same. This question/answer/comments are still relevant on iOS 12.

Update 2: Same solution seems to be needed on iOS 13 beta builds as well.

How to enable mod_rewrite for Apache 2.2

For my situation, I had

RewriteEngine On

in my .htaccess, along with the module being loaded, and it was not working.

The solution to my problem was to edit my vhost entry to inlcude

AllowOverride all

in the <Directory> section for the site in question.

In Java, what does NaN mean?

Not a valid floating-point value (e.g. the result of division by zero)

http://en.wikipedia.org/wiki/NaN

Sharepoint: How do I filter a document library view to show the contents of a subfolder?

Try this, pick or create one column and make that value required so that it's always populated such as title. A field that doesn't hold the name of the folder. Then in your filter put the filter you wanted that will select only the files you want. Then add an or to your filter, select your "required" field then set it equal to and leave the filter blank. Since all folders will have a blank in this required field your folders will show up with your files.

Incrementing a variable inside a Bash loop

while read -r country _; do
  if [[ $country = 'US' ]]; then
    ((USCOUNTER++))
    echo "US counter $USCOUNTER"
  fi
done < "$FILE"

setTimeout in for-loop does not print consecutive values

This's Because!

  1. The timeout function callbacks are all running well after the completion of the loop. In fact, as timers go, even if it was setTimeout(.., 0) on each iteration, all those function callbacks would still run strictly after the completion of the loop, that's why 3 was reflected!
  2. all two of those functions, though they are defined separately in each loop iteration, are closed over the same shared global scope, which has, in fact, only one i in it.

the Solution's declaring a single scope for each iteration by using a self-function executed(anonymous one or better IIFE) and having a copy of i in it, like this:

for (var i = 1; i <= 2; i++) {

     (function(){

         var j = i;
         setTimeout(function() { console.log(j) }, 100);

     })();

}

the cleaner one would be

for (var i = 1; i <= 2; i++) {

     (function(i){ 

         setTimeout(function() { console.log(i) }, 100);

     })(i);

}

The use of an IIFE(self-executed function) inside each iteration created a new scope for each iteration, which gave our timeout function callbacks the opportunity to close over a new scope for each iteration, one which had a variable with the right per-iteration value in it for us to access.

How to find the size of a table in SQL?

And in PostgreSQL:

SELECT pg_size_pretty(pg_relation_size('tablename'));

Java 8 Lambda function that throws exception?

There are a lot of great responses already posted here. Just attempting to solve the problem with a different perspective. Its just my 2 cents, please correct me if I am wrong somewhere.

Throws clause in FunctionalInterface is not a good idea

I think this is probably not a good idea to enforce throws IOException because of following reasons

  • This looks to me like an anti-pattern to Stream/Lambda. The whole idea is that the caller will decide what code to provide and how to handle the exception. In many scenarios, the IOException might not be applicable for the client. For example, if the client is getting value from cache/memory instead of performing actual I/O.

  • Also, the exceptions handling in streams becomes really hideous. For example, here is my code will look like if I use your API

               acceptMyMethod(s -> {
                    try {
                        Integer i = doSomeOperation(s);
                        return i;
                    } catch (IOException e) {
                        // try catch block because of throws clause
                        // in functional method, even though doSomeOperation
                        // might not be throwing any exception at all.
                        e.printStackTrace();
                    }
                    return null;
                });
    

    Ugly isn't it? Moreover, as I mentioned in my first point, that the doSomeOperation method may or may not be throwing IOException (depending on the implementation of the client/caller), but because of the throws clause in your FunctionalInterface method, I always have to write the try-catch.

What do I do if I really know this API throws IOException

  • Then probably we are confusing FunctionalInterface with typical Interfaces. If you know this API will throw IOException, then most probably you also know some default/abstract behavior as well. I think you should define an interface and deploy your library (with default/abstract implementation) as follows

    public interface MyAmazingAPI {
        Integer myMethod(String s) throws IOException;
    }
    

    But, the try-catch problem still exists for the client. If I use your API in stream, I still need to handle IOException in hideous try-catch block.

  • Provide a default stream-friendly API as follows

    public interface MyAmazingAPI {
        Integer myMethod(String s) throws IOException;
    
        default Optional<Integer> myMethod(String s, Consumer<? super Exception> exceptionConsumer) {
            try {
                return Optional.ofNullable(this.myMethod(s));
            } catch (Exception e) {
                if (exceptionConsumer != null) {
                    exceptionConsumer.accept(e);
                } else {
                    e.printStackTrace();
                }
            }
    
            return Optional.empty();
        }
    }
    

    The default method takes the consumer object as argument, which will be responsible to handle the exception. Now, from client's point of view, the code will look like this

    strStream.map(str -> amazingAPIs.myMethod(str, Exception::printStackTrace))
                    .filter(Optional::isPresent)
                    .map(Optional::get).collect(toList());
    

    Nice right? Of course, logger or other handling logic could be used instead of Exception::printStackTrace.

  • You can also expose a method similar to https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#exceptionally-java.util.function.Function- . Meaning that you can expose another method, which will contain the exception from previous method call. The disadvantage is that you are now making your APIs stateful, which means that you need to handle thread-safety and which will be eventually become a performance hit. Just an option to consider though.

Create line after text with css

This is the most easy way I found to achieve the result: Just use hr tag before the text, and set the margin top for text. Very short and easy to understand! jsfiddle

_x000D_
_x000D_
h2 {_x000D_
  background-color: #ffffff;_x000D_
  margin-top: -22px;_x000D_
  width: 25%;_x000D_
}_x000D_
_x000D_
hr {_x000D_
  border: 1px solid #e9a216;_x000D_
}
_x000D_
<br>_x000D_
_x000D_
<hr>_x000D_
<h2>ABOUT US</h2>
_x000D_
_x000D_
_x000D_

How to check if a database exists in SQL Server?

Actually it's best to use:

IF DB_ID('dms') IS NOT NULL
   --code mine :)
   print 'db exists'

See https://docs.microsoft.com/en-us/sql/t-sql/functions/db-id-transact-sql and note that this does not make sense with the Azure SQL Database.

ViewDidAppear is not called when opening app from background

Using Objective-C

You should register a UIApplicationWillEnterForegroundNotification in your ViewController's viewDidLoad method and whenever app comes back from background you can do whatever you want to do in the method registered for notification. ViewController's viewWillAppear or viewDidAppear won't be called when app comes back from background to foreground.

-(void)viewDidLoad{

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doYourStuff)

  name:UIApplicationWillEnterForegroundNotification object:nil];
}

-(void)doYourStuff{

   // do whatever you want to do when app comes back from background.
}

Don't forget to unregister the notification you are registered for.

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

Note if you register your viewController for UIApplicationDidBecomeActiveNotification then your method would be called every time your app becomes active, It is not recommended to register viewController for this notification .

Using Swift

For adding observer you can use the following code

 override func viewDidLoad() {
    super.viewDidLoad()

     NotificationCenter.default.addObserver(self, selector: "doYourStuff", name: UIApplication.willEnterForegroundNotification, object: nil)
 }

 func doYourStuff(){
     // your code
 }

To remove observer you can use deinit function of swift.

deinit {
    NotificationCenter.default.removeObserver(self)
}

Switch case in C# - a constant value is expected

Now you can use nameof:

public static void Output<T>(IEnumerable<T> dataSource) where T : class
{
    string dataSourceName = typeof(T).Name;
    switch (dataSourceName)
    {
        case nameof(CustomerDetails):
            var t = 123;
            break;
        default:
            Console.WriteLine("Test");
    }
}

nameof(CustomerDetails) is basically identical to the string literal "CustomerDetails", but with a compile-time check that it refers to some symbol (to prevent a typo).

nameof appeared in C# 6.0, so after this question was asked.

ES6 Map in Typescript

Not sure if this is official but this worked for me in typescript 2.7.1:

class Item {
   configs: Map<string, string>;
   constructor () {
     this.configs = new Map();
   }
}

In simple Map<keyType, valueType>

How to Run a jQuery or JavaScript Before Page Start to Load

Try the unload event. The unload event is sent to the window element when the user navigates away from the page.

$( window ).unload(function() {
    //do something
});

How do relative file paths work in Eclipse?

Yeah, eclipse sees the top directory as the working/root directory, for the purposes of paths.

...just thought I'd add some extra info. I'm new here! I'd like to help.

creating json object with variables

You're referencing a DOM element when doing something like $('#lastName'). That's an element with id attribute "lastName". Why do that? You want to reference the value stored in a local variable, completely unrelated. Try this (assuming the assignment to formObject is in the same scope as the variable declarations) -

var formObject = {
    formObject: [
        {
            firstName:firstName,  // no need to quote variable names
            lastName:lastName
        },
        {
            phoneNumber:phoneNumber,
            address:address
        }
    ]
};

This seems very odd though: you're creating an object "formObject" that contains a member called "formObject" that contains an array of objects.

How to clear browser cache with php?

With recent browser support of "Clear-Site-Data" headers, you can clear different types of data: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data

header('Clear-Site-Data: "cache", "cookies", "storage", "executionContexts"');

Python integer incrementing with ++

The main reason ++ comes in handy in C-like languages is for keeping track of indices. In Python, you deal with data in an abstract way and seldom increment through indices and such. The closest-in-spirit thing to ++ is the next method of iterators.

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

In the real world, an application will almost always have java bean or domain that is to be serialized/de-serialized to/from JSON. Its already mentioned that JSON Object specification does not guarantee order and any manipulation to that behavior does not justify the requirement. I had the same scenario in my application where I needed to preserve order just for the sack of readability purpose. I used standard jackson way to serialize my java bean to JSON:

Object object = getObject();  //the source java bean that needs conversion
String jsonString = new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(object);

In order to make the json with an ordered set of elements I just use JSON property annotation in the the Java bean I used for conversion. An example below:

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"name","phone","city","id"})
public class SampleBean implements Serializable {
    private int id;
    private String name:
    private String city;
    private String phone;

    //...standard getters and setters
}

the getObject() used above:

public SampleBean getObject(){
    SampleBean bean  = new SampleBean();
    bean.setId("100");
    bean.setName("SomeName");
    bean.setCity("SomeCity");
    bean.setPhone("1234567890");
    return bean;
}

The output shows as per Json property order annotation:

{
    name: "SomeName",
    phone: "1234567890",
    city: "SomeCity",
    id: 100
}

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

[A1].End(xlUp)
[A1].End(xlDown)
[A1].End(xlToLeft)
[A1].End(xlToRight)

is the VBA equivalent of being in Cell A1 and pressing Ctrl + Any arrow key. It will continue to travel in that direction until it hits the last cell of data, or if you use this command to move from a cell that is the last cell of data it will travel until it hits the next cell containing data.

If you wanted to find that last "used" cell in Column A, you could go to A65536 (for example, in an XL93-97 workbook) and press Ctrl + Up to "snap" to the last used cell. Or in VBA you would write:

Range("A65536").End(xlUp) which again can be re-written as Range("A" & Rows.Count).End(xlUp) for compatibility reasons across workbooks with different numbers of rows.

Is there a better alternative than this to 'switch on type'?

Create a superclass (S) and make A and B inherit from it. Then declare an abstract method on S that every subclass needs to implement.

Doing this the "foo" method can also change its signature to Foo(S o), making it type safe, and you don't need to throw that ugly exception.

How can I get double quotes into a string literal?

Escape the quotes with backslashes:

printf("She said \"time flies like an arrow, but fruit flies like a banana\"."); 

There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.

Certificate has either expired or has been revoked

Edit: This answer doesn't work for Xcode 10 and higher. See turkenh's answer.


I had experienced this problem and was able to find an answer.

The answer which this is coming from can be found here.

Here is what you have to do:

  1. Go to Preferences->Accounts
  2. Press on your account
  3. Click "View Details"
  4. Click "Download All" in the lower left hand corner.

These steps solved the problem for me.

How to lookup JNDI resources on WebLogic?

You should be able to simply do this:

Context context = new InitialContext();
dataSource = (javax.sql.DataSource) context.lookup("jdbc/myDataSource");

If you are looking it up from a remote destination you need to use the WL initial context factory like this:

Hashtable<String, String> h = new Hashtable<String, String>(7);
h.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
h.put(Context.PROVIDER_URL, pURL); //For example "t3://127.0.0.1:7001"
h.put(Context.SECURITY_PRINCIPAL, pUsername);
h.put(Context.SECURITY_CREDENTIALS, pPassword);

InitialContext context = new InitialContext(h);
dataSource = (javax.sql.DataSource) context.lookup("jdbc/myDataSource");

weblogic.jndi.WLInitialContextFactory

SQLAlchemy: how to filter date field?

In fact, your query is right except for the typo: your filter is excluding all records: you should change the <= for >= and vice versa:

qry = DBSession.query(User).filter(
        and_(User.birthday <= '1988-01-17', User.birthday >= '1985-01-17'))
# or same:
qry = DBSession.query(User).filter(User.birthday <= '1988-01-17').\
        filter(User.birthday >= '1985-01-17')

Also you can use between:

qry = DBSession.query(User).filter(User.birthday.between('1985-01-17', '1988-01-17'))

NoClassDefFoundError in Java: com/google/common/base/Function

you don't have the "google-collections" library on your classpath.

There are a number of ways to add libraries to your classpath, so please provide more info regarding how you are executing your program.

if from the command line, you can add libraries to the classpath via

java -classpath path/lib.jar ...

How to set up a Web API controller for multipart/form-data

5 years later on and .NET Core 3.1 allows you to do specify the media type like this:

[HttpPost]
[Consumes("multipart/form-data")]
public IActionResult UploadLogo()
{
    return Ok();
}

The type must be a reference type in order to use it as parameter 'T' in the generic type or method

If you put constrains on a generic class or method, every other generic class or method that is using it need to have "at least" those constrains.

CSS: auto height on containing div, 100% height on background div inside containing div

In 2018 a lot of browsers support the Flexbox and Grid which are very powerful CSS display modes that overshine classical methods such as Faux Columns or Tabular Displays (which are treated later in this answer).

In order to implement this with the Grid, it is enough to specify display: grid and grid-template-columns on the container. The grid-template-columns depends on the number of columns you have, in this example I will use 3 columns, hence the property will look: grid-template-columns: auto auto auto, which basically means that each of the columns will have auto width.

Full working example with Grid:

_x000D_
_x000D_
html, body {_x000D_
    padding: 0;_x000D_
    margin: 0;_x000D_
}_x000D_
_x000D_
.grid-container {_x000D_
    display: grid;_x000D_
    grid-template-columns: auto auto auto;_x000D_
    width: 100%;_x000D_
}_x000D_
_x000D_
.grid-item {_x000D_
    padding: 20px;_x000D_
}_x000D_
_x000D_
.a {_x000D_
    background-color: DarkTurquoise;_x000D_
}_x000D_
_x000D_
.b {_x000D_
    background-color: LightSalmon;_x000D_
}_x000D_
_x000D_
.c {_x000D_
    background-color: LightSteelBlue;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
    <title>Three Columns with Grid</title>_x000D_
    <link rel="stylesheet" type="text/css" href="style.css">_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
    <div class="grid-container">_x000D_
        <div class="grid-item a">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta.</p>_x000D_
        </div>_x000D_
        <div class="grid-item b">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta. Donec commodo elit mattis, bibendum turpis eu, malesuada nunc. Vestibulum sit amet dui tincidunt, mattis nisl et, tincidunt eros. Vivamus eu ultrices sapien. Integer leo arcu, lobortis sed tellus in, euismod ultricies massa. Mauris gravida quis ligula nec dignissim. Proin elementum mattis fringilla. Donec id malesuada orci, eu aliquam ipsum. Vestibulum fermentum elementum egestas. Quisque sit amet tempor mi.</p>_x000D_
        </div>_x000D_
        <div class="grid-item c">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis.</p>_x000D_
        </div>_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Another way would be to use the Flexbox by specifying display: flex on the container of the columns, and giving the columns a relevant width. In the example that I will be using, which is with 3 columns, you basically need to split 100% in 3, so it's 33.3333% (close enough, who cares about 0.00003333... which isn't visible anyway).

Full working example using Flexbox:

_x000D_
_x000D_
html, body {_x000D_
    padding: 0;_x000D_
    margin: 0;_x000D_
}_x000D_
_x000D_
.flex-container {_x000D_
    display: flex;_x000D_
    width: 100%;_x000D_
}_x000D_
_x000D_
.flex-column {_x000D_
    padding: 20px;_x000D_
    width: 33.3333%;_x000D_
}_x000D_
_x000D_
.a {_x000D_
    background-color: DarkTurquoise;_x000D_
}_x000D_
_x000D_
.b {_x000D_
    background-color: LightSalmon;_x000D_
}_x000D_
_x000D_
.c {_x000D_
    background-color: LightSteelBlue;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
    <title>Three Columns with Flexbox</title>_x000D_
    <link rel="stylesheet" type="text/css" href="style.css">_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
    <div class="flex-container">_x000D_
        <div class="flex-column a">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta.</p>_x000D_
        </div>_x000D_
        <div class="flex-column b">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta. Donec commodo elit mattis, bibendum turpis eu, malesuada nunc. Vestibulum sit amet dui tincidunt, mattis nisl et, tincidunt eros. Vivamus eu ultrices sapien. Integer leo arcu, lobortis sed tellus in, euismod ultricies massa. Mauris gravida quis ligula nec dignissim. Proin elementum mattis fringilla. Donec id malesuada orci, eu aliquam ipsum. Vestibulum fermentum elementum egestas. Quisque sit amet tempor mi.</p>_x000D_
        </div>_x000D_
        <div class="flex-column c">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis.</p>_x000D_
        </div>_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

The Flexbox and Grid are supported by all major browsers since 2017/2018, fact also confirmed by caniuse.com: Can I use grid, Can I use flex.

There are also a number of classical solutions, used before the age of Flexbox and Grid, like OneTrueLayout Technique, Faux Columns Technique, CSS Tabular Display Technique and there is also a Layering Technique.

I do not recommend using these methods for they have a hackish nature and are not so elegant in my opinion, but it is good to know them for academic reasons.

A solution for equally height-ed columns is the CSS Tabular Display Technique that means to use the display:table feature. It works for Firefox 2+, Safari 3+, Opera 9+ and IE8.

The code for the CSS Tabular Display:

_x000D_
_x000D_
#container {_x000D_
  display: table;_x000D_
  background-color: #CCC;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
_x000D_
.row {_x000D_
  display: table-row;_x000D_
}_x000D_
_x000D_
.col {_x000D_
  display: table-cell;_x000D_
}_x000D_
_x000D_
#col1 {_x000D_
  background-color: #0CC;_x000D_
  width: 200px;_x000D_
}_x000D_
_x000D_
#col2 {_x000D_
  background-color: #9F9;_x000D_
  width: 300px;_x000D_
}_x000D_
_x000D_
#col3 {_x000D_
  background-color: #699;_x000D_
  width: 200px;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div id="rowWraper" class="row">_x000D_
    <div id="col1" class="col">_x000D_
      Column 1<br />Lorem ipsum<br />ipsum lorem_x000D_
    </div>_x000D_
    <div id="col2" class="col">_x000D_
      Column 2<br />Eco cologna duo est!_x000D_
    </div>_x000D_
    <div id="col3" class="col">_x000D_
      Column 3_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Even if there is a problem with the auto-expanding of the width of the table-cell it can be resolved easy by inserting another div withing the table-cell and giving it a fixed width. Anyway, the over-expanding of the width happens in the case of using extremely long words (which I doubt anyone would use a, let's say, 600px long word) or some div's who's width is greater than the table-cell's width.

The Faux Column Technique is the most popular classical solution to this problem, but it has some drawbacks such as, you have to resize the background tiled image if you want to resize the columns and it is also not an elegant solution.

The OneTrueLayout Technique consists of creating a padding-bottom of an extreme big height and cut it out by bringing the real border position to the "normal logical position" by applying a negative margin-bottom of the same huge value and hiding the extent created by the padding with overflow: hidden applied to the content wraper. A simplified example would be:

Working example:

_x000D_
_x000D_
.wraper {_x000D_
    overflow: hidden; /* This is important */_x000D_
}_x000D_
_x000D_
.floatLeft {_x000D_
    float: left;_x000D_
}_x000D_
_x000D_
.block {_x000D_
    padding-left: 20px;_x000D_
    padding-right: 20px;_x000D_
    padding-bottom: 30000px; /* This is important */_x000D_
    margin-bottom: -30000px; /* This is important */_x000D_
    width: 33.3333%;_x000D_
    box-sizing: border-box; /* This is so that the padding right and left does not affect the width */_x000D_
}_x000D_
_x000D_
.a {_x000D_
    background-color: DarkTurquoise;_x000D_
}_x000D_
_x000D_
.b {_x000D_
    background-color: LightSalmon;_x000D_
}_x000D_
_x000D_
.c {_x000D_
    background-color: LightSteelBlue;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
  <title>OneTrueLayout</title>_x000D_
</head>_x000D_
<body>_x000D_
    <div class="wraper">_x000D_
        <div class="block floatLeft a">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras malesuada ipsum pretium tellus condimentum aliquam. Donec eget tempor mi, a consequat enim. Mauris a massa id nisl sagittis iaculis.</p>_x000D_
        </div>_x000D_
        <div class="block floatLeft b">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras malesuada ipsum pretium tellus condimentum aliquam. Donec eget tempor mi, a consequat enim. Mauris a massa id nisl sagittis iaculis. Duis mattis diam vitae tellus ornare, nec vehicula elit luctus. In auctor urna ac ante bibendum, a gravida nunc hendrerit. Praesent sed pellentesque lorem. Nam neque ante, egestas ut felis vel, faucibus tincidunt risus. Maecenas egestas diam massa, id rutrum metus lobortis non. Sed quis tellus sed nulla efficitur pharetra. Fusce semper sapien neque. Donec egestas dolor magna, ut efficitur purus porttitor at. Mauris cursus, leo ac porta consectetur, eros quam aliquet erat, condimentum luctus sapien tellus vel ante. Vivamus vestibulum id lacus vel tristique.</p>_x000D_
        </div>_x000D_
        <div class="block floatLeft c">_x000D_
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras malesuada ipsum pretium tellus condimentum aliquam. Donec eget tempor mi, a consequat enim. Mauris a massa id nisl sagittis iaculis. Duis mattis diam vitae tellus ornare, nec vehicula elit luctus. In auctor urna ac ante bibendum, a gravida nunc hendrerit.</p>_x000D_
        </div>_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

The Layering Technique must be a very neat solution that involves absolute positioning of div's withing a main relative positioned wrapper div. It basically consists of a number of child divs and the main div. The main div has imperatively position: relative to it's css attribute collection. The children of this div are all imperatively position:absolute. The children must have top and bottom set to 0 and left-right dimensions set to accommodate the columns with each another. For example if we have two columns, one of width 100px and the other one of 200px, considering that we want the 100px in the left side and the 200px in the right side, the left column must have {left: 0; right: 200px} and the right column {left: 100px; right: 0;}

In my opinion the unimplemented 100% height within an automated height container is a major drawback and the W3C should consider revising this attribute (which since 2018 is solvable with Flexbox and Grid).

Other resources: link1, link2, link3, link4, link5 (important)

Passing a Bundle on startActivity()?

You can pass values from one activity to another activity using the Bundle. In your current activity, create a bundle and set the bundle for the particular value and pass that bundle to the intent.

Intent intent = new Intent(this,NewActivity.class);
Bundle bundle = new Bundle();
bundle.putString(key,value);
intent.putExtras(bundle);
startActivity(intent);

Now in your NewActivity, you can get this bundle and retrive your value.

Bundle bundle = getArguments();
String value = bundle.getString(key);

You can also pass data through the intent. In your current activity, set intent like this,

Intent intent = new Intent(this,NewActivity.class);
intent.putExtra(key,value);
startActivity(intent);

Now in your NewActivity, you can get that value from intent like this,

String value = getIntent().getExtras().getString(key);

How to access the last value in a vector?

The xts package provides a last function:

library(xts)
a <- 1:100
last(a)
[1] 100

open read and close a file in 1 line of code

I think the most natural way for achieving this is to define a function.

def read(filename):
    f = open(filename, 'r')
    output = f.read()
    f.close()
    return output

Then you can do the following:

output = read('pagehead.section.htm')

node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]

You might consider using double slashes on your directory e.g

_x000D_
_x000D_
app.get('/',(req,res)=>{_x000D_
    res.sendFile('C:\\Users\\DOREEN\\Desktop\\Fitness Finder' + '/index.html')_x000D_
})
_x000D_
_x000D_
_x000D_

What's the difference between Cache-Control: max-age=0 and no-cache?

By the way, it's worth noting that some mobile devices, particularly Apple products like iPhone/iPad completely ignore headers like no-cache, no-store, Expires: 0, or whatever else you may try to force them to not re-use expired form pages.

This has caused us no end of headaches as we try to get the issue of a user's iPad say, being left asleep on a page they have reached through a form process, say step 2 of 3, and then the device totally ignores the store/cache directives, and as far as I can tell, simply takes what is a virtual snapshot of the page from its last state, that is, ignoring what it was told explicitly, and, not only that, taking a page that should not be stored, and storing it without actually checking it again, which leads to all kinds of strange Session issues, among other things.

I'm just adding this in case someone comes along and can't figure out why they are getting session errors with particularly iphones and ipads, which seem by far to be the worst offenders in this area.

I've done fairly extensive debugger testing with this issue, and this is my conclusion, the devices ignore these directives completely.

Even in regular use, I've found that some mobiles also totally fail to check for new versions via say, Expires: 0 then checking last modified dates to determine if it should get a new one.

It simply doesn't happen, so what I was forced to do was add query strings to the css/js files I needed to force updates on, which tricks the stupid mobile devices into thinking it's a file it does not have, like: my.css?v=1, then v=2 for a css/js update. This largely works.

User browsers also, by the way, if left to their defaults, as of 2016, as I continuously discover (we do a LOT of changes and updates to our site) also fail to check for last modified dates on such files, but the query string method fixes that issue. This is something I've noticed with clients and office people who tend to use basic normal user defaults on their browsers, and have no awareness of caching issues with css/js etc, almost invariably fail to get the new css/js on change, which means the defaults for their browsers, mostly MSIE / Firefox, are not doing what they are told to do, they ignore changes and ignore last modified dates and do not validate, even with Expires: 0 set explicitly.

This was a good thread with a lot of good technical information, but it's also important to note how bad the support for this stuff is in particularly mobile devices. Every few months I have to add more layers of protection against their failure to follow the header commands they receive, or to properly interpet those commands.

Notepad++ cached files location

I lost somehow my temporary notepad++ files, they weren't showing in tabs. So I did some search in appdata folder, and I found all my temporary files there. It seems that they are stored there for a long time.

C:\Users\USER\AppData\Roaming\Notepad++\backup

or

%AppData%\Notepad++\backup

Is Java "pass-by-reference" or "pass-by-value"?

I'd say it in another way:

In java references are passed (but not objects) and these references are passed-by-value (the reference itself is copied and you have 2 references as a result and you have no control under the 1st reference in the method).

Just saying: pass-by-value might be not clear enough for beginners. For instance in Python the same situation but there are articles, which describe that they call it pass-by-reference, only cause references are used.

How to change value of ArrayList element in java

I agree with Duncan ...I have tried it with mutable object but still get the same problem... I got a simple solution to this... use ListIterator instead Iterator and use set method of ListIterator

ListIterator<Integer> i = a.listIterator();
//changed the value of first element in List
Integer x =null;
        if(i.hasNext()) {
            x = i.next();
            x = Integer.valueOf(9);
        }
    //set method sets the recent iterated element in ArrayList
    i.set(x);
        //initialized the iterator again and print all the elements
        i = a.listIterator();
        while(i.hasNext())
        System.out.print(i.next());

But this constraints me to use this only for ArrayList only which can use ListIterator...i will have same problem with any other Collection

WCF Service, the type provided as the service attribute values…could not be found

Double check projects .net versions. Projects that referenced each other with different .net versions causes problems.

Capturing image from webcam in java?

Java usually doesn't like accessing hardware, so you will need a driver program of some sort, as goldenmean said. I've done this on my laptop by finding a command line program that snaps a picture. Then it's the same as goldenmean explained; you run the command line program from your java program in the takepicture() routine, and the rest of your code runs the same.

Except for the part about reading pixel values into an array, you might be better served by saving the file to BMP, which is nearly that format already, then using the standard java image libraries on it.

Using a command line program adds a dependency to your program and makes it less portable, but so was the webcam, right?

How to sum all column values in multi-dimensional array?

We need to check first if array key does exist.

CODE:

$sum = array();
foreach ($array as $key => $sub_array) {
    foreach ($sub_array as $sub_key => $value) {

        //If array key doesn't exists then create and initize first before we add a value.
        //Without this we will have an Undefined index error.
        if( ! array_key_exists($sub_key, $sum)) $sum[$sub_key] = 0;

        //Add Value
        $sum[$sub_key]+=$value;
    }
}
print_r($sum);

OUTPUT With Array Key Validation:

Array
(
    [gozhi] => 10
    [uzorong] => 1
    [ngangla] => 8
    [langthel] => 10
)

OUTPUT Without Array Key Validation:

Notice: Undefined index: gozhi in F:\web\index.php on line 37

Notice: Undefined index: uzorong in F:\web\index.php on line 37

Notice: Undefined index: ngangla in F:\web\index.php on line 37

Notice: Undefined index: langthel in F:\web\index.php on line 37

Array
(
    [gozhi] => 10
    [uzorong] => 1
    [ngangla] => 8
    [langthel] => 10
)

This is a bad practice although it prints the output. Always check first if key does exist.

How to change the default encoding to UTF-8 for Apache?

<meta charset='utf-8'> overrides the apache default charset (cf /etc/apache2/conf.d/charset)

If this is not enough, then you probably created your original file with iso-8859-1 encoding character set. You have to convert it to the proper character set:

iconv -f ISO-8859-1 -t UTF-8 source_file.php -o new file.php

$_SERVER['HTTP_REFERER'] missing

Referer is not a compulsory header. It may or may not be there or could be modified/fictitious. Rely on it at your own risk. Anyways, you should wrap your call so you do not get an undefined index error:

$server = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : "";

In Laravel, the best way to pass different types of flash messages in the session

My way is to always Redirect::back() or Redirect::to():

Redirect::back()->with('message', 'error|There was an error...');

Redirect::back()->with('message', 'message|Record updated.');

Redirect::to('/')->with('message', 'success|Record updated.');

I have a helper function to make it work for me, usually this is in a separate service:

function displayAlert()
{
      if (Session::has('message'))
      {
         list($type, $message) = explode('|', Session::get('message'));

         $type = $type == 'error' : 'danger';
         $type = $type == 'message' : 'info';

         return sprintf('<div class="alert alert-%s">%s</div>', $type, message);
      }

      return '';
}

And in my view or layout I just do

{{ displayAlert() }}

How to create hyperlink to call phone number on mobile devices?

- doesnt make matter but + sign is important when mobile user is in roaming
this is the standard format

<a href="tel:+4917640206387">+49 (0)176 - 402 063 87</a>

You can read more about it in the spec, see Make Telephone Numbers "Click-to-Call".

What is difference between sleep() method and yield() method of multi threading?

Yield : will make thread to wait for the currently executing thread and the thread which has called yield() will attaches itself at the end of the thread execution. The thread which call yield() will be in Blocked state till its turn.

Sleep : will cause the thread to sleep in sleep mode for span of time mentioned in arguments.

Join : t1 and t2 are two threads , t2.join() is called then t1 enters into wait state until t2 completes execution. Then t1 will into runnable state then our specialist JVM thread scheduler will pick t1 based on criteria's.

Pull new updates from original GitHub repository into forked GitHub repository

If you want to do it without cli, you can do it fully on Github website.

  1. Go to your fork repository.
  2. Click on New pull request.
  3. Make sure to set your fork as the base repository, and the original (upstream) repository as head repository. Usually you only want to sync the master branch.
  4. Create new pull request.
  5. Select the arrow to the right of the merging button, and make sure to choose rebase instead of merge. Then click the button. This way, it will not produce unnecessary merge commit.
  6. Done.

Put request with simple string as request body

axios.put(url,{body},{headers:{}})

example:

const body = {title: "what!"}
const api = {
  apikey: "safhjsdflajksdfh",
  Authorization: "Basic bwejdkfhasjk"
}

axios.put('https://api.xxx.net/xx', body, {headers: api})

Converting a UNIX Timestamp to Formatted Date String

<?php
$timestamp=1486830234542;
echo date('Y-m-d H:i:s', $timestamp/1000);
?>

python: SyntaxError: EOL while scanning string literal

In my case with Mac OS X, I had the following statement:

model.export_srcpkg(platform, toolchain, 'mymodel_pkg.zip', 'mymodel.dylib’)

I was getting the error:

  File "<stdin>", line 1
model.export_srcpkg(platform, toolchain, 'mymodel_pkg.zip', 'mymodel.dylib’)
                                                                             ^
SyntaxError: EOL while scanning string literal

After I change to:

model.export_srcpkg(platform, toolchain, "mymodel_pkg.zip", "mymodel.dylib")

It worked...

David

How to create custom view programmatically in swift having controls text field, button etc

Swift 3 / Swift 4 Update:

let screenSize: CGRect = UIScreen.main.bounds
let myView = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width - 10, height: 10))
self.view.addSubview(myView)

How to npm install to a specified directory?

In the documentation it's stated: Use the prefix option together with the global option:

The prefix config defaults to the location where node is installed. On most systems, this is /usr/local. On windows, this is the exact location of the node.exe binary. On Unix systems, it's one level up, since node is typically installed at {prefix}/bin/node rather than {prefix}/node.exe.

When the global flag is set, npm installs things into this prefix. When it is not set, it uses the root of the current package, or the current working directory if not in a package already.

(Emphasis by them)

So in your root directory you could install with

npm install --prefix <path/to/prefix_folder> -g

and it will install the node_modules folder into the folder

<path/to/prefix_folder>/lib/node_modules

How do I remove lines between ListViews on Android?

If this android:divider="@null" doesn't work, maybe changing your ListViews for Recycler Views? 

android asynctask sending callbacks to ui

I felt the below approach is very easy.

I have declared an interface for callback

public interface AsyncResponse {
    void processFinish(Object output);
}

Then created asynchronous Task for responding all type of parallel requests

 public class MyAsyncTask extends AsyncTask<Object, Object, Object> {

    public AsyncResponse delegate = null;//Call back interface

    public MyAsyncTask(AsyncResponse asyncResponse) {
        delegate = asyncResponse;//Assigning call back interfacethrough constructor
    }

    @Override
    protected Object doInBackground(Object... params) {

    //My Background tasks are written here

      return {resutl Object}

    }

    @Override
    protected void onPostExecute(Object result) {
        delegate.processFinish(result);
    }

}

Then Called the asynchronous task when clicking a button in activity Class.

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {

        Button mbtnPress = (Button) findViewById(R.id.btnPress);

        mbtnPress.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                MyAsyncTask asyncTask =new MyAsyncTask(new AsyncResponse() {

                    @Override
                    public void processFinish(Object output) {
                        Log.d("Response From Asynchronous task:", (String) output);          
                        mbtnPress.setText((String) output);
                    }
                });
                asyncTask.execute(new Object[] { "Youe request to aynchronous task class is giving here.." });

            }
        });
    }
}

Thanks

How to prevent vim from creating (and leaving) temporary files?

Put this in your .vimrc configuration file.

set nobackup

Is there a good JSP editor for Eclipse?

You could check out JBoss Tools plugin.

Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

In my specific case I seemed to have been missing the dependency

 <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
 <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>5.1.3.RELEASE</version>
 </dependency>

What is the garbage collector in Java?

The basic principles of garbage collection are to find data objects in a program that cannot be accessed in the future, and to reclaim the resources used by those objects. https://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29

Advantages

1) Saves from bugs, which occur when a piece of memory is freed while there are still pointers to it, and one of those pointers is dereferenced. https://en.wikipedia.org/wiki/Dangling_pointer

2) Double free bugs, which occur when the program tries to free a region of memory that has already been freed, and perhaps already been allocated again.

3) Prevents from certain kinds of memory leaks, in which a program fails to free memory occupied by objects that have become unreachable, which can lead to memory exhaustion.

Disadvantages

1) Consuming additional resources, performance impacts, possible stalls in program execution, and incompatibility with manual resource management. Garbage collection consumes computing resources in deciding which memory to free, even though the programmer may have already known this information.

2) The moment when the garbage is actually collected can be unpredictable, resulting in stalls (pauses to shift/free memory) scattered throughout a session. Unpredictable stalls can be unacceptable in real-time environments, in transaction processing, or in interactive programs.


Oracle tutorial http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html

Garbage collection is the process identifying which objects are in use and which are not, and deleting the unused objects.

In a programming languages like C, C++, allocating and freeing memory is a manual process.

int * array = new int[size];
processArray(array); //do some work.
delete array; //Free memory

The first step in the process is called marking. This is where the garbage collector identifies which pieces of memory are in use and which are not.

Step 2a. Normal deletion removes unreferenced objects leaving referenced objects and pointers to free space.

To improve performance, we want to delete unreferenced objects and also compact the remaining referenced objects. We want to keep referenced objects together, so it will be faster to allocate new memory.

As stated earlier, having to mark and compact all the objects in a JVM is inefficient. As more and more objects are allocated, the list of objects grows and grows leading to longer and longer garbage collection time.

Continue reading this tutorial, and you will know how GC takes this challenge.

In short, there are three regions of the heap, YoungGeneration for short life objects, OldGeneration for long period objects, and PermanentGeneration for objects that live during the application life, for example, classes, libraries.

Use of *args and **kwargs

The syntax is the * and **. The names *args and **kwargs are only by convention but there's no hard requirement to use them.

You would use *args when you're not sure how many arguments might be passed to your function, i.e. it allows you pass an arbitrary number of arguments to your function. For example:

>>> def print_everything(*args):
        for count, thing in enumerate(args):
...         print( '{0}. {1}'.format(count, thing))
...
>>> print_everything('apple', 'banana', 'cabbage')
0. apple
1. banana
2. cabbage

Similarly, **kwargs allows you to handle named arguments that you have not defined in advance:

>>> def table_things(**kwargs):
...     for name, value in kwargs.items():
...         print( '{0} = {1}'.format(name, value))
...
>>> table_things(apple = 'fruit', cabbage = 'vegetable')
cabbage = vegetable
apple = fruit

You can use these along with named arguments too. The explicit arguments get values first and then everything else is passed to *args and **kwargs. The named arguments come first in the list. For example:

def table_things(titlestring, **kwargs)

You can also use both in the same function definition but *args must occur before **kwargs.

You can also use the * and ** syntax when calling a function. For example:

>>> def print_three_things(a, b, c):
...     print( 'a = {0}, b = {1}, c = {2}'.format(a,b,c))
...
>>> mylist = ['aardvark', 'baboon', 'cat']
>>> print_three_things(*mylist)
a = aardvark, b = baboon, c = cat

As you can see in this case it takes the list (or tuple) of items and unpacks it. By this it matches them to the arguments in the function. Of course, you could have a * both in the function definition and in the function call.

How can I run dos2unix on an entire directory?

I have had the same problem and thanks to the posts here I have solved it. I knew that I have around a hundred files and I needed to run it for *.js files only. find . -type f -name '*.js' -print0 | xargs -0 dos2unix

Thank you all for your help.

Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?

main.cpp doesn't have to know what is in class.cpp. It just has to know the declarations of the functions/classes that it goes to use, and these declarations are in class.h.

The linker links between the places where the functions/classes declared in class.h are used and their implementations in class.cpp

How to get the url parameters using AngularJS

If you're using ngRoute, you can inject $routeParams into your controller

http://docs.angularjs.org/api/ngRoute/service/$routeParams

If you're using angular-ui-router, you can inject $stateParams

https://github.com/angular-ui/ui-router/wiki/URL-Routing

Checking Value of Radio Button Group via JavaScript?

If you are using a javascript library like jQuery, it's very easy:

alert($('input[name=gender]:checked').val());

This code will select the checked input with gender name, and gets it's value. Simple isn't it?

Live demo

Simplest way to do grouped barplot

There are several ways to do plots in R; lattice is one of them, and always a reasonable solution, +1 to @agstudy. If you want to do this in base graphics, you could try the following:

Reasonstats <- read.table(text="Category         Reason  Species
                                 Decline        Genuine       24
                                Improved        Genuine       16
                                Improved  Misclassified       85
                                 Decline  Misclassified       41
                                 Decline      Taxonomic        2
                                Improved      Taxonomic        7
                                 Decline        Unclear       41
                                Improved        Unclear      117", header=T)

ReasonstatsDec <- Reasonstats[which(Reasonstats$Category=="Decline"),]
ReasonstatsImp <- Reasonstats[which(Reasonstats$Category=="Improved"),]
Reasonstats3   <- cbind(ReasonstatsImp[,3], ReasonstatsDec[,3])
colnames(Reasonstats3) <- c("Improved", "Decline")
rownames(Reasonstats3) <- ReasonstatsImp$Reason

windows()
  barplot(t(Reasonstats3), beside=TRUE, ylab="number of species", 
          cex.names=0.8, las=2, ylim=c(0,120), col=c("darkblue","red"))
  box(bty="l")

enter image description here

Here's what I did: I created a matrix with two columns (because your data were in columns) where the columns were the species counts for Decline and for Improved. Then I made those categories the column names. I also made the Reasons the row names. The barplot() function can operate over this matrix, but wants the data in rows rather than columns, so I fed it a transposed version of the matrix. Lastly, I deleted some of your arguments to your barplot() function call that were no longer needed. In other words, the problem was that your data weren't set up the way barplot() wants for your intended output.

Please explain the exec() function and its family

what is the exec function and its family.

The exec function family is all functions used to execute a file, such as execl, execlp, execle, execv, and execvp.They are all frontends for execve and provide different methods of calling it.

why is this function used

Exec functions are used when you want to execute (launch) a file (program).

and how does it work.

They work by overwriting the current process image with the one that you launched. They replace (by ending) the currently running process (the one that called the exec command) with the new process that has launched.

For more details: see this link.

How to check if a String contains any of some strings

You can try with regular expression

string s;
Regex r = new Regex ("a|b|c");
bool containsAny = r.IsMatch (s);

How can I install a previous version of Python 3 in macOS using homebrew?

The easiest way for me was to install Anaconda: https://docs.anaconda.com/anaconda/install/

There I can create as many environments with different Python versions as I want and switch between them with a mouse click. It could not be easier.

To install different Python versions just follow these instructions https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-python.html

A new development environment with a different Python version was done within 2 minutes. And in the future I can easily switch back and forth.

Regular expression: find spaces (tabs/space) but not newlines

As @Eiríkr Útlendi noted, the accepted solution only considers two white space characters: the horizontal tab (U+0009), and a breaking space (U+0020). It does not consider other whitespace characters such as non-breaking spaces (which happen to be in the text I am trying to deal with). A more complete whitespace character listing is included on Wikipedia and also referenced in the linked Perl answer. A simple C# solution that accounts for these other characters can be built using character class subtraction

[\s-[\r\n]]

or, including Eiríkr Útlendi's solution, you get

[\s\u3000-[\r\n]]

Android Studio 3.0 Flavor Dimension Issue

Here you can resolve this issue, you need to add flavorDimension with productFlavors's name and need to define dimension as well, see below example and for more information see here https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html

flavorDimensions 'yourAppName' //here defined dimensions
productFlavors {
    production {
        dimension 'yourAppName' //you just need to add this line
        //here you no need to write applicationIdSuffix because by default it will point to your app package which is also available inside manifest.xml file.

    }

    staging {
        dimension 'yourAppName' //added here also
        applicationIdSuffix ".staging"//(.staging) will be added after your default package name.
        //or you can also use applicationId="your_package_name.staging" instead of applicationIdSuffix but remember if you are using applicationId then You have to mention full package name.
        //versionNameSuffix "-staging"

    }

    develop {
        dimension 'yourAppName' //add here too
        applicationIdSuffix ".develop"
        //versionNameSuffix "-develop"

    }

'adb' is not recognized as an internal or external command, operable program or batch file

If you want to use it every time add the path of adb to your system variables: enter to cmd (command prompt) and write the following:

echo %PATH%

this command will show you what it was before you will add adb path

setx PATH "%PATH%;C:\Program Files\android-sdk-windows\platform-tools"

be careful the path that you want to add if it contains double quote

after you restart your cmd rewrite:

echo %PATH%

you will find that the path is added

PS: if you just want to add the path to cmd just to this session you can use:

set PATH=%PATH%;C:\Program Files\android-sdk-windows\platform-tools

Selecting pandas column by location

You can also use df.icol(n) to access a column by integer.

Update: icol is deprecated and the same functionality can be achieved by:

df.iloc[:, n]  # to access the column at the nth position

How to get user name using Windows authentication in asp.net?

These are the different variables you have access to and their values, depending on the IIS configuration.

Scenario 1: Anonymous Authentication in IIS with impersonation off.

HttpContext.Current.Request.LogonUserIdentity.Name    SERVER1\IUSR_SERVER1 
HttpContext.Current.Request.IsAuthenticated           False                    
HttpContext.Current.User.Identity.Name                –                        
System.Environment.UserName                           ASPNET                   
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\ASPNET

Scenario 2: Windows Authentication in IIS, impersonation off.

HttpContext.Current.Request.LogonUserIdentity.Name    MYDOMAIN\USER1   
HttpContext.Current.Request.IsAuthenticated           True             
HttpContext.Current.User.Identity.Name                MYDOMAIN\USER1   
System.Environment.UserName                           ASPNET           
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\ASPNET

Scenario 3: Anonymous Authentication in IIS, impersonation on

HttpContext.Current.Request.LogonUserIdentity.Name    SERVER1\IUSR_SERVER1 
HttpContext.Current.Request.IsAuthenticated           False                    
HttpContext.Current.User.Identity.Name                –                        
System.Environment.UserName                           IUSR_SERVER1           
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\IUSR_SERVER1 

Scenario 4: Windows Authentication in IIS, impersonation on

HttpContext.Current.Request.LogonUserIdentity.Name    MYDOMAIN\USER1
HttpContext.Current.Request.IsAuthenticated           True          
HttpContext.Current.User.Identity.Name                MYDOMAIN\USER1
System.Environment.UserName                           USER1         
Security.Principal.WindowsIdentity.GetCurrent().Name  MYDOMAIN\USER1

Legend
SERVER1\ASPNET: Identity of the running process on server.
SERVER1\IUSR_SERVER1: Anonymous guest user defined in IIS.
MYDOMAIN\USER1: The user of the remote client.

Source

Regex to get NUMBER only from String

Either [0-9] or \d1 should suffice if you only need a single digit. Append + if you need more.


1 The semantics are slightly different as \d potentially matches any decimal digit in any script out there that uses decimal digits.

Android screen size HDPI, LDPI, MDPI

The documentation is quite sketchy as far as definitive resolutions go. After some research, here's the solution I came to: Android splash screen image sizes to fit all devices

It's basically guided towards splash screens, but it's perfectly applicable to images that should occupy full screen.

Redis strings vs Redis hashes to represent JSON: efficiency?

This article can provide a lot of insight here: http://redis.io/topics/memory-optimization

There are many ways to store an array of Objects in Redis (spoiler: I like option 1 for most use cases):

  1. Store the entire object as JSON-encoded string in a single key and keep track of all Objects using a set (or list, if more appropriate). For example:

    INCR id:users
    SET user:{id} '{"name":"Fred","age":25}'
    SADD users {id}
    

    Generally speaking, this is probably the best method in most cases. If there are a lot of fields in the Object, your Objects are not nested with other Objects, and you tend to only access a small subset of fields at a time, it might be better to go with option 2.

    Advantages: considered a "good practice." Each Object is a full-blown Redis key. JSON parsing is fast, especially when you need to access many fields for this Object at once. Disadvantages: slower when you only need to access a single field.

  2. Store each Object's properties in a Redis hash.

    INCR id:users
    HMSET user:{id} name "Fred" age 25
    SADD users {id}
    

    Advantages: considered a "good practice." Each Object is a full-blown Redis key. No need to parse JSON strings. Disadvantages: possibly slower when you need to access all/most of the fields in an Object. Also, nested Objects (Objects within Objects) cannot be easily stored.

  3. Store each Object as a JSON string in a Redis hash.

    INCR id:users
    HMSET users {id} '{"name":"Fred","age":25}'
    

    This allows you to consolidate a bit and only use two keys instead of lots of keys. The obvious disadvantage is that you can't set the TTL (and other stuff) on each user Object, since it is merely a field in the Redis hash and not a full-blown Redis key.

    Advantages: JSON parsing is fast, especially when you need to access many fields for this Object at once. Less "polluting" of the main key namespace. Disadvantages: About same memory usage as #1 when you have a lot of Objects. Slower than #2 when you only need to access a single field. Probably not considered a "good practice."

  4. Store each property of each Object in a dedicated key.

    INCR id:users
    SET user:{id}:name "Fred"
    SET user:{id}:age 25
    SADD users {id}
    

    According to the article above, this option is almost never preferred (unless the property of the Object needs to have specific TTL or something).

    Advantages: Object properties are full-blown Redis keys, which might not be overkill for your app. Disadvantages: slow, uses more memory, and not considered "best practice." Lots of polluting of the main key namespace.

Overall Summary

Option 4 is generally not preferred. Options 1 and 2 are very similar, and they are both pretty common. I prefer option 1 (generally speaking) because it allows you to store more complicated Objects (with multiple layers of nesting, etc.) Option 3 is used when you really care about not polluting the main key namespace (i.e. you don't want there to be a lot of keys in your database and you don't care about things like TTL, key sharding, or whatever).

If I got something wrong here, please consider leaving a comment and allowing me to revise the answer before downvoting. Thanks! :)

How do I drag and drop files into an application?

Yet another gotcha:

The framework code that calls the Drag-events swallow all exceptions. You might think your event code is running smoothly, while it is gushing exceptions all over the place. You can't see them because the framework steals them.

That's why I always put a try/catch in these event handlers, just so I know if they throw any exceptions. I usually put a Debugger.Break(); in the catch part.

Before release, after testing, if everything seems to behave, I remove or replace these with real exception handling.

How to convert password into md5 in jquery?

Get the field value through the id and send with ajax

var field = $("#field").val();
$.ajax({
    type: "POST",
    url: "db.php",
    data: {variable_name:field},
    async:false,
    dataType:"json",
    success: function(response) {
       alert(response);
    }
 });

At db.php file get the variable name

$variable_name = $_GET['variable_name'];
mysql_query("SELECT password FROM table_name WHERE password='".md5($variable_name)."'");

How to iterate through table in Lua?

If you want to refer to a nested table by multiple keys you can just assign them to separate keys. The tables are not duplicated, and still reference the same values.

arr = {}
apples = {'a', "red", 5 }
arr.apples = apples
arr[1] = apples

This code block lets you iterate through all the key-value pairs in a table (http://lua-users.org/wiki/TablesTutorial):

for k,v in pairs(t) do
 print(k,v)
end

How to append rows in a pandas dataframe in a for loop?

I have created a data frame in a for loop with the help of a temporary empty data frame. Because for every iteration of for loop, a new data frame will be created thereby overwriting the contents of previous iteration.

Hence I need to move the contents of the data frame to the empty data frame that was created already. It's as simple as that. We just need to use .append function as shown below :

temp_df = pd.DataFrame() #Temporary empty dataframe
for sent in Sentences:
    New_df = pd.DataFrame({'words': sent.words}) #Creates a new dataframe and contains tokenized words of input sentences
    temp_df = temp_df.append(New_df, ignore_index=True) #Moving the contents of newly created dataframe to the temporary dataframe

Outside the for loop, you can copy the contents of the temporary data frame into the master data frame and then delete the temporary data frame if you don't need it

How do I import a sql data file into SQL Server?

A .sql file is a set of commands that can be executed against the SQL server.

Sometimes the .sql file will specify the database, other times you may need to specify this.

You should talk to your DBA or whoever is responsible for maintaining your databases. They will probably want to give the file a quick look. .sql files can do a lot of harm, even inadvertantly.

See the other answers if you want to plunge ahead.

Bad Request - Invalid Hostname IIS7

Check your local hosts file (C:\Windows\System32\drivers\etc\hosts for example). In my case I had previously used this to point a URL to a dev box and then forgotten about it. When I then reused the same URL I kept getting Bad Request (Invalid Hostname) because the traffic was going to the wrong server.

Callback after all asynchronous forEach callbacks are completed

 var counter = 0;
 var listArray = [0, 1, 2, 3, 4];
 function callBack() {
     if (listArray.length === counter) {
         console.log('All Done')
     }
 };
 listArray.forEach(function(element){
     console.log(element);
     counter = counter + 1;
     callBack();
 });

Query to check index on a table

If you're using MySQL you can run SHOW KEYS FROM table or SHOW INDEXES FROM table

How to redirect to an external URL in Angular2?

An Angular approach to the methods previously described is to import DOCUMENT from @angular/common (or @angular/platform-browser in Angular < 4) and use

document.location.href = 'https://stackoverflow.com';

inside a function.

some-page.component.ts

import { DOCUMENT } from '@angular/common';
...
constructor(@Inject(DOCUMENT) private document: Document) { }

goToUrl(): void {
    this.document.location.href = 'https://stackoverflow.com';
}

some-page.component.html

<button type="button" (click)="goToUrl()">Click me!</button>

Check out the plateformBrowser repo for more info.

How to make a JSON call to a url?

You make a bog standard HTTP GET Request. You get a bog standard HTTP Response with an application/json content type and a JSON document as the body. You then parse this.

Since you have tagged this 'JavaScript' (I assume you mean "from a web page in a browser"), and I assume this is a third party service, you're stuck. You can't fetch data from remote URI in JavaScript unless explicit workarounds (such as JSONP) are put in place.

Oh wait, reading the documentation you linked to - JSONP is available, but you must say 'js' not 'json' and specify a callback: format=js&callback=foo

Then you can just define the callback function:

function foo(myData) { 
    // do stuff with myData
}

And then load the data:

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = theUrlForTheApi;
document.body.appendChild(script);

Why does a base64 encoded string have an = sign at the end

From Wikipedia:

The final '==' sequence indicates that the last group contained only one byte, and '=' indicates that it contained two bytes.

Thus, this is some sort of padding.

Importing JSON into an Eclipse project

You should take the json implementation from here : http://code.google.com/p/json-simple/ .

  • Download the *.jar
  • Add it to the classpath (right-click on the project, Properties->Libraries and add new JAR.)

How to create friendly URL in php?

Simple way to do this. Try this code. Put code in your htaccess file:

Options +FollowSymLinks

RewriteEngine on

RewriteRule profile/(.*)/ profile.php?u=$1

RewriteRule profile/(.*) profile.php?u=$1   

It will create this type pretty URL:

http://www.domain.com/profile/12345/

For more htaccess Pretty URL:http://www.webconfs.com/url-rewriting-tool.php

Sleep function in ORACLE

What's about Java code wrapped by a procedure? Simple and works fine.

CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED SNOOZE AS
public final class Snooze {
  private Snooze() {
  }
  public static void snooze(Long milliseconds) throws InterruptedException {
      Thread.sleep(milliseconds);
  }
}

CREATE OR REPLACE PROCEDURE SNOOZE(p_Milliseconds IN NUMBER) AS
    LANGUAGE JAVA NAME 'Snooze.snooze(java.lang.Long)';

Convert ndarray from float64 to integer

Use .astype.

>>> a = numpy.array([1, 2, 3, 4], dtype=numpy.float64)
>>> a
array([ 1.,  2.,  3.,  4.])
>>> a.astype(numpy.int64)
array([1, 2, 3, 4])

See the documentation for more options.

Tooltips for cells in HTML table (no Javascript)

if (data[j] =='B'){
    row.cells[j].title="Basic";
}

In Java script conditionally adding title by comparing value of Data. The Table is generated by Java script dynamically.

What are major differences between C# and Java?

Another good resource is http://www.javacamp.org/javavscsharp/ This site enumerates many examples that ilustrate almost all the differences between these two programming languages.

About the Attributes, Java has Annotations, that work almost the same way.

data.frame rows to a list

A couple of more options :

With asplit

asplit(xy.df, 1)
#[[1]]
#     x      y 
#0.1137 0.6936 

#[[2]]
#     x      y 
#0.6223 0.5450 

#[[3]]
#     x      y 
#0.6093 0.2827 
#....

With split and row

split(xy.df, row(xy.df)[, 1])

#$`1`
#       x      y
#1 0.1137 0.6936

#$`2`
#       x     y
#2 0.6223 0.545

#$`3`
#       x      y
#3 0.6093 0.2827
#....

data

set.seed(1234)
xy.df <- data.frame(x = runif(10),  y = runif(10))

How do you create a UIImage View Programmatically - Swift

In Swift 3.0 :

var imageView : UIImageView
    imageView  = UIImageView(frame:CGRect(x:10, y:50, width:100, height:300));
    imageView.image = UIImage(named:"Test.jpeg")
    self.view.addSubview(imageView)

Styling twitter bootstrap buttons

If you are already loading your own custom CSS file after loading bootstrap.css (version 3) you can add these 2 CSS styles to your custom.css and they will override the bootstrap defaults for the default button style.

.btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .open .dropdown-toggle.btn-primary {

  background-color: #A6A8C1;
  border-color: #31347B;
 }

.btn
{
  background-color: #9F418F;
  border-color: #9F418F;
}

How to use gitignore command in git

on my mac i found this file .gitignore_global ..it was in my home directory hidden so do a ls -altr to see it.

I added eclipse files i wanted git to ignore. the contents looks like this:

 *~
.DS_Store
.project
.settings
.classpath
.metadata

SVN undo delete before commit

svn revert deletedDirectory

Here's the documentation for the svn revert command.


EDIT

If deletedDirectory was deleted using rmdir and not svn rm, you'll need to do

svn update deletedDirectory

instead.

Why AVD Manager options are not showing in Android Studio

I had the same issue on my React Native Project. Was not just that ADV Manager didn't show up on the menu but other tools where missing as well.

Everything was back to normal when I opened the project using Import project option instead of Open an Existing Android Studio project.

enter image description here

Sending GET request with Authentication headers using restTemplate

A simple solution would be to configure static http headers needed for all calls in the bean configuration of the RestTemplate:

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate getRestTemplate(@Value("${did-service.bearer-token}") String bearerToken) {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getInterceptors().add((request, body, clientHttpRequestExecution) -> {
            HttpHeaders headers = request.getHeaders();
            if (!headers.containsKey("Authorization")) {
                String token = bearerToken.toLowerCase().startsWith("bearer") ? bearerToken : "Bearer " + bearerToken;
                request.getHeaders().add("Authorization", token);
            }
            return clientHttpRequestExecution.execute(request, body);
        });
        return restTemplate;
    }
}

Type of expression is ambiguous without more context Swift

In my case, this error message shown when I don't added optional property to constructor.

struct Event: Identifiable, Codable {

    var id: String
    var summary: String
    var description: String?
    // also has other props...

    init(id: String, summary: String, description: String?){
        self.id = id
        self.summary = summary
        self.description = description
    }
}

// skip pass description
// It show message "Type of expression is ambiguous without more context"
Event(
    id: "1",
    summary: "summary",
)

// pass description explicity pass nil to description
Event(
    id: "1",
    summary: "summary",
    description: nil
)

but it looks always not occured.

I test in my playground this code, it show warning about more concrete

var str = "Hello, playground"
struct User {
    var id: String
    var name: String?
    init(id: String, name: String?) {
        self.id = id
        self.name = name
    }
}

User(id: "hoge") // Missing argument for parameter 'name' in call

How to write a:hover in inline CSS?

You could do it at some point in the past. But now (according to the latest revision of the same standard, which is Candidate Recommendation) you can't .

Bi-directional Map in Java?

Creating a Guava BiMap and getting its inverted value is not so trivial.

A simple example:

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;

public class BiMapTest {

  public static void main(String[] args) {

    BiMap<String, String> biMap = HashBiMap.create();

    biMap.put("k1", "v1");
    biMap.put("k2", "v2");

    System.out.println("k1 = " + biMap.get("k1"));
    System.out.println("v2 = " + biMap.inverse().get("v2"));
  }
}

Understanding generators in Python

The only thing I can add to Stephan202's answer is a recommendation that you take a look at David Beazley's PyCon '08 presentation "Generator Tricks for Systems Programmers," which is the best single explanation of the how and why of generators that I've seen anywhere. This is the thing that took me from "Python looks kind of fun" to "This is what I've been looking for." It's at http://www.dabeaz.com/generators/.

Mean per group in a data.frame

I describe two ways to do this, one based on data.table and the other based on reshape2 package . The data.table way already has an answer, but I have tried to make it cleaner and more detailed.

The data is like this:

 d <- structure(list(Name = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 
3L, 3L), .Label = c("Aira", "Ben", "Cat"), class = "factor"), 
    Month = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), Rate1 = c(12L, 
    18L, 19L, 53L, 22L, 19L, 22L, 67L, 45L), Rate2 = c(23L, 73L, 
    45L, 19L, 87L, 45L, 87L, 43L, 32L)), .Names = c("Name", "Month", 
"Rate1", "Rate2"), class = "data.frame", row.names = c(NA, -9L
))
head(d)
  Name Month Rate1 Rate2
1 Aira     1    12    23
2 Aira     2    18    73
3 Aira     3    19    45
4  Ben     1    53    19
5  Ben     2    22    87
6  Ben     3    19    45


library("reshape2")
mym <- melt(d, id = c("Name"))
res <- dcast(mym, Name ~ variable, mean)
res
#Name Month    Rate1    Rate2
#1 Aira     2 16.33333 47.00000
#2  Ben     2 31.33333 50.33333
#3  Cat     2 44.66667 54.00000

Using data.table:

# At first, I convert the data.frame to data.table and then I group it 
setDT(d)
d[, .(Rate1 = mean(Rate1), Rate2 = mean(Rate2)), by = .(Name)]
#   Name    Rate1    Rate2
#1: Aira 16.33333 47.00000
#2:  Ben 31.33333 50.33333
#3:  Cat 44.66667 54.00000

There is another way of doing it by avoiding to write many argument for j in data.table using a .SD

d[, lapply(.SD, mean), by = .(Name)]
#   Name Month    Rate1    Rate2
#1: Aira     2 16.33333 47.00000
#2:  Ben     2 31.33333 50.33333
#3:  Cat     2 44.66667 54.00000

if we only want to have Rate1 and Rate2 then we can use the .SDcols as follows:

d[, lapply(.SD, mean), by = .(Name), .SDcols = 3:4]
#  Name    Rate1    Rate2
#1: Aira 16.33333 47.00000
#2:  Ben 31.33333 50.33333
#3:  Cat 44.66667 54.00000

Powershell: A positional parameter cannot be found that accepts argument "xxx"

In my case there was a corrupted character in one of the named params ("-StorageAccountName" for cmdlet "Get-AzureStorageKey") which showed as perfectly normal in my editor (SublimeText) but Windows Powershell couldn't parse it.

To get to the bottom of it, I moved the offending lines from the error message into another .ps1 file, ran that, and the error now showed a botched character at the beginning of my "-StorageAccountName" parameter.

Deleting the character (again which looks normal in the actual editor) and re-typing it fixes this issue.

Android EditText Hint

I don't know whether a direct way of doing this is available or not, but you surely there is a workaround via code: listen for onFocus event of EditText, and as soon it gains focus, set the hint to be nothing with something like editText.setHint(""):

This may not be exactly what you have to do, but it may be something like this-

myEditText.setOnFocusListener(new OnFocusListener(){
  public void onFocus(){
    myEditText.setHint("");
  }
});

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

DataTable's Select method only supports simple filtering expressions like {field} = {value}. It does not support complex expressions, let alone SQL/Linq statements.

You can, however, use Linq extension methods to extract a collection of DataRows then create a new DataTable.

dt = dt.AsEnumerable()
       .GroupBy(r => new {Col1 = r["Col1"], Col2 = r["Col2"]})
       .Select(g => g.OrderBy(r => r["PK"]).First())
       .CopyToDataTable();

Rollback one specific migration in Laravel

If you look in your migrations table, then you’ll see each migration has a batch number. So when you roll back, it rolls back each migration that was part of the last batch.

If you only want to roll back the very last migration, then just increment the batch number by one. Then next time you run the rollback command, it’ll only roll back that one migration as it’s in a “batch” of its own.

Alternatively, from Laravel 5.3 onwards, you can just run:

php artisan migrate:rollback --step=1

That will rollback the last migration, no matter what its batch number is.

Stop form from submitting , Using Jquery

Again, AJAX is async. So the showMsg function will be called only after success response from the server.. and the form submit event will not wait until AJAX success.

Move the e.preventDefault(); as first line in the click handler.

$("form").submit(function (e) {
      e.preventDefault(); // this will prevent from submitting the form.
      ...

See below code,

I want it to be allowed HasJobInProgress == False

$(document).ready(function () {
    $("form").submit(function (e) {
        e.preventDefault(); //prevent default form submit
        $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function (data) {
                showMsg(data);
            },
            cache: false
        });
    });
});
$("#cancelButton").click(function () {
    window.location = '@Url.Action("list", "default", new { clientId = Model.ClientId })';
});
$("[type=text]").focus(function () {
    $(this).select();
});
function showMsg(hasCurrentJob) {
    if (hasCurrentJob == "True") {
        alert("The current clients has a job in progress. No changes can be saved until current job completes");
        return false;
    } else {
       $("form").unbind('submit').submit();
    }
}

Generating random numbers with Swift

Just call this function and provide minimum and maximum range of number and you will get a random number.

eg.like randomNumber(MIN: 0, MAX: 10) and You will get number between 0 to 9.

func randomNumber(MIN: Int, MAX: Int)-> Int{
    return Int(arc4random_uniform(UInt32(MAX-MIN)) + UInt32(MIN));
}

Note:- You will always get output an Integer number.

How to create a WPF Window without a border that can be resized via a grip only?

While the accepted answer is very true, just want to point out that AllowTransparency has some downfalls. It does not allow child window controls to show up, ie WebBrowser, and it usually forces software rendering which can have negative performance effects.

There is a better work around though.

When you want to create a window with no border that is resizeable and is able to host a WebBrowser control or a Frame control pointed to a URL you simply couldn't, the contents of said control would show empty.

I found a workaround though; in the Window, if you set the WindowStyle to None, ResizeMode to NoResize (bear with me, you will still be able to resize once done) then make sure you have UNCHECKED AllowsTransparency you will have a static sized window with no border and will show the browser control.

Now, you probably still want to be able to resize right? Well we can to that with a interop call:

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

    [DllImportAttribute("user32.dll")]
    public static extern bool ReleaseCapture();

    //Attach this to the MouseDown event of your drag control to move the window in place of the title bar
    private void WindowDrag(object sender, MouseButtonEventArgs e) // MouseDown
    {
        ReleaseCapture();
        SendMessage(new WindowInteropHelper(this).Handle,
            0xA1, (IntPtr)0x2, (IntPtr)0);
    }

    //Attach this to the PreviewMousLeftButtonDown event of the grip control in the lower right corner of the form to resize the window
    private void WindowResize(object sender, MouseButtonEventArgs e) //PreviewMousLeftButtonDown
    {
        HwndSource hwndSource = PresentationSource.FromVisual((Visual)sender) as HwndSource;
        SendMessage(hwndSource.Handle, 0x112, (IntPtr)61448, IntPtr.Zero);
    }

And voila, A WPF window with no border and still movable and resizable without losing compatibility with with controls like WebBrowser

How to apply two CSS classes to a single element

As others have pointed out, you simply delimit them with a space.

However, knowing how the selectors work is also useful.

Consider this piece of HTML...

<div class="a"></div>
<div class="b"></div>
<div class="a b"></div>

Using .a { ... } as a selector will select the first and third. However, if you want to select one which has both a and b, you can use the selector .a.b { ... }. Note that this won't work in IE6, it will simply select .b (the last one).

Convert String to double in Java

If you have problems in parsing string to decimal values, you need to replace "," in the number to "."


String number = "123,321";
double value = Double.parseDouble( number.replace(",",".") );

POST request send json data java HttpUrlConnection

private JSONObject uploadToServer() throws IOException, JSONException {
            String query = "https://example.com";
            String json = "{\"key\":1}";

            URL url = new URL(query);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");

            OutputStream os = conn.getOutputStream();
            os.write(json.getBytes("UTF-8"));
            os.close();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
            JSONObject jsonObject = new JSONObject(result);


            in.close();
            conn.disconnect();

            return jsonObject;
    }

What is the "right" way to iterate through an array in Ruby?

If you use the enumerable mixin (as Rails does) you can do something similar to the php snippet listed. Just use the each_slice method and flatten the hash.

require 'enumerator' 

['a',1,'b',2].to_a.flatten.each_slice(2) {|x,y| puts "#{x} => #{y}" }

# is equivalent to...

{'a'=>1,'b'=>2}.to_a.flatten.each_slice(2) {|x,y| puts "#{x} => #{y}" }

Less monkey-patching required.

However, this does cause problems when you have a recursive array or a hash with array values. In ruby 1.9 this problem is solved with a parameter to the flatten method that specifies how deep to recurse.

# Ruby 1.8
[1,2,[1,2,3]].flatten
=> [1,2,1,2,3]

# Ruby 1.9
[1,2,[1,2,3]].flatten(0)
=> [1,2,[1,2,3]]

As for the question of whether this is a code smell, I'm not sure. Usually when I have to bend over backwards to iterate over something I step back and realize I'm attacking the problem wrong.

How to search through all Git and Mercurial commits in the repository for a certain string?

To add just one more solution not yet mentioned, I had to say that using gitg's graphical search box was the simplest solution for me. It will select the first occurrence and you can find the next with Ctrl-G.

Checking if sys.argv[x] is defined

I use this - it never fails:

startingpoint = 'blah'
if sys.argv[1:]:
   startingpoint = sys.argv[1]

Jackson - best way writes a java list to a json array

I can't find toByteArray() as @atrioom said, so I use StringWriter, please try:

public void writeListToJsonArray() throws IOException {  

    //your list
    final List<Event> list = new ArrayList<Event>(2);
    list.add(new Event("a1","a2"));
    list.add(new Event("b1","b2"));


    final StringWriter sw =new StringWriter();
    final ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(sw, list);
    System.out.println(sw.toString());//use toString() to convert to JSON

    sw.close(); 
}

Or just use ObjectMapper#writeValueAsString:

    final ObjectMapper mapper = new ObjectMapper();
    System.out.println(mapper.writeValueAsString(list));

How to change the MySQL root account password on CentOS7?

For me work like this: 1. Stop mysql: systemctl stop mysqld

  1. Set the mySQL environment option systemctl set-environment MYSQLD_OPTS="--skip-grant-tables"

  2. Start mysql usig the options you just set systemctl start mysqld

  3. Login as root mysql -u root

  4. After login I use FLUSH PRIVILEGES; tell the server to reload the grant tables so that account-management statements work. If i don't do that i receive this error trying to update the password: "Can't find any matching row in the user table"

Calling the base class constructor from the derived class constructor

The constructor of PetStore will call a constructor of Farm; there's no way you can prevent it. If you do nothing (as you've done), it will call the default constructor (Farm()); if you need to pass arguments, you'll have to specify the base class in the initializer list:

PetStore::PetStore()
    : Farm( neededArgument )
    , idF( 0 )
{
}

(Similarly, the constructor of PetStore will call the constructor of nameF. The constructor of a class always calls the constructors of all of its base classes and all of its members.)

ImportError: No module named sklearn.cross_validation

sklearn.cross_validation is now changed to sklearn.model_selection

Just use

from sklearn.model_selection import train_test_split

I think that will work.

DD/MM/YYYY Date format in Moment.js

for anyone who's using react-moment:

simply use format prop to your needed format:

const now = new Date()
<Moment format="DD/MM/YYYY">{now}</Moment>

Running SSH Agent when starting Git Bash on Windows

I could not get this to work based off the best answer, probably because I'm such a PC noob and missing something obvious. But just FYI in case it helps someone as challenged as me, what has FINALLY worked was through one of the links here (referenced in the answers). This involved simply pasting the following to my .bash_profile:

env=~/.ssh/agent.env

agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }

agent_start () {
    (umask 077; ssh-agent >| "$env")
    . "$env" >| /dev/null ; }

agent_load_env

# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)

if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
    agent_start
    ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
    ssh-add
fi

unset env

I probably have something configured weird, but was not successful when I added it to my .profile or .bashrc. The other real challenge I've run into is I'm not an admin on this computer and can't change the environment variables without getting it approved by IT, so this is a solution for those that can't access that.

You know it's working if you're prompted for your ssh password when you open git bash. Hallelujah something finally worked.

How to pad a string to a fixed length with spaces in Python?

You can use the ljust method on strings.

>>> name = 'John'
>>> name.ljust(15)
'John           '

Note that if the name is longer than 15 characters, ljust won't truncate it. If you want to end up with exactly 15 characters, you can slice the resulting string:

>>> name.ljust(15)[:15]

Check if application is on its first run

The following is an example of using SharedPreferences to achieve a 'forWhat' check.

    preferences = PreferenceManager.getDefaultSharedPreferences(context);
    preferencesEditor = preferences.edit();
public static boolean isFirstRun(String forWhat) {
    if (preferences.getBoolean(forWhat, true)) {
        preferencesEditor.putBoolean(forWhat, false).commit();
        return true;
    } else {
        return false;
    }
}

How to globally replace a forward slash in a JavaScript string?

Is this what you want?

'string with / in it'.replace(/\//g, '\\');

How can I remove a child node in HTML using JavaScript?

You should probably use a JavaScript library to do things like this.

For example, MochiKit has a function removeElement, and jQuery has remove.

What's the difference between abstraction and encapsulation?

Encapsulation : Suppose I have some confidential documents, now I hide these documents inside a locker so no one can gain access to them, this is encapsulation.

Abstraction : A huge incident took place which was summarised in the newspaper. Now the newspaper only listed the more important details of the actual incident, this is abstraction. Further the headline of the incident highlights on even more specific details in a single line, hence providing higher level of abstraction on the incident. Also highlights of a football/cricket match can be considered as abstraction of the entire match.

Hence encapsulation is hiding of data to protect its integrity and abstraction is highlighting more important details.

In programming terms we can see that a variable may be enclosed is the scope of a class as private hence preventing it from being accessed directly from outside, this is encapsulation. Whereas a a function may be written in a class to swap two numbers. Now the numbers may be swapped in either by either using a temporary variable or through bit manipulation or using arithmetic operation, but the goal of the user is to receive the numbers swapped irrespective of the method used for swapping, this is abstraction.

python pandas dataframe columns convert to dict key and value

If lakes is your DataFrame, you can do something like

area_dict = dict(zip(lakes.area, lakes.count))

Intercept page exit event

See this article. The feature you are looking for is the onbeforeunload

sample code:

  <script language="JavaScript">
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
  }
</script>

Java Embedded Databases Comparison

I personally favor HSQLDB, but mostly because it was the first I tried.

H2 is said to be faster and provides a nicer GUI frontend (which is generic and works with any JDBC driver, by the way).

At least HSQLDB, H2 and Derby provide server modes which is great for development, because you can access the DB with your application and some tool at the same time (which embedded mode usually doesn't allow).

SQLite Query in Android to count rows

Assuming you already have a Database (db) connection established, I think the most elegant way is to stick to the Cursor class, and do something like:

String selection = "uname = ? AND pwd = ?";
String[] selectionArgs = {loginname, loginpass};
String tableName = "YourTable";
Cursor c = db.query(tableName, null, selection, selectionArgs, null, null, null);
int result = c.getCount();
c.close();
return result;

Firing a Keyboard Event in Safari, using JavaScript

I am working on DOM Keyboard Event Level 3 polyfill . In latest browsers or with this polyfill you can do something like this:

element.addEventListener("keydown", function(e){ console.log(e.key, e.char, e.keyCode) })

var e = new KeyboardEvent("keydown", {bubbles : true, cancelable : true, key : "Q", char : "Q", shiftKey : true});
element.dispatchEvent(e);

//If you need legacy property "keyCode"
// Note: In some browsers you can't overwrite "keyCode" property. (At least in Safari)
delete e.keyCode;
Object.defineProperty(e, "keyCode", {"value" : 666})

UPDATE:

Now my polyfill supports legacy properties "keyCode", "charCode" and "which"

var e = new KeyboardEvent("keydown", {
    bubbles : true,
    cancelable : true,
    char : "Q",
    key : "q",
    shiftKey : true,
    keyCode : 81
});

Examples here

Additionally here is cross-browser initKeyboardEvent separately from my polyfill: (gist)

Polyfill demo

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

Alternatively if you don't need to decode the file, such as uploading the file to a website, open(filename, 'rb')

where r = reading, b = binary

Django template how to look up a dictionary value with a variable

Fetch both the key and the value from the dictionary in the loop:

{% for key, value in mydict.items %}
    {{ value }}
{% endfor %}

I find this easier to read and it avoids the need for special coding. I usually need the key and the value inside the loop anyway.

Reversing an Array in Java

 public void swap(int[] arr,int a,int b)
 {
    int temp=arr[a];
    arr[a]=arr[b];
    arr[b]=temp;        
}
public int[] reverseArray(int[] arr){
    int size=arr.length-1;

    for(int i=0;i<size;i++){

        swap(arr,i,size--); 

    }

    return arr;
}

.substring error: "is not a function"

document.location is an object, not a string. It returns (by default) the full path, but it actually holds more info than that.

Shortcut for solution: document.location.toString().substring(2,3);

Or use document.location.href or window.location.href

How to get current time and date in C++?

The ffead-cpp provides multiple utility classes for various tasks, one such class is the Date class which provides a lot of features right from Date operations to date arithmetic, there's also a Timer class provided for timing operations. You can have a look at the same.

(SC) DeleteService FAILED 1072

I had the same issue. After I closing and re-opening the Computer Management window the service was removed from the list. I'm running windows 7

Android Horizontal RecyclerView scroll Direction

XML approach using androidx:

<androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:id="@+id/my_recycler_view"
        android:orientation="horizontal"
        tools:listitem="@layout/my_item"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" 
        android:layout_height="wrap_content">

importing a CSV into phpmyadmin

Using the LOAD DATA INFILE SQL statement you can import the CSV file, but you can't update data. However, there is a trick you can use.

  • Create another temporary table to use for the import
  • Load onto this table from the CSC

    LOAD DATA LOCAL INFILE '/file.csv'
    INTO TABLE temp_table
    FIELDS TERMINATED BY ','
    LINES TERMINATED BY '\n'
    (field1, field2, field3); 
    
  • UPDATE the real table joining the table

    UPDATE maintable
    INNER JOIN temp_table A USING (field1)
    SET maintable.field1 = temp_table.field1
    

UITableView example for Swift

In Swift 4.1 and Xcode 9.4.1

  1. Add UITableViewDataSource, UITableViewDelegate delegated to your class.

  2. Create table view variable and array.

  3. In viewDidLoad create table view.

  4. Call table view delegates

  5. Call table view delegate functions based on your requirement.

import UIKit
// 1
class yourViewController: UIViewController , UITableViewDataSource, UITableViewDelegate { 

// 2
var yourTableView:UITableView = UITableView()
let myArray = ["row 1", "row 2", "row 3", "row 4"]

override func viewDidLoad() {
    super.viewDidLoad()

    // 3
    yourTableView.frame = CGRect(x: 10, y: 10, width: view.frame.width-20, height: view.frame.height-200)
    self.view.addSubview(yourTableView)

    // 4
    yourTableView.dataSource = self
    yourTableView.delegate = self

}

// 5
// MARK - UITableView Delegates
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return myArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

var cell : UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cell")
    if cell == nil {
        cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
    }
    if self. myArray.count > 0 {
        cell?.textLabel!.text = self. myArray[indexPath.row]
    }
    cell?.textLabel?.numberOfLines = 0

    return cell!
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return 50.0
}

If you are using storyboard, no need for Step 3.

But you need to create IBOutlet for your table view before Step 4.

How to round up with excel VBA round()?

This is an example j is the value you want to round up.

Dim i As Integer
Dim ii, j As Double

j = 27.11
i = (j) ' i is an integer and truncates the decimal

ii = (j) ' ii retains the decimal

If ii - i > 0 Then i = i + 1 

If the remainder is greater than 0 then it rounds it up, simple. At 1.5 it auto rounds to 2 so it'll be less than 0.

Align the form to the center in Bootstrap 4

<div class="d-flex justify-content-center align-items-center container ">

    <div class="row ">


        <form action="">
            <div class="form-group">
                <label for="inputUserName" class="control-label">Enter UserName</label>
                <input type="email" class="form-control" id="inputUserName" aria-labelledby="emailnotification">
                <small id="emailnotification" class="form-text text-muted">Enter Valid Email Id</small>
            </div>
            <div class="form-group">
                <label for="inputPassword" class="control-label">Enter Password</label>
                <input type="password" class="form-control" id="inputPassword" aria-labelledby="passwordnotification">

            </div>
        </form>

    </div>

</div>

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

You are single quoting your SQL statement which is making the variables text instead of variables.

$sql = "SELECT * 
    FROM $usertable 
    WHERE PartNumber = $partid";

Oracle - Why does the leading zero of a number disappear when converting it TO_CHAR

Below format try if number is like

ex 1 suppose number like 10.1 if apply below format it will be come as 10.10

ex 2 suppose number like .02 if apply below format it will be come as 0.02

ex 3 suppose number like 0.2 if apply below format it will be come as 0.20

to_char(round(to_number(column_name)/10000000,2),'999999999990D99') as column_name

How to check syslog in Bash on Linux?

tail -f /var/log/syslog | grep process_name where process_name is the name of the process we are interested in

How do I list loaded plugins in Vim?

:set runtimepath?

This lists the path of all plugins loaded when a file is opened with Vim.

Add column with constant value to pandas dataframe

Here is another one liner using lambdas (create column with constant value = 10)

df['newCol'] = df.apply(lambda x: 10, axis=1)

before

df
    A           B           C
1   1.764052    0.400157    0.978738
2   2.240893    1.867558    -0.977278
3   0.950088    -0.151357   -0.103219

after

df
        A           B           C           newCol
    1   1.764052    0.400157    0.978738    10
    2   2.240893    1.867558    -0.977278   10
    3   0.950088    -0.151357   -0.103219   10

Remove x-axis label/text in chart.js

Faced this issue of removing the labels in Chartjs now. Looks like the documentation is improved. http://www.chartjs.org/docs/#getting-started-global-chart-configuration

Chart.defaults.global.legend.display = false;

this global settings prevents legends from being shown in all Charts. Since this was enough for me, I used it. I am not sure to how to avoid legends for individual charts.

Python: Binding Socket: "Address already in use"

another solution, in development environment of course, is killing process using it, for example

def serve():
    server = HTTPServer(('', PORT_NUMBER), BaseHTTPRequestHandler)
    print 'Started httpserver on port ' , PORT_NUMBER
    server.serve_forever()
try:
    serve()
except Exception, e:
    print "probably port is used. killing processes using given port %d, %s"%(PORT_NUMBER,e)
    os.system("xterm -e 'sudo fuser -kuv %d/tcp'" % PORT_NUMBER)
    serve()
    raise e

Run .php file in Windows Command Prompt (cmd)

You should declare Environment Variable for PHP in path, so you could use like this:

C:\Path\to\somewhere>php cli.php

You can do it like this

Python and JSON - TypeError list indices must be integers not str

You can simplify your code down to

url = "http://worldcup.kimonolabs.com/api/players?apikey=xxx"
json_obj = urllib2.urlopen(url).read
player_json_list = json.loads(json_obj)
for player in readable_json_list:
    print player['firstName']

You were trying to access a list element using dictionary syntax. the equivalent of

foo = [1, 2, 3, 4]
foo["1"]

It can be confusing when you have lists of dictionaries and keeping the nesting in order.

server error:405 - HTTP verb used to access this page is not allowed

I've been pulling my hair out over this one for a couple of hours also. fakeartist appears correct though - I changed the file extension from .htm to .php and I can now see my page in Facebook! It also works if you change the extension to .aspx - perhaps it just needs to be a server side extension (I've not tried with .jsp).

How to select date from datetime column?

Here are all formats

Say this is the column that contains the datetime value, table data.

+--------------------+
| date_created       |
+--------------------+
| 2018-06-02 15:50:30|
+--------------------+

mysql> select DATE(date_created) from data;
+--------------------+
| DATE(date_created) |
+--------------------+
| 2018-06-02         |
+--------------------+

mysql> select YEAR(date_created) from data;
+--------------------+
| YEAR(date_created) |
+--------------------+
|               2018 |
+--------------------+

mysql> select MONTH(date_created) from data;
+---------------------+
| MONTH(date_created) |
+---------------------+
|                   6 |
+---------------------+

mysql> select DAY(date_created) from data;
+-------------------+
| DAY(date_created) |
+-------------------+
|                 2 |
+-------------------+

mysql> select HOUR(date_created) from data;
+--------------------+
| HOUR(date_created) |
+--------------------+
|                 15 |
+--------------------+

mysql> select MINUTE(date_created) from data;
+----------------------+
| MINUTE(date_created) |
+----------------------+
|                   50 |
+----------------------+

mysql> select SECOND(date_created) from data;
+----------------------+
| SECOND(date_created) |
+----------------------+
|                   31 |
+----------------------+

Filter spark DataFrame on string contains

In pyspark,SparkSql syntax:

where column_n like 'xyz%'

might not work.

Use:

where column_n RLIKE '^xyz' 

This works perfectly fine.

How to convert a byte array to Stream

Easy, simply wrap a MemoryStream around it:

Stream stream = new MemoryStream(buffer);

LINQ Aggregate algorithm explained

Aggregate is basically used to Group or Sum up data.

According to MSDN "Aggregate Function Applies an accumulator function over a sequence."

Example 1: Add all the numbers in a array.

int[] numbers = new int[] { 1,2,3,4,5 };
int aggregatedValue = numbers.Aggregate((total, nextValue) => total + nextValue);

*important: The initial aggregate value by default is the 1 element in the sequence of collection. i.e: the total variable initial value will be 1 by default.

variable explanation

total: it will hold the sum up value(aggregated value) returned by the func.

nextValue: it is the next value in the array sequence. This value is than added to the aggregated value i.e total.

Example 2: Add all items in an array. Also set the initial accumulator value to start adding with from 10.

int[] numbers = new int[] { 1,2,3,4,5 };
int aggregatedValue = numbers.Aggregate(10, (total, nextValue) => total + nextValue);

arguments explanation:

the first argument is the initial(starting value i.e seed value) which will be used to start addition with the next value in the array.

the second argument is a func which is a func that takes 2 int.

1.total: this will hold same as before the sum up value(aggregated value) returned by the func after the calculation.

2.nextValue: : it is the next value in the array sequence. This value is than added to the aggregated value i.e total.

Also debugging this code will give you a better understanding of how aggregate work.

How to upgrade Git to latest version on macOS?

In order to keep both versions, I just changed the value of PATH environment variable by putting the new version's git path "/usr/local/git/bin/" at the beginning, it forces to use the newest version:

$ echo $PATH

/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/local/git/bin/

$ git --version

git version 2.4.9 (Apple Git-60)

original value: /usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/local/git/bin/

new value: /usr/local/git/bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin

$ export PATH=/usr/local/git/bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin

$ git --version

git version 2.13.0

How to change JDK version for an Eclipse project

As I was facing this issue minutes ago, in case you are trying to open an existing project in an environment with a newer JDK, make sure you pdate the JDK version in Project Properties -> Project Facets -> Java.

Event on a disabled input

I find another solution:

<input type="text" class="disabled" name="test" value="test" />

Class "disabled" immitate disabled element by opacity:

<style type="text/css">
    input.disabled {
        opacity: 0.5;
    }
</style>

And then cancel the event if element is disabled and remove class:

$(document).on('click','input.disabled',function(event) {
    event.preventDefault();
    $(this).removeClass('disabled');
});

How to avoid annoying error "declared and not used"

According to the FAQ:

Some have asked for a compiler option to turn those checks off or at least reduce them to warnings. Such an option has not been added, though, because compiler options should not affect the semantics of the language and because the Go compiler does not report warnings, only errors that prevent compilation.

There are two reasons for having no warnings. First, if it's worth complaining about, it's worth fixing in the code. (And if it's not worth fixing, it's not worth mentioning.) Second, having the compiler generate warnings encourages the implementation to warn about weak cases that can make compilation noisy, masking real errors that should be fixed.

I don't necessarily agree with this for various reasons not worth going into. It is what it is, and it's not likely to change in the near future.

For packages, there's the goimports tool which automatically adds missing packages and removes unused ones. For example:

# Install it
$ go get golang.org/x/tools/cmd/goimports

# -w to write the source file instead of stdout
$ goimports -w my_file.go

You should be able to run this from any half-way decent editor - for example for Vim:

:!goimports -w %

The goimports page lists some commands for other editors, and you typically set it to be run automatically when you save the buffer to disk.

Note that goimports will also run gofmt.


As was already mentioned, for variables the easiest way is to (temporarily) assign them to _ :

// No errors
tasty := "ice cream"
horrible := "marmite"

// Commented out for debugging
//eat(tasty, horrible)

_, _ = tasty, horrible

How to remove specific elements in a numpy array

In case you don't have the indices of the elements you want to remove, you can use the function in1d provided by numpy.

The function returns True if the element of a 1-D array is also present in a second array. To delete the elements, you just have to negate the values returned by this function.

Notice that this method keeps the order from the original array.

In [1]: import numpy as np

        a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
        rm = np.array([3, 4, 7])
        # np.in1d return true if the element of `a` is in `rm`
        idx = np.in1d(a, rm)
        idx

Out[1]: array([False, False,  True,  True, False, False,  True, False, False])

In [2]: # Since we want the opposite of what `in1d` gives us, 
        # you just have to negate the returned value
        a[~idx]

Out[2]: array([1, 2, 5, 6, 8, 9])

How to ping ubuntu guest on VirtualBox

If you start tinkering with VirtualBox network settings, watch out for this: you might make new network adapters (eth1, eth2), yet have your /etc/network/interfaces still configured for eth0.

Diagnose:

ethtool -i eth0
Cannot get driver information: no such device

Find your interfaces:

ls /sys/class/net
eth1 eth2 lo

Fix it:

Edit /etc/networking/interfaces and replace eth0 with the appropriate interface name (e.g eth1, eth2, etc.)

:%s/eth0/eth2/g

NuGet auto package restore does not work with MSBuild

MSBuild 15 has a /t:restore option that does this. it comes with Visual Studio 2017.

If you want to use this, you also have to use the new PackageReference, which means replacing the packages.config file with elements like this (do this in *.csproj):

<ItemGroup>
  <!-- ... -->
  <PackageReference Include="Contoso.Utility.UsefulStuff" Version="3.6.0" />
  <!-- ... -->
</ItemGroup>

There is an automated migration to this format if you right click on 'References' (it might not show up if you just opened visual studio, rebuild or open up the 'Manage NuGet packages for solution' window and it will start appearing).

How to determine if a string is a number with C++?

I've found the following code to be the most robust (c++11). It catches both integers and floats.

#include <regex>
bool isNumber( std::string token )
{
    return std::regex_match( token, std::regex( ( "((\\+|-)?[[:digit:]]+)(\\.(([[:digit:]]+)?))?" ) ) );
}

How to find MySQL process list and to kill those processes?

Here is the solution:

  1. Login to DB;
  2. Run a command show full processlist;to get the process id with status and query itself which causes the database hanging;
  3. Select the process id and run a command KILL <pid>; to kill that process.

Sometimes it is not enough to kill each process manually. So, for that we've to go with some trick:

  1. Login to MySQL;
  2. Run a query Select concat('KILL ',id,';') from information_schema.processlist where user='user'; to print all processes with KILL command;
  3. Copy the query result, paste and remove a pipe | sign, copy and paste all again into the query console. HIT ENTER. BooM it's done.

How to alert using jQuery

For each works with JQuery as in

$(<selector>).each(function() {
   //this points to item
   alert('<msg>');
});

JQuery also, for a popup, has in the UI library a dialog widget: http://jqueryui.com/demos/dialog/

Check it out, works really well.

HTH.

How do I make a text input non-editable?

<input type="text" value="3" class="field left" readonly>

No styling necessary.

See <input> on MDN https://developer.mozilla.org/en/docs/Web/HTML/Element/input#Attributes

How do I format date in jQuery datetimepicker?

you can use :

$('#timePicker').datetimepicker({
        format:'d.m.Y H:i',
        minDate: ge_today_date(new Date())
});

 function ge_today_date(date) {
     var day = date.getDate();
     var month = date.getMonth() + 1;
     var year = date.getFullYear().toString().slice(2);
     return day + '-' + month + '-' + year;
 }

What is the difference between Normalize.css and Reset CSS?

I work on normalize.css.

The main differences are:

  1. Normalize.css preserves useful defaults rather than "unstyling" everything. For example, elements like sup or sub "just work" after including normalize.css (and are actually made more robust) whereas they are visually indistinguishable from normal text after including reset.css. So, normalize.css does not impose a visual starting point (homogeny) upon you. This may not be to everyone's taste. The best thing to do is experiment with both and see which gels with your preferences.

  2. Normalize.css corrects some common bugs that are out of scope for reset.css. It has a wider scope than reset.css, and also provides bug fixes for common problems like: display settings for HTML5 elements, the lack of font inheritance by form elements, correcting font-size rendering for pre, SVG overflow in IE9, and the button styling bug in iOS.

  3. Normalize.css doesn't clutter your dev tools. A common irritation when using reset.css is the large inheritance chain that is displayed in browser CSS debugging tools. This is not such an issue with normalize.css because of the targeted stylings.

  4. Normalize.css is more modular. The project is broken down into relatively independent sections, making it easy for you to potentially remove sections (like the form normalizations) if you know they will never be needed by your website.

  5. Normalize.css has better documentation. The normalize.css code is documented inline as well as more comprehensively in the GitHub Wiki. This means you can find out what each line of code is doing, why it was included, what the differences are between browsers, and more easily run your own tests. The project aims to help educate people on how browsers render elements by default, and make it easier for them to be involved in submitting improvements.

I've written in greater detail about this in an article about normalize.css

How to do "If Clicked Else .."

A click is an event; you can't query an element and ask it whether it's being clicked on or not. How about this:

jQuery('#id').click(function () {
   // do some stuff
});

Then if you really wanted to, you could just have a loop that executes every few seconds with your // run function..

How to get a substring of text?

if you need it in rails you can use first (source code)

'1234567890'.first(5) # => "12345"

there is also last (source code)

'1234567890'.last(2) # => "90"

alternatively check from/to (source code):

"hello".from(1).to(-2) # => "ell"

Powershell equivalent of bash ampersand (&) for forking/running background processes

From PowerShell Core 6.0 you are able to write & at end of command and it will be equivalent to running you pipeline in background in current working directory.

It's not equivalent to & in bash, it's just a nicer syntax for current PowerShell jobs feature. It returns a job object so you can use all other command that you would use for jobs. For example Receive-Job:

C:\utils> ping google.com &

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
35     Job35           BackgroundJob   Running       True            localhost            Microsoft.PowerShell.M...


C:\utils> Receive-Job 35

Pinging google.com [172.217.16.14] with 32 bytes of data:
Reply from 172.217.16.14: bytes=32 time=11ms TTL=55
Reply from 172.217.16.14: bytes=32 time=11ms TTL=55
Reply from 172.217.16.14: bytes=32 time=10ms TTL=55
Reply from 172.217.16.14: bytes=32 time=10ms TTL=55

Ping statistics for 172.217.16.14:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 10ms, Maximum = 11ms, Average = 10ms
C:\utils>

If you want to execute couple of statements in background you can combine & call operator, { } script block and this new & background operator like here:

& { cd .\SomeDir\; .\SomeLongRunningOperation.bat; cd ..; } &

Here's some more info from documentation pages:

from What's New in PowerShell Core 6.0:

Support backgrounding of pipelines with ampersand (&) (#3360)

Putting & at the end of a pipeline causes the pipeline to be run as a PowerShell job. When a pipeline is backgrounded, a job object is returned. Once the pipeline is running as a job, all of the standard *-Job cmdlets can be used to manage the job. Variables (ignoring process-specific variables) used in the pipeline are automatically copied to the job so Copy-Item $foo $bar & just works. The job is also run in the current directory instead of the user's home directory. For more information about PowerShell jobs, see about_Jobs.

from about_operators / Ampersand background operator &:

Ampersand background operator &

Runs the pipeline before it in a PowerShell job. The ampersand background operator acts similarly to the UNIX "ampersand operator" which famously runs the command before it as a background process. The ampersand background operator is built on top of PowerShell jobs so it shares a lot of functionality with Start-Job. The following command contains basic usage of the ampersand background operator.

Get-Process -Name pwsh &

This is functionally equivalent to the following usage of Start-Job.

Start-Job -ScriptBlock {Get-Process -Name pwsh}

Since it's functionally equivalent to using Start-Job, the ampersand background operator returns a Job object just like Start-Job does. This means that you are able to use Receive-Job and Remove-Job just as you would if you had used Start-Job to start the job.

$job = Get-Process -Name pwsh &
Receive-Job $job

Output

NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName
------    -----      -----     ------      --  -- -----------
    0     0.00     221.16      25.90    6988 988 pwsh
    0     0.00     140.12      29.87   14845 845 pwsh
    0     0.00      85.51       0.91   19639 988 pwsh


$job = Get-Process -Name pwsh &
Remove-Job $job

For more information on PowerShell jobs, see about_Jobs.

Fluid or fixed grid system, in responsive design, based on Twitter Bootstrap

Fluid layout in Bootstrap 3.

Unlike Boostrap 2, Bootstrap 3 doesn't have a .container-fluid mixin to make a fluid container. The .container is a fixed width responsive grid layout. In a large screen, there are excessive white spaces in both sides of one's Web page content.

container-fluid is added back in Bootstrap 3.1

A fluid grid layout uses all screen width and works better in large screen. It turns out that it is easy to create a fluid grid layout using Bootstrap 3 mixins. The following line makes a fluid responsive grid layout:

.container-fixed;

The .container-fixed mixin sets the content to the center of the screen and add paddings. It doesn't specifies a fixed page width.

Another approach is to use Eric Flowers' CSS style

.my-fluid-container {
    padding-left: 15px;
    padding-right: 15px;
    margin-left: auto;
    margin-right: auto;
}

Remove duplicate rows in MySQL

I keep visiting this page anytime I google "remove duplicates form mysql" but for my theIGNORE solutions don't work because I have an InnoDB mysql tables

this code works better anytime

CREATE TABLE tableToclean_temp LIKE tableToclean;
ALTER TABLE tableToclean_temp ADD UNIQUE INDEX (fontsinuse_id);
INSERT IGNORE INTO tableToclean_temp SELECT * FROM tableToclean;
DROP TABLE tableToclean;
RENAME TABLE tableToclean_temp TO tableToclean;

tableToclean = the name of the table you need to clean

tableToclean_temp = a temporary table created and deleted

PHP Change Array Keys

The solution to when you're using XMLWriter (native to PHP 5.2.x<) is using $xml->startElement('itemName'); this will replace the arrays key.

Remove substring from the string

How about str.gsub("subString", "") Check out the Ruby Doc

JSON array get length

The JSONArray.length() returns the number of elements in the JSONObject contained in the Array. Not the size of the array itself.

Resizing image in Java

            int newHeight = 150;
            int newWidth = 150; 
            holder.iv_arrow.requestLayout();
            holder.iv_arrow.getLayoutParams().height = newHeight;
            holder.iv_arrow.getLayoutParams().width = newWidth;
            holder.iv_arrow.setScaleType(ImageView.ScaleType.FIT_XY);
            holder.iv_arrow.setImageResource(R.drawable.video_menu);

Is Secure.ANDROID_ID unique for each device?

//Fields
String myID;
int myversion = 0;


myversion = Integer.valueOf(android.os.Build.VERSION.SDK);
if (myversion < 23) {
        TelephonyManager mngr = (TelephonyManager) 
getSystemService(Context.TELEPHONY_SERVICE);
        myID= mngr.getDeviceId();
    }
    else
    {
        myID = 
Settings.Secure.getString(getApplicationContext().getContentResolver(), 
Settings.Secure.ANDROID_ID);
    }

Yes, Secure.ANDROID_ID is unique for each device.

How do I change the background color of a plot made with ggplot2

Here's a custom theme to make the ggplot2 background white and a bunch of other changes that's good for publications and posters. Just tack on +mytheme. If you want to add or change options by +theme after +mytheme, it will just replace those options from +mytheme.

library(ggplot2)
library(cowplot)
theme_set(theme_cowplot())

mytheme = list(
    theme_classic()+
        theme(panel.background = element_blank(),strip.background = element_rect(colour=NA, fill=NA),panel.border = element_rect(fill = NA, color = "black"),
              legend.title = element_blank(),legend.position="bottom", strip.text = element_text(face="bold", size=9),
              axis.text=element_text(face="bold"),axis.title = element_text(face="bold"),plot.title = element_text(face = "bold", hjust = 0.5,size=13))
)

ggplot(data=data.frame(a=c(1,2,3), b=c(2,3,4)), aes(x=a, y=b)) + mytheme + geom_line()

custom ggplot theme

MySQL error 2006: mysql server has gone away

Just in case this helps anyone:

I got this error when I opened and closed connections in a function which would be called from several parts of the application. We got too many connections so we thought it might be a good idea to reuse the existing connection or throw it away and make a new one like so:

  public static function getConnection($database, $host, $user, $password)
 {
 if (!self::$instance) {
  return self::newConnection($database, $host, $user, $password);
 } elseif ($database . $host . $user != self::$connectionDetails) {

self::$instance->query('KILL CONNECTION_ID()'); self::$instance = null; return self::newConnection($database, $host, $user, $password); } return self::$instance; } Well turns out we've been a little too thorough with the killing and so the processes doing important things on the old connection could never finish their business. So we dropped these lines

  self::$instance->query('KILL CONNECTION_ID()');
  self::$instance = null;

and as the hardware and setup of the machine allows it we increased the number of allowed connections on the server by adding

max_connections = 500

to our configuration file. This fixed our problem for now and we learned something about killing mysql connections.

Java 8: How do I work with exception throwing methods in streams?

This question may be a little old, but because I think the "right" answer here is only one way which can lead to some issues hidden Issues later in your code. Even if there is a little Controversy, Checked Exceptions exist for a reason.

The most elegant way in my opinion can you find was given by Misha here Aggregate runtime exceptions in Java 8 streams by just performing the actions in "futures". So you can run all the working parts and collect not working Exceptions as a single one. Otherwise you could collect them all in a List and process them later.

A similar approach comes from Benji Weber. He suggests to create an own type to collect working and not working parts.

Depending on what you really want to achieve a simple mapping between the input values and Output Values occurred Exceptions may also work for you.

If you don't like any of these ways consider using (depending on the Original Exception) at least an own exception.

Initialize 2D array

You can follow what paxdiablo(on Dec '12) suggested for an automated, more versatile approach:

for (int row = 0; row < 3; row ++)
for (int col = 0; col < 3; col++)
    table[row][col] = (char) ('1' + row * 3 + col);

In terms of efficiency, it depends on the scale of your implementation. If it is to simply initialize a 2D array to values 0-9, it would be much easier to just define, declare and initialize within the same statement like this: private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};

Or if you're planning to expand the algorithm, the previous code would prove more, efficient.

View the change history of a file using Git versioning

For a graphical view I'd use gitk:

gitk [filename]

or to follow filename past renames

gitk --follow [filename]

Deprecated Java HttpClient - How hard can it be?

Examples from Apache use this:

CloseableHttpClient httpclient = HttpClients.createDefault();

The class org.apache.http.impl.client.HttpClients is there since version 4.3.

The code for HttpClients.createDefault() is the same as the accepted answer in here.

UNC path to a folder on my local computer

On Windows, you can also use the Win32 File Namespace prefixed with \\?\ to refer to your local directories:

\\?\C:\my_dir

See this answer for description.

Convert pyQt UI to python

I'm not sure if PyQt does have a script like this, but after you install PySide there is a script in pythons script directory "uic.py". You can use this script to convert a .ui file to a .py file:

python uic.py input.ui -o output.py -x

Laravel Redirect Back with() Message

Try

return Redirect::back()->withErrors(['msg', 'The Message']);

and inside your view call this

@if($errors->any())
<h4>{{$errors->first()}}</h4>
@endif