Programs & Examples On #Event based components

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

Opening new window in HTML for target="_blank"

You can't influence neither type (tab/window) nor dimensions that way. You'll have to use JavaScript's window.open() for that.

How to perform element-wise multiplication of two lists?

Use a list comprehension mixed with zip():.

[a*b for a,b in zip(lista,listb)]

Flask - Calling python function on button OnClick event

It sounds like you want to use this web application as a remote control for your robot, and a core issue is that you won't want a page reload every time you perform an action, in which case, the last link you posted answers your problem.

I think you may be misunderstanding a few things about Flask. For one, you can't nest multiple functions in a single route. You're not making a set of functions available for a particular route, you're defining the one specific thing the server will do when that route is called.

With that in mind, you would be able to solve your problem with a page reload by changing your app.py to look more like this:

from flask import Flask, render_template, Response, request, redirect, url_for
app = Flask(__name__)

@app.route("/")
def index():
    return render_template('index.html')

@app.route("/forward/", methods=['POST'])
def move_forward():
    #Moving forward code
    forward_message = "Moving Forward..."
    return render_template('index.html', forward_message=forward_message);

Then in your html, use this:

<form action="/forward/" method="post">
    <button name="forwardBtn" type="submit">Forward</button>
</form>

...To execute your moving forward code. And include this:

{{ forward_message }} 

... where you want the moving forward message to appear on your template.

This will cause your page to reload, which is inevitable without using AJAX and Javascript.

How to query MongoDB with "like"?

In PHP, you could use following code:

$collection->find(array('name'=> array('$regex' => 'm'));

How to add months to a date in JavaScript?

Split your date into year, month, and day components then use Date:

var d = new Date(year, month, day);
d.setMonth(d.getMonth() + 8);

Date will take care of fixing the year.

How do I make an HTML button not reload the page

In HTML:

<form onsubmit="return false">
</form>

in order to avoid refresh at all "buttons", even with onclick assigned.

Fragments within Fragments

I have an application that I am developing that is laid out similar with Tabs in the Action Bar that launches fragments, some of these Fragments have multiple embedded Fragments within them.

I was getting the same error when I tried to run the application. It seems like if you instantiate the Fragments within the xml layout after a tab was unselected and then reselected I would get the inflator error.

I solved this replacing all the fragments in xml with Linearlayouts and then useing a Fragment manager/ fragment transaction to instantiate the fragments everything seems to working correctly at least on a test level right now.

I hope this helps you out.

How to generate a random alpha-numeric string

  1. Change String characters as per as your requirements.

  2. String is immutable. Here StringBuilder.append is more efficient than string concatenation.


public static String getRandomString(int length) {
    final String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+";
    StringBuilder result = new StringBuilder();

    while(length > 0) {
        Random rand = new Random();
        result.append(characters.charAt(rand.nextInt(characters.length())));
        length--;
    }
    return result.toString();
}

Create a new file in git bash

If you are using the Git Bash shell, you can use the following trick:

> webpage.html

This is actually the same as:

echo "" > webpage.html

Then, you can use git add webpage.html to stage the file.

mysql server port number

port number 3306 is used for MySQL and tomcat using 8080 port.more port numbers are available for run the servers or software whatever may be for our instant compilation..8080 is default for number so only we are getting port error in eclipse IDE. jvm and tomcat always prefer the 8080.3306 is default port number for MySQL.So only do not want to mention every time as "localhost:3306"

  <?php  
    $dbhost = 'localhost:3306';
//3306 default port number $dbhost='localhost'; is enough to specify the port number
//when we are utilizing xammp default port number is 8080.
      $dbuser = 'root';
      $dbpass = '';
         $db='users';

             $conn = mysqli_connect($dbhost, $dbuser, $dbpass,$db) or die ("could not connect to mysql");      

              // mysqli_select_db("users") or die ("no database");  

    if(! $conn ) {
        die('Could not connect: ' . mysqli_error($conn));
    }else{
        echo 'Connected successfully';
    }
    ?>

PHP check if date between two dates

Another solution would have been to consider date written as Ymd.

Written in this "format" this is much easy to compare dates.

$paymentDate       = date('Ymd'); // on 4th may 2016, would have been 20160504
$contractBegin     = 20010101;
$contractEnd       = 20160101;
echo ($paymentDate >= $contractBegin && $paymentDate <= $contractEnd) ? "Between" : "Not Between";

It will always work for every day of the year and do not depends on any function or conversion (PHP will consider the int value of $paymentDate to compare with the int value of contractBegin and contractEnd).

How do I put a border around an Android textview?

I have solved this issue by extending the textview and drawing a border manually. I even added so you can select if a border is dotted or dashed.

public class BorderedTextView extends TextView {
        private Paint paint = new Paint();
        public static final int BORDER_TOP = 0x00000001;
        public static final int BORDER_RIGHT = 0x00000002;
        public static final int BORDER_BOTTOM = 0x00000004;
        public static final int BORDER_LEFT = 0x00000008;

        private Border[] borders;

        public BorderedTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init();
        }

        public BorderedTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }

        public BorderedTextView(Context context) {
            super(context);
            init();
        }
        private void init(){
            paint.setStyle(Paint.Style.STROKE);
            paint.setColor(Color.BLACK);
            paint.setStrokeWidth(4);        
        }
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            if(borders == null) return;

            for(Border border : borders){
                paint.setColor(border.getColor());
                paint.setStrokeWidth(border.getWidth());

                if(border.getStyle() == BORDER_TOP){
                    canvas.drawLine(0, 0, getWidth(), 0, paint);                
                } else
                if(border.getStyle() == BORDER_RIGHT){
                    canvas.drawLine(getWidth(), 0, getWidth(), getHeight(), paint);
                } else
                if(border.getStyle() == BORDER_BOTTOM){
                    canvas.drawLine(0, getHeight(), getWidth(), getHeight(), paint);
                } else
                if(border.getStyle() == BORDER_LEFT){
                    canvas.drawLine(0, 0, 0, getHeight(), paint);
                }
            }
        }

        public Border[] getBorders() {
            return borders;
        }

        public void setBorders(Border[] borders) {
            this.borders = borders;
        }
}

And the border class:

public class Border {
    private int orientation;
    private int width;
    private int color = Color.BLACK;
    private int style;
    public int getWidth() {
        return width;
    }
    public void setWidth(int width) {
        this.width = width;
    }
    public int getColor() {
        return color;
    }
    public void setColor(int color) {
        this.color = color;
    }
    public int getStyle() {
        return style;
    }
    public void setStyle(int style) {
        this.style = style;
    }
    public int getOrientation() {
        return orientation;
    }
    public void setOrientation(int orientation) {
        this.orientation = orientation;
    }
    public Border(int Style) {
        this.style = Style;
    }
}

Hope this helps someone :)

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

A suggestion - when using cross join please take care of the duplicate scenarios. For example in your case:

  • Table 1 may have >1 columns as part of primary keys(say table1_id, id2, id3, table2_id)
  • Table 2 may have >1 columns as part of primary keys(say table2_id, id3, id4)

since there are common keys between these two tables (i.e. foreign keys in one/other) - we will end up with duplicate results. hence using the following form is good:

WITH data_mined_table (col1, col2, col3, etc....) AS
SELECT DISTINCT col1, col2, col3, blabla
FROM table_1 (NOLOCK), table_2(NOLOCK))
SELECT * from data_mined WHERE data_mined_table.col1 = :my_param_value

How to push a new folder (containing other folders and files) to an existing git repo?

You can directly go to Web IDE and upload your folder there.

Steps:

  1. Go to Web IDE(Mostly located below the clone option).
  2. Create new directory at your path
  3. Upload your files and folders

In some cases you may not be able to directly upload entire folder containing folders, In such cases, you will have to create directory structure yourself.

List comprehension with if statement

If you use sufficiently big list not in b clause will do a linear search for each of the item in a. Why not use set? Set takes iterable as parameter to create a new set object.

>>> a = ["a", "b", "c", "d", "e"]
>>> b = ["c", "d", "f", "g"]
>>> set(a).intersection(set(b))
{'c', 'd'}

How to align an image dead center with bootstrap

Twitter bootstrap has a class that centers: .pagination-centered

It worked for me to do:

<div class="row-fluid">
   <div class="span12 pagination-centered"><img src="header.png" alt="header" /></div>
</div>

The css for the class is:

.pagination-centered {
  text-align: center;
}

How to index into a dictionary?

Addressing an element of dictionary is like sitting on donkey and enjoy the ride.

As a rule of Python, a DICTIONARY is orderless

If there is

dic = {1: "a", 2: "aa", 3: "aaa"}

Now suppose if I go like dic[10] = "b", then it will not add like this always

dic = {1:"a",2:"aa",3:"aaa",10:"b"}

It may be like

dic = {1: "a", 2: "aa", 3: "aaa", 10: "b"}

Or

dic = {1: "a", 2: "aa", 10: "b", 3: "aaa"}

Or

dic = {1: "a", 10: "b", 2: "aa", 3: "aaa"}

Or any such combination.

So a rule of thumb is that a DICTIONARY is orderless!

Best Practice for Forcing Garbage Collection in C#

Suppose your program doesn't have memory leakage, objects accumulates and cannot be GC-ed in Gen 0 because: 1) They are referenced for long time so get into Gen1 & Gen2; 2) They are large objects (>80K) so get into LOH (Large Object Heap). And LOH doesn't do compacting as in Gen0, Gen1 & Gen2.

Check the performance counter of ".NET Memory" can you can see that the 1) problem is really not a problem. Generally, every 10 Gen0 GC will trigger 1 Gen1 GC, and every 10 Gen1 GC will trigger 1 Gen2 GC. Theoretically, GC1 & GC2 can never be GC-ed if there is no pressure on GC0 (if the program memory usage is really wired). It never happens to me.

For problem 2), you can check ".NET Memory" performance counter to verify whether LOH is getting bloated. If it is really a issue to your problem, perhaps you can create a large-object-pool as this blog suggests http://blogs.msdn.com/yunjin/archive/2004/01/27/63642.aspx.

take(1) vs first()

Operators first() and take(1) aren't the same.

The first() operator takes an optional predicate function and emits an error notification when no value matched when the source completed.

For example this will emit an error:

import { EMPTY, range } from 'rxjs';
import { first, take } from 'rxjs/operators';

EMPTY.pipe(
  first(),
).subscribe(console.log, err => console.log('Error', err));

... as well as this:

range(1, 5).pipe(
  first(val => val > 6),
).subscribe(console.log, err => console.log('Error', err));

While this will match the first value emitted:

range(1, 5).pipe(
  first(),
).subscribe(console.log, err => console.log('Error', err));

On the other hand take(1) just takes the first value and completes. No further logic is involved.

range(1, 5).pipe(
  take(1),
).subscribe(console.log, err => console.log('Error', err));

Then with empty source Observable it won't emit any error:

EMPTY.pipe(
  take(1),
).subscribe(console.log, err => console.log('Error', err));

Jan 2019: Updated for RxJS 6

What is the difference between a framework and a library?

You call Library.

Framework calls you.


??? ??
?????
????

How to install ia32-libs in Ubuntu 14.04 LTS (Trusty Tahr)

For me, I have to run

sudo dpkg --add-architecture i386

before running Mike Tang's answer. Otherwise, I can't install ia32-libs.

Converting Swagger specification JSON to HTML documentation

See the swagger-api/swagger-codegen project on GitHub ; the project README shows how to use it to generate static HTML. See Generating static html api documentation.

If you want to view the swagger.json you can install the Swagger UI and run it. You just deploy it on a web server (the dist folder after you clone the repo from GitHub) and view the Swagger UI in your browser. It's a JavaScript app.

How do CSS triangles work?

And now something completely different...

Instead of using css tricks don't forget about solutions as simple as html entities:

&#9650;

Result:

See: What are the HTML entities for up and down triangles?

How does += (plus equal) work?

+= operator is used to concatenate strings or add numbers.

It will increment your sum variable with the amount next to it.

var sum = 0;
var valueAdded = 5; 

sum += valueAdded;

sum = 5

Can't bind to 'ngModel' since it isn't a known property of 'input'

_x000D_
_x000D_
import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [

    FormsModule
  ],

})
_x000D_
_x000D_
_x000D_

Hibernate Error executing DDL via JDBC Statement

I got this same error when i was trying to make a table with name "admin". Then I used @Table annotation and gave table a different name like @Table(name = "admins"). I think some words are reserved (like :- keywords in java) and you can not use them.

@Entity
@Table(name = "admins")
public class Admin extends TrackedEntity {

}

Get selected option from select element

Try following code

$('#ddlCodes').change(function() {
  $('#txtEntry2').val(  $('#ddlCodes :selected').text() );
});

C++, how to declare a struct in a header file

You've only got a forward declaration for student in the header file; you need to place the struct declaration in the header file, not the .cpp. The method definitions will be in the .cpp (assuming you have any).

Making a cURL call in C#

Don't forget to add System.Net.Http, specially if you receive this error:

Severity Code Description Project File Line Suppression State Error CS0246 The type or namespace name 'HttpClient' could not be found (are you missing a using directive or an assembly reference?) 1_default.aspx D:\Projetos\Testes\FacebookAPI\FB-CustomAudience\default.aspx.cs 56 Active

In this case you shoud:

  1. Add System.Net.Http from Nuget: Tools / NuGet Package Manager / Manager NuGet Packages for Solution;
  2. Search for System.Net.Http
  3. Add in the top of your page the follow code: using System.Net.Http;

JavaScript and getElementById for multiple elements with the same ID

The id is supposed to be unique, use the attribute "name" and "getelementsbyname" instead, and you'll have your array.

Adding header to all request with Retrofit 2

For Logging your request and response you need an interceptor and also for setting the header you need an interceptor, Here's the solution for adding both the interceptor at once using retrofit 2.1

 public OkHttpClient getHeader(final String authorizationValue ) {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okClient = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .addNetworkInterceptor(
                        new Interceptor() {
                            @Override
                            public Response intercept(Interceptor.Chain chain) throws IOException {
                                Request request = null;
                                if (authorizationValue != null) {
                                    Log.d("--Authorization-- ", authorizationValue);

                                    Request original = chain.request();
                                    // Request customization: add request headers
                                    Request.Builder requestBuilder = original.newBuilder()
                                            .addHeader("Authorization", authorizationValue);

                                    request = requestBuilder.build();
                                }
                                return chain.proceed(request);
                            }
                        })
                .build();
        return okClient;

    }

Now in your retrofit object add this header in the client

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(getHeader(authorizationValue))
                .addConverterFactory(GsonConverterFactory.create())
                .build();

Invalid Host Header when ngrok tries to connect to React dev server

I'm encountering a similar issue and found two solutions that work as far as viewing the application directly in a browser

ngrok http 8080 -host-header="localhost:8080"
ngrok http --host-header=rewrite 8080

obviously replace 8080 with whatever port you're running on

this solution still raises an error when I use this in an embedded page, that pulls the bundle.js from the react app. I think since it rewrites the header to localhost, when this is embedded, it's looking to localhost, which the app is no longer running on

how to parse JSONArray in android

If you're after the 'name', why does your code snippet look like an attempt to get the 'characters'?

Anyways, this is no different from any other list- or array-like operation: you just need to iterate over the dataset and grab the information you're interested in. Retrieving all the names should look somewhat like this:

List<String> allNames = new ArrayList<String>();

JSONArray cast = jsonResponse.getJSONArray("abridged_cast");
for (int i=0; i<cast.length(); i++) {
    JSONObject actor = cast.getJSONObject(i);
    String name = actor.getString("name");
    allNames.add(name);
}

(typed straight into the browser, so not tested).

Why should I use IHttpActionResult instead of HttpResponseMessage?

You might decide not to use IHttpActionResult because your existing code builds a HttpResponseMessage that doesn't fit one of the canned responses. You can however adapt HttpResponseMessage to IHttpActionResult using the canned response of ResponseMessage. It took me a while to figure this out, so I wanted to post it showing that you don't necesarily have to choose one or the other:

public IHttpActionResult SomeAction()
{
   IHttpActionResult response;
   //we want a 303 with the ability to set location
   HttpResponseMessage responseMsg = new HttpResponseMessage(HttpStatusCode.RedirectMethod);
   responseMsg.Headers.Location = new Uri("http://customLocation.blah");
   response = ResponseMessage(responseMsg);
   return response;
}

Note, ResponseMessage is a method of the base class ApiController that your controller should inherit from.

Can I use multiple versions of jQuery on the same page?

You can have as many different jQuery versions on your page as you want.

Use jQuery.noConflict():

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script>
    var $i = jQuery.noConflict();
    alert($i.fn.jquery);
</script> 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
    var $j = jQuery.noConflict();
    alert($j.fn.jquery);
</script> 

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
    var $k = jQuery.noConflict();
    alert($k.fn.jquery);
</script> 

DEMO | Source

Catching errors in Angular HttpClient

Let me please update the acdcjunior's answer about using HttpInterceptor with the latest RxJs features(v.6).

import { Injectable } from '@angular/core';
import {
  HttpInterceptor,
  HttpRequest,
  HttpErrorResponse,
  HttpHandler,
  HttpEvent,
  HttpResponse
} from '@angular/common/http';

import { Observable, EMPTY, throwError, of } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error.error instanceof Error) {
          // A client-side or network error occurred. Handle it accordingly.
          console.error('An error occurred:', error.error.message);
        } else {
          // The backend returned an unsuccessful response code.
          // The response body may contain clues as to what went wrong,
          console.error(`Backend returned code ${error.status}, body was: ${error.error}`);
        }

        // If you want to return a new response:
        //return of(new HttpResponse({body: [{name: "Default value..."}]}));

        // If you want to return the error on the upper level:
        //return throwError(error);

        // or just return nothing:
        return EMPTY;
      })
    );
  }
}

Image height and width not working?

You have a class on your CSS that is overwriting your width and height, the class reads as such:

.postItem img {
    height: auto;
    width: 450px;
}

Remove that and your width/height properties on the img tag should work.

"The file "MyApp.app" couldn't be opened because you don't have permission to view it" when running app in Xcode 6 Beta 4

I had the issue that the AppDelegate was missing.

Creating a minimal one solved the issue:

import UIKit

@UIApplicationMain
final class AppDelegate: UIResponder,UIApplicationDelegate {
}

How to remove newlines from beginning and end of a string?

Use String.trim() method to get rid of whitespaces (spaces, new lines etc.) from the beginning and end of the string.

String trimmedString = myString.trim();

C# get and set properties for a List Collection

If I understand your request correctly, you have to do the following:

public class Section 
{ 
    public String Head
    {
        get
        {
            return SubHead.LastOrDefault();
        }
        set
        {
            SubHead.Add(value);
        }

    public List<string> SubHead { get; private set; }
    public List<string> Content { get; private set; }
} 

You use it like this:

var section = new Section();
section.Head = "Test string";

Now "Test string" is added to the subHeads collection and will be available through the getter:

var last = section.Head; // last will be "Test string"

Hope I understood you correctly.

Get access to parent control from user control - C#

If you want to get any parent by any child control you can use this code, and when you find the UserControl/Form/Panel or others you can call funnctions or set/get values:

Control myControl= this;
while (myControl.Parent != null)
{

    if (myControl.Parent!=null)
    {
        myControl = myControl.Parent;
        if  (myControl.Name== "MyCustomUserControl")
        {
            ((MyCustomUserControl)myControl).lblTitle.Text = "FOUND IT";
        }
    }

}

How to check cordova android version of a cordova/phonegap project?

Run

cordova -v 

to see the currently running version. Run the npm info command

npm info cordova

for a longer listing that includes the current version along with other available version numbers

Latest jQuery version on Google's CDN

If you wish to use jQuery CDN other than Google hosted jQuery library, you might consider using this and ensures uses the latest version of jQuery:

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

Is there a way to take the first 1000 rows of a Spark Dataframe?

Limit is very simple, example limit first 50 rows

val df_subset = data.limit(50)

pros and cons between os.path.exists vs os.path.isdir

os.path.isdir() checks if the path exists and is a directory and returns TRUE for the case.

Similarly, os.path.isfile() checks if the path exists and is a file and returns TRUE for the case.

And, os.path.exists() checks if the path exists and doesn’t care if the path points to a file or a directory and returns TRUE in either of the cases.

Issue with background color and Google Chrome

After trying all of the other solutions here without success, I skeptically tried the solution found in this article, and got it to work.

Essentially, it boils down to removing @charset "utf-8"; from your CSS.

This seems like a poor implementation in DreamWeaver - but it did fix the issue for me, regardless.

ERROR! MySQL manager or server PID file could not be found! QNAP

screenshot

If you're using MySQL Workbench, the mysql.server stop/restart/start will not work.

You will need to login into the workbench and then click "shutdown server". See image attached.

What is the difference between a .cpp file and a .h file?

I know the difference between a declaration and a definition.

Whereas:

  • A CPP file includes the definitions from any header which it includes (because CPP and header file together become a single 'translation unit')
  • A header file might be included by more than one CPP file
  • The linker typically won't like anything defined in more than one CPP file

Therefore any definitions in a header file should be inline or static. Header files also contain declarations which are used by more than one CPP file.

Definitions that are neither static nor inline are placed in CPP files. Also, any declarations that are only needed within one CPP file are often placed within that CPP file itself, nstead of in any (sharable) header file.

'typeid' versus 'typeof' in C++

The primary difference between the two is the following

  • typeof is a compile time construct and returns the type as defined at compile time
  • typeid is a runtime construct and hence gives information about the runtime type of the value.

typeof Reference: http://www.delorie.com/gnu/docs/gcc/gcc_36.html

typeid Reference: https://en.wikipedia.org/wiki/Typeid

Tab Escape Character?

For someone who needs quick reference of C# Escape Sequences that can be used in string literals:

\t     Horizontal tab (ASCII code value: 9)

\n     Line feed (ASCII code value: 10)

\r     Carriage return (ASCII code value: 13)

\'     Single quotation mark

\"     Double quotation mark

\\     Backslash

\?     Literal question mark

\x12     ASCII character in hexadecimal notation (e.g. for 0x12)

\x1234     Unicode character in hexadecimal notation (e.g. for 0x1234)

It's worth mentioning that these (in most cases) are universal codes. So \t is 9 and \n is 10 char value on Windows and Linux. But newline sequence is not universal. On Windows it's \n\r and on Linux it's just \n. That's why it's best to use Environment.Newline which gets adjusted to current OS settings. With .Net Core it gets really important.

MATLAB error: Undefined function or method X for input arguments of type 'double'

You get this error when the function isn't on the MATLAB path or in pwd.

First, make sure that you are able to find the function using:

>> which divrat
c:\work\divrat\divrat.m

If it returns:

>> which divrat
'divrat' not found.

It is not on the MATLAB path or in PWD.

Second, make sure that the directory that contains divrat is on the MATLAB path using the PATH command. It may be that a directory that you thought was on the path isn't actually on the path.

Finally, make sure you aren't using a "private" directory. If divrat is in a directory named private, it will be accessible by functions in the parent directory, but not from the MATLAB command line:

>> foo

ans =

     1

>> divrat(1,1)
??? Undefined function or method 'divrat' for input arguments of type 'double'.

>> which -all divrat
c:\work\divrat\private\divrat.m  % Private to divrat

Why is __init__() always called after __new__()?

When __new__ returns instance of the same class, __init__ is run afterwards on returned object. I.e. you can NOT use __new__ to prevent __init__ from being run. Even if you return previously created object from __new__, it will be double (triple, etc...) initialized by __init__ again and again.

Here is the generic approach to Singleton pattern which extends vartec answer above and fixes it:

def SingletonClass(cls):
    class Single(cls):
        __doc__ = cls.__doc__
        _initialized = False
        _instance = None

        def __new__(cls, *args, **kwargs):
            if not cls._instance:
                cls._instance = super(Single, cls).__new__(cls, *args, **kwargs)
            return cls._instance

        def __init__(self, *args, **kwargs):
            if self._initialized:
                return
            super(Single, self).__init__(*args, **kwargs)
            self.__class__._initialized = True  # Its crucial to set this variable on the class!
    return Single

Full story is here.

Another approach, which in fact involves __new__ is to use classmethods:

class Singleton(object):
    __initialized = False

    def __new__(cls, *args, **kwargs):
        if not cls.__initialized:
            cls.__init__(*args, **kwargs)
            cls.__initialized = True
        return cls


class MyClass(Singleton):
    @classmethod
    def __init__(cls, x, y):
        print "init is here"

    @classmethod
    def do(cls):
        print "doing stuff"

Please pay attention, that with this approach you need to decorate ALL of your methods with @classmethod, because you'll never use any real instance of MyClass.

'innerText' works in IE, but not in Firefox

found this here:

<!--[if lte IE 8]>
    <script type="text/javascript">
        if (Object.defineProperty && Object.getOwnPropertyDescriptor &&
            !Object.getOwnPropertyDescriptor(Element.prototype, "textContent").get)
          (function() {
            var innerText = Object.getOwnPropertyDescriptor(Element.prototype, "innerText");
            Object.defineProperty(Element.prototype, "textContent",
              { // It won't work if you just drop in innerText.get
                // and innerText.set or the whole descriptor.
                get : function() {
                  return innerText.get.call(this)
                },
                set : function(x) {
                  return innerText.set.call(this, x)
                }
              }
            );
          })();
    </script>
<![endif]-->

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

@GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

@GetMapping is the newer annotaion. It supports consumes

Consume options are :

consumes = "text/plain"
consumes = {"text/plain", "application/*"}

For Further details see: GetMapping Annotation

or read: request mapping variants

RequestMapping supports consumes as well

GetMapping we can apply only on method level and RequestMapping annotation we can apply on class level and as well as on method level

How do I use dataReceived event of the SerialPort Port Object in C#?

I think your issue is the line:**

sp.DataReceived += port_OnReceiveDatazz;

Shouldn't it be:

sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);

**Nevermind, the syntax is fine (didn't realize the shortcut at the time I originally answered this question).

I've also seen suggestions that you should turn the following options on for your serial port:

sp.DtrEnable = true;    // Data-terminal-ready
sp.RtsEnable = true;    // Request-to-send

You may also have to set the handshake to RequestToSend (via the handshake enumeration).


UPDATE:

Found a suggestion that says you should open your port first, then assign the event handler. Maybe it's a bug?

So instead of this:

sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);
sp.Open();

Do this:

sp.Open();
sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);

Let me know how that goes.

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

Getting Django admin url for an object

Essentially the same as Mike Ramirez's answer, but simpler and closer in stylistics to django standard get_absolute_url method:

from django.urls import reverse

def get_admin_url(self):
    return reverse('admin:%s_%s_change' % (self._meta.app_label, self._meta.model_name),
                   args=[self.id])

grep using a character vector with multiple patterns

To add to Brian Diggs answer.

another way using grepl will return a data frame containing all your values.

toMatch <- myfile$Letter

matches <- myfile[grepl(paste(toMatch, collapse="|"), myfile$Letter), ]

matches

Letter Firstname
1     A1      Alex 
2     A6      Alex 
4     A1       Bob 
5     A9     Chris 
6     A6     Chris

Maybe a bit cleaner... maybe?

How to position a div scrollbar on the left hand side?

You could try direction:rtl; in your css. Then reset the text direction in the inner div

#scroll{
    direction:rtl; 
    overflow:auto; 
    height:50px; 
    width:50px;}

#scroll div{
    direction:ltr;
}

Untested.

How to make a text box have rounded corners?

You could use CSS to do that, but it wouldn't be supported in IE8-. You can use some site like http://borderradius.com to come up with actual CSS you'd use, which would look something like this (again, depending on how many browsers you're trying to support):

-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;

AngularJS Directive Restrict A vs E

One of the pitfalls as I know is IE problem with custom elements. As quoted from the docs:

3) you do not use custom element tags such as (use the attribute version instead)

4) if you do use custom element tags, then you must take these steps to make IE 8 and below happy

<!doctype html>
  <html xmlns:ng="http://angularjs.org" id="ng-app" ng-app="optionalModuleName">
    <head>
      <!--[if lte IE 8]>
        <script>
          document.createElement('ng-include');
          document.createElement('ng-pluralize');
          document.createElement('ng-view');

          // Optionally these for CSS
          document.createElement('ng:include');
          document.createElement('ng:pluralize');
          document.createElement('ng:view');
        </script>
      <![endif]-->
    </head>
    <body>
      ...
    </body>
  </html>

What is a MIME type?

MIME stands for Multipurpose Internet Mail Extensions. It's a way of identifying files on the Internet according to their nature and format.

For example, using the Content-type header value defined in a HTTP response, the browser can open the file with the proper extension/plugin.

Internet Media Type (also Content-type) is the same as a MIME type. MIME types were originally created for emails sent using the SMTP protocol. Nowadays, this standard is used in a lot of other protocols, hence the new naming convention "Internet Media Type".

A MIME type is a string identifier composed of two parts: a type and a subtype.

  • The "type" refers to a logical grouping of many MIME types that are closely related to each other; it's no more than a high level category.
  • "subtypes" are specific to one file type within the "type".

The x- prefix of a MIME subtype simply means that it's non-standard.
The vnd prefix means that the MIME value is vendor specific.

Source

How to send an HTTPS GET Request in C#

Simple Get Request using HttpClient Class

using System.Net.Http;

class Program
{
   static void Main(string[] args)
    {
        HttpClient httpClient = new HttpClient();
        var result = httpClient.GetAsync("https://www.google.com").Result;
    }

}

PHP - Notice: Undefined index:

How are you loading this page? Is it getting anything on POST to load? If it's not, then the $name = $_POST['Name']; assignation doesn't have any 'Name' on POST.

how to convert date to a format `mm/dd/yyyy`

As your data already in varchar, you have to convert it into date first:

select convert(varchar(10), cast(ts as date), 101) from <your table>

HTML5 LocalStorage: Checking if a key exists

The MDN documentation shows how the getItem method is implementated:

Object.defineProperty(oStorage, "getItem", {
      value: function (sKey) { return sKey ? this[sKey] : null; },
      writable: false,
      configurable: false,
      enumerable: false
    });

If the value isn't set, it returns null. You are testing to see if it is undefined. Check to see if it is null instead.

if(localStorage.getItem("username") === null){

Javascript Array inside Array - how can I call the child array name?

There is no way to know that the two members of the options array came from variables named size and color.

They are also not necessarily called that exclusively, any variable could also point to that array.

var notSize = size;

console.log(options[0]); // It is `size` or `notSize`?

One thing you can do is use an object there instead...

var options = {
    size: size,
    color: color
}

Then you could access options.size or options.color.

How to render an array of objects in React?

https://facebook.github.io/react/docs/jsx-in-depth.html#javascript-expressions

You can pass any JavaScript expression as children, by enclosing it within {}. For example, these expressions are equivalent:

<MyComponent>foo</MyComponent>

<MyComponent>{'foo'}</MyComponent>

This is often useful for rendering a list of JSX expressions of arbitrary length. For example, this renders an HTML list:

function Item(props) {
  return <li>{props.message}</li>;
}

function TodoList() {
  const todos = ['finish doc', 'submit pr', 'nag dan to review'];
  return (
    <ul>
      {todos.map((message) => <Item key={message} message={message} />)}
    </ul>
  );
}

_x000D_
_x000D_
class First extends React.Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
    this.state = {_x000D_
      data: [{name: 'bob'}, {name: 'chris'}],_x000D_
    };_x000D_
  }_x000D_
  _x000D_
  render() {_x000D_
    return (_x000D_
      <ul>_x000D_
        {this.state.data.map(d => <li key={d.name}>{d.name}</li>)}_x000D_
      </ul>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
  <First />,_x000D_
  document.getElementById('root')_x000D_
);_x000D_
  
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

BitBucket - download source as ZIP

For the latest version of Bitbucket (2016+), the download link can be found in the Download menu item.

enter image description here


Pre-2016

First method

In the Overview page of the repo, there is a link to download the project.

Direct download of a repo


Second method

Go to Downloads -> Branches -> Download the branch that you want (as .zip, .gz or .bz2). There you'll find download links for all tags. The links will be in the format:

https://bitbucket.org/owner/repository/get/v0.1.2.tar.gz

By tweaking it a little bit, you can also have access to any revision by changing the tag to the commit hash:

https://bitbucket.org/owner/repository/get/A0B1C2D.tar.gz

How to remove an iOS app from the App Store

To remove an app from the App Store, deselect all territories in your app's Rights and Pricing section on the App Summary page accessible from the Manage Your Applications module. Your app status will change to Developer Removed from Sale and will be removed from the App Store until you make it available again using the Rights and Pricing section.

JPanel vs JFrame in Java

You should not extend the JFrame class unnecessarily (only if you are adding extra functionality to the JFrame class)

JFrame:

JFrame extends Component and Container.

It is a top level container used to represent the minimum requirements for a window. This includes Borders, resizability (is the JFrame resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Events like windowClose, windowOpened etc.

JPanel:

JPanel extends Component, Container and JComponent

It is a generic class used to group other Components together.

  • It is useful when working with LayoutManagers e.g. GridLayout f.i adding components to different JPanels which will then be added to the JFrame to create the gui. It will be more manageable in terms of Layout and re-usability.

  • It is also useful for when painting/drawing in Swing, you would override paintComponent(..) and of course have the full joys of double buffering.

A Swing GUI cannot exist without a top level container like (JWindow, Window, JFrame Frame or Applet), while it may exist without JPanels.

How to force view controller orientation in iOS 8?

My requirements are

  1. lock all views in portrait mode
  2. use AVPlayerViewController to play video

When video is playing, if it's a landscape then allow the screen to rotate landscape right and landscape left. If it's a portrait then lock the view in portrait mode only.

First, define supportedInterfaceOrientationsForWindow in AppDelegate.swift

var portrait = true
func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
    if portrait {
        return .Portrait
    } else {
        return .Landscape
    }
}

Second, in your main view controller, define following functions

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    print("\(#function)")
    return .Portrait
}

override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
    return .Portrait
}

override func shouldAutorotate() -> Bool {
    return false
}

Then, you need to subclass AVPlayerViewController

class MyPlayerViewController: AVPlayerViewController {

    var size: CGSize?

    var supportedOrientationMask: UIInterfaceOrientationMask?
    var preferredOrientation: UIInterfaceOrientation?

    override func viewDidLoad() {
        super.viewDidLoad()

        if let size = size {
            if size.width > size.height {
                self.supportedOrientationMask =[.LandscapeLeft,.LandscapeRight]
                self.preferredOrientation =.LandscapeRight
            } else {
                self.supportedOrientationMask =.Portrait
                self.preferredOrientation =.Portrait
            }
        }
    }

Override these three functions in MyPlayerViewController.swift

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    return self.supportedOrientationMask!
}

override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
    return self.preferredOrientation!
}

Because user might rotate device landscape left or landscape right, we need to set auto rotate to be true

override func shouldAutorotate() -> Bool {
    return true
}

Finally, create MyPlayerViewController instance in your view controller and set the property size value.

let playerViewController = MyPlayerViewController()

// Get the thumbnail  
let thumbnail = MyAlbumFileManager.sharedManager().getThumbnailFromMyVideoMedia(......)

let size = thumbnail?.size
playerViewController.size = size

Initiate your player with proper videoUrl, then assign your player to playerViewController. Happy coding!

Android Shared preferences for creating one time activity (example)

Write to Shared Preferences

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
 editor.commit(); 

Read from Shared Preferences

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);

Reading file line by line (with space) in Unix Shell scripting - Issue

You want to read raw lines to avoid problems with backslashes in the input (use -r):

while read -r line; do
   printf "<%s>\n" "$line"
done < file.txt

This will keep whitespace within the line, but removes leading and trailing whitespace. To keep those as well, set the IFS empty, as in

while IFS= read -r line; do
   printf "%s\n" "$line"
done < file.txt

This now is an equivalent of cat < file.txt as long as file.txt ends with a newline.

Note that you must double quote "$line" in order to keep word splitting from splitting the line into separate words--thus losing multiple whitespace sequences.

How to get request URI without context path?

A way to do this is to rest the servelet context path from request URI.

String p = request.getRequestURI();
String cp = getServletContext().getContextPath();

if (p.startsWith(cp)) {
  String.err.println(p.substring(cp.length());
}

Read here .

Cannot drop database because it is currently in use

Just wanted to give a vb.net (as with c language if want to convert..) I was having similar problem for uninstal of one of my programs, dropping the DB was bit tricky, yes could get users to go into server drop it using Express, but thats not clean, after few looks around got a perfect little bit of code together...

    Sub DropMyDatabase()
    Dim Your_DB_To_Drop_Name As String = "YourDB"
    Dim Your_Connection_String_Here As String = "SERVER=MyServer;Integrated Security=True"
    Dim Conn As SqlConnection = New SqlConnection(Your_Connection_String_Here)

    Dim AlterStr As String = "ALTER DATABASE " & Your_DB_To_Drop_Name & " SET OFFLINE WITH ROLLBACK IMMEDIATE"
    Dim AlterCmd = New SqlCommand(AlterStr, Conn)

    Dim DropStr As String = "DROP DATABASE " & Your_DB_To_Drop_Name
    Dim DropCmd = New SqlCommand(DropStr, Conn)

    Try
        Conn.Open()
        AlterCmd.ExecuteNonQuery()
        DropCmd.ExecuteNonQuery()
        Conn.Close()

    Catch ex As Exception
        If (Conn.State = ConnectionState.Open) Then
            Conn.Close()
        End If
        MsgBox("Failed... Sorry!" & vbCrLf & vbCrLf & ex.Message)
    End Try
End Sub

Hope this helps anyone looking xChickenx

UPDATE Using this converter here is the C# version :

public void DropMyDatabase()
    {
        var Your_DB_To_Drop_Name = "YourDB";
        var Your_Connection_String_Here = "SERVER=MyServer;Integrated Security=True";
        var Conn = new SqlConnection(Your_Connection_String_Here);

        var AlterStr = "ALTER DATABASE " + Your_DB_To_Drop_Name + " SET OFFLINE WITH ROLLBACK IMMEDIATE";
        var AlterCmd = new SqlCommand(AlterStr, Conn);

        var DropStr = "DROP DATABASE " + Your_DB_To_Drop_Name;
        var DropCmd = new SqlCommand(DropStr, Conn);

        try
        {
            Conn.Open();
            AlterCmd.ExecuteNonQuery();
            DropCmd.ExecuteNonQuery();
            Conn.Close();

        }
        catch(Exception ex)
        {
            if((Conn.State == ConnectionState.Open))
            {
                Conn.Close();
            }
            Trace.WriteLine("Failed... Sorry!" + Environment.NewLine + ex.Message);
        }
    }

In C#, what's the difference between \n and \r\n?

They are just \r\n and \n are variants.

\r\n is used in windows

\n is used in mac and linux

How to use Class<T> in Java?

Just use the beef class:

public <T> T beefmarshal( Class<beef> beefClass, InputBeef inputBeef )
     throws JAXBException {
     String packageName = docClass.getPackage().getBeef();
     JAXBContext beef = JAXBContext.newInstance( packageName );
     Unmarshaller u = beef.createBeef();
     JAXBElement<T> doc = (JAXBElement<T>)u.beefmarshal( inputBeef );
     return doc.getBeef();
}

Make browser window blink in task Bar

you could change the title of the web page with each new message to alert the user. I did this for a browser chat client and most users thought it worked well enough.

document.title = "[user] hello world";

Regex to match only letters

You can try this regular expression : [^\W\d_] or [a-zA-Z].

Put icon inside input element in a form

This works for me for more or less standard forms:

  <button type="submit" value="Submit" name="ButtonType" id="whateveristheId" class="button-class">Submit<img src="/img/selectedImage.png" alt=""></button>

Difference between size and length methods?

length variable:

In Java, array (not java.util.Array) is a predefined class in the language itself. To find the elements of an array, designers used length variable (length is a field member in the predefined class). They must have given length() itself to have uniformity in Java; but did not. The reason is by performance, executing length variable is speedier than calling the method length(). It is like comparing two strings with == and equals(). equals() is a method call which takes more time than executing == operator.

size() method:

It is used to find the number of elements present in collection classes. It is defined in java.util.Collection interface.

What do column flags mean in MySQL Workbench?

PK - Primary Key

NN - Not Null

BIN - Binary (stores data as binary strings. There is no character set so sorting and comparison is based on the numeric values of the bytes in the values.)

UN - Unsigned (non-negative numbers only. so if the range is -500 to 500, instead its 0 - 1000, the range is the same but it starts at 0)

UQ - Create/remove Unique Key

ZF - Zero-Filled (if the length is 5 like INT(5) then every field is filled with 0’s to the 5th digit. 12 = 00012, 400 = 00400, etc. )

AI - Auto Increment

G - Generated column. i.e. value generated by a formula based on the other columns

Ruby on Rails: How do I add placeholder text to a f.text_field?

With rails >= 3.0, you can simply use the placeholder option.

f.text_field :attr, placeholder: "placeholder text"

Search for all occurrences of a string in a mysql database

Using the MySQL Workbench, you can search for a string from the "Database" -> "Search Table Data" menu option.

Specify LIKE %URL_TO_SEARCH% and on the left side select all the tables you want to search through. You can use "Cntrl + A" to select the whole tree on the left, and then deselect the objects you don't care about.

enter image description here

How to fix the error "Windows SDK version 8.1" was not found?

I encountered this issue while trying to build an npm project. It was failing to install a node-sass package and this was the error it was printing. I solved it by setting my npm proxy correctly so that i

Align button at the bottom of div using CSS

CSS3 flexbox can also be used to align button at the bottom of parent element.

Required HTML:

<div class="container">
  <div class="btn-holder">
    <button type="button">Click</button>
  </div>
</div>

Necessary CSS:

.container {
  justify-content: space-between;
  flex-direction: column;
  height: 100vh;
  display: flex;
}
.container .btn-holder {
  justify-content: flex-end;
  display: flex;
}

Screenshot:

Output Image

Useful Resources:

_x000D_
_x000D_
* {box-sizing: border-box;}_x000D_
body {_x000D_
  background: linear-gradient(orange, yellow);_x000D_
  font: 14px/18px Arial, sans-serif;_x000D_
  margin: 0;_x000D_
}_x000D_
.container {_x000D_
  justify-content: space-between;_x000D_
  flex-direction: column;_x000D_
  height: 100vh;_x000D_
  display: flex;_x000D_
  padding: 10px;_x000D_
}_x000D_
.container .btn-holder {_x000D_
  justify-content: flex-end;_x000D_
  display: flex;_x000D_
}_x000D_
.container .btn-holder button {_x000D_
  padding: 10px 25px;_x000D_
  background: blue;_x000D_
  font-size: 16px;_x000D_
  border: none;_x000D_
  color: #fff;_x000D_
}
_x000D_
<div class="container">_x000D_
  <p>Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... </p>_x000D_
  <div class="btn-holder">_x000D_
    <button type="button">Click</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

git ignore exception

This is how I do it, with a README.md file in each directory:

/data/*
!/data/README.md

!/data/input/
/data/input/*
!/data/input/README.md

!/data/output/
/data/output/*
!/data/output/README.md

Using XPATH to search text containing &nbsp;

I cannot get a match using Xpather, but the following worked for me with plain XML and XSL files in Microsoft's XML Notepad:

<xsl:value-of select="count(//td[text()='&nbsp;'])" />

The value returned is 1, which is the correct value in my test case.

However, I did have to declare nbsp as an entity within my XML and XSL using the following:

<!DOCTYPE xsl:stylesheet [ <!ENTITY nbsp "&#160;"> ]>

I'm not sure if that helps you, but I was able to actually find nbsp using an XPath expression.

Edit: My code sample actually contains the characters '&nbsp;' but the JavaScript syntax highlight converts it to the space character. Don't be mislead!

Aborting a shell script if any command returns a non-zero value

If you have cleanup you need to do on exit, you can also use 'trap' with the pseudo-signal ERR. This works the same way as trapping INT or any other signal; bash throws ERR if any command exits with a nonzero value:

# Create the trap with   
#    trap COMMAND SIGNAME [SIGNAME2 SIGNAME3...]
trap "rm -f /tmp/$MYTMPFILE; exit 1" ERR INT TERM
command1
command2
command3
# Partially turn off the trap.
trap - ERR
# Now a control-C will still cause cleanup, but
# a nonzero exit code won't:
ps aux | grep blahblahblah

Or, especially if you're using "set -e", you could trap EXIT; your trap will then be executed when the script exits for any reason, including a normal end, interrupts, an exit caused by the -e option, etc.

How to center horizontally div inside parent div

.parent-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.child-canvas {
  flex-shrink: 0;
}

What is the default lifetime of a session?

According to a user on PHP.net site, his efforts to keep session alive failed, so he had to make a workaround.

<?php

$Lifetime = 3600;
$separator = (strstr(strtoupper(substr(PHP_OS, 0, 3)), "WIN")) ? "\\" : "/";

$DirectoryPath = dirname(__FILE__) . "{$separator}SessionData";
//in Wamp for Windows the result for $DirectoryPath
//would be C:\wamp\www\your_site\SessionData

is_dir($DirectoryPath) or mkdir($DirectoryPath, 0777);

if (ini_get("session.use_trans_sid") == true) {
    ini_set("url_rewriter.tags", "");
    ini_set("session.use_trans_sid", false);

}

ini_set("session.gc_maxlifetime", $Lifetime);
ini_set("session.gc_divisor", "1");
ini_set("session.gc_probability", "1");
ini_set("session.cookie_lifetime", "0");
ini_set("session.save_path", $DirectoryPath);
session_start();

?>

In SessionData folder it will be stored text files for holding session information, each file would be have a name similar to "sess_a_big_hash_here".

How to get the PID of a process by giving the process name in Mac OS X ?

You can try this

pid=$(ps -o pid=,comm= | grep -m1 $procname | cut -d' ' -f1)

Can you call ko.applyBindings to bind a partial view?

ko.applyBindings accepts a second parameter that is a DOM element to use as the root.

This would let you do something like:

<div id="one">
  <input data-bind="value: name" />
</div>

<div id="two">
  <input data-bind="value: name" />
</div>

<script type="text/javascript">
  var viewModelA = {
     name: ko.observable("Bob")
  };

  var viewModelB = {
     name: ko.observable("Ted")
  };

  ko.applyBindings(viewModelA, document.getElementById("one"));
  ko.applyBindings(viewModelB, document.getElementById("two"));
</script>

So, you can use this technique to bind a viewModel to the dynamic content that you load into your dialog. Overall, you just want to be careful not to call applyBindings multiple times on the same elements, as you will get multiple event handlers attached.

Split page vertically using CSS

Here is the flex-box approach:

CSS

 .parent {
  display:flex;
  height:100vh;
  }
  .child{
    flex-grow:1;
  }
  .left{
    background:#ddd;
  }
  .center{
    background:#666;
  }

  .right{
    background:#999;
  }

HTML

<div class="parent">
    <div class="child left">Left</div>
    <div class="child center">Center</div>
    <div class="child right">Right</div>
</div>

You can try the same in js fiddle.

Measuring Query Performance : "Execution Plan Query Cost" vs "Time Taken"

Use SET STATISTICS TIME ON

above your query.

Below near result tab you can see a message tab. There you can see the time.

Lock down Microsoft Excel macro

You can check out this new product at http://hivelink.io, it allows you to properly protect your sensitive macros.

The Excel password system is extremely weak - you can crack it in 2 minutes just using a basic HEX editor. I wouldn't recommend relying on this to protect anything.

I wrote an extensive post on this topic here: Protecting Code in an Excel Workbook?

Access to the path denied error in C#

If your problem persist with all those answers, try to change the file attribute to:

File.SetAttributes(yourfile, FileAttributes.Normal);

Linq: GroupBy, Sum and Count

sometimes you need to select some fields by FirstOrDefault() or singleOrDefault() you can use the below query:

List<ResultLine> result = Lines
    .GroupBy(l => l.ProductCode)
    .Select(cl => new Models.ResultLine
            {
                ProductName = cl.select(x=>x.Name).FirstOrDefault(),
                Quantity = cl.Count().ToString(),
                Price = cl.Sum(c => c.Price).ToString(),
            }).ToList();

PHP create key => value pairs within a foreach

function createOfferUrlArray($Offer) {
    $offerArray = array();
    foreach ($Offer as $key => $value) { 
        $offerArray[$key] = $value[4];
    }
    return $offerArray;
}

or

function createOfferUrlArray($offer) {
    foreach ( $offer as &$value ) {
        $value = $value[4];
    }
    unset($value);
    return $offer;
}

Excel 2007 - Compare 2 columns, find matching values

VLOOKUP deosnt work for String literals

How does Subquery in select statement work in oracle

In the Oracle RDBMS, it is possible to use a multi-row subquery in the select clause as long as the (sub-)output is encapsulated as a collection. In particular, a multi-row select clause subquery can output each of its rows as an xmlelement that is encapsulated in an xmlforest.

Scala check if element is present in a list

Just use contains

myFunction(strings.contains(myString))

Java: how can I split an ArrayList in multiple small ArrayLists?

I'm guessing that the issue you're having is with naming 100 ArrayLists and populating them. You can create an array of ArrayLists and populate each of those using a loop.

The simplest (read stupidest) way to do this is like this:

ArrayList results = new ArrayList(1000);
    // populate results here
    for (int i = 0; i < 1000; i++) {
        results.add(i);
    }
    ArrayList[] resultGroups = new ArrayList[100];
    // initialize all your small ArrayList groups
    for (int i = 0; i < 100; i++) {
            resultGroups[i] = new ArrayList();
    }
    // put your results into those arrays
    for (int i = 0; i < 1000; i++) {
       resultGroups[i/10].add(results.get(i));
    } 

(XML) The markup in the document following the root element must be well-formed. Start location: 6:2

After insuring that the string "strOutput" has a correct XML structure, you can do this:

Matcher junkMatcher = (Pattern.compile("^([\\W]+)<")).matcher(strOutput);
strOutput = junkMatcher.replaceFirst("<");

How to install grunt and how to build script with it

I got the same issue, but i solved it with changing my Grunt.js to Gruntfile.js Check your file name before typing grunt.cmd on windows cmd (if you're using windows).

Can I set subject/content of email using mailto:?

Yes, you can like this:

mailto: [email protected]?subject=something

How to get only the date value from a Windows Forms DateTimePicker control?

Datum = DateTime.Parse(DateTimePicker1.Value.ToString("dd/MM/yyyy"))

Validate fields after user has left a field

From version 1.3.0 this can easily be done with $touched, which is true after the user has left the field.

<p ng-show="form.field.$touched && form.field.$invalid">Error</p>

https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

Android-java- How to sort a list of objects by a certain value within the object

You can compare two String by using this.

Collections.sort(contactsList, new Comparator<ContactsData>() {

                    @Override
                    public int compare(ContactsData lhs, ContactsData rhs) {

                        char l = Character.toUpperCase(lhs.name.charAt(0));

                        if (l < 'A' || l > 'Z')

                            l += 'Z';

                        char r = Character.toUpperCase(rhs.name.charAt(0));

                        if (r < 'A' || r > 'Z')

                            r += 'Z';

                        String s1 = l + lhs.name.substring(1);

                        String s2 = r + rhs.name.substring(1);

                        return s1.compareTo(s2);

                    }

                });

And Now make a ContactData Class.

public class ContactsData {

public String name;
public String id;
public String email;
public String avatar; 
public String connection_type;
public String thumb;
public String small;
public String first_name;
public String last_name;
public String no_of_user;
public int grpIndex;

public ContactsData(String name, String id, String email, String avatar, String connection_type)
{
    this.name = name;
    this.id = id;
    this.email = email;
    this.avatar = avatar;
    this.connection_type = connection_type;

}
}

Here contactsList is :

public static ArrayList<ContactsData> contactsList = new ArrayList<ContactsData>();

How to import Maven dependency in Android Studio/IntelliJ?

Android Studio 3

The answers that talk about Maven Central are dated since Android Studio uses JCenter as the default repository center now. Your project's build.gradle file should have something like this:

repositories {
    google()
    jcenter()
}

So as long as the developer has their Maven repository there (which Picasso does), then all you would have to do is add a single line to the dependencies section of your app's build.gradle file.

dependencies {
    // ...
    implementation 'com.squareup.picasso:picasso:2.5.2'
}

What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?

ClassNotFoundException and NoClassDefFoundError occur when a particular class is not found at runtime.However, they occur at different scenarios.

ClassNotFoundException is an exception that occurs when you try to load a class at run time using Class.forName() or loadClass() methods and mentioned classes are not found in the classpath.

    public class MainClass
    {
        public static void main(String[] args)
        {
            try
            {
                Class.forName("oracle.jdbc.driver.OracleDriver");
            }catch (ClassNotFoundException e)
            {
                e.printStackTrace();
            }
        }
    }



    java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at pack1.MainClass.main(MainClass.java:17)

NoClassDefFoundError is an error that occurs when a particular class is present at compile time, but was missing at run time.

    class A
    {
      // some code
    }
    public class B
    {
        public static void main(String[] args)
        {
            A a = new A();
        }
    }

When you compile the above program, two .class files will be generated. One is A.class and another one is B.class. If you remove the A.class file and run the B.class file, Java Runtime System will throw NoClassDefFoundError like below:

    Exception in thread "main" java.lang.NoClassDefFoundError: A
    at MainClass.main(MainClass.java:10)
    Caused by: java.lang.ClassNotFoundException: A
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

Build .so file from .c file using gcc command line

To generate a shared library you need first to compile your C code with the -fPIC (position independent code) flag.

gcc -c -fPIC hello.c -o hello.o

This will generate an object file (.o), now you take it and create the .so file:

gcc hello.o -shared -o libhello.so

EDIT: Suggestions from the comments:

You can use

gcc -shared -o libhello.so -fPIC hello.c

to do it in one step. – Jonathan Leffler

I also suggest to add -Wall to get all warnings, and -g to get debugging information, to your gcc commands. – Basile Starynkevitch

Android WebView progress bar

I have just found a really good example of how to do this here: http://developer.android.com/reference/android/webkit/WebView.html . You just need to change the setprogress from:

activity.setProgress(progress * 1000);

to

activity.setProgress(progress * 100);

What's the difference between ng-model and ng-bind

ng-bind has one-way data binding ($scope --> view). It has a shortcut {{ val }} which displays the scope value $scope.val inserted into html where val is a variable name.

ng-model is intended to be put inside of form elements and has two-way data binding ($scope --> view and view --> $scope) e.g. <input ng-model="val"/>.

Program to find prime numbers

The Sieve of Eratosthenes answer above is not quite correct. As written it will find all the primes between 1 and 1000000. To find all the primes between 1 and num use:

private static IEnumerable Primes01(int num)
{
    return Enumerable.Range(1, Convert.ToInt32(Math.Floor(Math.Sqrt(num))))
        .Aggregate(Enumerable.Range(1, num).ToList(),
        (result, index) =>
            {
                result.RemoveAll(i => i > result[index] && i%result[index] == 0);
                return result;
            }
        );
}

The seed of the Aggregate should be range 1 to num since this list will contain the final list of primes. The Enumerable.Range(1, Convert.ToInt32(Math.Floor(Math.Sqrt(num)))) is the number of times the seed is purged.

Using Java 8 to convert a list of objects into a string obtained from the toString() method

Just in case anyone is trying to do this without java 8, there is a pretty good trick. List.toString() already returns a collection that looks like this:

[1,2,3]

Depending on your specific requirements, this can be post-processed to whatever you want as long as your list items don't contain [] or , .

For instance:

list.toString().replace("[","").replace("]","") 

or if your data might contain square brackets this:

String s=list.toString();
s = s.substring(1,s.length()-1) 

will get you a pretty reasonable output.

One array item on each line can be created like this:

list.toString().replace("[","").replace("]","").replaceAll(",","\r\n")

I used this technique to make html tooltips from a list in a small app, with something like:

list.toString().replace("[","<html>").replace("]","</html>").replaceAll(",","<br>")

If you have an array then start with Arrays.asList(list).toString() instead

I'll totally own the fact that this is not optimal, but it's not as inefficient as you might think and is pretty straightforward to read and understand. It is, however, quite inflexible--in particular don't try to separate the elements with replaceAll if your data might contain commas and use the substring version if you have square brackets in your data, but for an array of numbers it's pretty much perfect.

Qt - reading from a text file

You have to replace string line

QString line = in.readLine();

into while:

QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
    QMessageBox::information(0, "error", file.errorString());
}

QTextStream in(&file);

while(!in.atEnd()) {
    QString line = in.readLine();    
    QStringList fields = line.split(",");    
    model->appendRow(fields);    
}

file.close();

Java: How to read a text file

Just for fun, here's what I'd probably do in a real project, where I'm already using all my favourite libraries (in this case Guava, formerly known as Google Collections).

String text = Files.toString(new File("textfile.txt"), Charsets.UTF_8);
List<Integer> list = Lists.newArrayList();
for (String s : text.split("\\s")) {
    list.add(Integer.valueOf(s));
}

Benefit: Not much own code to maintain (contrast with e.g. this). Edit: Although it is worth noting that in this case tschaible's Scanner solution doesn't have any more code!

Drawback: you obviously may not want to add new library dependencies just for this. (Then again, you'd be silly not to make use of Guava in your projects. ;-)

How can I convert an image into Base64 string using JavaScript?

Well, if you are using Dojo Toolkit, it gives us a direct way to encode or decode into Base64.

Try this:

To encode an array of bytes using dojox.encoding.base64:

var str = dojox.encoding.base64.encode(myByteArray);

To decode a Base64-encoded string:

var bytes = dojox.encoding.base64.decode(str);

HtmlEncode from Class Library

If you are using C#3 a good tip is to create an extension method to make this even simpler. Just create a static method (preferably in a static class) like so:

public static class Extensions
{
    public static string HtmlEncode(this string s)
    {
        return HttpUtility.HtmlEncode(s);
    }
}

You can then do neat stuff like this:

string encoded = "<div>I need encoding</div>".HtmlEncode();

How to remove an item from an array in Vue.js

Splice is the best to remove element from specific index. The given example is tested on console.

card = [1, 2, 3, 4];
card.splice(1,1);  // [2]
card   // (3) [1, 3, 4]
splice(startingIndex, totalNumberOfElements)

startingIndex start from 0.

UIScrollView scroll to bottom programmatically

For Horizontal ScrollView

If you like me has a Horizontal ScrollView and want to scroll to end of it (in my case to most right of it), you need to change some parts of the accepted answer:

Objective-C

CGPoint rightOffset = CGPointMake(self.scrollView.contentSize.width - self.scrollView.bounds.size.width + self.scrollView.contentInset.right, 0 );
[self.scrollView setContentOffset:rightOffset animated:YES];

Swift

let rightOffset: CGPoint = CGPoint(x: self.scrollView.contentSize.width - self.scrollView.bounds.size.width + self.scrollView.contentInset.right, y: 0)
self.scrollView.setContentOffset(rightOffset, animated: true)

how to set windows service username and password through commandline

This works:

sc.exe config "[servicename]" obj= "[.\username]" password= "[password]"

Where each of the [bracketed] items are replaced with the true arguments. (Keep the quotes, but don't keep the brackets.)

Just keep in mind that:

  • The spacing in the above example matters. obj= "foo" is correct; obj="foo" is not.
  • '.' is an alias to the local machine, you can specify a domain there (or your local computer name) if you wish.
  • Passwords aren't validated until the service is started
  • Quote your parameters, as above. You can sometimes get by without quotes, but good luck.

Best Way to Refresh Adapter/ListView on Android

If you are using LoaderManager try with this statement:

getLoaderManager().restartLoader(0, null, this);

Drop-down box dependent on the option selected in another drop-down box

I am posting this answer because in this way you will never need any plugin like jQuery and any other, This has the solution by simple javascript.

<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script language="javascript" type="text/javascript">
    function dynamicdropdown(listindex)
    {
        switch (listindex)
        {
        case "manual" :
            document.getElementById("status").options[0]=new Option("Select status","");
            document.getElementById("status").options[1]=new Option("OPEN","open");
            document.getElementById("status").options[2]=new Option("DELIVERED","delivered");
            break;
        case "online" :
            document.getElementById("status").options[0]=new Option("Select status","");
            document.getElementById("status").options[1]=new Option("OPEN","open");
            document.getElementById("status").options[2]=new Option("DELIVERED","delivered");
            document.getElementById("status").options[3]=new Option("SHIPPED","shipped");
            break;
        }
        return true;
    }
    </script>
    </head>
    <title>Dynamic Drop Down List</title>
    <body>
    <div class="category_div" id="category_div">Source:
        <select id="source" name="source" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
        <option value="">Select source</option>
        <option value="manual">MANUAL</option>
        <option value="online">ONLINE</option>
        </select>
    </div>
    <div class="sub_category_div" id="sub_category_div">Status:
        <script type="text/javascript" language="JavaScript">
        document.write('<select name="status" id="status"><option value="">Select status</option></select>')
        </script>
        <noscript>
        <select id="status" name="status">
            <option value="open">OPEN</option>
            <option value="delivered">DELIVERED</option>
        </select>
        </noscript>
    </div>
    </body>
</html>

For more details, I mean to make dynamic and more dependency please take a look at my article create dynamic drop-down list

Cannot get a text value from a numeric cell “Poi”

Use that code it definitely works and I modified it.

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
//import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.*;

public class TestApp {

    public static void main(String[] args) throws Exception {

        try {

            Class forName = Class.forName("com.mysql.jdbc.Driver");
            Connection con = null;
            con = DriverManager.getConnection("jdbc:mysql://localhost/tables", "root", "root");
            con.setAutoCommit(false);
            PreparedStatement pstm = null;
            FileInputStream input = new FileInputStream("C:\\Users\\Desktop\\a1.xls");
            POIFSFileSystem fs = new POIFSFileSystem(input);
            Workbook workbook;
            workbook = WorkbookFactory.create(fs);
            Sheet sheet = workbook.getSheetAt(0);
            Row row;
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                row = (Row) sheet.getRow(i);
                String name = row.getCell(0).getStringCellValue();
                String add = row.getCell(1).getStringCellValue();

                int  contact = (int) row.getCell(2).getNumericCellValue();

                String email = row.getCell(3).getStringCellValue();

                String sql = "INSERT INTO employee (name, address, contactNo, email) VALUES('" + name + "','" + add + "'," + contact + ",'" + email + "')";
                pstm = (PreparedStatement) con.prepareStatement(sql);
                pstm.execute();
                System.out.println("Import rows " + i);
            }
            con.commit();
            pstm.close();
            con.close();
            input.close();
            System.out.println("Success import excel to mysql table");
        } catch (IOException e) {
        }
    }

}

Escape string Python for MySQL

{!a} applies ascii() and hence escapes non-ASCII characters like quotes and even emoticons. Here is an example

cursor.execute("UPDATE skcript set author='{!a}',Count='{:d}' where url='{!s}'".format(authors),leng,url))

Python3 docs

How to get a unique device ID in Swift?

class func uuid(completionHandler: @escaping (String) -> ()) {
    if let uuid = UIDevice.current.identifierForVendor?.uuidString {
        completionHandler(uuid)
    }
    else {
        // If the value is nil, wait and get the value again later. This happens, for example, after the device has been restarted but before the user has unlocked the device.
        // https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor?language=objc
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
            uuid(completionHandler: completionHandler)
        }
    }
}

How to get base URL in Web API controller?

From HttpRequestMessage

request.Headers.Host

Matplotlib connect scatterplot points with line - Python

In addition to what provided in the other answers, the keyword "zorder" allows one to decide the order in which different objects are plotted vertically. E.g.:

plt.plot(x,y,zorder=1) 
plt.scatter(x,y,zorder=2)

plots the scatter symbols on top of the line, while

plt.plot(x,y,zorder=2)
plt.scatter(x,y,zorder=1)

plots the line over the scatter symbols.

See, e.g., the zorder demo

How to escape % in String.Format?

To complement the previous stated solution, use:

str = str.replace("%", "%%");

Android: how to get the current day of the week (Monday, etc...) in the user's language?

//selected date from calender
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy"); //Date and time
String currentDate = sdf.format(myCalendar.getTime());

//selcted_day name
SimpleDateFormat sdf_ = new SimpleDateFormat("EEEE");
String dayofweek=sdf_.format(myCalendar.getTime());
current_date.setText(currentDate);
lbl_current_date.setText(dayofweek);

Log.e("dayname", dayofweek);

node.js: cannot find module 'request'

ReferenceError: Can't find variable: require.

You have installed "npm", you can run as normal the script to a "localhost" "127.0.0.1".

When you use the http.clientRequest() with "options" in a "npm" you need to install "RequireJS" inside of the module.

A module is any file or directory in the node_modules directory that can be loaded by the Node. Install "RequiereJS" for to make work the http.clientRequest(options).

How to convert date into this 'yyyy-MM-dd' format in angular 2

_x000D_
_x000D_
const formatDate=(dateObj)=>{
const days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const months = ["January","February","March","April","May","June","July","August","September","October","November","December"];

const dateOrdinal=(dom)=> {
    if (dom == 31 || dom == 21 || dom == 1) return dom + "st";
    else if (dom == 22 || dom == 2) return dom + "nd";
    else if (dom == 23 || dom == 3) return dom + "rd";
    else return dom + "th";
};
return dateOrdinal(dateObj.getDate())+', '+days[dateObj.getDay()]+' '+ months[dateObj.getMonth()]+', '+dateObj.getFullYear();
}
const ddate = new Date();
const result=formatDate(ddate)
document.getElementById("demo").innerHTML = result
_x000D_
<!DOCTYPE html>
<html>
<body>
<h2>Example:20th, Wednesday September, 2020 <h2>
<p id="demo"></p>
</body>
</html>
_x000D_
_x000D_
_x000D_

How do I configure HikariCP in my Spring Boot app in my application.properties files?

So it turns out that almost all the default settings for HikariCP work for me except the number of DB connections. I set that property in my application.properties:

spring.datasource.maximumPoolSize=20

And Andy Wilkinson is correct as far as I can tell in that you can't use the dataSourceClassName configuration approach for HikariCP with Spring Boot.

Asynchronous Process inside a javascript for loop

_x000D_
_x000D_
var i = 0;_x000D_
var length = 10;_x000D_
_x000D_
function for1() {_x000D_
  console.log(i);_x000D_
  for2();_x000D_
}_x000D_
_x000D_
function for2() {_x000D_
  if (i == length) {_x000D_
    return false;_x000D_
  }_x000D_
  setTimeout(function() {_x000D_
    i++;_x000D_
    for1();_x000D_
  }, 500);_x000D_
}_x000D_
for1();
_x000D_
_x000D_
_x000D_

Here is a sample functional approach to what is expected here.

PHP using Gettext inside <<<EOF string

As far as I can see, you just added heredoc by mistake
No need to use ugly heredoc syntax here.
Just remove it and everything will work:

<p>Hello</p>
<p><?= _("World"); ?></p>

Convert row to column header for Pandas DataFrame,

To rename the header without reassign df:

df.rename(columns=df.iloc[0], inplace = True)

To drop the row without reassign df:

df.drop(df.index[0], inplace = True)

jquery data selector

At the moment I'm selecting like this:

$('a[data-attribute=true]')

Which seems to work just fine, but it would be nice if jQuery was able to select by that attribute without the 'data-' prefix.

I haven't tested this with data added to elements via jQuery dynamically, so that could be the downfall of this method.

Laravel: How to Get Current Route Name? (v5 ... v7)

You can used this line of code : url()->current()

In blade file : {{url()->current()}}

what is the difference between $_SERVER['REQUEST_URI'] and $_GET['q']?

In the context of Drupal, the difference will depend whether clean URLs are on or not.

With them off, $_SERVER['REQUEST_URI'] will have the full path of the page as called w/ /index.php, while $_GET["q"] will just have what is assigned to q.

With them on, they will be nearly identical w/o other arguments, but $_GET["q"] will be missing the leading /. Take a look towards the end of the default .htaccess to see what is going on. They will also differ if additional arguments are passed into the page, eg when a pager is active.

Passing 'this' to an onclick event

The code that you have would work, but is executed from the global context, which means that this refers to the global object.

<script type="text/javascript">
var foo = function(param) {
    param.innerHTML = "Not a button";
};
</script>
<button onclick="foo(this)" id="bar">Button</button>

You can also use the non-inline alternative, which attached to and executed from the specific element context which allows you to access the element from this.

<script type="text/javascript">
document.getElementById('bar').onclick = function() {
    this.innerHTML = "Not a button";
};
</script>
<button id="bar">Button</button>

How do I import a .dmp file into Oracle?

.dmp files are dumps of oracle databases created with the "exp" command. You can import them using the "imp" command.

If you have an oracle client intalled on your machine, you can executed the command

imp help=y

to find out how it works. What will definitely help is knowing from wich schema the data was exported and what the oracle version was.

Merge two json/javascript arrays in to one array

Upon first appearance, the word "merg" leads one to think you need to use .extend, which is the proper jQuery way to "merge" JSON objects. However, $.extend(true, {}, json1, json2); will cause all values sharing the same key name to be overridden by the latest supplied in the params. As review of your question shows, this is undesired.

What you seek is a simple javascript function known as .concat. Which would work like:

var finalObj = json1.concat(json2);

While this is not a native jQuery function, you could easily add it to the jQuery library for simple future use as follows:

;(function($) {
    if (!$.concat) {
        $.extend({
            concat: function() {
                return Array.prototype.concat.apply([], arguments);
            }
        });
    }
})(jQuery);

And then recall it as desired like:

var finalObj = $.concat(json1, json2);

You can also use it for multiple array objects of this type with a like:

var finalObj = $.concat(json1, json2, json3, json4, json5, ....);

And if you really want it jQuery style and very short and sweet (aka minified)

;(function(a){a.concat||a.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);

_x000D_
_x000D_
;(function($){$.concat||$.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);_x000D_
_x000D_
$(function() {_x000D_
    var json1 = [{id:1, name: 'xxx'}],_x000D_
        json2 = [{id:2, name: 'xyz'}],_x000D_
        json3 = [{id:3, name: 'xyy'}],_x000D_
        json4 = [{id:4, name: 'xzy'}],_x000D_
        json5 = [{id:5, name: 'zxy'}];_x000D_
    _x000D_
    console.log(Array(10).join('-')+'(json1, json2, json3)'+Array(10).join('-'));_x000D_
    console.log($.concat(json1, json2, json3));_x000D_
    console.log(Array(10).join('-')+'(json1, json2, json3, json4, json5)'+Array(10).join('-'));_x000D_
    console.log($.concat(json1, json2, json3, json4, json5));_x000D_
    console.log(Array(10).join('-')+'(json4, json1, json2, json5)'+Array(10).join('-'));_x000D_
    console.log($.concat(json4, json1, json2, json5));_x000D_
});
_x000D_
center { padding: 3em; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<center>See Console Log</center>
_x000D_
_x000D_
_x000D_

jsFiddle

How to add a boolean datatype column to an existing table in sql?

The answer given by P????? creates a nullable bool, not a bool, which may be fine for you. For example in C# it would create: bool? AdminApprovednot bool AdminApproved.

If you need to create a bool (defaulting to false):

    ALTER TABLE person
    ADD AdminApproved BIT
    DEFAULT 0 NOT NULL;

How can I exclude directories from grep -R?

A simple working command:

root/dspace# grep -r --exclude-dir={log,assetstore} "creativecommons.org"

Above I grep for text "creativecommons.org" in current directory "dspace" and exclude dirs {log,assetstore}.

Done.

Windows git "warning: LF will be replaced by CRLF", is that warning tail backward?

--Update on 9th July---

Removed "It is correct and accurate" as commented by @mgiuca

======

NO. It is NOT talking about your files currently with CRLF. It is instead talking about files with LF.

It should read:

warning: (If you check it out/or clone to another folder with your current core.autocrlf configuration,)LF will be replaced by CRLF

The file will have its original line endings in your (current) working directory.

This picture should explain what it means. enter image description here

Do Git tags only apply to the current branch?

When calling just git tag <TAGNAME> without any additional parameters, Git will create a new tag from your current HEAD (i.e. the HEAD of your current branch). When adding additional commits into this branch, the branch HEAD will keep up with those new commits, while the tag always refers to the same commit.

When calling git tag <TAGNAME> <COMMIT> you can even specify which commit to use for creating the tag.

Regardless, a tag is still simply a "pointer" to a certain commit (not a branch).

How to implement class constants?

All of the replies with readonly are only suitable when this is a pure TS environment - if it's ever being made into a library then this doesn't actually prevent anything, it just provides warnings for the TS compiler itself.

Static is also not correct - that's adding a method to the Class, not to an instance of the class - so you need to address it directly.

There are several ways to manage this, but the pure TS way is to use a getter - exactly as you have done already.

The alternative way is to put it in as readonly, but then use Object.defineProperty to lock it - this is almost the same thing that is being done via the getter, but you can lock it to have a value, rather than a method to use to get it -

class MyClass {
    MY_CONSTANT = 10;

    constructor() {
        Object.defineProperty(this, "MY_CONSTANT", {value: this.MY_CONSTANT});
    }
}

The defaults make it read-only, but check out the docs for more details.

MySql export schema without data

Dumping without using output.

mysqldump --no-data <database name> --result-file=schema.sql

Select query to remove non-numeric characters

I have created a function for this

Create FUNCTION RemoveCharacters (@text varchar(30))
RETURNS VARCHAR(30)
AS
BEGIN
declare @index as int 
declare @newtexval as varchar(30)
set @index = (select PATINDEX('%[A-Z.-/?]%', @text))
if (@index =0)
begin 
return @text
end
else
begin 
set @newtexval  = (select STUFF ( @text , @index , 1 , '' ))
return dbo.RemoveCharacters(@newtexval)
end
return 0
END
GO

strcpy() error in Visual studio 2012

I had to use strcpy_s and it worked.

#include "stdafx.h"
#include<iostream>
#include<string>

using namespace std;

struct student
{
    char name[30];
    int age;
};

int main()
{

    struct student s1;
    char myname[30] = "John";
    strcpy_s (s1.name, strlen(myname) + 1 ,myname );
    s1.age = 21;

    cout << " Name: " << s1.name << " age: " << s1.age << endl;
    return 0;
}

How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line?

MSDocs state this for your scenario:

In order to execute the first time, PackageManagement requires an internet connection to download the Nuget package provider. However, if your computer does not have an internet connection and you need to use the Nuget or PowerShellGet provider, you can download them on another computer and copy them to your target computer. Use the following steps to do this:

  1. Run Install-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201 -Force to install the provider from a computer with an internet connection.

  2. After the install, you can find the provider installed in $env:ProgramFiles\PackageManagement\ReferenceAssemblies\\\<ProviderName\>\\\<ProviderVersion\> or $env:LOCALAPPDATA\PackageManagement\ProviderAssemblies\\\<ProviderName\>\\\<ProviderVersion\>.

  3. Place the folder, which in this case is the Nuget folder, in the corresponding location on your target computer. If your target computer is a Nano server, you need to run Install-PackageProvider from Nano Server to download the correct Nuget binaries.

  4. Restart PowerShell to auto-load the package provider. Alternatively, run Get-PackageProvider -ListAvailable to list all the package providers available on the computer. Then use Import-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201 to import the provider to the current Windows PowerShell session.

What is the $$hashKey added to my JSON.stringify result

Angular adds this to keep track of your changes, so it knows when it needs to update the DOM.

If you use angular.toJson(obj) instead of JSON.stringify(obj) then Angular will strip out these internal-use values for you.

Also, if you change your repeat expression to use the track by {uniqueProperty} suffix, Angular won't have to add $$hashKey at all. For example

<ul>
    <li ng-repeat="link in navLinks track by link.href">
        <a ng-href="link.href">{{link.title}}</a>
    </li>
</ul>

Just always remember you need the "link." part of the expression - I always tend to forget that. Just track by href will surely not work.

VB.NET: Clear DataGridView

Can you not bind the datagridview to an empty collection (instead of null). That do the trick?

How to restart a node.js server

I had the same problem and then wrote this shell script which kills all of the existing node processes:

#!/bin/bash
echo "The following node processes were found:"
ps aux | grep " node " | grep -v grep
nodepids=$(ps aux | grep " node " | grep -v grep | cut -c10-15)

echo "OK, so we will stop these process/es now..."

for nodepid in ${nodepids[@]}
do
echo "Stopping PID :"$nodepid
kill -9 $nodepid
done
echo "Done"

After this is saved as a shell script (xxx.sh) file you might want to add it to your PATH as described here.

(Please note that this will kill all of the processes with " node " in it's name except grep's own, so I guess in some cases it may also kill some other processes with a similar name)

What is "git remote add ..." and "git push origin master"?

Update: note that the currently accepted answer perpetuates a common misunderstanding about the behaviour of git push, which hasn't been corrected despite a comment pointing it out.

Your summary of what remotes are - like a nickname for the URL of a repository - is correct.

So why does the URL not git://[email protected]/peter/first_app.git but in the other syntax -- what syntax is it? Why must it end with .git? I tried not using .git at the end and it works too. If not .git, what else can it be? The git at the beginner seems to be a user account on the git server?

The two URLs that you've mentioned indicate that two different transport protocols should be used. The one beginning with git:// is for the git protocol, which is usually only used for read-only access to repositories. The other one, [email protected]:peter/first_app.git, is one of the different ways of specifying access to a repository over SSH - this is the "scp-style syntax" described in the documentation. That the username in the scp-style syntax is git is because of the way that GitHub deals with identifying users - essentially that username is ignored, and the user is identified based on the SSH key-pair that they used to authenticate.

As for the verbosity of git push origin master, you've noticed that after the first push, you can then just do git push. This is because of a series of difficult-to-remember-but-generally-helpful defaults :)

  • If no remote is specified, the remote configured for the current branch (in remote.master.url in your case) is used. If that's not set up, then origin is used.
  • If there's no "refspec" (e.g. master, master:my-experiment, etc.) specified, then git defaults to pushing every local branch that has the same name as a branch on the remote. If you just have a branch called master in common between your repository and the remote one, that'll be the same as pushing your master to the remote master.

Personally, since I tend to have many topic branches (and often several remotes) I always use the form:

git push origin master

... to avoid accidentally pushing other branches.


In reply to your comments on one of the other answers, it sounds to me as if are learning about git in a top-down way very effectively - you've discovered that the defaults work, and your question is asking about why ;) To be more serious, git can be used essentially as simply as SVN, but knowing a bit about remotes and branches means you can use it much more flexibily and this can really change the way you work for the better. Your remark about a semester course makes me think of something Scott Chacon said in a podcast interview - students are taught about all kinds of basic tools in computer science and software engineering, but very rarely version control. Distributed version control systems such as git and Mercurial are now so important, and so flexible, that it would be worth teaching courses on them to give people a good grounding.

My view is that with git, this learning curve is absolutely worth it - working with lots of topic branches, merging them easily, and pushing and pulling them about between different repositories is fantastically useful once you become confident with the system. It's just unfortunate that:

  • The primary documentation for git is so hard to parse for newcomers. (Although I'd argue that if you Google for almost any git question, helpful tutorial material (or Stack Overflow answers :)) come up nowadays.)
  • There are a few odd behaviours in git that are hard to change now because many scripts may rely on them, but are confusing to people.

How to create dictionary and add key–value pairs dynamically?

You could create a class Dictionary so you can interact with the Dictionary list easily:

_x000D_
_x000D_
class Dictionary {_x000D_
  constructor() {_x000D_
    this.items = {};_x000D_
  }_x000D_
  has(key) {_x000D_
    return key in this.items;_x000D_
  }_x000D_
  set(key,value) {_x000D_
    this.items[key] = value;_x000D_
  }_x000D_
  delete(key) {_x000D_
    if( this.has(key) ){_x000D_
      delete this.items[key]_x000D_
      return true;_x000D_
    }_x000D_
    return false;_x000D_
  }_x000D_
}_x000D_
_x000D_
var d = new Dictionary();_x000D_
d.set(1, "value1")_x000D_
d.set(2, "value2")_x000D_
d.set(3, "value3")_x000D_
console.log(d.has(2));_x000D_
d.delete(2);_x000D_
console.log(d.has(2));
_x000D_
_x000D_
_x000D_

Taskkill /f doesn't kill a process

If taskkill /F /T /PID <pid> does not work. Try opening your terminal elevated using Run as Administrator.

Search cmd in your windows menu, and right click Run as Administrator, then run the command again. This worked for me.

How to remove the bottom border of a box with CSS

You could just set the width to auto. Then the width of the div will equal 0 if it has no content.

width:auto;

Eclipse error "Could not find or load main class"

I faced similar problem in my maven webapp project after spending nearly one hour , I found a solution which worked for me .I typed the following maven command and It worked

mvn clean install -U
I dont know the exact reason behind it.

How to return a value from try, catch, and finally?

The problem is what happens when you get NumberFormatexception thrown? You print it and return nothing.

Note: You don't need to catch and throw an Exception back. Usually it is done to wrap it or print stack trace and ignore for example.

catch(RangeException e) {
     throw e;
}

How to debug Javascript with IE 8

You can get more information about IE8 Developer Toolbar debugging at Debugging JScript or Debugging Script with the Developer Tools.

Group by in LINQ

You can also Try this:

var results= persons.GroupBy(n => new { n.PersonId, n.car})
                .Select(g => new {
                               g.Key.PersonId,
                               g.Key.car)}).ToList();

C# Timer or Thread.Sleep

I have used both timers and Thread.Sleep(x), or either, depending on the situation.

If I have a short piece of code that needs to run repeadedly, I probably use a timer.

If I have a piece of code that might take longer to run than the delay timer (such as retrieving files from a remote server via FTP, where I don't control or know the network delay or file sizes / count), I will wait for a fixed period of time between cycles.

Both are valid, but as pointed out earlier they do different things. The timer runs your code every x milliseconds, even if the previous instance hasn't finished. The Thread.Sleep(x) waits for a period of time after completing each iteration, so the total delay per loop will always be longer (perhaps not by much) than the sleep period.

Regular expression to stop at first match

You need to make your regular expression non-greedy, because by default, "(.*)" will match all of "file path/level1/level2" xxx some="xxx".

Instead you can make your dot-star non-greedy, which will make it match as few characters as possible:

/location="(.*?)"/

Adding a ? on a quantifier (?, * or +) makes it non-greedy.

Adjust UILabel height to text

Here is how to calculate the text height in Swift. You can then get the height from the rect and set the constraint height of the label or textView, etc.

let font = UIFont(name: "HelveticaNeue", size: 25)!
let text = "This is some really long text just to test how it works for calculating heights in swift of string sizes. What if I add a couple lines of text?"

let textString = text as NSString

let textAttributes = [NSFontAttributeName: font]

let textRect = textString.boundingRectWithSize(CGSizeMake(320, 2000), options: .UsesLineFragmentOrigin, attributes: textAttributes, context: nil)

Declare variable in SQLite and use it

Herman's solution worked for me, but the ... had me mixed up for a bit. I'm including the demo I worked up based on his answer. The additional features in my answer include foreign key support, auto incrementing keys, and use of the last_insert_rowid() function to get the last auto generated key in a transaction.

My need for this information came up when I hit a transaction that required three foreign keys but I could only get the last one with last_insert_rowid().

PRAGMA foreign_keys = ON;   -- sqlite foreign key support is off by default
PRAGMA temp_store = 2;      -- store temp table in memory, not on disk

CREATE TABLE Foo(
    Thing1 INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
);

CREATE TABLE Bar(
    Thing2 INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    FOREIGN KEY(Thing2) REFERENCES Foo(Thing1)
);

BEGIN TRANSACTION;

CREATE TEMP TABLE _Variables(Key TEXT, Value INTEGER);

INSERT INTO Foo(Thing1)
VALUES(2);

INSERT INTO _Variables(Key, Value)
VALUES('FooThing', last_insert_rowid());

INSERT INTO Bar(Thing2)
VALUES((SELECT Value FROM _Variables WHERE Key = 'FooThing'));

DROP TABLE _Variables;

END TRANSACTION;

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

A very simple example is that if you have a UserService that has @Autowired jpa resposiroty UserRepository

...
class UserService{

  @Autowired
  UserRepository userRepository;
...
}

then in the test class for UserService you will do

...
class TestUserService{
  @Mock 
  UserRepository userRepository;

  @InjectMocks
  UserService userService;

...
}

@InjectMocks tells the framework that take the @Mock UserRepository userRespository; and inject that into userService so rather than auto wiring a real instance of UserRepository a Mock of UserRepository will be injected in userService.

Set Radiobuttonlist Selected from Codebehind

Try this option:

radio1.Items.FindByValue("1").Selected = true;

How to plot two columns of a pandas data frame using points?

Now in latest pandas you can directly use df.plot.scatter function

df = pd.DataFrame([[5.1, 3.5, 0], [4.9, 3.0, 0], [7.0, 3.2, 1],
                   [6.4, 3.2, 1], [5.9, 3.0, 2]],
                  columns=['length', 'width', 'species'])
ax1 = df.plot.scatter(x='length',
                      y='width',
                      c='DarkBlue')

https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.DataFrame.plot.scatter.html

Inserting a blank table row with a smaller height

You don't need an extra table row to create space inside a table. See this jsFiddle.
(I made the gap light grey in colour, so you can see it, but you can change that to transparent.)

Using a table row just for display purposes is table abuse!

How to reload apache configuration for a site without restarting apache?

If you are using Ubuntu server, you can use systemctl

systemctl reload apache2

NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext

After exiting eclipse I moved .eclipse (found in the user's home directory) to .eclipse.old (just in case I may have had to undo). The error does not show up any more and my projects are working fine after restarting eclipse.

Caution: I have a simple setup and this may not be the best for environments with advanced settings.

I am posting this as a separate answer as previously listed methods did not work for me.

How to get JS variable to retain value after page refresh?

In addition to cookies and localStorage, there's at least one other place you can store "semi-persistent" client data: window.name. Any string value you assign to window.name will stay there until the window is closed.

To test it out, just open the console and type window.name = "foo", then refresh the page and type window.name; it should respond with foo.

This is a bit of a hack, but if you don't want cookies filled with unnecessary data being sent to the server with every request, and if you can't use localStorage for whatever reason (legacy clients), it may be an option to consider.

window.name has another interesting property: it's visible to windows served from other domains; it's not subject to the same-origin policy like nearly every other property of window. So, in addition to storing "semi-persistent" data there while the user navigates or refreshes the page, you can also use it for CORS-free cross-domain communication.

Note that window.name can only store strings, but with the wide availability of JSON, this shouldn't be much of an issue even for complex data.

What is the LDF file in SQL Server?

The LDF is the transaction log. It keeps a record of everything done to the database for rollback purposes.

You do not want to delete, but you can shrink it with the dbcc shrinkfile command. You can also right-click on the database in SQL Server Management Studio and go to Tasks > Shrink.

python 2.7: cannot pip on windows "bash: pip: command not found"

On Windows, pip lives in C:\[pythondir]\scripts.

So you'll need to add that to your system path in order to run it from the command prompt. You could alternatively cd into that directory each time, but that's a hassle.

See the top answer here for info on how to do that: Adding Python Path on Windows 7

Also, that is a terrifying way to install pip. Grab it from Christophe Gohlke. Grab everything else from there for that matter. http://www.lfd.uci.edu/~gohlke/pythonlibs/

How do I check if an integer is even or odd?

One more solution to the problem
(children are welcome to vote)

bool isEven(unsigned int x)
{
  unsigned int half1 = 0, half2 = 0;
  while (x)
  {
     if (x) { half1++; x--; }
     if (x) { half2++; x--; }

  }
  return half1 == half2;
}

Selenium: Can I set any of the attribute value of a WebElement in Selenium?

I have created this jquery that solved my problem.

public void ChangeClassIntoSelected(String name,String div) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("Array.from($(\"div." + div +" ul[name=" + name + "]\")[0].children).forEach((element, index) => {\n" +
                "   $(element).addClass('ui-selected');\n" +
                "});");
    }

With this script you are able to change the actual class name into some other thing.

Using partial views in ASP.net MVC 4

You're passing the same model to the partial view as is being passed to the main view, and they are different types. The model is a DbSet of Notes, where you need to pass in a single Note.

You can do this by adding a parameter, which I'm guessing as it's the create form would be a new Note

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

How to completely hide the navigation bar in iPhone / HTML5

Remy Sharp has a good description of the process in his article "Doing it right: skipping the iPhone url bar":

Making the iPhone hide the url bar is fairly simple, you need run the following JavaScript:

window.scrollTo(0, 1); 

However there's the question of when? You have to do this once the height is correct so that the iPhone can scroll to the first pixel of the document, otherwise it will try, then the height will load forcing the url bar back in to view.

You could wait until the images have loaded and the window.onload event fires, but this doesn't always work, if everything is cached, the event fires too early and the scrollTo never has a chance to jump. Here's an example using window.onload: http://jsbin.com/edifu4/4/

I personally use a timer for 1 second - which is enough time on a mobile device while you wait to render, but long enough that it doesn't fire too early:

setTimeout(function () {   window.scrollTo(0, 1); }, 1000);

However, you only want this to setup if it's an iPhone (or just mobile) browser, so a sneaky sniff (I don't generally encourage this, but I'm comfortable with this to prevent "normal" desktop browsers from jumping one pixel):

/mobile/i.test(navigator.userAgent) && setTimeout(function
() {   window.scrollTo(0, 1); }, 1000); 

The very last part of this, and this is the part that seems to be missing from some examples I've seen around the web is this: if the user specifically linked to a url fragment, i.e. the url has a hash on it, you don't want to jump. So if I navigate to http://full-frontal.org/tickets#dayconf - I want the browser to scroll naturally to the element whose id is dayconf, and not jump to the top using scrollTo(0, 1):

/mobile/i.test(navigator.userAgent) && !location.hash &&
setTimeout(function () {   window.scrollTo(0, 1); }, 1000);?

Try this out on an iPhone (or simulator) http://jsbin.com/edifu4/10 and you'll see it will only scroll when you've landed on the page without a url fragment.

How to duplicate a git repository? (without forking)

I have noticed some of the other answers here use a bare clone and then mirror push to the new repository, however this does not work for me and when I open the new repository after that, the files look mixed up and not as I expect.

Here is a solution that definitely works for copying the files, although it does not preserve the original repository's revision history.

  1. git clone the repository onto your local machine.
  2. cd into the project directory and then run rm -rf .git to remove all the old git metadata including commit history, etc.
  3. Initialize a fresh git repository by running git init.
  4. Run git add . ; git commit -am "Initial commit" - Of course you can call this commit what you want.
  5. Set the origin to your new repository git remote add origin https://github.com/user/repo-name (replace the url with the url to your new repository)
  6. Push it to your new repository with git push origin master.

Git: Find the most recent common ancestor of two branches

As noted in a prior answer, although git merge-base works,

$ git merge-base myfeature develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

If myfeature is the current branch, as is common, you can use --fork-point:

$ git merge-base --fork-point develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

This argument works only in sufficiently recent versions of git. Unfortunately it doesn't always work, however, and it is not clear why. Please refer to the limitations noted toward the end of this answer.


For full commit info, consider:

$ git log -1 $(git merge-base --fork-point develop) 

How to copy a folder via cmd?

xcopy "%userprofile%\Desktop\?????????" "D:\Backup\" /s/h/e/k/f/c

should work, assuming that your language setting allows Cyrillic (or you use Unicode fonts in the console).

For reference about the arguments: http://ss64.com/nt/xcopy.html

How to position two divs horizontally within another div

This answer adds to the solutions above to address your last sentence that reads:

how do I ensure that sub-left and sub-right stay within sub-title

The problem is that as the content of sub-left or sub-right expands they will extend below sub-title. This behaviour is designed into CSS but does cause problems for most of us. The easiest solution is to have a div that is styled with the CSS Clear declaration.

To do this include a CSS statement to define a closing div (can be Clear Left or RIght rather than both, depending on what Float declarations have been used:

#sub_close {clear:both;}

And the HTML becomes:

<div id="sub-title">
<div id="sub-left">Right</div>
<div id="sub-right">Left</div>
<div id="sub-close"></div>
</div>

Sorry, just realized this was posted previously, shouldn't have made that cup of coffee while typing my reply!

@Darko Z: you are right, the best description for the overflow:auto (or overflow:hidden) solution that I have found was in a a post on SitePoint a while ago Simple Clearing of FLoats and there is also a good description in a 456bereastreet article CSS Tips and Tricks Part-2. Have to admit to being too lazy to implement these solutions myself, as the closing div cludge works OK although it is of course very inelegant. So will make an effort from now on to clean up my act.

How to properly seed random number generator

I tried the program below and saw different string each time

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func RandomString(count int){
  rand.Seed(time.Now().UTC().UnixNano()) 
  for(count > 0 ){
    x := Random(65,91)
    fmt.Printf("%c",x)
    count--;
  }
}

func Random(min, max int) (int){
 return min+rand.Intn(max-min) 
}

func main() {
 RandomString(12)
}

And the output on my console is

D:\james\work\gox>go run rand.go
JFBYKAPEBCRC
D:\james\work\gox>go run rand.go
VDUEBIIDFQIB
D:\james\work\gox>go run rand.go
VJYDQPVGRPXM

Using a custom typeface in Android

I use DataBinding for this (with Kotlin).


Set up BindingAdapter:

BindingAdapter.kt

import android.graphics.Typeface
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.databinding.BindingAdapter
import java.util.*


object BindingAdapters {


    @JvmStatic
    @BindingAdapter("typeface", "typefaceStyle")
    fun setTypeface(v: TextView, tf: Typeface?, style: Int?) {
        v.setTypeface(tf ?: Typeface.DEFAULT, style ?: Typeface.NORMAL)
    }
}

Usage:

fragment_custom_view.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <import type="android.graphics.Typeface" />

        <variable
            name="typeface"
            type="android.graphics.Typeface" />

    </data>


    <TextView
        android:id="@+id/reference"
        style="@style/TextAppearance.MaterialComponents.Body1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I'm formatted text"
        app:typeface="@{typeface}"
        app:typefaceStyle="@{Typeface.ITALIC}" />

</layout>

MyFragment.kt

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding = FragmentCustomView.bind(view)
        binding.typeface = // some code to get user selected typeface

}

Now, if the user selects a new typeface you can just update the binding value and all your TextViews that you've set app:typeface will get updated.

How to use default Android drawables

Better you copy and move them to your own resources. Some resources might not be available on previous Android versions. Here is a link with all drawables available on each Android version thanks to @fiXedd

MVC 4 Razor adding input type date

You will get it by tag type="date"...then it will render beautiful calendar and all...

@Html.TextBoxFor(model => model.EndTime, new { type = "date" })

npm throws error without sudo

On Mac OS X, when installing with Homebrew's brew install npm, the installation path is /usr/local/share/npm/ with both bin/ and lib/node_modules/ subfolders.

Running this command to change to owner to your currently logged in user should fix it all up, and allow you to install global NPM packages without sudo.

sudo chown -R $USER ~/.npm /usr/local/share/npm/

Concatenating two one-dimensional NumPy arrays

There are several possibilities for concatenating 1D arrays, e.g.,

numpy.r_[a, a],
numpy.stack([a, a]).reshape(-1),
numpy.hstack([a, a]),
numpy.concatenate([a, a])

All those options are equally fast for large arrays; for small ones, concatenate has a slight edge:

enter image description here

The plot was created with perfplot:

import numpy
import perfplot

perfplot.show(
    setup=lambda n: numpy.random.rand(n),
    kernels=[
        lambda a: numpy.r_[a, a],
        lambda a: numpy.stack([a, a]).reshape(-1),
        lambda a: numpy.hstack([a, a]),
        lambda a: numpy.concatenate([a, a]),
    ],
    labels=["r_", "stack+reshape", "hstack", "concatenate"],
    n_range=[2 ** k for k in range(19)],
    xlabel="len(a)",
)

Adding ID's to google map markers

Marker already has unique id

marker.__gm_id

Trusting all certificates using HttpClient over HTTPS

You can disable HttpURLConnection SSL checking for testing purposes this way since API 8:

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    if (conn instanceof HttpsURLConnection) {
        HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
        httpsConn.setSSLSocketFactory(SSLCertificateSocketFactory.getInsecure(0, null));
        httpsConn.setHostnameVerifier(new AllowAllHostnameVerifier());
    }

PHP: trying to create a new line with "\n"

PHP generates HTML. You may want:

echo "foo";
echo "<br />\n";
echo "bar";

Pandas: Appending a row to a dataframe and specify its index label

I shall refer to the same sample of data as posted in the question:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
print('The original data frame is: \n{}'.format(df))

Running this code will give you

The original data frame is:

          A         B         C         D
0  0.494824 -0.328480  0.818117  0.100290
1  0.239037  0.954912 -0.186825 -0.651935
2 -1.818285 -0.158856  0.359811 -0.345560
3 -0.070814 -0.394711  0.081697 -1.178845
4 -1.638063  1.498027 -0.609325  0.882594
5 -0.510217  0.500475  1.039466  0.187076
6  1.116529  0.912380  0.869323  0.119459
7 -1.046507  0.507299 -0.373432 -1.024795

Now you wish to append a new row to this data frame, which doesn't need to be copy of any other row in the data frame. @Alon suggested an interesting approach to use df.loc to append a new row with different index. The issue, however, with this approach is if there is already a row present at that index, it will be overwritten by new values. This is typically the case for datasets when row index is not unique, like store ID in transaction datasets. So a more general solution to your question is to create the row, transform the new row data into a pandas series, name it to the index you want to have and then append it to the data frame. Don't forget to overwrite the original data frame with the one with appended row. The reason is df.append returns a view of the dataframe and does not modify its contents. Following is the code:

row = pd.Series({'A':10,'B':20,'C':30,'D':40},name=3)
df = df.append(row)
print('The new data frame is: \n{}'.format(df))

Following would be the new output:

The new data frame is:

           A          B          C          D
0   0.494824  -0.328480   0.818117   0.100290
1   0.239037   0.954912  -0.186825  -0.651935
2  -1.818285  -0.158856   0.359811  -0.345560
3  -0.070814  -0.394711   0.081697  -1.178845
4  -1.638063   1.498027  -0.609325   0.882594
5  -0.510217   0.500475   1.039466   0.187076
6   1.116529   0.912380   0.869323   0.119459
7  -1.046507   0.507299  -0.373432  -1.024795
3  10.000000  20.000000  30.000000  40.000000

Ways to save enums in database

We just store the enum name itself - it's more readable.

We did mess around with storing specific values for enums where there are a limited set of values, e.g., this enum that has a limited set of statuses that we use a char to represent (more meaningful than a numeric value):

public enum EmailStatus {
    EMAIL_NEW('N'), EMAIL_SENT('S'), EMAIL_FAILED('F'), EMAIL_SKIPPED('K'), UNDEFINED('-');

    private char dbChar = '-';

    EmailStatus(char statusChar) {
        this.dbChar = statusChar;
    }

    public char statusChar() {
        return dbChar;
    }

    public static EmailStatus getFromStatusChar(char statusChar) {
        switch (statusChar) {
        case 'N':
            return EMAIL_NEW;
        case 'S':
            return EMAIL_SENT;
        case 'F':
            return EMAIL_FAILED;
        case 'K':
            return EMAIL_SKIPPED;
        default:
            return UNDEFINED;
        }
    }
}

and when you have a lot of values you need to have a Map inside your enum to keep that getFromXYZ method small.