Programs & Examples On #Figures

Is there a way to get LaTeX to place figures in the same page as a reference to that figure?

You can always add the "!" into your float-options. This way, latex tries really hard to place the figure where you want it (I mostly use [h!tb]), stretching the normal rules of type-setting.

I have found another solution:
Use the float-package. This way you can place the figures where you want them to be.

ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known

This was happening to me when trying to access Github. The problem is that I was in the habit of doing:

git remote add <xyz> ssh:\\[email protected]......

But, if you are having this error from the question, removing ssh:\\ may resolve the issue. It solved it for me!

Note that you will have to do a git remote remove <xyz> and re-add the remote url without ssh:\\.

Showing the stack trace from a running Python application

How to debug any function in console:

Create function where you use pdb.set_trace(), then function you want debug.

>>> import pdb
>>> import my_function

>>> def f():
...     pdb.set_trace()
...     my_function()
... 

Then call created function:

>>> f()
> <stdin>(3)f()
(Pdb) s
--Call--
> <stdin>(1)my_function()
(Pdb) 

Happy debugging :)

What are good message queue options for nodejs?

I used KUE with socketIO like you described. I stored the socketID with the job and could then retreive it in the Job Complete.. KUE is based on redis and has good examples on github

something like this....

jobs.process('YourQueuedJob',10, function(job, done){
    doTheJob(job, done);
});


function doTheJob(job, done){
    var socket = io.sockets.sockets[job.data.socketId];
    try {
        socket.emit('news', { status : 'completed' , task : job.data.task });
    } catch(err){
        io.sockets.emit('news', { status : 'fail' , task : job.data.task , socketId: job.data.socketId});
    }
    job.complete();
}

Connect Device to Mac localhost Server?

I had the same problem. I turned off my WI-FI on my Mac and then turned it on again, which solved the problem. Click Settings > Turn WI-FI Off.

I tested it by going to Safari on my iPhone and entering my host name or IP address. For example: http://<name>.local or http://10.0.1.5

Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

  1. Add ssh public key to Google cloud
  • cat ~/.ssh/id_rsa.pub
  • go and click your VM instances
  • edit VM instances
  • add ssh public key(from id_rsa.pub) in SSH keys area toptruyenfull.com enter image description here enter image description here enter image description here enter image description hereenter image description here
  1. ssh login from Git bash on your computer

    ssh -i ~/.ssh/id_rsa [email protected]

How can I view live MySQL queries?

Even though an answer has already been accepted, I would like to present what might even be the simplest option:

$ mysqladmin -u bob -p -i 1 processlist

This will print the current queries on your screen every second.

  • -u The mysql user you want to execute the command as
  • -p Prompt for your password (so you don't have to save it in a file or have the command appear in your command history)
  • i The interval in seconds.
  • Use the --verbose flag to show the full process list, displaying the entire query for each process. (Thanks, nmat)

There is a possible downside: fast queries might not show up if they run between the interval that you set up. IE: My interval is set at one second and if there is a query that takes .02 seconds to run and is ran between intervals, you won't see it.

Use this option preferably when you quickly want to check on running queries without having to set up a listener or anything else.

Programmatically Add CenterX/CenterY Constraints

A solution for me was to create a UILabel and add it to the UIButton as a subview. Finally I added a constraint to center it within the button.

UILabel * myTextLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 75, 75)];
myTextLabel.text = @"Some Text";
myTextLabel.translatesAutoresizingMaskIntoConstraints = false;

[myButton addSubView:myTextLabel];

// Add Constraints
[[myTextLabel centerYAnchor] constraintEqualToAnchor:myButton.centerYAnchor].active = true;
[[myTextLabel centerXAnchor] constraintEqualToAnchor:myButton.centerXAnchor].active = true; 

Tomcat is not running even though JAVA_HOME path is correct

I had Win 8 x86 installed. My Path variable had entry C:\Program Files\Java\jdk1.6.0_31\bin and I also had following variables:

  • JAVA_HOME : C:\Program Files\Java\jdk1.6.0_31;
  • JRE_HOME : C:\Program Files\Java\jre6;

My tomcat is installed at C:\Program Files\Apache Software Foundation\apache-tomcat-7.0.41

And still it did not worked for me.

I tried by replacing Program Files in those paths with Progra~1. I also tried by moving JAVA to another folder so that full path to it does not contain any spaces. But nothing worked.

Finally environment variables that worked for me are:

  • Kept path variable as is with full Program Files i.e. C:\Program Files\Java\jdk1.6.0_31\bin
  • JAVA_HOME : C:\Program Files\Java\jdk1.6.0_31
  • Deleted JRE_HOME

So what I did is removed JRE_HOME and removed semicolon at the end of JAVA_HOME. I think semicolon should not be an issue, though I removed it. I am giving these settings, since after a lot of googling nothing worked for me and suddenly these seem to work. You can replicate and see if it works for you.

This also worked for Win 7 x64, where

  • Path variable contained C:\Program Files (x86)\Java\jdk1.7.0_17\bin
  • JAVA_HOME is set to C:\Program Files (x86)\Java\jdk1.7.0_17 (without semicoln)

Please tell me why this worked, I know removing JRE_HOME was weird solution, but any guesses what difference it makes?

Select All as default value for Multivalue parameter

Using dataset with default values is one way, but you must use query for Available values and for Default Values, if values are hard coded in Available values tab, then you must define default values as expressions. Pictures should explain everything

Create Parameter (if not automaticly created)

Create Parameter

Define values - wrong way example

Define values - wrong way

Define values - correct way example

Define values - correct way

Set default values - you must define all default values reflecting available values to make "Select All" by default, if you won't define all only those defined will be selected by default.

Set default values

The Result

The result

One picture for Data type: Int

One picture for Data type Int

Try/catch does not seem to have an effect

In my case, it was because I was only catching specific types of exceptions:

try
  {
    get-item -Force -LiteralPath $Path -ErrorAction Stop

    #if file exists
    if ($Path -like '\\*') {$fileType = 'n'}  #Network
    elseif ($Path -like '?:\*') {$fileType = 'l'} #Local
    else {$fileType = 'u'} #Unknown File Type

  }
catch [System.UnauthorizedAccessException] {$fileType = 'i'} #Inaccessible
catch [System.Management.Automation.ItemNotFoundException]{$fileType = 'x'} #Doesn't Exist

Added these to handle additional the exception causing the terminating error, as well as unexpected exceptions

catch [System.Management.Automation.DriveNotFoundException]{$fileType = 'x'} #Doesn't Exist
catch {$fileType='u'} #Unknown

In Java, should I escape a single quotation mark (') in String (double quoted)?

It's best practice only to escape the quotes when you need to - if you can get away without escaping it, then do!

The only times you should need to escape are when trying to put " inside a string, or ' in a character:

String quotes = "He said \"Hello, World!\"";
char quote = '\'';

VSCode: How to Split Editor Vertically

The key bindings has been changed with version 1.20:

SHIFT+ALT+0 for Linux.

Presumably the same works for Windows also and CMD+OPT+0 for Mac.

Convert bytes to bits in python

Here how to do it using format()

print "bin_signedDate : ", ''.join(format(x, '08b') for x in bytevector)

It is important the 08b . That means it will be a maximum of 8 leading zeros be appended to complete a byte. If you don't specify this then the format will just have a variable bit length for each converted byte.

How to remove time portion of date in C# in DateTime object only?

If you want to remove part of time from a DateTime, try using this code:

DateTime dt = new DateTime();

dt = DateTime.Now; //ex: 31/1/2017 6:30:20 PM

TimeSpan remainingTime = new TimeSpan(0, dt.Hour - 5, dt.Minute - 29, dt.Second - 19);
dt=dt.Add(remainingTime);

label1.Text = dt.ToString("HH:mm:ss"); // must be HH not hh

the output : 01:01:01

dropping a global temporary table

-- First Truncate temporary table
SQL> TRUNCATE TABLE test_temp1;

-- Then Drop temporary table
SQL> DROP TABLE test_temp1;

Select and trigger click event of a radio button in jquery

My solution is a bit different:

$( 'input[name="your_radio_input_name"]:radio:first' ).click();

Checking that a List is not empty in Hamcrest

Create your own custom IsEmpty TypeSafeMatcher:

Even if the generics problems are fixed in 1.3 the great thing about this method is it works on any class that has an isEmpty() method! Not just Collections!

For example it will work on String as well!

/* Matches any class that has an <code>isEmpty()</code> method
 * that returns a <code>boolean</code> */ 
public class IsEmpty<T> extends TypeSafeMatcher<T>
{
    @Factory
    public static <T> Matcher<T> empty()
    {
        return new IsEmpty<T>();
    }

    @Override
    protected boolean matchesSafely(@Nonnull final T item)
    {
        try { return (boolean) item.getClass().getMethod("isEmpty", (Class<?>[]) null).invoke(item); }
        catch (final NoSuchMethodException e) { return false; }
        catch (final InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); }
    }

    @Override
    public void describeTo(@Nonnull final Description description) { description.appendText("is empty"); }
}

How to get UTC timestamp in Ruby?

if you need a human-readable timestamp (like rails migration has) ex. "20190527141340"

Time.now.utc.to_formatted_s(:number)  # using Rails

Time.now.utc.strftime("%Y%m%d%H%M%S") # using Ruby

In the shell, what does " 2>&1 " mean?

echo test > afile.txt

redirects stdout to afile.txt. This is the same as doing

echo test 1> afile.txt

To redirect stderr, you do:

echo test 2> afile.txt

>& is the syntax to redirect a stream to another file descriptor - 0 is stdin, 1 is stdout, and 2 is stderr.

You can redirect stdout to stderr by doing:

echo test 1>&2 # or echo test >&2

Or vice versa:

echo test 2>&1

So, in short... 2> redirects stderr to an (unspecified) file, appending &1 redirects stderr to stdout.

Angular and Typescript: Can't find names - Error: cannot find name

A known issue: https://github.com/angular/angular/issues/4902

Core reason: the .d.ts file implicitly included by TypeScript varies with the compile target, so one needs to have more ambient declarations when targeting es5 even if things are actually present in the runtimes (e.g. chrome). More on lib.d.ts

How can I see the current value of my $PATH variable on OS X?

for MacOS, make sure you know where the GO install

export GOPATH=/usr/local/go
PATH=$PATH:$GOPATH/bin

How to determine the current iPhone/device model?

You can use BDLocalizedDevicesModels framework to parse device info and get the name.

Then just call UIDevice.currentDevice.productName in your code.

UICollectionView - Horizontal scroll, horizontal layout?

You can write a custom UICollectionView layout to achieve this, here is demo image of my implementation:

demo image

Here's code repository: KSTCollectionViewPageHorizontalLayout

@iPhoneDev (this maybe help you too)

Use :hover to modify the css of another class?

You can do it by making the following CSS. you can put here the css you need to affect child class in case of hover on the root

_x000D_
_x000D_
.root:hover    .child {_x000D_
   _x000D_
}
_x000D_
_x000D_
_x000D_

IE Driver download location Link for Selenium

You can download IE Driver (both 32 and 64-bit) from Selenium official site: http://docs.seleniumhq.org/download/

32 bit Windows IE

64 bit Windows IE

IE Driver is also available in the following site:

http://selenium-release.storage.googleapis.com/index.html

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

Since the name is likely to change in future versions of Android (currently the latest is AppCompatActivity but it will probably change at some point), I believe a good thing to have is a class Activity that extends AppCompatActivity and then all your activities extend from that one. If tomorrow, they change the name to AppCompatActivity2 for instance you will have to change it just in one place.

How to increase the gap between text and underlining in CSS

This is what i use:

html:

<h6><span class="horizontal-line">GET IN</span> TOUCH</h6>

css:

.horizontal-line { border-bottom: 2px solid  #FF0000; padding-bottom: 5px; }

Detect backspace and del on "input" event?

$('div[contenteditable]').keydown(function(e) {
// trap the return key being pressed
if (e.keyCode === 13 || e.keyCode === 8)
{
    return false;
}
});

How to play .mp4 video in videoview in android?

In Kotlin you can do as

 val videoView = findViewById<VideoView>(R.id.videoView)

       // If url is from raw
   /* val url = "android.resource://" + packageName
        .toString() + "/" + R.raw.video*/

    // If url is from network
    val url = "http://www.servername.com/projects/projectname/videos/1361439400.mp4"

    val video =
        Uri.parse(url)
    videoView.setVideoURI(video)
    videoView.setOnPreparedListener{
        videoView.start()
    }

Android Relative Layout Align Center

You can use gravity with aligning top and bottom.

 android:gravity="center_vertical"
 android:layout_alignTop="@id/place_category_icon"
 android:layout_alignBottom="@id/place_category_icon"

jquery $(this).id return Undefined

$(this) and this aren't the same. The first represents a jQuery object wrapped around your element. The second is just your element. The id property exists on the element, but not the jQuery object. As such, you have a few options:

  1. Access the property on the element directly:

    this.id

  2. Access it from the jQuery object:

    $(this).attr("id")

  3. Pull the object out of jQuery:

    $(this).get(0).id; // Or $(this)[0].id

  4. Get the id from the event object:

    When events are raised, for instance a click event, they carry important information and references around with them. In your code above, you have a click event. This event object has a reference to two items: currentTarget and target.

    Using target, you can get the id of the element that raised the event. currentTarget would simply tell you which element the event is currently bubbling through. These are not always the same.

    $("#button").on("click", function(e){ console.log( e.target.id ) });

Of all of these, the best option is to just access it directly from this itself, unless you're engaged in a series of nested events, then it might be best to use the event object of each nested event (give them all unique names) to reference elements in higher or lower scopes.

Recyclerview and handling different type of row inflation

The trick is to create subclasses of ViewHolder and then cast them.

public class GroupViewHolder extends RecyclerView.ViewHolder {
    TextView mTitle;
    TextView mContent;
    public GroupViewHolder(View itemView) {
        super (itemView);
        // init views...
    }
}

public class ImageViewHolder extends RecyclerView.ViewHolder {
    ImageView mImage;
    public ImageViewHolder(View itemView) {
        super (itemView);
        // init views...
    }
}

private static final int TYPE_IMAGE = 1;
private static final int TYPE_GROUP = 2;  

And then, at runtime do something like this:

@Override
public int getItemViewType(int position) {
    // here your custom logic to choose the view type
    return position == 0 ? TYPE_IMAGE : TYPE_GROUP;
}

@Override
public void onBindViewHolder (ViewHolder viewHolder, int i) {

    switch (viewHolder.getItemViewType()) {

        case TYPE_IMAGE:
            ImageViewHolder imageViewHolder = (ImageViewHolder) viewHolder;
            imageViewHolder.mImage.setImageResource(...);
            break;

        case TYPE_GROUP:
            GroupViewHolder groupViewHolder = (GroupViewHolder) viewHolder;
            groupViewHolder.mContent.setText(...)
            groupViewHolder.mTitle.setText(...);
            break;
    }
}

Hope it helps.

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

The easiest and most reliable solution is to try and start a transaction and see it if succeeds. If some code already started a transaction but has not yet issued any DML, then the V$TRANSACTION view won't show anything.

In this example below, I handle the exception to raise a user-defined application error. To defer to an existing exception handler, just do a SET TRANSACTION and then immediately COMMIT to undo it.

DECLARE
    transaction_in_progress EXCEPTION;
    PRAGMA EXCEPTION_INIT(transaction_in_progress, -1453);
BEGIN
    SET TRANSACTION NAME 'CHECK_FOR_TRANSACTION_ALREADY_SET';
    COMMIT; -- end transaction
EXCEPTION
    WHEN transaction_in_progress THEN
        RAISE_APPLICATION_ERROR(-20000,'Transaction is already in progress');
END;
/

Swift alert view with OK and Cancel: which button tapped?

Updated for swift 3:

// function defination:

@IBAction func showAlertDialog(_ sender: UIButton) {
        // Declare Alert
        let dialogMessage = UIAlertController(title: "Confirm", message: "Are you sure you want to Logout?", preferredStyle: .alert)

        // Create OK button with action handler
        let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
             print("Ok button click...")
             self.logoutFun()
        })

        // Create Cancel button with action handlder
        let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in
            print("Cancel button click...")
        }

        //Add OK and Cancel button to dialog message
        dialogMessage.addAction(ok)
        dialogMessage.addAction(cancel)

        // Present dialog message to user
        self.present(dialogMessage, animated: true, completion: nil)
    }

// logoutFun() function definaiton :

func logoutFun()
{
    print("Logout Successfully...!")
}

Index inside map() function

Using Ramda:

import {addIndex, map} from 'ramda';

const list = [ 'h', 'e', 'l', 'l', 'o'];
const mapIndexed = addIndex(map);
mapIndexed((currElement, index) => {
  console.log("The current iteration is: " + index);
  console.log("The current element is: " + currElement);
  console.log("\n");
  return 'X';
}, list);

How to convert a datetime to string in T-SQL

There are 3 different methods depending on what I is my requirement and which version I am using.

Here are the methods..

1) Using Convert

DECLARE @DateTime DATETIME = GETDATE();
--Using Convert
SELECT
    CONVERT(NVARCHAR, @DateTime,120) AS 'myDateTime'
    ,CONVERT(NVARCHAR(10), @DateTime, 120) AS 'myDate'
    ,RIGHT(CONVERT(NVARCHAR, @DateTime, 120),8) AS 'myTime'

2) Using Cast (SQL Server 2008 and beyond)

SELECT
    CAST(@DateTime AS DATETIME2) AS 'myDateTime'
    ,CAST(@DateTime AS DATETIME2(3)) AS 'myDateTimeWithPrecision'
    ,CAST(@DateTime AS DATE) AS 'myDate'
    ,CAST(@DateTime AS TIME) AS 'myTime'
    ,CAST(@DateTime AS TIME(3)) AS 'myTimeWithPrecision'

3) Using Fixed-length character data type

DECLARE @myDateTime NVARCHAR(20) = CONVERT(NVARCHAR, @DateTime, 120);
DECLARE @myDate NVARCHAR(10) = CONVERT(NVARCHAR, @DateTime, 120);

SELECT
    @myDateTime AS 'myDateTime'
    ,@myDate AS 'myDate'

How to ignore ansible SSH authenticity checking?

Changing host_key_checking to false for all hosts is a very bad idea.

The only time you want to ignore it, is on "first contact", which these two tasks will accomplish:

    - name: Check SSH known_hosts for {{ inventory_hostname }}
      local_action: shell ssh-keygen -F {{ inventory_hostname }}
      register: checkForKnownHostsEntry
      failed_when: false
      changed_when: false
      ignore_errors: yes
    - name: Add {{ inventory_hostname }} to SSH known hosts automatically
      when: checkForKnownHostsEntry.rc == 1
      changed_when: checkForKnownHostsEntry.rc == 1
      set_fact:
        ansible_ssh_common_args: '-o StrictHostKeyChecking=no'

So we only turn off host key checking if we don't have the host key in our known_hosts file.

Convert a character digit to the corresponding integer in C

Check this,

char s='A';

int i = (s<='9')?(s-'0'):(s<='F')?((s-'A')+10):((s-'a')+10);

for only 0,1,2,....,E,F.

SQL Current month/ year question

This should work for SQL Server:

SELECT * FROM myTable
WHERE month = DATEPART(m, GETDATE()) AND
year = DATEPART(yyyy, GETDATE())

Does a `+` in a URL scheme/host/path represent a space?

Space characters may only be encoded as "+" in one context: application/x-www-form-urlencoded key-value pairs.

The RFC-1866 (HTML 2.0 specification), paragraph 8.2.1. subparagraph 1. says: "The form field names and values are escaped: space characters are replaced by `+', and then reserved characters are escaped").

Here is an example of such a string in URL where RFC-1866 allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses (in other cases, spaces should be encoded to %20). This way of encoding form data is also given in later HTML specifications, for example, look for relevant paragraphs about application/x-www-form-urlencoded in HTML 4.01 Specification, and so on.

But, because it's hard to always correctly determine the context, it's the best practice to never encode spaces as "+". It's better to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3. Here is a code example that illustrates what should be encoded. It is given in Delphi (pascal) programming language, but it is very easy to understand how it works for any programmer regardless of the language possessed:

(* percent-encode all unreserved characters as defined in RFC-3986, p.2.3 *)
function UrlEncodeRfcA(const S: AnsiString): AnsiString;
const    
  HexCharArrA: array [0..15] of AnsiChar = '0123456789ABCDEF';
var
  I: Integer;
  c: AnsiChar;
begin
 // percent-encoding, see RFC-3986, p. 2.1
  Result := S;
  for I := Length(S) downto 1 do
  begin
    c := S[I];
    case c of
      'A' .. 'Z', 'a' .. 'z', // alpha
      '0' .. '9',             // digit
      '-', '.', '_', '~':;    // rest of unreserved characters as defined in the RFC-3986, p.2.3
      else
        begin
          Result[I] := '%';
          Insert('00', Result, I + 1);
          Result[I + 1] := HexCharArrA[(Byte(C) shr 4) and $F)];
          Result[I + 2] := HexCharArrA[Byte(C) and $F];
        end;
    end;
  end;
end;

function UrlEncodeRfcW(const S: UnicodeString): AnsiString;
begin
  Result := UrlEncodeRfcA(Utf8Encode(S));
end;

How to create an integer array in Python?

Use the array module. With it you can store collections of the same type efficiently.

>>> import array
>>> import itertools
>>> a = array_of_signed_ints = array.array("i", itertools.repeat(0, 10))

For more information - e.g. different types, look at the documentation of the array module. For up to 1 million entries this should feel pretty snappy. For 10 million entries my local machine thinks for 1.5 seconds.

The second parameter to array.array is a generator, which constructs the defined sequence as it is read. This way, the array module can consume the zeros one-by-one, but the generator only uses constant memory. This generator does not get bigger (memory-wise) if the sequence gets longer. The array will grow of course, but that should be obvious.

You use it just like a list:

>>> a.append(1)
>>> a.extend([1, 2, 3])
>>> a[-4:]
array('i', [1, 1, 2, 3])
>>> len(a)
14

...or simply convert it to a list:

>>> l = list(a)
>>> len(l)
14

Surprisingly

>>> a = [0] * 10000000

is faster at construction than the array method. Go figure! :)

How do I get a button to open another activity?

Write code on xml file.

<Button android:width="wrap_content"
        android:height="wrap_content"
        android:id="@+id/button"
        android:text="Click"/>

Write Code in your java file

Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            startActivity(new Intent(getApplicationContext(),Secondclass.class));
           /* if you want to finish the first activity then just call
            finish(); */
        }
    });

Auto code completion on Eclipse

Now in eclipse Neon this feature is present. No need of any special settings or configuation .On Ctrl+Space the code suggestion is available

Script to get the HTTP status code of a list of urls?

This relies on widely available wget, present almost everywhere, even on Alpine Linux.

wget --server-response --spider --quiet "${url}" 2>&1 | awk 'NR==1{print $2}'

The explanations are as follow :

--quiet

Turn off Wget's output.

Source - wget man pages

--spider

[ ... ] it will not download the pages, just check that they are there. [ ... ]

Source - wget man pages

--server-response

Print the headers sent by HTTP servers and responses sent by FTP servers.

Source - wget man pages

What they don't say about --server-response is that those headers output are printed to standard error (sterr), thus the need to redirect to stdin.

The output sent to standard input, we can pipe it to awk to extract the HTTP status code. That code is :

  • the second ($2) non-blank group of characters: {$2}
  • on the very first line of the header: NR==1

And because we want to print it... {print $2}.

wget --server-response --spider --quiet "${url}" 2>&1 | awk 'NR==1{print $2}'

How to define a circle shape in an Android XML drawable file?

This is a simple circle as a drawable in Android.

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

   <solid 
       android:color="#666666"/>

   <size 
       android:width="120dp"
        android:height="120dp"/>
</shape>

How do I choose grid and block dimensions for CUDA kernels?

The blocksize is usually selected to maximize the "occupancy". Search on CUDA Occupancy for more information. In particular, see the CUDA Occupancy Calculator spreadsheet.

Unable to add window -- token null is not valid; is your activity running?

If you use another view make sure to use view.getContext() instead of this or getApplicationContext()

iOS Swift - Get the Current Local Time and Date Timestamp

First I would recommend you to store your timestamp as a NSNumber in your Firebase Database, instead of storing it as a String.

Another thing worth mentioning here, is that if you want to manipulate dates with Swift, you'd better use Date instead of NSDate, except if you're interacting with some Obj-C code in your app.

You can of course use both, but the Documentation states:

Date bridges to the NSDate class. You can use these interchangeably in code that interacts with Objective-C APIs.

Now to answer your question, I think the problem here is because of the timezone.

For example if you print(Date()), as for now, you would get:

2017-09-23 06:59:34 +0000

This is the Greenwich Mean Time (GMT).

So depending on where you are located (or where your users are located) you need to adjust the timezone before (or after, when you try to access the data for example) storing your Date:

    let now = Date()

    let formatter = DateFormatter()

    formatter.timeZone = TimeZone.current

    formatter.dateFormat = "yyyy-MM-dd HH:mm"

    let dateString = formatter.string(from: now)

Then you have your properly formatted String, reflecting the current time at your location, and you're free to do whatever you want with it :) (convert it to a Date / NSNumber, or store it directly as a String in the database..)

How do I check for null values in JavaScript?

Strict equality operator:-

We can check null by ===

if ( value === null ){

}

Just by using if

if( value ) {

}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • false
  • 0

Reading a plain text file in Java

Using BufferedReader:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

BufferedReader br;
try {
    br = new BufferedReader(new FileReader("/fileToRead.txt"));
    try {
        String x;
        while ( (x = br.readLine()) != null ) {
            // Printing out each line in the file
            System.out.println(x);
        }
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}
catch (FileNotFoundException e) {
    System.out.println(e);
    e.printStackTrace();
}

Ignore 'Security Warning' running script from command line

To avoid warnings, you can:

Set-ExecutionPolicy bypass

Spring MVC: How to return image in @ResponseBody?

In addition to registering a ByteArrayHttpMessageConverter, you may want to use a ResponseEntity instead of @ResponseBody. The following code works for me :

@RequestMapping("/photo2")
public ResponseEntity<byte[]> testphoto() throws IOException {
    InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_PNG);

    return new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, HttpStatus.CREATED);
}

Zooming MKMapView to fit annotation pins?

Swift 3 This is de correct way for fit all annotations in map.

func zoomMapaFitAnnotations() {

        var zoomRect = MKMapRectNull
        for annotation in mapview.annotations {

            let annotationPoint = MKMapPointForCoordinate(annotation.coordinate)

            let pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0)

            if (MKMapRectIsNull(zoomRect)) {
                zoomRect = pointRect
            } else {
                zoomRect = MKMapRectUnion(zoomRect, pointRect)
            }
        }
        self.mapview.setVisibleMapRect(zoomRect, edgePadding: UIEdgeInsetsMake(50, 50, 50, 50), animated: true)

    }

Can a class member function template be virtual?

Templates are all about the compiler generating code at compile-time. Virtual functions are all about the run-time system figuring out which function to call at run-time.

Once the run-time system figured out it would need to call a templatized virtual function, compilation is all done and the compiler cannot generate the appropriate instance anymore. Therefore you cannot have virtual member function templates.

However, there are a few powerful and interesting techniques stemming from combining polymorphism and templates, notably so-called type erasure.

Carriage return and Line feed... Are both required in C#?

I know this is a little old, but for anyone stumbling across this page should know there is a difference between \n and \r\n.

The \r\n gives a CRLF end of line and the \n gives an LF end of line character. There is very little difference to the eye in general.

Create a .txt from the string and then try and open in notepad (normal not notepad++) and you will notice the difference

SHA,PCT,PRACTICE,BNF CODE,BNF NAME,ITEMS,NIC,ACT COST,QUANTITY,PERIOD
Q44,01C,N81002,0101021B0AAALAL,Sod Algin/Pot Bicarb_Susp S/F,3,20.48,19.05,2000,201901
Q44,01C,N81002,0101021B0AAAPAP,Sod Alginate/Pot Bicarb_Tab Chble 500mg,1,3.07,2.86,60,201901

The above is using 'CRLF' and the below is what 'LF only' would look like (There is a character that cant be seen where the LF shows).

SHA,PCT,PRACTICE,BNF CODE,BNF NAME,ITEMS,NIC,ACT COST,QUANTITY,PERIODQ44,01C,N81002,0101021B0AAALAL,Sod Algin/Pot Bicarb_Susp S/F,3,20.48,19.05,2000,201901Q44,01C,N81002,0101021B0AAAPAP,Sod Alginate/Pot Bicarb_Tab Chble 500mg,1,3.07,2.86,60,201901

If the Line Ends need to be corrected and the file is small enough in size, you can change the line endings in NotePad++ (or paste into word then back into Notepad - although this will make CRLF only).

This may cause some functions that read these files to potenitially no longer function (The example lines given are from GP Prescribing data - England. The file has changed from a CRLF Line end to an LF line end). This stopped an SSIS job from running and failed as couldn't read the LF line endings.

Source of Line Ending Information: https://en.wikipedia.org/wiki/Newline#Representations_in_different_character_encoding_specifications

Hope this helps someone in future :) CRLF = Windows based, LF or CF are from Unix based systems (Linux, MacOS etc.)

Convert string to variable name in python

You can use a Dictionary to keep track of the keys and values.

For instance...

dictOfStuff = {} ##Make a Dictionary

x = "Buffalo" ##OR it can equal the input of something, up to you.

dictOfStuff[x] = 4 ##Get the dict spot that has the same key ("name") as what X is equal to. In this case "Buffalo". and set it to 4. Or you can set it to  what ever you like

print(dictOfStuff[x]) ##print out the value of the spot in the dict that same key ("name") as the dictionary.

A dictionary is very similar to a real life dictionary. You have a word and you have a definition. You can look up the word and get the definition. So in this case, you have the word "Buffalo" and it's definition is 4. It can work with any other word and definition. Just make sure you put them into the dictionary first.

Where to put the gradle.properties file

Actually there are 3 places where gradle.properties can be placed:

  1. Under gradle user home directory defined by the GRADLE_USER_HOME environment variable, which if not set defaults to USER_HOME/.gradle
  2. The sub-project directory (myProject2 in your case)
  3. The root project directory (under myProject)

Gradle looks for gradle.properties in all these places while giving precedence to properties definition based on the order above. So for example, for a property defined in gradle user home directory (#1) and the sub-project (#2) its value will be taken from gradle user home directory (#1).

You can find more details about it in gradle documentation here.

How to run a JAR file

You have to add a manifest to the jar, which tells the java runtime what the main class is. Create a file 'Manifest.mf' with the following content:

Manifest-Version: 1.0
Main-Class: your.programs.MainClass

Change 'your.programs.MainClass' to your actual main class. Now put the file into the Jar-file, in a subfolder named 'META-INF'. You can use any ZIP-utility for that.

How to set a Postgresql default value datestamp like 'YYYYMM'?

Thanks for everyone who answered, and thanks for those who gave me the function-format idea, i'll really study it for future using.

But for this explicit case, the 'special yyyymm field' is not to be considered as a date field, but just as a tag, o whatever would be used for matching the exactly year-month researched value; there is already another date field, with the full timestamp, but if i need all the rows of january 2008, i think that is faster a select like

SELECT  [columns] FROM table WHERE yearmonth = '200801'

instead of

SELECT  [columns] FROM table WHERE date BETWEEN DATE('2008-01-01') AND DATE('2008-01-31')

How to run (not only install) an android application using .apk file?

I put this in my makefile, right the next line after adb install ...

adb shell monkey -p `cat .identifier` -c android.intent.category.LAUNCHER 1

For this to work there must be a .identifier file with the app's bundle identifier in it, like com.company.ourfirstapp

No need to hunt activity name.

Changing three.js background to transparent or other color

For transparency, this is also mandatory: renderer = new THREE.WebGLRenderer( { alpha: true } ) via Transparent background with three.js

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

The best answer I have ever seen is How to run 32-bit applications on Ubuntu 64-bit?

sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386
sudo ./adb

Laravel 5 Application Key

From the line

'key' => env('APP_KEY', 'SomeRandomString'),

APP_KEY is a global environment variable that is present inside the .env file.

You can replace the application key if you trigger

php artisan key:generate

command. This will always generate the new key.

The output may be like this:


Application key [Idgz1PE3zO9iNc0E3oeH3CHDPX9MzZe3] set successfully.

Application key [base64:uynE8re8ybt2wabaBjqMwQvLczKlDSQJHCepqxmGffE=] set successfully.

Base64 encoding should be the default in Laravel 5.4

Note that when you first create your Laravel application, key:generate is automatically called.

If you change the key be aware that passwords saved with Hash::make() will no longer be valid.

how to release localhost from Error: listen EADDRINUSE

To kill node server first run this command in your terminal :

  1. top
  2. open another window then copy the server id from the previous window: PID number -9 kill so now you killed your node server try again to run your app.

Missing MVC template in Visual Studio 2015

I'm going to add my 2 cents in case someone finds himself in a position like mine. I too was looking for an MVC project type and could not see it. All I saw is a "Web Application Project". So I freaked out and rushed into trying all solutions listed on this page.

But.

IT IS ACTUALLY THERE.

enter image description here

Just go with the "Web application" project and it will give you the MVC option on the next step.

How to change indentation mode in Atom?

See Soft Tabs and Tab Length under Settings > Editor Settings.

To toggle indentation modes quickly you can use Ctrl-Shift-P and search for Editor: Toggle Soft Tabs.

Relative imports - ModuleNotFoundError: No module named x

Setting PYTHONPATH can also help with this problem.

Here is how it can be done on Windows

set PYTHONPATH=.

Iframe transparent background

I've used this creating an IFrame through Javascript and it worked for me:

// IFrame points to the IFrame element, obviously
IFrame.src = 'about: blank';
IFrame.style.backgroundColor = "transparent";
IFrame.frameBorder = "0";
IFrame.allowTransparency="true";

Not sure if it makes any difference, but I set those properties before adding the IFrame to the DOM. After adding it to the DOM, I set its src to the real URL.

Python: Removing spaces from list objects

Strings in Python are immutable (meaning that their data cannot be modified) so the replace method doesn't modify the string - it returns a new string. You could fix your code as follows:

for i in hello:
    j = i.replace(' ','')
    k.append(j)

However a better way to achieve your aim is to use a list comprehension. For example the following code removes leading and trailing spaces from every string in the list using strip:

hello = [x.strip(' ') for x in hello]

passing object by reference in C++

What seems to be confusing you is the fact that functions that are declared to be pass-by-reference (using the &) aren't called using actual addresses, i.e. &a.

The simple answer is that declaring a function as pass-by-reference:

void foo(int& x);

is all we need. It's then passed by reference automatically.

You now call this function like so:

int y = 5;
foo(y);

and y will be passed by reference.

You could also do it like this (but why would you? The mantra is: Use references when possible, pointers when needed) :

#include <iostream>
using namespace std;

class CDummy {
public:
    int isitme (CDummy* param);
};


int CDummy::isitme (CDummy* param)
{
    if (param == this) return true;
    else return false;
}

int main () {
    CDummy a;
    CDummy* b = &a;             // assigning address of a to b
    if ( b->isitme(&a) )        // Called with &a (address of a) instead of a
        cout << "yes, &a is b";
    return 0;
}

Output:

yes, &a is b

how to set value of a input hidden field through javascript?

Your code for setting value for hidden input is correct. Here is the example. Maybe you have some conditions in your if statements that are not allowing your scripts to execute.

How to create empty data frame with column names specified in R?

Perhaps:

> data.frame(aname=NA, bname=NA)[numeric(0), ]
[1] aname bname
<0 rows> (or 0-length row.names)

Change Default branch in gitlab

In Gitlab CE 9.0, You can change the default branch from the Settings Tab in a repository's header.

How do I remove a property from a JavaScript object?

I have used lodash "unset" to make it happen for nested object also.. only this need to write small logic to get path of property key which expected by omit method.

  1. Method which returns property path as array

_x000D_
_x000D_
var a = {"bool":{"must":[{"range":{"price_index.final_price":{"gt":"450","lt":"500"}}},{"bool":{"should":[{"term":{"color_value.keyword":"Black"}}]}}]}};_x000D_
_x000D_
function getPathOfKey(object,key,currentPath, t){_x000D_
     var currentPath = currentPath || [];_x000D_
_x000D_
    for(var i in object){_x000D_
  if(i == key){_x000D_
        t = currentPath;_x000D_
      }_x000D_
      else if(typeof object[i] == "object"){_x000D_
        currentPath.push(i)_x000D_
       return getPathOfKey(object[i], key,currentPath)_x000D_
      }_x000D_
    }_x000D_
 t.push(key);_x000D_
    return t;_x000D_
}_x000D_
document.getElementById("output").innerHTML =JSON.stringify(getPathOfKey(a,"price_index.final_price"))
_x000D_
<div id="output"> _x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

  1. Then just using lodash unset method remove property from object.

_x000D_
_x000D_
var unset = require('lodash.unset');_x000D_
unset(a,getPathOfKey(a,"price_index.final_price"));
_x000D_
_x000D_
_x000D_

Polling the keyboard (detect a keypress) in python

None of these answers worked well for me. This package, pynput, does exactly what I need.

https://pypi.python.org/pypi/pynput

from pynput.keyboard import Key, Listener

def on_press(key):
    print('{0} pressed'.format(
        key))

def on_release(key):
    print('{0} release'.format(
        key))
    if key == Key.esc:
        # Stop listener
        return False

# Collect events until released
with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

Setting the target version of Java in ant javac

Both source and target should be specified. I recommend providing ant defaults, that way you do not need to specify source/target attribute for every javac task:

<property name="ant.build.javac.source" value="1.5"/>
<property name="ant.build.javac.target" value="1.5"/>

See Java cross-compiling notes for more information.

How do I deal with corrupted Git object files?

Recovering from Repository Corruption is the official answer.

The really short answer is: find uncorrupted objects and copy them.

How to get text from each cell of an HTML table?

Thanks for the earlier reply.

I figured out the solutions using selenium 2.0 classes.

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class WebTableExample 
{
    public static void main(String[] args) 
    {
        WebDriver driver = new InternetExplorerDriver();
        driver.get("http://localhost/test/test.html");      

        WebElement table_element = driver.findElement(By.id("testTable"));
        List<WebElement> tr_collection=table_element.findElements(By.xpath("id('testTable')/tbody/tr"));

        System.out.println("NUMBER OF ROWS IN THIS TABLE = "+tr_collection.size());
        int row_num,col_num;
        row_num=1;
        for(WebElement trElement : tr_collection)
        {
            List<WebElement> td_collection=trElement.findElements(By.xpath("td"));
            System.out.println("NUMBER OF COLUMNS="+td_collection.size());
            col_num=1;
            for(WebElement tdElement : td_collection)
            {
                System.out.println("row # "+row_num+", col # "+col_num+ "text="+tdElement.getText());
                col_num++;
            }
            row_num++;
        } 
    }
}

Error: unmappable character for encoding UTF8 during maven compilation

In my case I resolved that problem using such approach:

  1. Set new environment variable: JAVA_TOOL_OPTIONS = -Dfile.encoding=UTF8
  2. Or set MAVEN_OPTS= -Dfile.encoding=UTF-8

Mailto on submit button

What you need to do is use the onchange event listener in the form and change the href attribute of the send button according to the context of the mail:

<form id="form" onchange="mail(this)">
  <label>Name</label>
  <div class="row margin-bottom-20">
    <div class="col-md-6 col-md-offset-0">
      <input class="form-control" name="name" type="text">
    </div>
  </div>

  <label>Email <span class="color-red">*</span></label>
  <div class="row margin-bottom-20">
    <div class="col-md-6 col-md-offset-0">
      <input class="form-control" name="email" type="text">
    </div>
  </div>

  <label>Date of visit/departure </label>
  <div class="row margin-bottom-20">
    <div class="col-md-3 col-md-offset-0">
      <input class="form-control w8em" name="adate" type="text">
      <script>
        datePickerController.createDatePicker({
          // Associate the text input to a DD/MM/YYYY date format
          formElements: {
            "adate": "%d/%m/%Y"
          }
        });
      </script>
    </div>
    <div class="col-md-3 col-md-offset-0">
      <input class="form-control" name="ddate" type="date">
    </div>
  </div>

  <label>No. of people travelling with</label>
  <div class="row margin-bottom-20">
    <div class="col-md-3 col-md-offset-0">
      <input class="form-control" placeholder="Adults" min=1 name="adult" type="number">
    </div>
    <div class="col-md-3 col-md-offset-0">
      <input class="form-control" placeholder="Children" min=0 name="childeren" type="number">
    </div>
  </div>

  <label>Cities you want to visit</label><br />
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Cassablanca">Cassablanca</label>
  </div>
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Fez">Fez</label>
  </div>
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Tangier">Tangier</label>
  </div>
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Marrakech">Marrakech</label>
  </div>
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Rabat">Rabat</label>
  </div>

  <div class="row margin-bottom-20">
    <div class="col-md-8 col-md-offset-0">
      <textarea rows="4" placeholder="Activities Intersted in" name="activities" class="form-control"></textarea>
    </div>
  </div>


  <div class="row margin-bottom-20">
    <div class="col-md-8 col-md-offset-0">
      <textarea rows="6" class="form-control" name="comment" placeholder="Comment"></textarea>
    </div>
  </div>

  <p><a id="send" class="btn btn-primary">Create Message</a></p>
</form>

JavaScript

function mail(form) {
    var name = form.name.value;
    var city = "";
    var adate = form.adate.value;
    var ddate = form.ddate.value;
    var activities = form.activities.value;
    var adult = form.adult.value;
    var child = form.childeren.value;
    var comment = form.comment.value;
    var warning = ""
    for (i = 0; i < form.city.length; i++) {
        if (form.city[i].checked)
            city += " " + form.city[i].value;
    }
    var str = "mailto:[email protected]?subject=travel to morocco&body=";
    if (name.length > 0) {
        str += "Hi my name is " + name + ", ";
    } else {
        warning += "Name is required"
    }
    if (city.length > 0) {
        str += "I am Intersted in visiting the following citis: " + city + ", ";
    }
    if (activities.length > 0) {
        str += "I am Intersted in following activities: " + activities + ". "
    }
    if (adate.length > 0) {
        str += "I will be ariving on " + adate;
    }
    if (ddate.length > 0) {
        str += " And departing on " + ddate;
    }
    if (adult.length > 0) {
        if (adult == 1 && child == null) {
            str += ". I will be travelling alone"
        } else if (adult > 1) {
            str += ".We will have a group of " + adult + " adults ";
        }
        if (child == null) {
            str += ".";
        } else if (child > 1) {
            str += "along with " + child + " children.";
        } else if (child == 1) {
            str += "along with a child.";
        }
    }

    if (comment.length > 0) {
        str += "%0D%0A" + comment + "."
    }

    if (warning.length > 0) {
        alert(warning)
    } else {
        str += "%0D%0ARegards,%0D%0A" + name;
        document.getElementById('send').href = str;
    }
}

JQuery/Javascript: check if var exists

I suspect there are many answers like this on SO but here you go:

if ( typeof pagetype !== 'undefined' && pagetype == 'textpage' ) {
  ...
}

Generate table relationship diagram from existing schema (SQL Server)

For SQL statements you can try reverse snowflakes. You can join at sourceforge or the demo site at http://snowflakejoins.com/.

How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

You can use the getters of java.time.LocalDateTime for that.

LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
int month = now.getMonthValue();
int day = now.getDayOfMonth();
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();
int millis = now.get(ChronoField.MILLI_OF_SECOND); // Note: no direct getter available.

System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);

Or, when you're not on Java 8 yet, make use of java.util.Calendar.

Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1; // Note: zero based!
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int millis = now.get(Calendar.MILLISECOND);

System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);

Either way, this prints as of now:

2010-04-16 15:15:17.816

To convert an int to String, make use of String#valueOf().


If your intent is after all to arrange and display them in a human friendly string format, then better use either Java8's java.time.format.DateTimeFormatter (tutorial here),

LocalDateTime now = LocalDateTime.now();
String format1 = now.format(DateTimeFormatter.ISO_DATE_TIME);
String format2 = now.atZone(ZoneId.of("GMT")).format(DateTimeFormatter.RFC_1123_DATE_TIME);
String format3 = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss", Locale.ENGLISH));

System.out.println(format1);
System.out.println(format2);
System.out.println(format3);

or when you're not on Java 8 yet, use java.text.SimpleDateFormat:

Date now = new Date(); // java.util.Date, NOT java.sql.Date or java.sql.Timestamp!
String format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH).format(now);
String format2 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH).format(now);
String format3 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH).format(now);

System.out.println(format1);
System.out.println(format2);
System.out.println(format3);

Either way, this yields:

2010-04-16T15:15:17.816
Fri, 16 Apr 2010 15:15:17 GMT
20100416151517

See also:

Sorting object property by values

Couln't find answer above that would both work and be SMALL, and would support nested objects (not arrays), so I wrote my own one :) Works both with strings and ints.

  function sortObjectProperties(obj, sortValue){
      var keysSorted = Object.keys(obj).sort(function(a,b){return obj[a][sortValue]-obj[b][sortValue]});
      var objSorted = {};
      for(var i = 0; i < keysSorted.length; i++){
          objSorted[keysSorted[i]] = obj[keysSorted[i]];
      }
      return objSorted;
    }

Usage:

    /* sample object with unsorder properties, that we want to sort by 
    their "customValue" property */

    var objUnsorted = {
       prop1 : {
          customValue : 'ZZ'
       },
       prop2 : {
          customValue : 'AA'
       }
    }

    // call the function, passing object and property with it should be sorted out
    var objSorted = sortObjectProperties(objUnsorted, 'customValue');

    // now console.log(objSorted) will return:
    { 
       prop2 : {
          customValue : 'AA'
       },
       prop1 : {
          customValue : 'ZZ'
       } 
    }

How to split string using delimiter char using T-SQL?

You need a split function:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create Function [dbo].[udf_Split]
(   
    @DelimitedList nvarchar(max)
    , @Delimiter nvarchar(2) = ','
)
RETURNS TABLE 
AS
RETURN 
    (
    With CorrectedList As
        (
        Select Case When Left(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
            + @DelimitedList
            + Case When Right(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
            As List
            , Len(@Delimiter) As DelimiterLen
        )
        , Numbers As 
        (
        Select TOP( Coalesce(DataLength(@DelimitedList)/2,0) ) Row_Number() Over ( Order By c1.object_id ) As Value
        From sys.columns As c1
            Cross Join sys.columns As c2
        )
    Select CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen As Position
        , Substring (
                    CL.List
                    , CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen     
                    , CharIndex(@Delimiter, CL.list, N.Value + 1)                           
                        - ( CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen ) 
                    ) As Value
    From CorrectedList As CL
        Cross Join Numbers As N
    Where N.Value <= DataLength(CL.List) / 2
        And Substring(CL.List, N.Value, CL.DelimiterLen) = @Delimiter
    )

With your split function, you would then use Cross Apply to get the data:

Select T.Col1, T.Col2
    , Substring( Z.Value, 1, Charindex(' = ', Z.Value) - 1 ) As AttributeName
    , Substring( Z.Value, Charindex(' = ', Z.Value) + 1, Len(Z.Value) ) As Value
From Table01 As T
    Cross Apply dbo.udf_Split( T.Col3, '|' ) As Z

How to replace all special character into a string using C#

Also, It can be done with LINQ

var str = "Hello@Hello&Hello(Hello)";
var characters = str.Select(c => char.IsLetter(c) ? c : ',')).ToArray();             
var output = new string(characters);
Console.WriteLine(output);

Possible reason for NGINX 499 error codes

...came here from a google search

I found the answer elsewhere here --> https://stackoverflow.com/a/15621223/1093174

which was to raise the connection idle timeout of my AWS elastic load balancer!

(I had setup a Django site with nginx/apache reverse proxy, and a really really really log backend job/view was timing out)

Completely removing phpMyAdmin

I was having a similar problem. PHP was working on my sites configured by virtualmin but not for phpmyadmin. PHPMyAdmin would not execute and the file was being downloaded by the browser. Everything I was reading was saying that libapache2-mod-php5 was not installed but I knew it was... so the thing to do was to purge it and reinstall.

sudo apt-get purge libapache2-mod-php5

sudo apt-get install libapache2-mod-php5

sudo apt-get purge phpmyadmin

sudo apt-get install phpmyadmin

sudo /etc/init.d/apache2 restart

Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?

Is your type really arbitrary? If you know it is just going to be a int float or string you could just do

 if val.dtype == float and np.isnan(val):

assuming it is wrapped in numpy , it will always have a dtype and only float and complex can be NaN

New warnings in iOS 9: "all bitcode will be dropped"

After Xcode 7, the bitcode option will be enabled by default. If your library was compiled without bitcode, but the bitcode option is enabled in your project settings, you can:

  1. Update your library with bit code,
  2. Say NO to Enable Bitcode in your target Build Settings

Enter image description here

And the Library Build Settings to remove the warnings.

For more information, go to documentation of bitcode in developer library.

And WWDC 2015 Session 102: "Platforms State of the Union"

Enter image description here

How do you create optional arguments in php?

The date function would be defined something like this:

function date($format, $timestamp = null)
{
    if ($timestamp === null) {
        $timestamp = time();
    }

    // Format the timestamp according to $format
}

Usually, you would put the default value like this:

function foo($required, $optional = 42)
{
    // This function can be passed one or more arguments
}

However, only literals are valid default arguments, which is why I used null as default argument in the first example, not $timestamp = time(), and combined it with a null check. Literals include arrays (array() or []), booleans, numbers, strings, and null.

How to parse string into date?

Although the CONVERT thing works, you actually shouldn't use it. You should ask yourself why you are parsing string values in SQL-Server. If this is a one-time job where you are manually fixing some data you won't get that data another time, this is ok, but if any application is using this, you should change something. Best way would be to use the "date" data type. If this is user input, this is even worse. Then you should first do some checking in the client. If you really want to pass string values where SQL-Server expects a date, you can always use ISO format ('YYYYMMDD') and it should convert automatically.

Styling JQuery UI Autocomplete

Based on @md-nazrul-islam reply, This is what I did with SCSS:

ul.ui-autocomplete {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 1000;
    float: left;
    display: none;
    min-width: 160px;
    margin: 0 0 10px 25px;
    list-style: none;
    background-color: #ffffff;
    border: 1px solid #ccc;
    border-color: rgba(0, 0, 0, 0.2);
    //@include border-radius(5px);
    @include box-shadow( rgba(0, 0, 0, 0.1) 0 5px 10px );
    @include background-clip(padding-box);
    *border-right-width: 2px;
    *border-bottom-width: 2px;

    li.ui-menu-item{
        padding:0 .5em;
        line-height:2em;
        font-size:.8em;
        &.ui-state-focus{
            background: #F7F7F7;
        }
    }

}

Submit form without page reloading

Here is some jQuery for posting to a php page and getting html back:

$('form').submit(function() {
    $.post('tip.php', function(html) {
       // do what you need in your success callback
    }
    return false;
});

How can I use custom fonts on a website?

CSS lets you use custom fonts, downloadable fonts on your website. You can download the font of your preference, let’s say myfont.ttf, and upload it to your remote server where your blog or website is hosted.

@font-face {
    font-family: myfont;
    src: url('myfont.ttf');
}

Insert Multiple Rows Into Temp Table With SQL Server 2012

Yes, SQL Server 2012 supports multiple inserts - that feature was introduced in SQL Server 2008.

That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server 2005 instance ...

What version of the SQL Server engine do you get from SELECT @@VERSION ??

How do I find the size of a struct?

If you want to manually count it, the size of a struct is just the size of each of its data members after accounting for alignment. There's no magic overhead bytes for a struct.

Error:Execution failed for task ':app:dexDebug'. com.android.ide.common.process.ProcessException

For me I had multiple versions of the same library included in /app/libs. I was using Parse and I had both ParseFacebookUtilsV3-1.9.0.jar and ParseFacebookUtilsV4-1.9.0.jar.

Deleting the V3 jar solves the problem.

$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP

Try this

$_SERVER['HTTP_CF_CONNECTING_IP'];

instead of

$_SERVER["REMOTE_ADDR"];

How to convert std::string to LPCSTR?

str.c_str() gives you a const char *, which is an LPCSTR (Long Pointer to Constant STRing) -- means that it's a pointer to a 0 terminated string of characters. W means wide string (composed of wchar_t instead of char).

SQL set values of one column equal to values of another column in the same table

UPDATE YourTable
SET ColumnB=ColumnA
WHERE
ColumnB IS NULL 
AND ColumnA IS NOT NULL

Redirecting to URL in Flask

You can use like this:

import os
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
     # Redirect from here, replace your custom site url "www.google.com"
    return redirect("https://www.google.com", code=200)

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

Here is the referenced link to this code.

Xcode 6: Keyboard does not show up in simulator

You can use : ?+?+K to show keyboard on simulator.

selecting an entire row based on a variable excel vba

I solved the problem for me by addressing also the worksheet first:

ws.rows(x & ":" & y).Select

without the reference to the worksheet (ws) I got an error.

Python: Tuples/dictionaries as keys, select, sort

Your best option will be to create a simple data structure to model what you have. Then you can store these objects in a simple list and sort/retrieve them any way you wish.

For this case, I'd use the following class:

class Fruit:
    def __init__(self, name, color, quantity): 
        self.name = name
        self.color = color
        self.quantity = quantity

    def __str__(self):
        return "Name: %s, Color: %s, Quantity: %s" % \
     (self.name, self.color, self.quantity)

Then you can simply construct "Fruit" instances and add them to a list, as shown in the following manner:

fruit1 = Fruit("apple", "red", 12)
fruit2 = Fruit("pear", "green", 22)
fruit3 = Fruit("banana", "yellow", 32)
fruits = [fruit3, fruit2, fruit1] 

The simple list fruits will be much easier, less confusing, and better-maintained.

Some examples of use:

All outputs below is the result after running the given code snippet followed by:

for fruit in fruits:
    print fruit

Unsorted list:

Displays:

Name: banana, Color: yellow, Quantity: 32
Name: pear, Color: green, Quantity: 22
Name: apple, Color: red, Quantity: 12

Sorted alphabetically by name:

fruits.sort(key=lambda x: x.name.lower())

Displays:

Name: apple, Color: red, Quantity: 12
Name: banana, Color: yellow, Quantity: 32
Name: pear, Color: green, Quantity: 22

Sorted by quantity:

fruits.sort(key=lambda x: x.quantity)

Displays:

Name: apple, Color: red, Quantity: 12
Name: pear, Color: green, Quantity: 22
Name: banana, Color: yellow, Quantity: 32

Where color == red:

red_fruit = filter(lambda f: f.color == "red", fruits)

Displays:

Name: apple, Color: red, Quantity: 12

How to start activity in another application?

If both application have the same signature (meaning that both APPS are yours and signed with the same key), you can call your other app activity as follows:

Intent LaunchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(CALC_PACKAGE_NAME);
startActivity(LaunchIntent);

Hope it helps.

Difference between OpenJDK and Adoptium/AdoptOpenJDK

Update: AdoptOpenJDK has changed its name to Adoptium, as part of its move to the Eclipse Foundation.


OpenJDK ? source code
Adoptium/AdoptOpenJDK ? builds

Difference between OpenJDK and AdoptOpenJDK

The first provides source-code, the other provides builds of that source-code.

Several vendors of Java & OpenJDK

Adoptium of the Eclipse Foundation, formerly known as AdoptOpenJDK, is only one of several vendors distributing implementations of the Java platform. These include:

  • Eclipse Foundation (Adoptium/AdoptOpenJDK)
  • Azul Systems
  • Oracle
  • Red Hat / IBM
  • BellSoft
  • SAP
  • Amazon AWS
  • … and more

See this flowchart of mine to help guide you in picking a vendor for an implementation of the Java platform. Click/tap to zoom.

Flowchart guiding you in choosing a vendor for a Java 11 implementation

Another resource: This comparison matrix by Azul Systems is useful, and seems true and fair to my mind.

Here is a list of considerations and motivations to consider in choosing a vendor and implementation.

Motivations in choosing a vendor for Java

Some vendors offer you a choice of JIT technologies.

Diagram showing history of HotSpot & JRockit merging, and OpenJ9 both available in AdoptOpenJDK

To understand more about this Java ecosystem, read Java Is Still Free

How can I set the 'backend' in matplotlib in Python?

This can also be set in the configuration file matplotlibrc (as explained in the error message), for instance:

# The default backend; one of GTK GTKAgg GTKCairo GTK3Agg GTK3Cairo
# CocoaAgg MacOSX Qt4Agg Qt5Agg TkAgg WX WXAgg Agg Cairo GDK PS PDF SVG
backend : Agg

That way, the backend does not need to be hardcoded if the code is shared with other people. For more information, check the documentation.

What is the right way to check for a null string in Objective-C?

I only check null string with

if ([myString isEqual:[NSNull null]])

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

Implementing multiple interfaces is very useful and doesn't cause much problems to language implementers nor programmers. So it is allowed. Multiple inheritance while also useful, can cause serious problems to users (dreaded diamond of death). And most things you do with multiple inheritance can be also done by composition or using inner classes. So multiple inheritance is forbidden as bringing more problems than gains.

Date Comparison using Java

It is easier to compare dates using the java.util.Calendar. Here is what you might do:

Calendar toDate = Calendar.getInstance();
Calendar nowDate = Calendar.getInstance();
toDate.set(<set-year>,<set-month>,<set-day>);  
if(!toDate.before(nowDate)) {
    //display your report
} else {
    // don't display the report
}

'sudo gem install' or 'gem install' and gem locations

You can also install gems in your local environment (without sudo) with

gem install --user-install <gemname>

I recommend that so you don't mess with your system-level configuration even if it's a single-user computer.

You can check where the gems go by looking at gempaths with gem environment. In my case it's "~/.gem/ruby/1.8".

If you need some binaries from local installs added to your path, you can add something to your bashrc like:

if which ruby >/dev/null && which gem >/dev/null; then
    PATH="$(ruby -r rubygems -e 'puts Gem.user_dir')/bin:$PATH"
fi

(from http://guides.rubygems.org/faqs/#user-install)

MySQL Nested Select Query?

You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t below) and alias the columns as well.

The DISTINCT can also be safely removed as the internal GROUP BY makes it redundant:

SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
    SELECT MIN(`date`) AS `date`, `player_name`
    FROM `player_playtime`
    GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;

Since the COUNT is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*) and further simplify the query:

SELECT t.date , COUNT(*) AS player_count
FROM (
    SELECT DATE(MIN(`date`)) AS date
    FROM player_playtime
    GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;

Setting user agent of a java URLConnection

Off hand, setting the http.agent system property to "" might do the trick (I don't have the code in front of me).

You might get away with:

 System.setProperty("http.agent", "");

but that might require a race between you and initialisation of the URL protocol handler, if it caches the value at startup (actually, I don't think it does).

The property can also be set through JNLP files (available to applets from 6u10) and on the command line:

-Dhttp.agent=

Or for wrapper commands:

-J-Dhttp.agent=

Edit existing excel workbooks and sheets with xlrd and xlwt

As I wrote in the edits of the op, to edit existing excel documents you must use the xlutils module (Thanks Oliver)

Here is the proper way to do it:

#xlrd, xlutils and xlwt modules need to be installed.  
#Can be done via pip install <module>
from xlrd import open_workbook
from xlutils.copy import copy

rb = open_workbook("names.xls")
wb = copy(rb)

s = wb.get_sheet(0)
s.write(0,0,'A1')
wb.save('names.xls')

This replaces the contents of the cell located at a1 in the first sheet of "names.xls" with the text "a1", and then saves the document.

How to select a single column with Entity Framework?

You can use LINQ's .Select() to do that. In your case it would go something like:

string Name = yourDbContext
  .MyTable
  .Where(u => u.UserId == 1)
  .Select(u => u.Name)
  .SingleOrDefault(); // This is what actually executes the request and return a response

If you are expecting more than one entry in response, you can use .ToList() instead, to execute the request. Something like this, to get the Name of everyone with age 30:

string[] Names = yourDbContext
  .MyTable
  .Where(u => u.Age == 30)
  .Select(u => u.Name)
  .ToList();

In python, what is the difference between random.uniform() and random.random()?

According to the documentation on random.uniform:

Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.

while random.random:

Return the next random floating point number in the range [0.0, 1.0).

I.e. with random.uniform you specify a range you draw pseudo-random numbers from, e.g. between 3 and 10. With random.random you get a number between 0 and 1.

PHP add elements to multidimensional array with array_push

I know the topic is old, but I just fell on it after a google search so... here is another solution:

$array_merged = array_merge($array_going_first, $array_going_second);

This one seems pretty clean to me, it works just fine!

SQL join: selecting the last records in a one-to-many relationship

Another approach would be to use a NOT EXISTS condition in your join condition to test for later purchases:

SELECT *
FROM customer c
LEFT JOIN purchase p ON (
       c.id = p.customer_id
   AND NOT EXISTS (
     SELECT 1 FROM purchase p1
     WHERE p1.customer_id = c.id
     AND p1.id > p.id
   )
)

ImportError: Couldn't import Django

if you don't want to deactivate or activate the already installed venv just ensure you have set the pythonpath set

set pythonpath=C:\software\venv\include;C:\software\venv\lib;C:\software\venv\scripts;C:\software\venv\tcl;C:\software\venv\Lib\site-packages;

and then execute

"%pythonpath%" %venvpath%Scripts\mytestsite\manage.py runserver "%ipaddress%":8000

Cross-Origin Request Headers(CORS) with PHP headers

Handling CORS requests properly is a tad more involved. Here is a function that will respond more fully (and properly).

/**
 *  An example CORS-compliant method.  It will allow any GET, POST, or OPTIONS requests from any
 *  origin.
 *
 *  In a production environment, you probably want to be more restrictive, but this gives you
 *  the general idea of what is involved.  For the nitty-gritty low-down, read:
 *
 *  - https://developer.mozilla.org/en/HTTP_access_control
 *  - https://fetch.spec.whatwg.org/#http-cors-protocol
 *
 */
function cors() {
    
    // Allow from any origin
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        // Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
        // you want to allow, and if so:
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }
    
    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            // may also be using PUT, PATCH, HEAD etc
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
        
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    
        exit(0);
    }
    
    echo "You have CORS!";
}

Security Notes

When a browser wants to execute a cross-site request it first confirms that this is okay with a "pre-flight" request to the URL. By allowing CORS you are telling the browser that responses from this URL can be shared with other domains.

CORS does not protect your server. CORS attempts to protect your users by telling browsers what the restrictions should be on sharing responses with other domains. Normally this kind of sharing is utterly forbidden, so CORS is a way to poke a hole in the browser's normal security policy. These holes should be as small as possible, so always check the HTTP_ORIGIN against some kind of internal list.

There are some dangers here, especially if the data the URL serves up is normally protected. You are effectively allowing browser content that originated on some other server to read (and possibly manipulate) data on your server.

If you are going to use CORS, please read the protocol carefully (it is quite small) and try to understand what you're doing. A reference URL is given in the code sample for that purpose.

Header security

It has been observed that the HTTP_ORIGIN header is insecure, and that is true. In fact, all HTTP headers are insecure to varying meanings of the term. Unless a header includes a verifiable signature/hmac, or the whole conversation is authenticated via TLS, headers are just "something the browser has told me".

In this case, the browser is saying "an object from domain X wants to get a response from this URL. Is that okay?" The point of CORS is to be able to answer, "yes I'll allow that".

How do you return the column names of a table?

I just use a query like Martin Smith mentioned, just little shorter:

SELECT COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'YourTableName'

Disable a Maven plugin defined in a parent POM

The following works for me when disabling Findbugs in a child POM:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>findbugs-maven-plugin</artifactId>
    <executions>
        <execution>
            <id>ID_AS_IN_PARENT</id> <!-- id is necessary sometimes -->
            <phase>none</phase>
        </execution>
    </executions>
</plugin>

Note: the full definition of the Findbugs plugin is in our parent/super POM, so it'll inherit the version and so-on.

In Maven 3, you'll need to use:

 <configuration>
      <skip>true</skip>
 </configuration>

for the plugin.

How to overcome TypeError: unhashable type: 'list'

As indicated by the other answers, the error is to due to k = list[0:j], where your key is converted to a list. One thing you could try is reworking your code to take advantage of the split function:

# Using with ensures that the file is properly closed when you're done
with open('filename.txt', 'rb') as f:
  d = {}
  # Here we use readlines() to split the file into a list where each element is a line
  for line in f.readlines():
    # Now we split the file on `x`, since the part before the x will be
    # the key and the part after the value
    line = line.split('x')
    # Take the line parts and strip out the spaces, assigning them to the variables
    # Once you get a bit more comfortable, this works as well:
    # key, value = [x.strip() for x in line] 
    key = line[0].strip()
    value = line[1].strip()
    # Now we check if the dictionary contains the key; if so, append the new value,
    # and if not, make a new list that contains the current value
    # (For future reference, this is a great place for a defaultdict :)
    if key in d:
      d[key].append(value)
    else:
      d[key] = [value]

print d
# {'AAA': ['111', '112'], 'AAC': ['123'], 'AAB': ['111']}

Note that if you are using Python 3.x, you'll have to make a minor adjustment to get it work properly. If you open the file with rb, you'll need to use line = line.split(b'x') (which makes sure you are splitting the byte with the proper type of string). You can also open the file using with open('filename.txt', 'rU') as f: (or even with open('filename.txt', 'r') as f:) and it should work fine.

How to delete all files and folders in a directory?

Yes, that's the correct way to do it. If you're looking to give yourself a "Clean" (or, as I'd prefer to call it, "Empty" function), you can create an extension method.

public static void Empty(this System.IO.DirectoryInfo directory)
{
    foreach(System.IO.FileInfo file in directory.GetFiles()) file.Delete();
    foreach(System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
}

This will then allow you to do something like..

System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(@"C:\...");

directory.Empty();

HTML5 event handling(onfocus and onfocusout) using angular 2

<input name="date" type="text" (focus)="focusFunction()" (focusout)="focusOutFunction()">

works for me from Pardeep Jain

How do you run CMD.exe under the Local System Account?

if you can write a batch file that does not need to be interactive, try running that batch file as a service, to do what needs to be done.

How to get the children of the $(this) selector?

If your DIV tag is immediately followed by the IMG tag, you can also use:

$(this).next();

Handling Enter Key in Vue.js

Event Modifiers

You can refer to event modifiers in vuejs to prevent form submission on enter key.

It is a very common need to call event.preventDefault() or event.stopPropagation() inside event handlers.

Although we can do this easily inside methods, it would be better if the methods can be purely about data logic rather than having to deal with DOM event details.

To address this problem, Vue provides event modifiers for v-on. Recall that modifiers are directive postfixes denoted by a dot.

<form v-on:submit.prevent="<method>">
  ...
</form>

As the documentation states, this is syntactical sugar for e.preventDefault() and will stop the unwanted form submission on press of enter key.

Here is a working fiddle.

_x000D_
_x000D_
new Vue({_x000D_
  el: '#myApp',_x000D_
  data: {_x000D_
    emailAddress: '',_x000D_
    log: ''_x000D_
  },_x000D_
  methods: {_x000D_
    validateEmailAddress: function(e) {_x000D_
      if (e.keyCode === 13) {_x000D_
        alert('Enter was pressed');_x000D_
      } else if (e.keyCode === 50) {_x000D_
        alert('@ was pressed');_x000D_
      }      _x000D_
      this.log += e.key;_x000D_
    },_x000D_
    _x000D_
    postEmailAddress: function() {_x000D_
   this.log += '\n\nPosting';_x000D_
    },_x000D_
    noop () {_x000D_
      // do nothing ?_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
html, body, #editor {_x000D_
  margin: 0;_x000D_
  height: 100%;_x000D_
  color: #333;_x000D_
}
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<div id="myApp" style="padding:2rem; background-color:#fff;">_x000D_
<form v-on:submit.prevent="noop">_x000D_
  <input type="text" v-model="emailAddress" v-on:keyup="validateEmailAddress" />_x000D_
  <button type="button" v-on:click="postEmailAddress" >Subscribe</button> _x000D_
  <br /><br />_x000D_
  _x000D_
  <textarea v-model="log" rows="4"></textarea>  _x000D_
</form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Populating a ListView using an ArrayList?

Here's an example of how you could implement a list view:

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

    //We have our list view
    final ListView dynamic = findViewById(R.id.dynamic);

    //Create an array of elements
    final ArrayList<String> classes = new ArrayList<>();
    classes.add("Data Structures");
    classes.add("Assembly Language");
    classes.add("Calculus 3");
    classes.add("Switching Systems");
    classes.add("Analysis Tools");

    //Create adapter for ArrayList
    final ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, classes);

    //Insert Adapter into List
    dynamic.setAdapter(adapter);

    //set click functionality for each list item
    dynamic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.i("User clicked ", classes.get(position));
        }
    });



}

What does the "$" sign mean in jQuery or JavaScript?

Additional to the jQuery thing treated in the other answers there is another meaning in JavaScript - as prefix for the RegExp properties representing matches, for example:

"test".match( /t(e)st/ );
alert( RegExp.$1 );

will alert "e"

But also here it's not "magic" but simply part of the properties name

How do I get a file name from a full path with PHP?

You're looking for basename.

The example from the PHP manual:

<?php
$path = "/home/httpd/html/index.php";
$file = basename($path);         // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
?>

How to convert upper case letters to lower case

str.lower() converts all cased characters to lowercase.

Errors: "INSERT EXEC statement cannot be nested." and "Cannot use the ROLLBACK statement within an INSERT-EXEC statement." How to solve this?

Declare an output cursor variable to the inner sp :

@c CURSOR VARYING OUTPUT

Then declare a cursor c to the select you want to return. Then open the cursor. Then set the reference:

DECLARE c CURSOR LOCAL FAST_FORWARD READ_ONLY FOR 
SELECT ...
OPEN c
SET @c = c 

DO NOT close or reallocate.

Now call the inner sp from the outer one supplying a cursor parameter like:

exec sp_abc a,b,c,, @cOUT OUTPUT

Once the inner sp executes, your @cOUT is ready to fetch. Loop and then close and deallocate.

Replace the single quote (') character from a string

As for how to represent a single apostrophe as a string in Python, you can simply surround it with double quotes ("'") or you can escape it inside single quotes ('\'').

To remove apostrophes from a string, a simple approach is to just replace the apostrophe character with an empty string:

>>> "didn't".replace("'", "")
'didnt'

Make REST API call in Swift

Swift 4 - GET request

var request = URLRequest(url: URL(string: "http://example.com/api/v1/example")!)
request.httpMethod = "GET"

URLSession.shared.dataTask(with: request, completionHandler: { data, response, error -> Void in
    do {
        let jsonDecoder = JSONDecoder()
        let responseModel = try jsonDecoder.decode(CustomDtoClass.self, from: data!)
        print(responseModel)
    } catch {
        print("JSON Serialization error")
    }
}).resume()

Don't forget to configure App Transport Security Settings to add your domain to the exceptions and allow insecure http requests if you're hitting endpoints without using HTTPS.

You can use a tool like http://www.json4swift.com/ to autogenerate your Codeable Mappings from your JSON responses.

How to calculate a Mod b in Casio fx-991ES calculator

Here's how I usually do it. For example, to calculate 1717 mod 2:

  • Take 1717 / 2. The answer is 858.5
  • Now take 858 and multiply it by the mod (2) to get 1716
  • Finally, subtract the original number (1717) minus the number you got from the previous step (1716) -- 1717-1716=1.

So 1717 mod 2 is 1.

To sum this up all you have to do is multiply the numbers before the decimal point with the mod then subtract it from the original number.

How can I return two values from a function in Python?

def test():
    r1 = 1
    r2 = 2
    r3 = 3
    return r1, r2, r3

x,y,z = test()
print x
print y
print z


> test.py 
1
2
3

SQL Query Multiple Columns Using Distinct on One Column Only

you have various ways to distinct values on one column or multi columns.

  • using the GROUP BY

    SELECT DISTINCT MIN(o.tblFruit_ID)  AS tblFruit_ID,
       o.tblFruit_FruitType,
       MAX(o.tblFruit_FruitName)
    FROM   tblFruit  AS o
    GROUP BY
         tblFruit_FruitType
    
  • using the subquery

    SELECT b.tblFruit_ID,
       b.tblFruit_FruitType,
       b.tblFruit_FruitName
    FROM   (
           SELECT DISTINCT(tblFruit_FruitType),
                  MIN(tblFruit_ID) tblFruit_ID
           FROM   tblFruit
           GROUP BY
                  tblFruit_FruitType
       ) AS a
       INNER JOIN tblFruit b
            ON  a.tblFruit_ID = b.tblFruit_I
    
  • using the join with subquery

    SELECT t1.tblFruit_ID,
        t1.tblFruit_FruitType,
        t1.tblFruit_FruitName
    FROM   tblFruit  AS t1
       INNER JOIN (
                SELECT DISTINCT MAX(tblFruit_ID) AS tblFruit_ID,
                       tblFruit_FruitType
                FROM   tblFruit
                GROUP BY
                       tblFruit_FruitType
            )  AS t2
            ON  t1.tblFruit_ID = t2.tblFruit_ID 
    
  • using the window functions only one column distinct

    SELECT tblFruit_ID,
        tblFruit_FruitType,
        tblFruit_FruitName
    FROM   (
             SELECT tblFruit_ID,
                  tblFruit_FruitType,
                  tblFruit_FruitName,
                  ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType ORDER BY tblFruit_ID) 
        rn
           FROM   tblFruit
        ) t
        WHERE  rn = 1 
    
  • using the window functions multi column distinct

    SELECT tblFruit_ID,
        tblFruit_FruitType,
        tblFruit_FruitName
    FROM   (
             SELECT tblFruit_ID,
                  tblFruit_FruitType,
                  tblFruit_FruitName,
                  ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType,     tblFruit_FruitName 
        ORDER BY tblFruit_ID) rn
              FROM   tblFruit
         ) t
        WHERE  rn = 1 
    

When should I use the Visitor Design Pattern?

One way to look at it is that the visitor pattern is a way of letting your clients add additional methods to all of your classes in a particular class hierarchy.

It is useful when you have a fairly stable class hierarchy, but you have changing requirements of what needs to be done with that hierarchy.

The classic example is for compilers and the like. An Abstract Syntax Tree (AST) can accurately define the structure of the programming language, but the operations you might want to do on the AST will change as your project advances: code-generators, pretty-printers, debuggers, complexity metrics analysis.

Without the Visitor Pattern, every time a developer wanted to add a new feature, they would need to add that method to every feature in the base class. This is particularly hard when the base classes appear in a separate library, or are produced by a separate team.

(I have heard it argued that the Visitor pattern is in conflict with good OO practices, because it moves the operations of the data away from the data. The Visitor pattern is useful in precisely the situation that the normal OO practices fail.)

Increment a database field by 1

I not expert in MySQL but you probably should look on triggers e.g. BEFORE INSERT. In the trigger you can run select query on your original table and if it found something just update the row 'logins' instead of inserting new values. But all this depends on version of MySQL you running.

The server committed a protocol violation. Section=ResponseStatusLine ERROR

None of the solutions worked for me, so I had to use a WebClient instead of a HttpWebRequest and the issue was no more.

I needed to use a CookieContainer, so I used the solution posted by Pavel Savara in this thread - Using CookieContainer with WebClient class

just remove "protected" from this line:

private readonly CookieContainer container = new CookieContainer();

Using C# to check if string contains a string in string array

I used the following code to check if the string contained any of the items in the string array:

foreach (string s in stringArray)
{
    if (s != "")
    {
        if (stringToCheck.Contains(s))
        {
            Text = "matched";
        }
    }
}

Display date/time in user's locale format and time offset

The best solution I've come across is to create [time display="llll" datetime="UTC TIME" /] Tags, and use javascript (jquery) to parse and display it relative to the user's time.

http://momentjs.com/ Moment.js

will display the time nicely.

font size in html code

you dont need those quotes

<td style="padding-left: 5px;padding-bottom:3px; font-size: 35px;"> <b>Datum:</b><br/>
                        November 2010 </td>

Best way to find if an item is in a JavaScript array?

[ ].has(obj)

assuming .indexOf() is implemented

Object.defineProperty( Array.prototype,'has',
{
    value:function(o, flag){
    if (flag === undefined) {
        return this.indexOf(o) !== -1;
    } else {   // only for raw js object
        for(var v in this) {
            if( JSON.stringify(this[v]) === JSON.stringify(o)) return true;
        }
        return false;                       
    },
    // writable:false,
    // enumerable:false
})

!!! do not make Array.prototype.has=function(){... because you'll add an enumerable element in every array and js is broken.

//use like          
[22 ,'a', {prop:'x'}].has(12) // false
["a","b"].has("a") //  true

[1,{a:1}].has({a:1},1) // true
[1,{a:1}].has({a:1}) // false

the use of 2nd arg (flag) forces comparation by value instead of reference

comparing raw objects

[o1].has(o2,true) // true if every level value is same

How to extend a class in python?

Use:

import color

class Color(color.Color):
    ...

If this were Python 2.x, you would also want to derive color.Color from object, to make it a new-style class:

class Color(object):
    ...

This is not necessary in Python 3.x.

How to load image files with webpack file-loader

I had an issue uploading images to my React JS project. I was trying to use the file-loader to load the images; I was also using Babel-loader in my react.

I used the following settings in the webpack:

{test: /\.(jpe?g|png|gif|svg)$/i, loader: "file-loader?name=app/images/[name].[ext]"},

This helped load my images, but the images loaded were kind of corrupted. Then after some research I came to know that file-loader has a bug of corrupting the images when babel-loader is installed.

Hence, to work around the issue I tried to use URL-loader which worked perfectly for me.

I updated my webpack with the following settings

{test: /\.(jpe?g|png|gif|svg)$/i, loader: "url-loader?name=app/images/[name].[ext]"},

I then used the following command to import the images

import img from 'app/images/GM_logo_2.jpg'
<div className="large-8 columns">

      <img  style={{ width: 300, height: 150 }} src={img} />
</div>

How to make a HTML list appear horizontally instead of vertically using CSS only?

Using display: inline-flex

_x000D_
_x000D_
#menu ul {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  display: inline-flex_x000D_
}
_x000D_
<div id="menu">_x000D_
  <ul>_x000D_
    <li>1 menu item</li>_x000D_
    <li>2 menu item</li>_x000D_
    <li>3 menu item</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using display: inline-block

_x000D_
_x000D_
#menu ul {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
#menu li {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div id="menu">_x000D_
  <ul>_x000D_
    <li>1 menu item</li>_x000D_
    <li>2 menu item</li>_x000D_
    <li>3 menu item</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Regex Named Groups in Java

(Update: August 2011)

As geofflane mentions in his answer, Java 7 now support named groups.
tchrist points out in the comment that the support is limited.
He details the limitations in his great answer "Java Regex Helper"

Java 7 regex named group support was presented back in September 2010 in Oracle's blog.

In the official release of Java 7, the constructs to support the named capturing group are:

  • (?<name>capturing text) to define a named group "name"
  • \k<name> to backreference a named group "name"
  • ${name} to reference to captured group in Matcher's replacement string
  • Matcher.group(String name) to return the captured input subsequence by the given "named group".

Other alternatives for pre-Java 7 were:


(Original answer: Jan 2009, with the next two links now broken)

You can not refer to named group, unless you code your own version of Regex...

That is precisely what Gorbush2 did in this thread.

Regex2

(limited implementation, as pointed out again by tchrist, as it looks only for ASCII identifiers. tchrist details the limitation as:

only being able to have one named group per same name (which you don’t always have control over!) and not being able to use them for in-regex recursion.

Note: You can find true regex recursion examples in Perl and PCRE regexes, as mentioned in Regexp Power, PCRE specs and Matching Strings with Balanced Parentheses slide)

Example:

String:

"TEST 123"

RegExp:

"(?<login>\\w+) (?<id>\\d+)"

Access

matcher.group(1) ==> TEST
matcher.group("login") ==> TEST
matcher.name(1) ==> login

Replace

matcher.replaceAll("aaaaa_$1_sssss_$2____") ==> aaaaa_TEST_sssss_123____
matcher.replaceAll("aaaaa_${login}_sssss_${id}____") ==> aaaaa_TEST_sssss_123____ 

(extract from the implementation)

public final class Pattern
    implements java.io.Serializable
{
[...]
    /**
     * Parses a group and returns the head node of a set of nodes that process
     * the group. Sometimes a double return system is used where the tail is
     * returned in root.
     */
    private Node group0() {
        boolean capturingGroup = false;
        Node head = null;
        Node tail = null;
        int save = flags;
        root = null;
        int ch = next();
        if (ch == '?') {
            ch = skip();
            switch (ch) {

            case '<':   // (?<xxx)  look behind or group name
                ch = read();
                int start = cursor;
[...]
                // test forGroupName
                int startChar = ch;
                while(ASCII.isWord(ch) && ch != '>') ch=read();
                if(ch == '>'){
                    // valid group name
                    int len = cursor-start;
                    int[] newtemp = new int[2*(len) + 2];
                    //System.arraycopy(temp, start, newtemp, 0, len);
                    StringBuilder name = new StringBuilder();
                    for(int i = start; i< cursor; i++){
                        name.append((char)temp[i-1]);
                    }
                    // create Named group
                    head = createGroup(false);
                    ((GroupTail)root).name = name.toString();

                    capturingGroup = true;
                    tail = root;
                    head.next = expr(tail);
                    break;
                }

Set transparent background using ImageMagick and commandline prompt

Yep. Had this same problem too. Here's the command I ran and it worked perfectly: convert transparent-img1.png transparent-img2.png transparent-img3.png -channel Alpha favicon.ico

Jquery resizing image

Modifying Aleksandar's answer to make it as jquery plugin and accepts maxwidth and maxheight as arguments, suggested by Nathan.

$.fn.resize = function(maxWidth,maxHeight) {
return this.each(function() {
    var ratio = 0;
    var width = $(this).width();
    var height = $(this).height();
    if(width > maxWidth){
        ratio = maxWidth / width;
        $(this).css("width", maxWidth);
        $(this).css("height", height * ratio);
        height = height * ratio;
    }
    var width = $(this).width();
    var height = $(this).height();
    if(height > maxHeight){
        ratio = maxHeight / height;
        $(this).css("height", maxHeight);
        $(this).css("width", width * ratio);
        width = width * ratio;
    }
});
};

Used as $('.imgClass').resize(300,50);

Can I access constants in settings.py from templates in Django?

If using a class-based view:

#
# in settings.py
#
YOUR_CUSTOM_SETTING = 'some value'

#
# in views.py
#
from django.conf import settings #for getting settings vars

class YourView(DetailView): #assuming DetailView; whatever though

    # ...

    def get_context_data(self, **kwargs):

        context = super(YourView, self).get_context_data(**kwargs)
        context['YOUR_CUSTOM_SETTING'] = settings.YOUR_CUSTOM_SETTING

        return context

#
# in your_template.html, reference the setting like any other context variable
#
{{ YOUR_CUSTOM_SETTING }}

Reading data from a website using C#

If you're downloading text then I'd recommend using the WebClient and get a streamreader to the text:

        WebClient web = new WebClient();
        System.IO.Stream stream = web.OpenRead("http://www.yoursite.com/resource.txt");
        using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
        {
            String text = reader.ReadToEnd();
        }

If this is taking a long time then it is probably a network issue or a problem on the web server. Try opening the resource in a browser and see how long that takes. If the webpage is very large, you may want to look at streaming it in chunks rather than reading all the way to the end as in that example. Look at http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx to see how to read from a stream.

Change background position with jQuery

$('#submenu li').hover(function(){
    $('#carousel').css('backgroundPosition', newValue);
});

How to get images in Bootstrap's card to be the same height/width?

.card-img-top {
width: 100%;
height: 30vh;
object-fit: contain;
}

Contain will help in getting Complete Image displayed inside Card.

Adjust height "30vh" according to your need!

How can I count the rows with data in an Excel sheet?

You should use the sumif function in Excel:

=SUMIF(A5:C10;"Text_to_find";C5:C10)

This function takes a range like this square A5:C10 then you have some text to find this text can be in A or B then it will add the number from the C-row.

Assigning strings to arrays of characters

You can use this:

yylval.sval=strdup("VHDL + Volcal trance...");

Where yylval is char*. strdup from does the job.

Run git pull over all subdirectories

Original answer 2010:

If all of those directories are separate git repo, you should reference them as submodules.

That means your "origin" would be that remote repo 'plugins' which only contains references to subrepos 'cms', 'admin', 'chart'.

A git pull followed by a git submodule update would achieve what your are looking for.


Update January 2016:

With Git 2.8 (Q1 2016), you will be able to fetch submodules in parallel (!) with git fetch --recurse-submodules -j2.
See "How to speed up / parallelize downloads of git submodules using git clone --recursive?"

Out-File -append in Powershell does not produce a new line and breaks string into characters

Out-File defaults to unicode encoding which is why you are seeing the behavior you are. Use -Encoding Ascii to change this behavior. In your case

Out-File -Encoding Ascii -append textfile.txt. 

Add-Content uses Ascii and also appends by default.

"This is a test" | Add-Content textfile.txt.

As for the lack of newline: You did not send a newline so it will not write one to file.

Lazy Loading vs Eager Loading

I think it is good to categorize relations like this

When to use eager loading

  1. In "one side" of one-to-many relations that you sure are used every where with main entity. like User property of an Article. Category property of a Product.
  2. Generally When relations are not too much and eager loading will be good practice to reduce further queries on server.

When to use lazy loading

  1. Almost on every "collection side" of one-to-many relations. like Articles of User or Products of a Category
  2. You exactly know that you will not need a property instantly.

Note: like Transcendent said there may be disposal problem with lazy loading.

Why is it common to put CSRF prevention tokens in cookies?

A good reason, which you have sort of touched on, is that once the CSRF cookie has been received, it is then available for use throughout the application in client script for use in both regular forms and AJAX POSTs. This will make sense in a JavaScript heavy application such as one employed by AngularJS (using AngularJS doesn't require that the application will be a single page app, so it would be useful where state needs to flow between different page requests where the CSRF value cannot normally persist in the browser).

Consider the following scenarios and processes in a typical application for some pros and cons of each approach you describe. These are based on the Synchronizer Token Pattern.

Request Body Approach

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. If not yet generated for this session, server generates CSRF token, stores it against the user session and outputs it to a hidden field.
  5. User submits form.
  6. Server checks hidden field matches session stored token.

Advantages:

  • Simple to implement.
  • Works with AJAX.
  • Works with forms.
  • Cookie can actually be HTTP Only.

Disadvantages:

  • All forms must output the hidden field in HTML.
  • Any AJAX POSTs must also include the value.
  • The page must know in advance that it requires the CSRF token so it can include it in the page content so all pages must contain the token value somewhere, which could make it time consuming to implement for a large site.

Custom HTTP Header (downstream)

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. Page loads in browser, then an AJAX request is made to retrieve the CSRF token.
  5. Server generates CSRF token (if not already generated for session), stores it against the user session and outputs it to a header.
  6. User submits form (token is sent via hidden field).
  7. Server checks hidden field matches session stored token.

Advantages:

Disadvantages:

  • Doesn't work without an AJAX request to get the header value.
  • All forms must have the value added to its HTML dynamically.
  • Any AJAX POSTs must also include the value.
  • The page must make an AJAX request first to get the CSRF token, so it will mean an extra round trip each time.
  • Might as well have simply output the token to the page which would save the extra request.

Custom HTTP Header (upstream)

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. If not yet generated for this session, server generates CSRF token, stores it against the user session and outputs it in the page content somewhere.
  5. User submits form via AJAX (token is sent via header).
  6. Server checks custom header matches session stored token.

Advantages:

Disadvantages:

  • Doesn't work with forms.
  • All AJAX POSTs must include the header.

Custom HTTP Header (upstream & downstream)

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. Page loads in browser, then an AJAX request is made to retrieve the CSRF token.
  5. Server generates CSRF token (if not already generated for session), stores it against the user session and outputs it to a header.
  6. User submits form via AJAX (token is sent via header) .
  7. Server checks custom header matches session stored token.

Advantages:

Disadvantages:

  • Doesn't work with forms.
  • All AJAX POSTs must also include the value.
  • The page must make an AJAX request first to get the CRSF token, so it will mean an extra round trip each time.

Set-Cookie

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. Server generates CSRF token, stores it against the user session and outputs it to a cookie.
  5. User submits form via AJAX or via HTML form.
  6. Server checks custom header (or hidden form field) matches session stored token.
  7. Cookie is available in browser for use in additional AJAX and form requests without additional requests to server to retrieve the CSRF token.

Advantages:

  • Simple to implement.
  • Works with AJAX.
  • Works with forms.
  • Doesn't necessarily require an AJAX request to get the cookie value. Any HTTP request can retrieve it and it can be appended to all forms/AJAX requests via JavaScript.
  • Once the CSRF token has been retrieved, as it is stored in a cookie the value can be reused without additional requests.

Disadvantages:

  • All forms must have the value added to its HTML dynamically.
  • Any AJAX POSTs must also include the value.
  • The cookie will be submitted for every request (i.e. all GETs for images, CSS, JS, etc, that are not involved in the CSRF process) increasing request size.
  • Cookie cannot be HTTP Only.

So the cookie approach is fairly dynamic offering an easy way to retrieve the cookie value (any HTTP request) and to use it (JS can add the value to any form automatically and it can be employed in AJAX requests either as a header or as a form value). Once the CSRF token has been received for the session, there is no need to regenerate it as an attacker employing a CSRF exploit has no method of retrieving this token. If a malicious user tries to read the user's CSRF token in any of the above methods then this will be prevented by the Same Origin Policy. If a malicious user tries to retrieve the CSRF token server side (e.g. via curl) then this token will not be associated to the same user account as the victim's auth session cookie will be missing from the request (it would be the attacker's - therefore it won't be associated server side with the victim's session).

As well as the Synchronizer Token Pattern there is also the Double Submit Cookie CSRF prevention method, which of course uses cookies to store a type of CSRF token. This is easier to implement as it does not require any server side state for the CSRF token. The CSRF token in fact could be the standard authentication cookie when using this method, and this value is submitted via cookies as usual with the request, but the value is also repeated in either a hidden field or header, of which an attacker cannot replicate as they cannot read the value in the first place. It would be recommended to choose another cookie however, other than the authentication cookie so that the authentication cookie can be secured by being marked HttpOnly. So this is another common reason why you'd find CSRF prevention using a cookie based method.

How can you integrate a custom file browser/uploader with CKEditor?

Start by registering your custom browser/uploader when you instantiate CKEditor.

<script type="text/javascript">
CKEDITOR.replace('content', {
    filebrowserUploadUrl: "Upload File Url",//http://localhost/phpwork/test/ckFileUpload.php
    filebrowserWindowWidth  : 800,
    filebrowserWindowHeight : 500
});
</script>

Code for upload file(ckFileUpload.php) & put the upload file on root dir of your project.

// HERE SET THE PATH TO THE FOLDERS FOR IMAGES AND AUDIO ON YOUR SERVER (RELATIVE TO THE ROOT OF YOUR WEBSITE ON SERVER)

$upload_dir = array(
 'img'=> '/phpwork/test/uploads/editor-images/',
 'audio'=> '/phpwork/ezcore_v1/uploads/editor-images/'
);

// HERE PERMISSIONS FOR IMAGE
$imgset = array(
 'maxsize' => 2000,     // maximum file size, in KiloBytes (2 MB)
 'maxwidth' => 900,     // maximum allowed width, in pixels
 'maxheight' => 800,    // maximum allowed height, in pixels
 'minwidth' => 10,      // minimum allowed width, in pixels
 'minheight' => 10,     // minimum allowed height, in pixels
 'type' => array('bmp', 'gif', 'jpg', 'jpeg', 'png'),  // allowed extensions
);

// HERE PERMISSIONS FOR AUDIO
$audioset = array(
 'maxsize' => 20000,    // maximum file size, in KiloBytes (20 MB)
 'type' => array('mp3', 'ogg', 'wav'),  // allowed extensions
);

// If 1 and filename exists, RENAME file, adding "_NR" to the end of filename (name_1.ext, name_2.ext, ..)
// If 0, will OVERWRITE the existing file
define('RENAME_F', 1);

$re = '';
if(isset($_FILES['upload']) && strlen($_FILES['upload']['name']) >1) {
  define('F_NAME', preg_replace('/\.(.+?)$/i', '', basename($_FILES['upload']['name'])));  //get filename without extension

  // get protocol and host name to send the absolute image path to CKEditor
  $protocol = !empty($_SERVER['HTTPS']) ? 'https://' : 'http://';
  $site = $protocol. $_SERVER['SERVER_NAME'] .'/';
  $sepext = explode('.', strtolower($_FILES['upload']['name']));
  $type = end($sepext);    // gets extension
  $upload_dir = in_array($type, $imgset['type']) ? $upload_dir['img'] : $upload_dir['audio'];
  $upload_dir = trim($upload_dir, '/') .'/';

  //checkings for image or audio
  if(in_array($type, $imgset['type'])){
    list($width, $height) = getimagesize($_FILES['upload']['tmp_name']);  // image width and height
    if(isset($width) && isset($height)) {
      if($width > $imgset['maxwidth'] || $height > $imgset['maxheight']) $re .= '\\n Width x Height = '. $width .' x '. $height .' \\n The maximum Width x Height must be: '. $imgset['maxwidth']. ' x '. $imgset['maxheight'];
      if($width < $imgset['minwidth'] || $height < $imgset['minheight']) $re .= '\\n Width x Height = '. $width .' x '. $height .'\\n The minimum Width x Height must be: '. $imgset['minwidth']. ' x '. $imgset['minheight'];
      if($_FILES['upload']['size'] > $imgset['maxsize']*1000) $re .= '\\n Maximum file size must be: '. $imgset['maxsize']. ' KB.';
    }
  }
  else if(in_array($type, $audioset['type'])){
    if($_FILES['upload']['size'] > $audioset['maxsize']*1000) $re .= '\\n Maximum file size must be: '. $audioset['maxsize']. ' KB.';
  }
  else $re .= 'The file: '. $_FILES['upload']['name']. ' has not the allowed extension type.';

  //set filename; if file exists, and RENAME_F is 1, set "img_name_I"
  // $p = dir-path, $fn=filename to check, $ex=extension $i=index to rename
  function setFName($p, $fn, $ex, $i){
    if(RENAME_F ==1 && file_exists($p .$fn .$ex)) return setFName($p, F_NAME .'_'. ($i +1), $ex, ($i +1));
    else return $fn .$ex;
  }

  $f_name = setFName($_SERVER['DOCUMENT_ROOT'] .'/'. $upload_dir, F_NAME, ".$type", 0);
  $uploadpath = $_SERVER['DOCUMENT_ROOT'] .'/'. $upload_dir . $f_name;  // full file path

  // If no errors, upload the image, else, output the errors
  if($re == '') {
    if(move_uploaded_file($_FILES['upload']['tmp_name'], $uploadpath)) {
      $CKEditorFuncNum = $_GET['CKEditorFuncNum'];
      $url = $site. $upload_dir . $f_name;
      $msg = F_NAME .'.'. $type .' successfully uploaded: \\n- Size: '. number_format($_FILES['upload']['size']/1024, 2, '.', '') .' KB';
      $re = in_array($type, $imgset['type']) ? "window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum, '$url', '$msg')"  //for img
       : 'var cke_ob = window.parent.CKEDITOR; for(var ckid in cke_ob.instances) { if(cke_ob.instances[ckid].focusManager.hasFocus) break;} cke_ob.instances[ckid].insertHtml(\'<audio src="'. $url .'" controls></audio>\', \'unfiltered_html\'); alert("'. $msg .'"); var dialog = cke_ob.dialog.getCurrent();  dialog.hide();';
    }
    else $re = 'alert("Unable to upload the file")';
  }
  else $re = 'alert("'. $re .'")';
}

@header('Content-type: text/html; charset=utf-8');
echo '<script>'. $re .';</script>';

Ck-editor documentation is not clear after doing alot of R&D for custom file upload finally i have found this solution. It work for me and i hope it will helpful to others as well.

Using Excel VBA to export data to MS Access table

@Ahmed

Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".

Sub test()
    dbWb = Application.ActiveWorkbook.FullName
    dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2"  'Data2 is a named range


sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh

Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command

dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon

dbCommand.CommandText = sCommand
dbCommand.Execute

dbCon.Close


End Sub

How to negate the whole regex?

Apply this if you use laravel.

Laravel has a not_regex where field under validation must not match the given regular expression; uses the PHP preg_match function internally.

'email' => 'not_regex:/^.+$/i'

What is a clean, Pythonic way to have multiple constructors in Python?

class Cheese:
    def __init__(self, *args, **kwargs):
        """A user-friendly initialiser for the general-purpose constructor.
        """
        ...

    def _init_parmesan(self, *args, **kwargs):
        """A special initialiser for Parmesan cheese.
        """
        ...

    def _init_gauda(self, *args, **kwargs):
        """A special initialiser for Gauda cheese.
        """
        ...

    @classmethod
    def make_parmesan(cls, *args, **kwargs):
        new = cls.__new__(cls)
        new._init_parmesan(*args, **kwargs)
        return new

    @classmethod
    def make_gauda(cls, *args, **kwargs):
        new = cls.__new__(cls)
        new._init_gauda(*args, **kwargs)
        return new

Show a number to two decimal places

$twoDecNum = sprintf('%0.2f', round($number, 2));

The rounding correctly rounds the number and the sprintf forces it to 2 decimal places if it happens to to be only 1 decimal place after rounding.

What is the difference between a "line feed" and a "carriage return"?

Both of these are primary from the old printing days.

Carriage return is from the days of the teletype printers/old typewriters, where literally the carriage would return to the next line, and push the paper up. This is what we now call \r.

Line feed LF signals the end of the line, it signals that the line has ended - but doesn't move the cursor to the next line. In other words, it doesn't "return" the cursor/printer head to the next line.

For more sundry details, the mighty wikipedia to the rescue.

CSS background image alt attribute

It''s not clear to me what you want.

If you want a CSS property to render the alt attribute value, then perhaps you're looking for the CSS attribute function for example:

IMG:before { content: attr(alt) }

If you want to put the alt attribute on a background image, then ... that's odd because the alt attribute is an HTML attribute whereas the background image is a CSS property. If you want to use the HTML alt attribute then I think you'd need a corresponding HTML element to put it in.

Why do you "need to use alt tags on background images": is this for a semantic reason or for some visual-effect reason (and if so, then what effect or what reason)?

T-SQL: Deleting all duplicate rows but keeping one

You didn't say what version you were using, but in SQL 2005 and above, you can use a common table expression with the OVER Clause. It goes a little something like this:

WITH cte AS (
  SELECT[foo], [bar], 
     row_number() OVER(PARTITION BY foo, bar ORDER BY baz) AS [rn]
  FROM TABLE
)
DELETE cte WHERE [rn] > 1

Play around with it and see what you get.

(Edit: In an attempt to be helpful, someone edited the ORDER BY clause within the CTE. To be clear, you can order by anything you want here, it needn't be one of the columns returned by the cte. In fact, a common use-case here is that "foo, bar" are the group identifier and "baz" is some sort of time stamp. In order to keep the latest, you'd do ORDER BY baz desc)

How can I list all the deleted files in a Git repository?

Show all deleted files in some_branch

git diff origin/master...origin/some_branch --name-status | grep ^D

or

git diff origin/master...origin/some_branch --name-status --diff-filter=D 

AJAX cross domain call

You will need to dynamically insert a script tag into the page that references the data. Using JSONP, you can execute some callback function when the script has loaded.

The wikipedia page on JSONP has a concise example; the script tag:

<script type="text/javascript" src="http://domain1.com/getjson?jsonp=parseResponse">
</script>

would return the JSON data wrapped in a call to parseResponse:

parseResponse({"Name": "Cheeso", "Rank": 7})

(depending on the configuration of the getjson script on domain1.com)

The code to insert the tag dynamically would be something like:

var s = document.createElement("script");
s.src = "http://domain1.com/getjson?jsonp=parseResponse";
s.type = "text/javascript";
document.appendChild(s);

CSS to set A4 paper size

I looked into this a bit more and the actual problem seems to be with assigning initial to page width under the print media rule. It seems like in Chrome width: initial on the .page element results in scaling of the page content if no specific length value is defined for width on any of the parent elements (width: initial in this case resolves to width: auto ... but actually any value smaller than the size defined under the @page rule causes the same issue).

So not only the content is now too long for the page (by about 2cm), but also the page padding will be slightly more than the initial 2cm and so on (it seems to render the contents under width: auto to the width of ~196mm and then scale the whole content up to the width of 210mm ~ but strangely exactly the same scaling factor is applied to contents with any width smaller than 210mm).

To fix this problem you can simply in the print media rule assign the A4 paper width and hight to html, body or directly to .page and in this case avoid the initial keyword.

DEMO

@page {
  size: A4;
  margin: 0;
}
@media print {
  html, body {
    width: 210mm;
    height: 297mm;
  }
  /* ... the rest of the rules ... */
}

This seems to keep everything else the way it is in your original CSS and fix the problem in Chrome (tested in different versions of Chrome under Windows, OS X and Ubuntu).

Python - Get path of root project structure

If you are working with anaconda-project, you can query the PROJECT_ROOT from the environment variable --> os.getenv('PROJECT_ROOT'). This works only if the script is executed via anaconda-project run .

If you do not want your script run by anaconda-project, you can query the absolute path of the executable binary of the Python interpreter you are using and extract the path string up to the envs directory exclusiv. For example: The python interpreter of my conda env is located at:

/home/user/project_root/envs/default/bin/python

# You can first retrieve the env variable PROJECT_DIR.
# If not set, get the python interpreter location and strip off the string till envs inclusiv...

if os.getenv('PROJECT_DIR'):
    PROJECT_DIR = os.getenv('PROJECT_DIR')
else:
    PYTHON_PATH = sys.executable
    path_rem = os.path.join('envs', 'default', 'bin', 'python')
    PROJECT_DIR = py_path.split(path_rem)[0]

This works only with conda-project with fixed project structure of a anaconda-project

How to declare an array of strings in C++?

#include <iostream>
#include <string>
#include <vector>
#include <boost/assign/list_of.hpp>

int main()
{
    const std::vector< std::string > v = boost::assign::list_of( "abc" )( "xyz" );
    std::copy(
        v.begin(),
        v.end(),
        std::ostream_iterator< std::string >( std::cout, "\n" ) );
}

Changing java platform on which netbeans runs

You can change the JDK for Netbeans by modifying the config file:

  1. Open netbeans.conf file available under etc folder inside the NetBeans installation.
  2. Modify the netbeans_jdkhome variable to point to new JDK path, and then
  3. Restart your Netbeans.

Dynamically Add C# Properties at Runtime

Thanks @Clint for the great answer:

Just wanted to highlight how easy it was to solve this using the Expando Object:

    var dynamicObject = new ExpandoObject() as IDictionary<string, Object>;
    foreach (var property in properties) {
        dynamicObject.Add(property.Key,property.Value);
    }

SQL Server: the maximum number of rows in table

SELECT Top 1 sysobjects.[name], max(sysindexes.[rows]) AS TableRows, 
  CAST( 
    CASE max(sysindexes.[rows]) 
      WHEN 0 THEN -0 
      ELSE LOG10(max(sysindexes.[rows])) 
    END 
    AS NUMERIC(5,2)) 
  AS L10_TableRows 
FROM sysindexes INNER JOIN sysobjects ON sysindexes.[id] = sysobjects.[id] 
WHERE sysobjects.xtype = 'U' 
GROUP BY sysobjects.[name] 
ORDER BY max(rows) DESC

Remove #N/A in vlookup result

If you only want to return a blank when B2 is blank you can use an additional IF function for that scenario specifically, i.e.

=IF(B2="","",VLOOKUP(B2,Index!A1:B12,2,FALSE))

or to return a blank with any error from the VLOOKUP (e.g. including if B2 is populated but that value isn't found by the VLOOKUP) you can use IFERROR function if you have Excel 2007 or later, i.e.

=IFERROR(VLOOKUP(B2,Index!A1:B12,2,FALSE),"")

in earlier versions you need to repeat the VLOOKUP, e.g.

=IF(ISNA(VLOOKUP(B2,Index!A1:B12,2,FALSE)),"",VLOOKUP(B2,Index!A1:B12,2,FALSE))

How do I embed a mp4 movie into my html?

Most likely the TinyMce editor is adding its own formatting to the post. You'll need to see how you can escape TinyMce's editing abilities. The code works fine for me. Is it a wordpress blog?

OpenCV - DLL missing, but it's not?

Copy all .dll from /bin in System32

How to Delete a directory from Hadoop cluster which is having comma(,) in its name?

Run the command in the terminal

$hadoop fs -rm -r /path/to/directory

Makefile ifeq logical or

You can introduce another variable. It doesnt consolidate both checks, but it at least avoids having to put the body in twice:

do_it = 
ifeq ($(GCC_MINOR), 4)
    do_it = yes
endif
ifeq ($(GCC_MINOR), 5)
    do_it = yes
endif
ifdef do_it
    CFLAGS += -fno-strict-overflow
endif

Java, how to compare Strings with String Arrays

I presume you are wanting to check if the array contains a certain value, yes? If so, use the contains method.

if(Arrays.asList(codes).contains(userCode))

PostgreSQL error 'Could not connect to server: No such file or directory'

"Postgres.app" is a better fix if you are on OS X


Here is the fix:

  1. Stop the database
  2. cd /var
  3. sudo rm -r pgsql_socket
  4. sudo ln -s /tmp pgsql_socket
  5. chown _postgres:_postgres pgsql_socket
  6. Restart PostgreSQL (not your computer)

More information is available at "postgresql 9.0.3. on Lion Dev Preview 1".

How to align center the text in html table row?

HTML in line styling example:

<td style='text-align:center; vertical-align:middle'></td> 

CSS file example:

td {
    text-align: center;
    vertical-align: middle;
}

How do I specify the columns and rows of a multiline Editor-For in ASP.MVC?

In .net VB - you could achieve control over columns and rows with the following in your razor file:

@Html.EditorFor(Function(model) model.generalNotes, New With {.htmlAttributes = New With {.class = "someClassIfYouWant", .rows = 5,.cols=6}})

How do you detect where two line segments intersect?

This based on Gareth Ree's answer. It also returns the overlap of the line segments if they do. Coded in C++, V is a simple vector class. Where the cross product of two vectors in 2D returns a single scalar. It was tested and passed by my schools automatic testing system.

//Required input point must be colinear with the line
bool on_segment(const V& p, const LineSegment& l)
{
    //If a point is on the line, the sum of the vectors formed by the point to the line endpoints must be equal
    V va = p - l.pa;
    V vb = p - l.pb;
    R ma = va.magnitude();
    R mb = vb.magnitude();
    R ml = (l.pb - l.pa).magnitude();
    R s = ma + mb;
    bool r = s <= ml + epsilon;
    return r;
}

//Compute using vector math
// Returns 0 points if the lines do not intersect or overlap
// Returns 1 point if the lines intersect
//  Returns 2 points if the lines overlap, contain the points where overlapping start starts and stop
std::vector<V> intersect(const LineSegment& la, const LineSegment& lb)
{
    std::vector<V> r;

    //http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
    V oa, ob, da, db; //Origin and direction vectors
    R sa, sb; //Scalar values
    oa = la.pa;
    da = la.pb - la.pa;
    ob = lb.pa;
    db = lb.pb - lb.pa;

    if (da.cross(db) == 0 && (ob - oa).cross(da) == 0) //If colinear
    {
        if (on_segment(lb.pa, la) && on_segment(lb.pb, la))
        {
            r.push_back(lb.pa);
            r.push_back(lb.pb);
            dprintf("colinear, overlapping\n");
            return r;
        }

        if (on_segment(la.pa, lb) && on_segment(la.pb, lb))
        {
            r.push_back(la.pa);
            r.push_back(la.pb);
            dprintf("colinear, overlapping\n");
            return r;
        }

        if (on_segment(la.pa, lb))
            r.push_back(la.pa);

        if (on_segment(la.pb, lb))
            r.push_back(la.pb);

        if (on_segment(lb.pa, la))
            r.push_back(lb.pa);

        if (on_segment(lb.pb, la))
            r.push_back(lb.pb);

        if (r.size() == 0)
            dprintf("colinear, non-overlapping\n");
        else
            dprintf("colinear, overlapping\n");

        return r;
    }

    if (da.cross(db) == 0 && (ob - oa).cross(da) != 0)
    {
        dprintf("parallel non-intersecting\n");
        return r;
    }

    //Math trick db cross db == 0, which is a single scalar in 2D.
    //Crossing both sides with vector db gives:
    sa = (ob - oa).cross(db) / da.cross(db);

    //Crossing both sides with vector da gives
    sb = (oa - ob).cross(da) / db.cross(da);

    if (0 <= sa && sa <= 1 && 0 <= sb && sb <= 1)
    {
        dprintf("intersecting\n");
        r.push_back(oa + da * sa);
        return r;
    }

    dprintf("non-intersecting, non-parallel, non-colinear, non-overlapping\n");
    return r;
}

C - determine if a number is prime

Check the modulus of each integer from 2 up to the root of the number you're checking.

If modulus equals zero then it's not prime.

pseudo code:

bool IsPrime(int target)
{
  for (i = 2; i <= root(target); i++)
  {
    if ((target mod i) == 0)
    {
      return false;
    }
  }

  return true;
}

parsing a tab-separated file in Python

You can use the csv module to parse tab seperated value files easily.

import csv

with open("tab-separated-values") as tsv:
    for line in csv.reader(tsv, dialect="excel-tab"): #You can also use delimiter="\t" rather than giving a dialect.
        ... 

Where line is a list of the values on the current row for each iteration.

Edit: As suggested below, if you want to read by column, and not by row, then the best thing to do is use the zip() builtin:

with open("tab-separated-values") as tsv:
    for column in zip(*[line for line in csv.reader(tsv, dialect="excel-tab")]):
        ...

int *array = new int[n]; what is this function actually doing?

int *array = new int[n];

It declares a pointer to a dynamic array of type int and size n.

A little more detailed answer: new allocates memory of size equal to sizeof(int) * n bytes and return the memory which is stored by the variable array. Also, since the memory is dynamically allocated using new, you've to deallocate it manually by writing (when you don't need anymore, of course):

delete []array;

Otherwise, your program will leak memory of at least sizeof(int) * n bytes (possibly more, depending on the allocation strategy used by the implementation).

Read a text file using Node.js?

You can use readstream and pipe to read the file line by line without read all the file into memory one time.

var fs = require('fs'),
    es = require('event-stream'),
    os = require('os');

var s = fs.createReadStream(path)
    .pipe(es.split())
    .pipe(es.mapSync(function(line) {
        //pause the readstream
        s.pause();
        console.log("line:", line);
        s.resume();
    })
    .on('error', function(err) {
        console.log('Error:', err);
    })
    .on('end', function() {
        console.log('Finish reading.');
    })
);

Custom Listview Adapter with filter Android

First you create the EditText in the xml file and assign an id, eg con_pag_etPesquisa. After that, we will create two lists, where one is the list view and the other to receive the same content but will remain as a backup. Before moving objects to lists first initializes Them the below:

//Declaring

public EditText etPesquisa;

public ContasPagarAdapter adapterNormal;

public List<ContasPagar> lstBkp;

public List<ContasPagar> lstCp;

//Within the onCreate method, type the following:

etPesquisa = (EditText) findViewById(R.id.con_pag_etPesquisa);

etPesquisa.addTextChangedListener(new TextWatcher(){

    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3){
        filter(String.valueOf(cs));
    }
    @Override
    public void beforeTextChanged(CharSequence cs, int arg1, int arg2, int arg3){

    // TODO Auto-generated method stub
    }
    @Override
    public void afterTextChanged(Editable e){

    }

});

//Before moving objects to lists first initializes them as below:

lstCp = new ArrayList<ContasPagar>();

lstBkp = new ArrayList<ContasPagar>();


//When you add objects to the main list, repeat the procedure also for bkp list, as follows:

lstCp.add(cp);

lstBkp.add(cp);


//Now initializes the adapter and let the listener, as follows:

adapterNormal = new ContasPagarAdapter(ContasPagarActivity.this, lstCp);

lvContasPagar.setAdapter(adapterNormal);
                    lvContasPagar.setOnItemClickListener(verificaClickItemContasPagar(lstCp));


//Now create the methods inside actito filter the text entered by the user, as follows:

public void filter(String charText){

    charText = charText.toLowerCase();

    lstCp.clear();

    if (charText.length() == 0){

        lstCp.addAll(lstBkp);

        appendAddItem(lstBkp);

    } 

    else {

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

            if((lstBkp.get(i).getNome_lancamento() + " - " + String.valueOf(lstBkp.get(i).getCodigo())).toLowerCase().contains(charText)){

                lstCp.add(lstBkp.get(i));

            }

        }

        appendAddItem(lstCp);
    }
}

private void appendAddItem(final List<ContasPagar> novaLista){
    runOnUiThread(new Runnable(){

        @Override
            public void run(){
                adapterNormal.notifyDataSetChanged();               
            }
        });
    }

Check if PHP-page is accessed from an iOS device

It's work for Iphone

<?php
  $browser = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
  if ($browser == true){
    $browser = 'iphone';
  }
?>

Drop multiple tables in one shot in MySQL

declare @sql1 nvarchar(max) 
SELECT @sql1 =
  STUFF(
         (
           select ' drop table dbo.[' + name + ']'

           FROM sys.sysobjects AS sobjects
           WHERE (xtype = 'U') AND (name LIKE 'GROUP_BASE_NEW_WORK_%')
           for xml path('')
        ),
     1, 1, '')

  execute sp_executesql @sql1

How to initialize an array of objects in Java

If you can hard-code the number of players

Player[] thePlayers = {
    new Player(0),
    new Player(1),
    new Player(2),
    new Player(3)
};