text:
Q: How to create a label inside an  element? I would like to insert a descriptive text inside an input element that disappers when the user click on it.
I know it is a very common trick, but I do not know how to do that..
What is the simplest/better solution?

A: The common approach is to use the default value as a label, and then remove it when the field gains the focus.
I really dislike this approach as it has accessibility and usability implications.
Instead, I would start by using a standard  element next to the field.
Then, if JavaScript is active, set a class on an ancestor element which causes some new styles to apply that:

*

*Relatively position a div that contains the input and label

*Absolutely position the label

*Absolutely position the input on top of the label

*Remove the borders of the input and set its background-color to transparent

Then, and also whenever the input loses the focus, I test to see if the input has a value. If it does, ensure that an ancestor element has a class (e.g. "hide-label"), otherwise ensure that it does not have that class.
Whenever the input gains the focus, set that class.
The stylesheet would use that classname in a selector to hide the label (using text-indent: -9999px; usually).
This approach provides a decent experience for all users, including those with JS disabled and those using screen readers.

A: I've put together solutions proposed by
@Cory Walker with the extensions from @Rafael
and the one form @Tex witch was a bit complicated for me
and came up with a solution that is hopefully
error-proof with javascript and CSS disabled.
It manipulates with the background-color of the form field to show/hide the label.
<head>

<style type="text/css">
<!--
    input {position:relative;background:transparent;}
-->
</style>

<script>
    function labelPosition() {
        document.getElementById("name").style.position="absolute";
            // label is moved behind the textfield using the script,
            // so it doesnt apply when javascript disabled
    }
</script>

</head>
<body onload="labelPosition()">

<form>
        <label id="name">Your name</label>
        <input type="text" onblur="if(this.value==''){this.style.background='transparent';}" onfocus="this.style.background='white'">
</form>

</body>

View the script in action: http://mattr.co.uk/work/form_label.html

A: <input name="searchbox" onfocus="if (this.value=='search') this.value = ''" type="text" value="search">

A better example would be the SO search button! That's where I got this code from. Viewing page source is a valuable tool.

A: In my opinion, the best solution involves neither images nor using the input's default value. Rather, it looks something like David Dorward's solution.
It's easy to implement and degrades nicely for screen readers and users with no javascript.
Take a look at the two examples here:
http://attardi.org/labels/
I usually use the second method (labels2) on my forms.

A: If you're using HTML5, you can use the placeholder attribute.
<input type="text" name="user" placeholder="Username">

A: <input name="searchbox" onfocus="if (this.value=='search') this.value = ''" onblur="if (this.value=='') this.value = 'search'" type="text" value="search">

Add an onblur event too.

A: When you start typing it will disappear.If empty it will appear again.
        <%= f.text_field :user_email,:value=>"",:placeholder => "Eg:abc@gmail.com"%>

Simplest way...

A: Please use PlaceHolder.JS its works in all browsers and very easy for non html5 compliant browsers
 http://jamesallardice.github.io/Placeholders.js/

A: One hint about HTML property placeholder and the tag textarea, please make sure there is no any space between <textarea> and </textarea>, otherwise the placeholder doesn't work, for example:
<textarea id="inputJSON" spellcheck="false" placeholder="JSON response string" style="flex: 1;"> </textarea>

This won't work, because there is a space between...

A: use this
style:
<style type="text/css">
    .defaultLabel_on { color:#0F0; }
    .defaultLabel_off { color:#CCC; }
</style>

html:

javascript:
function defaultLabelClean() {
    inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++)  {
        if (inputs[i].value == inputs[i].getAttribute("innerLabel")) {
            inputs[i].value = '';
        }
    }
}

function defaultLabelAttachEvents(element, label) {
    element.setAttribute("innerLabel", label);
    element.onfocus = function(e) {
        if (this.value==label) {
            this.className = 'defaultLabel_on';
            this.value = '';
        }
    }
    element.onblur = function(e) {
        if (this.value=='') {
            this.className = 'defaultLabel_off';
            this.value = element.getAttribute("innerLabel");
        }
    }

    if (element.value=='') {
        element.className = 'defaultLabel_off';
        element.value = element.getAttribute("innerLabel");
    }
}

defaultLabelAttachEvents(document.getElementById('MYID'), "MYLABEL");

Just remember to call defaultLabelClean() function before submit form.
good work

A: You do not need a Javascript code for that...
I think you mean the placeholder attribute. Here is the code:
<input type="text" placeholder="Your descriptive text goes here...">

The default text will be grey-ish and when clicked, it will dissapear!

A: I think its good to keep the Label and not to use placeholder as mentioned above. Its good for UX as explain here:
https://www.smashingmagazine.com/2018/03/ux-contact-forms-essentials-conversions/
Here example with Label inside Input fields:
 codepen.io/jdax/pen/mEBJNa

A: Here is a simple example, all it does is overlay an image (with whatever wording you want).  I saw this technique somewhere.  I am using the prototype library so you would need to modify if using something else.  With the image loading after window.load it fails gracefully if javascript is disabled.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1;" />
    <meta http-equiv="Expires" content="Fri, Jan 1 1981 08:00:00 GMT" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Cache-Control" content="no-cache" />
    <style type="text/css" >

        input.searcher
        {
            background-image: url(/images/search_back.png);
            background-repeat: no-repeat;
            background-attachment: scroll;
            background-x-position: left;
            background-y-position: center;
        }

    </style>

    <script type="text/javascript" src="/logist/include/scripts/js/prototype.js" ></script>
</head>
<body>
    <input type="text" id="q" name="q" value="" />

    <script type="text/javascript" language="JavaScript" >
    //  <![CDATA[
        function f(e){
            $('q').removeClassName('searcher');
        }

        function b(e){
            if ( $F('q') == '' )
            {
                $('q').addClassName('searcher');
            }
        }

        Event.observe( 'q', 'focus', f);
        Event.observe( 'q', 'blur', b);
        Event.observe( window, 'load', b);

    //  ]]>
    </script>
</body>
</html>


text:
Q: How to get rid of value error showing could not convert string to float in python I was running the following code
lr=LinearRegression()
lr.fit(x_train,y_train)
print(lr.coef_)

But I was getting error like
Value Error: could not convert string to float: '20140527T000000'
How can I solve this?

A: It's look like you tried to convert a string that does not contain a float number to a float. If the python string is not formatted as a floating point number, you could not convert string to float.
Try to find which column is throwing this error and review the column to find the outliers. If the column only contains numerical and null values, then your code will run without the given error

redpajama_set_name: RedPajamaStackExchange


text:
Q: Laravel like query exact match I'm uploading a CSV file to my database and I want to automatically add a projecttype_id to a project, given this two project types:

*

*Roads, new construction, widening

*Roads, new construction

when I tried to upload "Roads, new construction" it always gives me the first id.
Tried removing % but still the same:
$projecttypeid = ProjectType::where('name', 'LIKE', "%{$projecttype}%")->first('id');

A: No need for LIKE if you want an exact match. where('name', $projecttype)


text:
Q: Cleaning Search History: Windows-10 I am giving away my laptop without deleting my user account. I want to clean the hard disk as much as possible.
I have already deleted the search history and cleared search indexing. But still, as soon as I type any applications name, I start seeing suggestion about some related file names. The funny thing is, those do not exist on the computer anymore.
How can I clear the recent suggestions?

A: The search results shown are from the "recently opened items" for the App Jump lists, the pop-up menu when you right-click on an App.
To delete them through windows, go into "settings" and select the "Personalization" option. Once inside, select the "Start" option on the left-side menu, and look for the toggle for "Show recently opened items in Jump Lists..." on the right-side panel. Make sure you switch the toggle to "off" and it should clear the recent suggestions. There is an illustrated guide on How-To Geek, just be aware that the windows 10 shown there is an older version and may have slightly different options than current versions.


text:
Q: Align equation to bracket in Microsoft Word I need to align the second equation to the left, do you have any advice on how to do it?
Already tried through the align left(Alt+L), and inserting "&" before the second equation.

A: Press Alt + = to insert an equation box. Or for mac user may use Ctlr + =.
Then, write
\cases (&sin(\alpha-\varphi)=0 \Rightarrow \alpha-\varphi-0@&-l_m e^(t/T_a )=0 \Rightarrow l_m=0)

A: It depends on how you got the double-height curly bracket in the first place. Here is a way to do it starting from scratch.
From this Microsoft Answers article:

*

*Press Alt+= to insert an equation box.

*On the Equation Tools tab, click the Bracket button. Scroll down the gallery and click the icon for the single left bracket, which is accompanied by a little placeholder box.

*Click inside the placeholder box. On the Equation Tools tab, click the Matrix button and click the icon for the two boxes set up vertically. Now your placeholder box has turned into two placeholder boxes, and the bracket has stretched to the proper height.

*Right-click any of the two placeholders, click Column Alignment, and click Left.

*Click in each of the two placeholder boxes in turn and type the [content] that you want there.

A: Add spaces at the end of the second equation.
The entire string will stay centered, but the relevant equation will be shifted leftwards due to the introduction of space characters.


text:
Q: Search Text and Replace with JavaScript Example I've this code:

 I make you smile.

Transformed to:

 I make you think.

Note: "smile" was replaced to "think"
How can I replace it, using javascript jQuery? It's possible to change several words?

A: var ele = $("div.description");                     //Let ele be target element
ele.html(ele.html().replace(/smile/gi,"think"));    //Replace the word in string,
                                                    // then put it back in.

.replace: MDN
Demo: http://jsfiddle.net/DerekL/FdyEH/


text:
Q: Servers can only ping to domain controllers and not to each other I have made my own test environment and I am having problems with pinging other servers from one server. All servers can ping to domain controllers and they get responded back. When I ping from a server to another server, I get following message "Destination host unreachable." Running Windows Server 2012 R2 all on servers and DCs
They all have static IPs

A: Check to make sure all systems are listed properly in DNS. For your DC follow this, or check your install against it.
http://social.technet.microsoft.com/wiki/contents/articles/12370.windows-server-2012-set-up-your-first-domain-controller-step-by-step.aspx
We typically assume that if you don't mention the version of OS your using the most current, if not don't forget to mention the version (2005/2008/2012) you'll get more specific answers that way.
ALSO check your hosts files:
C:\windows\system32\drivers\etc\hosts
The best way to find this is windows explorer and type the path, the etc folder is typically hidden.

A: I infer you're referring to ICMP (IPv4) echo-request, not to its ICMPv6 analogon.
It appears your servers are connected by a node that acts as a gateway in the sense of rfc792:

Destination Unreachable Message
     [...]
    Code
      [...]
      1 = host unreachable;

  [...]

  Codes 0, 1, 4, and 5 may be received from a gateway.  Codes 2 and
  3 may be received from a host.

that cannot (or doesn't) forward the ICMP echo-request.
More in-depth analysis of the issue would require more in-depth information about your network topology.


text:
Q: find the nth fibonacci number where each number of is sum of last 3 numbers. Using differential equations , I have seen some sites which solve the fibonacci number problem and give us a formula to find the nth fibonacci number.
Similarly I want to find the nth fibonacci number where each number is equal to "LAST THREE" numbers.
Example :
0 1 1 2 4 7 13 .....
How to get the exact formula to find the Nth fibonacci number by removing the recursion from it ?
F(n) = F(n-1) + F(n-2) + F(n-3)

After solving the differential equations :
F(n) = Expression of constants which only depends on "n" .

What is the formula for F(n) ?

Also is it possible to get a formula to find the Nth fibonacci number where each number is equal to the sum of previous "M" numbers ?
F(n,m) = ???

Note : I am not a math student :/

A: The solutions of these generalized Fibonacci problems rest on the resolution of the characteristic equation
$$r^m=r^{m-1}+r^{m-2}+\cdots r+1.$$
which can also be written
$$r^{m+1}-2r^{m}+1=0$$
or
$$1-2s+s^{m+1}=0$$
(where the solution $r=1$ must be discarded, and $s:=r^{-1}$). This equation has real as well as complex roots.
Hence the solution of the recurrence is a linear combination of terms $$(a\cos(n\omega)+b\sin(n\omega))e^{n\tau}$$ where the constants $a,b$ are determined from the initial terms of the sequence (which you forgot to specify) and $\tau,\omega$ are the real and imaginary parts of the roots.
Note that one of the roots clearly dominates the others in modulus, and tends to $2$ with increasing $m$. Hence for large $m$ and large $n$, the solution is close to
$$c2^n.$$
This is justified by
$$2^{m}\approx 2^{m-1}+2^{m-2}+\cdots 2+1.$$


text:
Q: Inherent UIView leak When ran in activity monitor, the real memory usage for a program running the following piece of code will increase endlessly:
CGRect frame = CGRectMake(0,0,0,0);
while(true)
{
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    UIView *test = [[UIView alloc] initWithFrame:frame];
    [test release];
    [pool release];
}

What happens is that all objects derived from UIView will leak. Some will leak more than others (UITextView in particular has drawn atention to this problem). The leaks are not actualy discovered in the leaks monitor - their presence is only revealed by the constant increase in memory usage - which eventualy leads to the app being terminated by the OS because of memory exhaustion.
Has anyone noticed this before? For the record, the code was compiled for OS 3.0.

A: I guess this is an issue with Instruments. Instruments does not work correctly when using with iPhone OS 3.0, e.g. you can't see a stack trace. When using 3.1 in the simulator, this issue disappears (see images). The fact that these do not show up as leaks in Instruments contributes to my assumption.
Of course it could also be that this was indeed an issue with iPhone OS 3.0 and has been fixed in iPhone OS 3.1.

(source: hillrippers.ch)
^^ Instruments with OS 3.0

(source: hillrippers.ch)
^^ Instruments with OS 3.1
This is the code used (in applicationDidFinishLaunching:)
NSUInteger i = 0;
CGRect frame = CGRectMake(0.f, 0.f, 100.f, 50.f);
while (i < 100000) {
    UIView *test = [[UIView alloc] initWithFrame:frame];
    [test release];
    i++;
}

A: It could be that UIKit is using shared singleton objects when constructing UIView and something allocated by those singletons are not necessarily cleaned by NSAutoreleasePool but is cleaned during standard event loop execution via other means.

A: I agree this is likely a bug in iPhoneOS. It looks like the CALayer is not getting released. If you force an extra release of the CALayer ([test.layer release], which is an insane thing to do, but "works"), you'll dramatically reduce memory usage, but you'll find that QuartCore is still leaking at least 16 bytes per iteration, which adds up fast in your stress case. I'd open a radar (bugreporter.apple.com).


text:
Q: Github: Reject commits containing DOS newline characters Is there a way for github to completely reject a commit if DOS newline characters are in any of the files?
(I know the github interface has a setting to make sure the DOS newline characters are not committed, but in the case that this setting isn't turned on, I'd like some insurance.)

A:
Is there a way for github to completely reject a commit

That sounds like a server-side hook. That isn't possible: a GitHub webhook can register a push event, not reject a push.
That leaves you with a client side hook (which needs to be deployed on all client, and can be bypassed anyway)
A pre-commit hook is more sensible in that case (no need to wait for the push to discover a commit with a wrong content).
You also have then option of .gitattributes (see "Mind the End of Your Line") in order to instruct git to always replace CRLF by LF (*.txt eol=lf): see .gitattributes End-of-line conversion.
That is more robust than a client-side hook.


text:
Q: Web Programming Cross Browser Frustrations Normal? So I'm a relatively junior programmer, been doing it for a couple years now and have been recently working on a redo of the company's website, and have ran into some frustrations and was just wondering if that's the way it goes or if I'm missing something. I am by no means a designer, I focus on the code and don't pay much attention to how pretty it looks, that's someone else's job as far as I'm concerned.
That being said, I have been working on getting some things to work and the cross Browser problems have made me hate Web Development. I try to get html5 videos and no go, put in a flash backup and only works on half. Throw a Google api in and it looks like crap in ie and opera. The actual code behind doesn't work in ie7. It just seems like one thing after another. As I said I'm new to Web Development. Is this just the way it is? Throw some basic code in, then take all day/week to make it work everywhere?  I've cooled off since my initial frustration but I'm just wondering if this is normal practice or how typical web programming goes, because it seems pretty lousy to be right about now. Thanks!

A: In the beginning, there were standards. Then, every browser decided to interpret them differently, add new features, and just plain forget the standard. Unfortunately, coding against all these browsers is a headache. Most of the normal layout will "just work," but fancy things (HTML5, CSS3, etc.) will not work in older versions of IE and probably doesn't work quite the same across all browsers (we have the standard border-shading CSS property, the -webkit and -mozilla prefixes for older versions of those browsers, and ActiveX filters to make IE do the same thing).
There is some hope, though. Browsers are getting better every release. IE 10 is far more compliant than IE 7, which is something you specifically called out. There are also HTML 5 shims that you can use to add some support for older browsers. JavaScript frameworks like jQuery iron out peculiar DOM bugs and other inconsistencies in implementations (although you'll want to use the 1.9 branch rather than the new 2.0 branch to keep support for legacy browsers). The web is slowly getting better, but until we can all agree on everything, you have ease of programming, browser support, and functionality to consider. You can only pick two.


text:
Q: Location services across multiple activities UPDATE - edited code to display my broadcast idea. Using the method causes a !!! FAILED BINDER TRANSACTION !!! and no location data to be displayed by toast.
I was wondering if there was an elegant way to separate google fused location services away from activities. My warning class currently implements location services but I have another activity that takes photos. When a photo is taken I want to associate a location with the image. My current idea is to just use my broadcast receiver in my Bluetooth warning class to listen for a broadcast my camera will send and associate it then with a location. I'm not a fan of the idea because it doesn't separate functionality very well so was hoping for some suggestions or patterns. Code for classes below.
CAMERA CLASS
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CameraOperations extends AppCompatActivity {
    public final static String ACTION_PICTURE_RECEIVED = "ACTION_PICTURE_RECEIVED";
    public final static String TRANSFER_DATA = "bitmap";
    ImageView mImageView;
    String photoPath;
    int REQUEST_IMAGE_CAPTURE = 1;
    File photoFile = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera_view);
        mImageView = (ImageView) findViewById(R.id.imageView);

        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            Toast.makeText(CameraOperations.this, "No Camera", Toast.LENGTH_SHORT).show();
        } else {
            dispatchTakePictureIntent();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK){
            if(data == null){
                Toast.makeText(this, "Data is null", Toast.LENGTH_SHORT);
                Bitmap pictureMap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
                mImageView.setImageBitmap(pictureMap);
                broadcastUpdate(ACTION_PICTURE_RECEIVED, pictureMap);
            }else {
                Toast.makeText(this, "Error Occurred", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void broadcastUpdate(final String action, Bitmap picture) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        picture.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte[] bytes = stream.toByteArray();

        Intent intent = new Intent(action);
        intent.putExtra(TRANSFER_DATA, bytes);
        sendBroadcast(intent);

        intent = new Intent(CameraOperations.this, Warning.class);
        startActivity(intent);
        finish();
    }

    private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(imageFileName, ".jpg", storageDir);

        photoPath = "file:" + image.getAbsolutePath();
        return image;
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        try{
            photoFile = createImageFile();
        }catch(IOException e){
            e.printStackTrace();
        }

        if(photoFile != null){
            Uri photoUri = Uri.fromFile(photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        }
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }
}

BLUETOOTH WARNING CLASS
import android.Manifest;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

public class Warning extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
    private final static String TAG = Warning.class.getSimpleName();
    private String mDeviceAddress;
    private HandleConnectionService mBluetoothLeService;
    private boolean quitService;
    private final int PLAY_SERVICES_REQUEST_TIME = 1000;
    private Location mLastLocation;
    private GoogleApiClient mGoogleClient;
    private boolean requestingLocationUpdates = false;
    private LocationRequest locationRequest;

    private int UPDATE_INTERVAL = 10000; // 10 seconds
    private int FASTEST_INTERVAL = 5000; // 5 seconds
    private int DISTANCEMOVED = 10; //In meters

    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((HandleConnectionService.LocalBinder) service).getService();
            if (!mBluetoothLeService.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth");
                finish();
            }
            mBluetoothLeService.connect(mDeviceAddress);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };

    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();

            if (HandleConnectionService.ACTION_GATT_DISCONNECTED.equals(action)) {
                if (!quitService) {
                    mBluetoothLeService.connect(mDeviceAddress);
                    Log.w(TAG, "Attempting to reconnect");
                }
                Log.w(TAG, "Disconnected, activity closing");
            } else if (HandleConnectionService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                getGattService(mBluetoothLeService.getSupportedGattService());
            } else if (HandleConnectionService.ACTION_DATA_AVAILABLE.equals(action)) {
                checkWarning(intent.getByteArrayExtra(HandleConnectionService.EXTRA_DATA));
            }else if(CameraOperations.ACTION_PICTURE_RECEIVED.equals(action)){
                byte[] bytes = intent.getByteArrayExtra("bitmap");
                Bitmap picture = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                findLocation();
            }
        }
    };

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

        Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(myToolbar);

        if (checkGoogleServices()) {
            buildGoogleApiClient();
        }

        quitService = false;
        Intent intent = getIntent();
        mDeviceAddress = intent.getStringExtra(Device.EXTRA_DEVICE_ADDRESS);

        Intent gattServiceIntent = new Intent(this, HandleConnectionService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.mainmenu, menu);
        MenuItem connect = menu.findItem(R.id.connect);
        connect.setVisible(false);
        MenuItem disconnect = menu.findItem(R.id.disconnect);
        disconnect.setVisible(true);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent;
        switch (item.getItemId()) {
            case R.id.home:
                new AlertDialog.Builder(this)
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setTitle("Return Home")
                        .setMessage("Returning home will disconnect you, continue?")
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                quitService = true;
                                mBluetoothLeService.disconnect();
                                mBluetoothLeService.close();

                                Intent intent = new Intent(Warning.this, Main.class);
                                startActivity(intent);
                            }
                        })
                        .setNegativeButton("No", null)
                        .show();

                return true;
            case R.id.connect:
                Toast.makeText(this, "Connect Pressed", Toast.LENGTH_SHORT).show();
                return true;

            case R.id.disconnect:
                disconnectOperation();
                intent = new Intent(Warning.this, Main.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                return true;

            case R.id.profiles:
                Toast.makeText(this, "Profiles Pressed", Toast.LENGTH_SHORT).show();
                return true;

            case R.id.camera:
                Toast.makeText(this, "Camera Pressed", Toast.LENGTH_SHORT).show();
                intent = new Intent(Warning.this, CameraOperations.class);
                startActivity(intent);
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            quitService = true;
            mBluetoothLeService.disconnect();
            mBluetoothLeService.close();

            Intent intent = new Intent(Warning.this, Main.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBluetoothLeService.disconnect();
        mBluetoothLeService.close();

        System.exit(0);
    }

    public boolean disconnectOperation(){
        this.quitService = true;
        mBluetoothLeService.disconnect();
        mBluetoothLeService.close();
        return true;
    }

    private void checkWarning(byte[] byteArray) {
        if (byteArray != null) {
            for (int i = 0; i < byteArray.length; i++) {
                if (byteArray[i] == 48) {
                   findLocation();
                }
            }
        }
    }

    private void getGattService(BluetoothGattService gattService) {
        if (gattService == null) {
            return;
        }

        BluetoothGattCharacteristic characteristicRx = gattService.getCharacteristic(HandleConnectionService.UUID_BLE_SHIELD_RX);
        mBluetoothLeService.setCharacteristicNotification(characteristicRx, true);
        mBluetoothLeService.readCharacteristic(characteristicRx);
    }

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(HandleConnectionService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(HandleConnectionService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(HandleConnectionService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(HandleConnectionService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(CameraOperations.ACTION_PICTURE_RECEIVED);

        return intentFilter;
    }

    private boolean checkGoogleServices() {
        GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
        int available = googleAPI.isGooglePlayServicesAvailable(this);
        if (available != ConnectionResult.SUCCESS) {
            if (googleAPI.isUserResolvableError(available)) {
                googleAPI.getErrorDialog(this, available, PLAY_SERVICES_REQUEST_TIME).show();
            }
            return false;
        }

        return true;
    }

    public void findLocation() {
        int REQUEST_CODE_ASK_PERMISSIONS = 123;
        double latitude = 0.0;
        double longitude = 0.0;

        if(Build.VERSION.SDK_INT >= 23){
            boolean fineLocationAccess = ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
            boolean courseLocationAccess = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
            boolean accessGranted = fineLocationAccess && courseLocationAccess;

            if (accessGranted) {
                mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleClient);
                if(mLastLocation != null) {
                    latitude = mLastLocation.getLatitude();
                    longitude = mLastLocation.getLongitude();

                    Toast.makeText(this, "latitude: " + latitude + " longitude: " + longitude, Toast.LENGTH_LONG).show();
                }else{
                    Log.i("Warning", "Unable to get Location");
                }
            }else{
                Log.i("Connection", "Request permission");
            }
        }else{
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleClient);
            if(mLastLocation != null) {
                latitude = mLastLocation.getLatitude();
                longitude = mLastLocation.getLongitude();

                Toast.makeText(this, "latitude: " + latitude + " longitude: " + longitude, Toast.LENGTH_LONG).show();
            }else{
                Log.i("Warning", "Unable to get Location");
            }
        }
    }

    public void buildGoogleApiClient() {
        mGoogleClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();
    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.w("Connected", " : " + mGoogleClient.isConnected());
    }

    @Override
    public void onConnectionSuspended(int i) {
        Toast.makeText(this, "Location Services Stopped", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(this, "Location Services Connection Fail", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (mGoogleClient != null) {
            mGoogleClient.connect();
        }
    }
}

A: I think your original idea is actually pretty sound as long as you construct it a certain way. The activity that is knowledgeable about the location information can update and store that location independent of any other activity. This would probably be ideal to have as a service actually that runs every x amount of time, or when the location changes.
Inside of that same class you can have a generic broadcast receiver that handles request for that location information. You can make this as generic as you want in terms of allowing other applications/activities you make also being to leverage it, as long as the location data is returned in a way that is usable to each requester.
From within your activity that takes photos (and eventually any activity you desire), when you take a photo, you can send a broadcast requesting that location information, with some default or null info if none is returned. One of the complexities is knowing how long to wait for this location info before  completing. In this scenario the location activity is the 'generalized' one in that multiple activities can request location data if you construct it correctly.
Another potentially robust approach is to make the photo taking activity the generalized one. One way to do this is that when you take a photo, you can have your photo activity send broadcast to the location activity that contains the photos filepath/uri/identifying information, but you don't wait for a response. Instead, you make the location activity listen for this broadcast, and write to the photos meta data with the location using the provided identifying info to find said photo. In this way your photo taking app isn't stuck waiting for the location activity to finish (or event start if it ever does).
Good luck, sounds like a fun project.


text:
Q: Is it recommended to set the FTDI delay (latency_timer) to 1ms? I've struggled over an article from FTDI about the Latency Timer. Setting a Custom Default Latency Timer Value

... although 1ms is not recommended as this is the same as the USB frame length.

I've setup in several project the latency to 1ms (I want low round robin delays). So is this not recommended? Would be 2ms the "correct" alternative?

A: I don't know, how old the web page "Setting a Custom Default Latency Timer Value" is. Application note AN232B-04 does not have a special note for 1 ms latency timer.
Note: Latency timer matters only for small amounts of data (see page 6 of the application note) including last fragment of large data.
From my experience: FT2232C/L/D work fine with 1 ms latency, but in case of MPSSE mode SEND IMMEDIATE command gives even faster data transmission.
For UART mode an EVENT CHARACTER (one can set the character to '\n' in text mode or packet delimiter in packet mode) also triggers transmission with no regards on latency timer.

A: As you can read in the linked documentation 2ms should be correct.

The valid range for the latency timer is 1ms - 255ms


text:
Q: wpdb->prepare function remove single quote for %s in SQL statment I am using the below wpdb->prepare function in a sql statement.  I am passing in several variables some field names and some values.  When I try to use the %s for the field name it puts single quotes around it.  How can I prevent the single quotes around the field name?  The  sql statement will not execute with the single quotes?
 $query = $wpdb->prepare("SELECT DISTINCT wp_geo.%s, wp_geo.$field2
FROM wp_geo
WHERE wp_geo.$field3=%s",$field1, $typevalue);
Output with single quotes around 'county_short' field name:
SELECT DISTINCT wp_geo.'county_short', wp_geo.county_slug FROM wp_geo WHERE wp_geo.type='trailers'

A: You can use %1s which excludes single quotes wrapper.
By using %1s, you will note that the string won't be having single quotes and you will get the values directly as needed.
$query = $wpdb->prepare("
              SELECT DISTINCT wp_geo.%1s, wp_geo.%1s
              FROM wp_geo
              WHERE wp_geo.%1s = %1s",
              $field1,
              $field2,
              $field3,
              $typevalue
         );

Note: Here, the sequence should follow for %1s and the variable you are providing after the query.

A: You can't use prepare() on column names, only on values.

A: You cannot suppress the quotes in $wpdb. Run mysqli_real_escape_string() in your script on these variables.


text:
Q: Spark Can't Find JDBC Driver from SBT I'm trying to use JDBC in a Scala Spark application, and I'm compiling with sbt. However when I add the line Class.forName("com.mysql.jdbc.Driver"), it throws a ClassNotFoundException.
My sbt file is this:
name := "SparkApp"
version := "1.0"
scalaVersion := "2.11.8"
libraryDependencies += "org.apache.spark" %% "spark-core" % "2.1.0"
libraryDependencies += "org.apache.spark" %% "spark-sql" % "2.1.0"
libraryDependencies += "com.databricks" %% "spark-csv" % "1.5.0"
libraryDependencies += "org.apache.spark" %% "spark-mllib" % "2.1.0"
libraryDependencies += "mysql" % "mysql-connector-java" % "6.0.5"

As far as I can tell that last line is all I should need to add the JDBC driver, but it doesn't seem to be working. I've also tried Class.forName("com.mysql.jdbc.Driver").newInstance() but it has the same result, so I assume the issue is with the jdbc classes not being added correctly at all.

A: You don't need to supply the class name to use JDBC to load data frames. Following the Spark SQL documentation, you only have to supply "jdbc" as the data source format (and indeed add the connector as a dependency) and set the right options:
val host: String = ???
val port: Int = ???
val database: String = ???
val table: String = ???
val user: String = ???
val password: String = ???

val options = Map(
      "url" -> s"jdbc:mysql://$host:$port/$database?zeroDateTimeBehavior=convertToNull",
      "dbtable" -> table,
      "user" -> user,
      "password" -> password)

val df = spark.read.format("jdbc").options(options).load()

When you submit your application to Spark, you have to either include the MySQL connector into your final jar file, or tell spark-submit to get the package as a dependency:
spark-submit --packages mysql:mysql-connector-java:6.0.5 ...

This flag also works on spark-shell or pyspark.

A: Your mysql driver class com.mysql.jdbc.Driver it's not present on your classpath at runtime. If your are running your spark job with spark-submit than you have at least two options:

*

*provide --jar options to specify the path for the mysql-*.jar (see this post) (if both worker and driver need the class then take a close look on the spark.executor.extraJavaOptions and spark.driver.extraJavaOptions)

*build an uber jar (fat jar) that will include your mysql-* classes on your application jar (see this post)

A: spark-submit \
              --class com.mypack.MyClass \
              --master yarn --deploy-mode cluster \
              --conf spark.executor.extraClassPath=$POSTGRESQL_JAR_PATH:$MYSQL_JAR_PATH \
               --conf spark.driver.extraClassPath=$POSTGRESQL_JAR_PATH:$MYSQL_JAR_PATH \
where, $POSTGRESQL_JAR_PATH and $MYSQL_JAR_PATH should be set with hdfs path to jar files.
hope this helps.
spark.executor.extraClassPath if you are running it in cluster mode.
spark.driver.extraClassPath if you are running it in local.
I recommend setting both option to be on safer side.

A: You should pass driver jar while submitting the spark job like below:
1)
spark-submit --jars mysql-connector-java-5.1.39.jar and rest of the parameters as you are passing
2) if you just wanna try on local using shell
spark-shell --jars mysql-connector-java-5.1.39.jar
Update the driver to the one which you already have available and provide the absolute path to that


text:
Q: Computer is telling me, "Not connected - No connections are available" Despite the fact I am connected to the internet? Just got a new PSU because my old one was on the way out.
Started up my computer and everything works fine except for a yellow triangle with a warning tick on the Network and Sharing center icon on my task bar.
The network adapter looks like this:

The device manager looks like this:

Ethernet adapter IP/DNS settings:

Some how I am connected to the internet though, any help would be appreciated.
I have already deleted and reinstalled drivers for the device, rebooted my PC, rebooted my router, reset my modem, turned my PC on and off and taken my Ethernet cable out and put it back in.

A: A yellow triangle means that your drivers and hardware are working properly.
The problem is with the IP, your PC is not able to obtain an IP address to assess internet.
You can check it by opening cmd and type ipconfig command and hit enter.
Check for ip v4 address as well as v6.
If they exists then it's ok. Otherwise type ipconfig /renew or /release to obtain a new one.
If it doesn't work turn off router and connect the Ethernet cable in the same port as it as before the maintenance.
Leave it for few minutes and turn it on.

A: Some options you should check:

*

*Verify there is a DHCP server on the same physical network as your computer (usually, the router on home networks)

*Check if this DHCP server is active and has spare IPs to distribute (should be in the DHCP settings of your router, can't help you there)

*If the DHCP is enabled, open a command prompt and run the commands @Rohitkr suggested.

*If DHCP is not enabled, or not working, check "Use the following IP address" in your IPv4 settings and manually enter the IP you want to give to your computer, as well as its subnet mask (usually 255.255.255.0) and it default gateway (the router's IP in this subnet).

*Do point 4 if there is no DHCP at all on this network.

A: The reason for the issue may be broken registry permissions.
To fix:

*

*Run regedit.exe.

*To HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList's ACL, add NT Service\netprofm and grant it all rights except Write DAC and Write Owner. Check the "Replace all child object permission entries with inheritable permission entries from this object" checkbox.

*To HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Nla's ACL, add NT Service\NlaSvc and grant it the same rights as in step 1.

Alternatively, you may use SetACL:
setacl.exe -ot reg -on "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList" -actn ace -ace "n:NT Service\netprofm;p:query_val,set_val,create_subkey,enum_subkeys,notify,create_link,delete,read_access" -actn rstchldrn -rst dacl
setacl.exe -ot reg -on "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Nla" -actn ace -ace "n:NT Service\NlaSvc;p:query_val,set_val,create_subkey,enum_subkeys,notify,create_link,delete,read_access"

Then log off and log on again.
Tested on Windows 7.


text:
Q: Raise an error if a subquery returns no result In DB2 it is possible to raise an error if a subquery returns no results with the help of coalesce and the raise_error scalar function. But how can this be done in oracle?
I checked scalar functions so far, but there is no raise error function.
example for db2 (note: the subquery needs to be replaced by something meaningful...):
SELECT
    COALESCE(
        (SELECT 1 FROM SYSIBM.SYSDUMMY1 LIMIT 0),
        RAISE_ERROR('70NUL', 'Value is missing'))
FROM
    SYSIBM.SYSDUMMY1;

UPDATE 1:
The use case is about finding a matching value in another table during an export of millions of records. The idea is to raise an error if there is no matching value so it is detected early and not afterwards.

A: You can use RAISE_APPLICATION_ERROR feature of oracle to resolve your problem. You can declare a procedure and define when to raise the exception in that procedure. Simply call the procedure to execute your task and it will raise the error whenever your given condition staisfies.
For knowing in details, please see the trapping user defined exceptions section of oracle documentation with example.

A: The way you describe it it sounds as if you need to mark a number of records based on whenever some values exist in a table. If PLSQL is an option you can just use the no_data_found exception:
invalid_data CONSTANT NUMBER := -70;

   DECLARE
     l_var NUMBER;
   BEGIN
     SELECT 1
       INTO l_var
       FROM dual
      WHERE 1 <> 1;

   EXCEPTION WHEN no_data_found THEN
     /* do your updating or error handling */  RAISE_APPLICATION_ERROR(invalid_data ,'Value is missing');
   END;

A: In Oracle, you'd use similar query:
SQL> select coalesce((select dummy from dual where 1 = 2), 'Value is missing') result from dual;

RESULT
----------------
Value is missing

SQL> select coalesce((select dummy from dual where 1 = 1), 'Value is missing') result from dual;

RESULT
----------------
X

SQL>

I don't speak MS SQL Server so I can't comment it.

A: Alternative to @Gnqz solution is to write a user function wrapper around raise_application_error() in conjunction with coalesce.
    CREATE OR REPLACE FUNCTION raise_error
    RETURN NUMBER
    IS
    BEGIN
        raise_application_error(-70, 'Mapping value is missing');
        RETURN(0);
    END;

    select coalesce((select 5 AS result from dual fetch first 1 row only), raise_error()) AS result from dual;


text:
Q: How to add dependencies in hybris using external-dependencies.xml file? I'm newbie in hybris. I want to add maven dependency in hybris using external-dependencies.xml. But I can't see any of those jar(s) popped-in. Is it possible to get jar using external-dependencies.xml, if yes, please provide your response.

A: My official answer: add usemaven="true" in your extensioninfo.xml (extension tag)

A: The platform build is coupled with ant but you can use maven dependency (by default is disabled because all necessary libraries are shipped with the hybris).
In order to activate dependency management you have to follow these steps:
1) Make sure you have maven installed
2) Open the extensioninfo.xml from your extension
  2.1) Include usemaven="true", for instance

3) Manage your dependencies inside "external-dependencies.xml" file (Inside this file is a regular maven pom.xml)
4) build your project (ant all). Hybris fetch required libraries into \lib and \web\webroot\WEB-INF\lib (Bear in mind that there are two "external-dependencies.xml", one for the core module and other for the web module)
Besides if you look the ant targets you will see there is one call "updateMavenDependencies". This task delete all jars in the lib folder and replaces them with the  defined maven dependencies. In case you dont want maven to manage a few libraries you can handle this, creating a file in the root of your extension call "unmanaged-dependencies.txt".On this file you will include all libraries maven is not going to manage (therefore the ant target is not going to delete the libraries include on this file)

A: I'm newbie too to Hybris but what I know is that whenever you need a dependency in a Hybris extension you need to add the name of the dependency to hybris/config/localextensions.xml and in extensioninfo.xml in the extension you want to add the dependency.
As for the Maven dependency, I'm not sure how to do that because I mostly use the out-of-the-box build system which is based on Ant.


text:
Q: Natural vs Innate I wonder what do you normally call those talents of an individual which have been with them from the beginning?
I know two fixed phrases:

*

*Natural talents

*Innate talents

Also I need to know what do you call a person who has such a quality?

*

*Naturally talented person

*Innately talented person

As you see, Ngram shows that comparing to the word "innate", the adjective "natural" has a more prevalence in this case.
Please let me know whether they mean the same thing and that is just a matter if preference to use each one!

A: Innate is the better word to convey a talent that one possessed at birth.
Natural works and will probably be understood in context but natural can be interpreted to mean things other than possessed at birth.  If your talent is playing the violin and my talent is shooting lightning bolts from my fingers, your talent might be called natural and mine might be called unnatural. Although it's doubtful that either is innate.

A: While both "innate and "natural" can be used to refer to an ability one has had since birth, there is a difference.
The common collocated phrases

innate sense
  innate ability

can be used to refer to a talent or ability which does not need any coaching or further learning

He has an innate sense of timing.
  She has an innate ability for design.

For example, an idiot savant's ability is innate.
Whereas another commonly collocated phrase

naturally talented

can be used to refer to having an ability which can be (and possibly needs to be) further trained

He is a natural when it comes to playing sports.
  She is naturally talented at singing.

These mean the base (foundation) abilities and talent exist and can be further refined.


text:
Q: sql to transpose rows to columns I have an Oracle view (joined from multiple tables) like the first screen shot. the address_type should be always either owner or property. I want to get results like the second screen shot. How to use SQL to do that? Sorry I am a very beginner to SQL.

A: You can use an inner join:
select tab1.address_id, tab1.address as owner_address,
       tab1.city as owner_city, tab1.state as owner_state,
       tab1.zip as owner_zip, tab2.address as property_address,
       tab2.city as property_city, tab2.state as property_state,
       tab2.zip as property_zip
from tab1
full outer join tab2
on tab1.address_id = tab2.address_id
where tab1.address_type = 'owner'
      and tab2.address_type = 'property'

tab1 contains all owner informations, tab2 contains all property informations. You can join them using address_id.
Sorry i can't test it!


text:
Q: Find items within a list which exist in another list I have two entity models-
public SalesPerson
{
   int PersonId; int DistributionHouseId;
{

public SalesRecord
{
   int RecordId; int PersonId; datetime SalesDate;
{

var persons = Db.SalesPersons.Where(m => m.DistributionHouseId == 1).ToList();

var salesRecords = Db.SalesRecords.Where(m =>
                       persons.Any(x => x.PersonId==m.PersonId)
                       && DbFunctions.TruncateTime(m.SalesDate) == date)
                       .ToList();

It gives me exception Only primitive types or enumeration types are supported in this context.

A: The most likely reason is this condition:
persons.Any(x => x.PersonId==m.PersonId)

You can rework it as follows:
var personIds = Db.SalesPersons
    .Where(m => m.DistributionHouseId == 1)
    .Select(p => PersonId)
    .ToList();

Then the corresponding part of the condition would become
personIds.Contains(m.PersonId)

which is now a condition that uses a collection of primitive types.

A: i think the problem is with the date comparison, sometimes LINQ can translate DBFunction right.
try this:
    var salesRecords = Db.SalesRecords.Where(m =>
    persons.Any(x => x.PersonId == m.PersonId))
    .ToList()
    .where(m=> m.SalesDate.Date == date);

when the .ToList method is used it loads the data from SQL to the memory, there you can compare the dates


text:
Q: How to show an image in the intersection between two polygons? I have an idea for an effect that I'm trying to code with Javascript and html5 Canvas, but I'm not sure exactly where to start.
Say you have multiple different colored polygons (let's say Rectangles for now but ideally pseudo-random irregular polygons). You can move the polygons around by clicking and dragging.
When you drag one of the polygons over another polygon, I'd like to show an image in the intersected area. Imagine dragging a blue polygon over a red polygon to create an area of purple, except instead of purple it's a leopard print pattern, or a photo, or similar.
Any help would be appreciated! Thanks!

A: Using the 2d context clip function. Draw the shape as normal then draw them again but instead of fill use clip after each shape.
Each clip is applied to the previous clip.
When all the clips shapes have been set then draw the image/shape over the top and only the parts inside the clip area will show.
To remove the clip you need to use save and restore (see demo);
Using code from another example I just wrote, being a bit lazy.
Example shows the union of 3 boxes as blue using the clip functionality of 2D context.

/** SimpleUpdate.js begin **/
// short cut vars
var ctx = canvas.getContext("2d");
var w = canvas.width;
var h = canvas.height;
ctx.font = "18px arial";
var cw = w / 2;  // center
var ch = h / 2;
var angle = 0;
var focused = false;
var rotated = false;

// Handle all key input
const keys = {  // key input object
    ArrowLeft : false,  // only add key names you want to listen to
    ArrowRight : false,
    keyEvent (event) {
        if (keys[event.code] !== undefined) {  // are we interested in this key
            keys[event.code] = event.type === "keydown";
            rotated = true; // to turn off help
        }
    }
}
// add key listeners
document.addEventListener("keydown", keys.keyEvent)
document.addEventListener("keyup", keys.keyEvent)

// check if focus click
canvas.addEventListener("click",()=>focused = true);

// main update function
function update (timer) {
    ctx.setTransform(1, 0, 0, 1, 0, 0);  // reset transform
    ctx.clearRect(0,0,w,h);

    // draw outside box
    ctx.fillStyle = "red"
    ctx.fillRect(50, 50, w - 100, h - 100);

    // rotate if input
    angle += keys.ArrowLeft ? -0.1 : 0;
    angle += keys.ArrowRight ? 0.1 : 0;

    // set orgin to center of canvas
    ctx.setTransform(1, 0, 0, 1, cw, ch);

    // rotate
    ctx.rotate(angle);

    // draw rotated box
    ctx.fillStyle = "Black"
    ctx.fillRect(-50, -50, 100, 100);

    // set transform to center
    ctx.setTransform(1, 0, 0, 1, cw, ch);
    // rotate
    ctx.rotate(angle);
    // move to corner
    ctx.translate(50,50);
    // rotate once more, Doubles the rotation
    ctx.rotate(angle);

    ctx.fillStyle = "yellow"
    ctx.fillRect(-40, -40,80, 80);

    ctx.setTransform(1, 0, 0, 1, 0, 0);  // restore default

    // set up the clip area
    ctx.save();  // save the non cliped canvas state
    ctx.beginPath();
    ctx.rect(50, 50, w - 100, h - 100);
    ctx.clip(); // clip main box

    // set orgin to center of canvas
    ctx.setTransform(1, 0, 0, 1, cw, ch);
    ctx.rotate(angle);
    ctx.beginPath();
    ctx.rect(-50, -50, 100, 100);
    ctx.clip(); // add to clip (reduces area

    ctx.setTransform(1, 0, 0, 1, cw, ch);
    ctx.rotate(angle);
    ctx.translate(50,50);
    ctx.rotate(angle);
    ctx.beginPath();
    ctx.rect(-40, -40,80, 80);
    ctx.clip();

    ctx.setTransform(1, 0, 0, 1, 0, 0);  // restore default

    ctx.fillStyle = "blue"
    ctx.fillRect(0, 0, w, h);

    ctx.restore();  // this removes the clip. It is the only way to remove it
                    // apart from reseting the context

    ctx.fillStyle = "white"
    ctx.lineWidth = 3;
    if(!focused){
        ctx.strokeText("Click on canvas to get focus.",10,20);
        ctx.fillText("Click on canvas to get focus.",10,20);
    }else if(!rotated){
        ctx.strokeText("Left right arrow to rotate.",10,20);
        ctx.fillText("Left right arrow to rotate.",10,20);
    }else{
        ctx.strokeText("Blue is the union of the...",10,20);
        ctx.fillText("Blue is the union of the...",10,20);
        ctx.strokeText("...yellow, black, and red boxes.",10,h-5);
        ctx.fillText("...yellow, black, and red boxes.",10,h-5);
    }

    requestAnimationFrame(update);

}
requestAnimationFrame(update);

/** SimpleUpdate.js end **/
<canvas id = canvas></canvas>

A: It's a little simpler with SVG.  :)

<svg viewBox="0 0 800 500">
  <defs>
    <circle id="left" cx="250" cy="250" r="250"/>
    <circle id="right" cx="550" cy="250" r="250"/>
    <mask id="intersect">
      <rect width="100%" height="100%" fill="black"/>
      <use xlink:href="#right" fill="white" mask="url(#maskleft)"/>
    </mask>
    <mask id="maskleft">
      <rect width="100%" height="100%" fill="black"/>
      <use xlink:href="#left" fill="white"/>
    </mask>
  </defs>

  <use xlink:href="#left" fill="red"/>
  <use xlink:href="#right" fill="blue"/>
  <image xlink:href="http://lorempixel.com/output/animals-q-c-500-500-8.jpg"
         x="280" y="0" width="500" height="500" mask="url(#intersect)"/>
</svg>

Animated version

var start = null;
var maskleftcircle = document.getElementById("maskleftcircle");
var puppygroup = document.getElementById("puppygroup");

function step(timestamp) {
  if (!start) start = timestamp;
  var angle = ((timestamp - start)/250) % 360;

  var dx = 100 * Math.cos(angle);
  var dy = -100 * Math.sin(angle);

  puppygroup.setAttribute("transform", "translate("+dx+","+dy+")");
  maskleftcircle.setAttribute("transform", "translate("+(-dx)+","+(-dy)+")");

  window.requestAnimationFrame(step);
}

window.requestAnimationFrame(step);
<svg viewBox="0 0 800 500">
  <defs>
    <circle id="left" cx="250" cy="250" r="250"/>
    <circle id="right" cx="550" cy="250" r="250"/>
    <mask id="intersect">
      <rect width="100%" height="100%" fill="black"/>
      <use xlink:href="#right" fill="white" mask="url(#maskleft)"/>
    </mask>
    <mask id="maskleft">
      <rect width="100%" height="100%" fill="black"/>
      <use xlink:href="#left" fill="white" id="maskleftcircle"/>
    </mask>
  </defs>

  <use xlink:href="#left" fill="red"/>
  <g id="puppygroup">
    <use xlink:href="#right" fill="blue"/>
    <image xlink:href="http://lorempixel.com/output/animals-q-c-500-500-8.jpg"
           x="300" y="0" width="500" height="500" mask="url(#intersect)"/>
  </g>
</svg>

A: For the ones that don't like clipping (like me), you can also achieve it with compositing.
Basically, you'd need to draw your shapes twice : once on the visible canvas, and once on an hidden one, used only to create the intersection area.
Draw the first shape with normal compositing mode 'source-over'.
Then, draw all your shapes with the compositing mode 'source-in'. This will keep only the new pixels which overlaps previously drawn ones.
When you're done drawing your shapes, only the intersection part should remain on this hidden canvas. So still with this composition mode, you can draw your image, the size of the canvas. Your image will be clipped.
As I am lazy too, I shamelessly took Blindman67's code*, and didn't even bothered to rewrite it in a more elegant way to avoid boilerplate, while it should probably be done.

/** SimpleUpdate.js begin **/
// short cut vars
var ctx = canvas.getContext("2d");
// create an hidden canvas' context
var ctx1 = canvas.cloneNode().getContext('2d');
var w = canvas.width;
var h = canvas.height;
ctx.font = "18px arial";
var cw = w / 2; // center
var ch = h / 2;
var angle = 0;
var focused = false;
var rotated = false;
var img = new Image();
img.src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/5/55/John_William_Waterhouse_A_Mermaid.jpg/100px-John_William_Waterhouse_A_Mermaid.jpg';

// Handle all key input
const keys = { // key input object
  ArrowLeft: false, // only add key names you want to listen to
  ArrowRight: false,
  keyEvent(event) {
    if (keys[event.code] !== undefined) { // are we interested in this key
      keys[event.code] = event.type === "keydown";
      rotated = true; // to turn off help
    }
  }
}
// add key listeners
document.addEventListener("keydown", keys.keyEvent)
document.addEventListener("keyup", keys.keyEvent)

// check if focus click
canvas.addEventListener("click", () => focused = true);

// main update function
function update(timer) {
  ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
  ctx1.setTransform(1, 0, 0, 1, 0, 0);
  ctx.clearRect(0, 0, w, h);
  ctx1.clearRect(0, 0, w, h);
  // draw outside box
  ctx.fillStyle = "red"
  ctx.fillRect(50, 50, w - 100, h - 100);
  // reset default compositing mode
  ctx1.globalCompositeOperation = 'source-over';
  // and draw the first shape
  ctx1.fillRect(50, 50, w - 100, h - 100);
  // now we will keep only the new pixels which overlap with existing ones
  ctx1.globalCompositeOperation = 'source-in';
  // rotate if input
  angle += keys.ArrowLeft ? -0.1 : 0;
  angle += keys.ArrowRight ? 0.1 : 0;

  // set origin to center of canvas
  ctx.setTransform(1, 0, 0, 1, cw, ch);
  // apply all the same transforms to the hidden canvas
  ctx1.setTransform(1, 0, 0, 1, cw, ch);
  // rotate
  ctx.rotate(angle);
  ctx1.rotate(angle);
  // draw rotated box
  ctx.fillStyle = "Black"
  ctx.fillRect(-50, -50, 100, 100);
  ctx1.fillRect(-50, -50, 100, 100);

  // set transform to center
  ctx.setTransform(1, 0, 0, 1, cw, ch);
  ctx1.setTransform(1, 0, 0, 1, cw, ch);
  // rotate
  ctx.rotate(angle);
  ctx1.rotate(angle);
  // move to corner
  ctx.translate(50, 50);
  ctx1.translate(50, 50);
  // rotate once more, Doubles the rotation
  ctx.rotate(angle);
  ctx1.rotate(angle);

  ctx.fillStyle = "yellow"
  ctx.fillRect(-40, -40, 80, 80);
  ctx1.fillRect(-40, -40, 80, 80);

  ctx.setTransform(1, 0, 0, 1, 0, 0); // restore default
  ctx1.setTransform(1, 0, 0, 1, 0, 0);

  // our hidden canvas only contains the overlapping of all our shapes
  // we can draw our image on this intersection area
  ctx1.drawImage(img, 0, 0, w, h);
  // and draw this back on the main canvas
  ctx.drawImage(ctx1.canvas, 0, 0);

  ctx.fillStyle = "white"
  ctx.lineWidth = 3;
  if (!focused) {
    ctx.strokeText("Click on canvas to get focus.", 10, 20);
    ctx.fillText("Click on canvas to get focus.", 10, 20);
  } else if (!rotated) {
    ctx.strokeText("Left right arrow to rotate.", 10, 20);
    ctx.fillText("Left right arrow to rotate.", 10, 20);
  } else {
    ctx.strokeText("Image is the union of the...", 10, 20);
    ctx.fillText("Image is the union of the...", 10, 20);
    ctx.strokeText("...yellow, black, and red boxes.", 10, h - 5);
    ctx.fillText("...yellow, black, and red boxes.", 10, h - 5);
  }

  requestAnimationFrame(update);

}
requestAnimationFrame(update);

/** SimpleUpdate.js end **/
<canvas id="canvas"></canvas>

*I hope he won't mind, and if he does, he just has to let me know.


text:
Q: One-To-Many Join I have a ZIP3 boundary feature class that contains roughly 900 records.
I then have a table in a geodatabase that has 21000~ records and a ZIP3 field.
How would I go about making a feature class that has the ZIP3 boundaries for each of the 21000~ records from my table?

A: I think a query table will do what you are looking for.
Make sure the table and the feature class are in the same geodatabase.
Open the Make Query Table tool. Add the table FIRST. Then add the feature class.
Click ok to create the Query Table. Then right click the resulting layer and export.
Note: I've used this before in 10.1 and it worked fine. Trying now in 10.2 and it's crashing ArcMap. A comment in the knowledge base thread suggests this may not work in 10.2

A: I have a multi-step MANUAL process to achieve the feature-class creation you are looking for.  First, realize that the resulting polygon layer will likely have the same geometry repeated for those rows in your source table where the ZIP3 attribute repeats. -- and realize that this is a less-than-ideal geometry storage method.
But if it has to be that way, here is one way (not the only way) to get there:
0) Make a copy of your source data, because during this process you will be deleting rows and you should have an original copy to refer to if needed.
1) Perform a frequency on your table using the ZIP3 column to find the maximum number of occurrences of any ZIP3 value. -- you will be performing this many sequential joins...
2) Add your table, the frequency table, and the ZIP3 polygon FC to an MXD; join the table and frequency result so that each row of your table also shows the frequency of that ZIP3.
3a) Using a query definition, Reselect the COUNT = 1 from your table+frequency result, then be sure to SORT the table on OBJECTID or Primary Key column.
3b) Join the ZIP3 polygons to the reduced table above, joining on ZIP3 column.
3c) Export the polygon result to a GDB with a featureclass name ending in _001
3d) remove the join between the polygons and your table
3e) SELECT and DELETE the rows of your table matching COUNT = 1 frequency criteria.
4) repeat steps 3a - e for COUNT = 2, COUNT = 3, COUNT = 4 and so on, with the following ABSOLUTELY CRITICAL exceptions:
    for COUNT = 2, you will need to export one time, then reselect only the first occurrence of the ZIPs and delete these rows in 3e, then re-join from polygons to your table, and export a second set of matching rows.
    for COUNT = 3, you will need to go through the process 3 times, selecting and deleting the first occurrence of the table entries in 3e and re-joining from polygons after each sub-set is removed.
    Continue this process until all the rows in your table are removed, then APPEND all the component featureclasses into a single result.
Why will this work?  Each time a set is joined from the Polygons to the Table, only the first occurrence (by ObjectID) is joined to the polygon...by removing the join, selecting and deleting the exported rows, and re-joining/re-exporting, you can get the next set within the one-to-many join.
I told you it was a multi-step and MANUAL process, but it should get the repeating geometries into a single featureclass, together with the table attributes of interest to you.


text:
Q: How can i optimize SUM() mysql Query I have a mysql SUM query that runs on more than 0.6 million records.
what i am currently doing is like this
 SELECT SUM (payment)
    FROM payment_table
    WHERE
       payment_date BETWEEN ... AND ...
       AND
       payment_status = 'paid'

I changed the query to this format to reduce the recordset but it is still taking almost same time.
SELECT SUM(Payments)
FROM (
    SELECT payment AS Payments FROM payment_table WHERE
     payment_date BETWEEN DATE_FORMAT(NOW(), '2012-2-01') AND DATE_FORMAT(LAST_DAY(DATE_FORMAT(NOW(), '2012-2-01')), '%Y-%m-%d')
    AND
    payment_status = 'paid'
) AS tmp_table

Is their any way to optimize this sum query.
EDIT:
This is the result when query is run with EXPLAIN

insert into ` (id,select_type,table,type,possible_keys,
  key,key_len,ref,rows,Extra`)
  values('1','SIMPLE','lps','index_merge','assigned_user_id,scheduled_payment_date,payment_status,deleted','deleted,assigned_user_id,payment_status','2,109,303',NULL,'23347','Using
  intersect(deleted,assigned_user_id,payment_status); Using where');

A: You should match the data type of the preducate with the column. Because payment_type is DATE, make the BETWEEN values DATE also:
 WHERE payment_date BETWEEN
     CURDATE() AND LAST_DAY(CURDATE())

Matching types ensures the index will be used.

In contrast, your query is using DATE_FORMAT(), which produces a text data type, so in order to perform the comparison, mysql is converting the payment_dare column to text, so it can't use the index (the index contains DATE values, not text values), so every single row is converted and compared.

If you are still having performance problems after making the change above, execute this:
ANALYZE TABLE payment_table;

Which will check the distribution of values in the indexed columns, which helps mysql make the right choice of index.


text:
Q: java.lang.IllegalStateException: getOutputStream() has already been called for this response in JSF 2 i have a legacy code that writes a jsp page in xml, and i am trying to convert it to JSF 2
but i am getting the following exception:
    Jul 10, 2012 11:34:57 AM com.sun.faces.application.view.FaceletViewHandlingStrategy handleRenderException
SEVERE: Error Rendering View[/pages/xmlservices/SendPic.xhtml]
java.lang.IllegalStateException: getOutputStream() has already been called for this response
    at org.apache.catalina.connector.Response.getWriter(Response.java:627)
    at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:215)
    at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:105)
    at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:105)
    at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:105)
    at com.sun.faces.context.ExternalContextImpl.getResponseOutputWriter(ExternalContextImpl.java:723)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.createResponseWriter(FaceletViewHandlingStrategy.java:938)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:377)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
    at org.springframework.faces.webflow.FlowViewHandler.renderView(FlowViewHandler.java:99)
    at com.ocpsoft.pretty.faces.application.PrettyViewHandler.renderView(PrettyViewHandler.java:163)
    at org.springframework.faces.webflow.FlowViewHandler.renderView(FlowViewHandler.java:99)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:118)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:368)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:99)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:60)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:119)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:57)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:169)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:70)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:471)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:402)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329)
    at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:110)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:368)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:119)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:169)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:964)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:304)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)
Jul 10, 2012 11:34:57 AM org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet Faces Servlet threw exception

JSP/XML:
<%@ page  language="java" import="java.net.* ,weather.*, XMLObjects.*,beans.*,daos.*,java.util.*,CampaignManipulation.*, adstreamer.*, java.net.*"%>

<%

        response.setContentType("text/xml");
        response.addDateHeader("Expires", 0);

        String urExit = "http://localhost:8080/myapp/anotherjsfxmlpage";
        response.addHeader("Refresh", urExit);

        XMLExecute exe = new XMLExecute();
        out.print(exe.GetXMLObject()); // String representation  of xml code <CiscoIPPhoneExecute> .... </CiscoIPPhoneExecute>
%>

JSF/XHTML:
<?xml version="1.0" encoding="UTF-8"?>
<f:view contentType="text/xml"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core">
    <f:event type="preRenderView" listener="#{sendPicController.preRender}"/>
</f:view>

JSF/Backing Bean:
public void preRender() throws Exception {

        log.debug("preRender");

        FacesContext ctx = FacesContext.getCurrentInstance();
        HttpServletRequest request = GeneralUtils.getHttpServlettRequest();
        HttpServletResponse response = GeneralUtils.getHttpServlettResponse();

        response.setContentType("text/xml");
        response.addDateHeader("Expires", 0);

        String urExit = "http://localhost:8080/myapp/anotherjsfxmlpage";
        response.addHeader("Refresh", urExit);

        response.getOutputStream().write(exe.GetXMLObject().getBytes()); // bytes representation  of xml
        response.getOutputStream().flush();
        response.getOutputStream().close();
        ctx.responseComplete();
    }

please advise why i am getting this exception and how to fix it.

A: This will happen if during the request processing both HttpServletResponse.getWriter() and HttpServletResponse.getOutputStream() are being called. And as per the spec, it is illegal to use both OutputStream and Writer.
Check the code which is calling HttpServletResponse.getOutputStream() somewhere else in your code.
Possible Duplicate of getting error "getOutputStream() has already been called for this response".

A: my problem was that i was forgetting to close the outputstream in some other place in the code that was not posted above.


text:
Q: Reputation change text is not centered vertically inside green block in Android Chrome In Chrome on Android 7.0 reputation change in topbar is not aligned vertically (i.e. shifted to the top):

In Chrome on iOS reputation change looks fine:


text:
Q: Full length navbar I want my navbar to span the entire width like this www.ramenchicago.com but right now i can only get it all on the right.
I have my css set up like this

.navbar-wrapper > .container {
    padding-right: 0;
    padding-left: 0;
    width: 100%;
}
.navbar-wrapper .navbar {
    padding-right: 15px;
    padding-left: 15px;
    width: 100%;
    background-color: rgba(0,0,0,0.8);

}

li {
    border-left: solid 1px white;
}

li:hover {
    background: rgba(0,0,0,0.3);
}

#navbar {
    display: table-row;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

                            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                                Toggle navigation

                            </button>

HOME

                                    ABOUT

LOCATION

PRESS

STRINGS 1

STRINGS 2

HELL RAMEN

JOBS

DARK CHEFS

Should I change my ul or li? Please help me out!
Also, it's my first time using Bootstrap so I'm not familiar with it yet. How do I remove the little arrow on the dropdown menu?
Thanks!

A: Set ul width to 100%
.navbar-nav {
        float: left;
        margin: 0;
        width: 100%;
    }

and it's li as 100% divide by number of li it has. You have 7 li, So it will be width: 14%; like this
.navbar-nav>li {
        float: left;
        text-align: center;
        width: 14%; /* 100 divide by 7 li = 14 */
    }

For the arrow on dropdown, Just remove  there.

.navbar-wrapper > .container {
    padding-right: 0;
    padding-left: 0;
    width: 100%;
}
.navbar-wrapper .navbar {
    padding-right: 15px;
    padding-left: 15px;
    width: 100%;
    background-color: rgba(0,0,0,0.8);

}

.navbar-nav {
    float: left;
    margin: 0;
    width: 100%;
}

.navbar-nav>li {
    float: left;
    text-align: center;
    width: 14%; /* 100 divide by 7 li = 14 */
}

li {
    border-left: solid 1px white;
}

li:first-child{
   border: 0;
}

li:hover {
    background: rgba(0,0,0,0.3);
}

#navbar {
    display: table-row;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

                            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                                Toggle navigation

                            </button>

HOME

                                    ABOUT

LOCATION

PRESS

STRINGS 1

STRINGS 2

HELL RAMEN

JOBS

DARK CHEFS

A: You shouldn't need to nest containers and if you change your display properties to a table format you should see the results you're looking for.
.navbar-nav {
  display: table;
  width: 100%;
}
.navbar-nav > li {
  display: table-cell;
  float: none;
}
.navbar-nav > li > a {
  text-align: center;
}

*Note: I would place these inside a media query so it doesn't disturb your mobile navigation.
See working examples.
Full width of the browser

@media (min-width: 768px) {
  .navbar-wrapper .container-fluid {
    padding-right: 0;
    padding-left: 0;
    width: 100%;
  }
  .navbar-wrapper .navbar.navbar-inverse .navbar-nav {
    display: table;
    width: 100%;
  }
  .navbar-wrapper .navbar.navbar-inverse .navbar-nav > li {
    display: table-cell;
    float: none;
  }
  .navbar-wrapper .navbar.navbar-inverse .navbar-nav > li > a {
    text-align: center;
  }
}
.navbar-wrapper .navbar {
  background-color: rgba(0, 0, 0, 0.8);
}
.navbar-wrapper .navbar.navbar-inverse .navbar-nav > li {
  border-left: solid 1px white;
}
.navbar-wrapper .navbar.navbar-inverse .navbar-nav > li:hover {
  background: rgba(0, 0, 0, 0.3);
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false">
          Toggle navigation

        </button>

HOME

            ABOUT

LOCATION

PRESS

STRINGS 1

STRINGS 2

HELL RAMEN

JOBS

DARK CHEFS

Alternative: Full width of a container

@media (min-width: 768px) {
  .navbar-wrapper .navbar.navbar-inverse .navbar-nav {
    display: table;
    width: 100%;
  }
  .navbar-wrapper .navbar.navbar-inverse .navbar-nav > li {
    display: table-cell;
    float: none;
  }
  .navbar-wrapper .navbar.navbar-inverse .navbar-nav > li > a {
    text-align: center;
  }
}
.navbar-wrapper .navbar {
  background-color: rgba(0, 0, 0, 0.8);
}
.navbar-wrapper .navbar.navbar-inverse .navbar-nav > li {
  border-left: solid 1px white;
}
.navbar-wrapper .navbar.navbar-inverse .navbar-nav > li:hover {
  background: rgba(0, 0, 0, 0.3);
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false">
          Toggle navigation

        </button>

HOME

            ABOUT

LOCATION

PRESS

STRINGS 1

STRINGS 2

HELL RAMEN

JOBS

DARK CHEFS


text:
Q: Nginx config file only working for ''/" I am setting up nginx as a sort of static file server.  For some reason it is only working when I go to 123.123.123.123/ or 123.123.123.123.  However, when I go to 123.123.123.123/static/content/ or 123.123.123.123/static/content/another.mp3 it returns a 404 not found.  Here is the config file that is located in /etc/nginx/sites-available and linked to /etc/nginx/sites-enabled.  I am really stumped as to why it is not working.
Any pointers or tips would be appreciated.

server {
    listen 123.123.123.123:80;
    server_name "";

     location / {
         root /srv/homepage;
         index  index.html;
     }

     location /static/content/ {
         root /srv/static/content;
         index  song.mp3;
     }

}

A: If you look in your error log, you'll see that a request for 123.123.123.123/static/content/another.mp3, nginx will look for /srv/static/content/static/content/another.mp3.  This is due to the way that the root directive works in nginx.  When using root, nginx will append the request uri path to the given root, so you'll get one /static/content from the root directive, and another from the request.  The correct approach is to just set your root to /srv:
location /static/content/ {
  root /srv;
  index song.mp3;
}

Since all requests handled by this location will start with /static/content, it will only server files out of /srv/static/content.


text:
Q: How do I migrate from Azure to a Windows VPS? Basically I've been using Microsoft Azure to host my stuff for about a year now. I have a SQL instance and a "free" web site, and more recently, a scheduler to run a program that refreshes the DB daily. This is starting to cost up into $30 a month for these things, and I'm wondering how easy it would be to shuffle my hosting from Azure onto a VPS.
I'm probably going to host it on a service called Winity.io (about $22 a month for a fairly powerful VPS), but I don't know what the most straight forward way to do this would be. I have the original source code and everything on my computer still, so that part is sorted.
Once its on the VPS, what would be the best way to deploy it it as well?  Azure works well with SQL updates and stuff like that… does a similar technology exist in WebDeploy on a VPS host?

A:
I don't know what the most straight forward way to do this would be. I
  have the original source code and everything on my computer still, so
  that part is sorted.

Web Contents
To migrate the web contents, either you can transfer web content through FTP or map your local drives to Remote Desktop connection and copy the content to VPS. Here is a excellent article you wish to refer.
https://manage.accuwebhosting.com/knowledgebase/939/How-to-uploadordownload-contents-fromorto-VPSorDedicated-server-via-RDP.html
Database
To migrate the database, the best approach would be take the MS SQL database backup through MS SQL Server Management Studio and download it in local system. Create database with the same name and restore database from  previously taken backup at VPS SQL Server.

Once its on the VPS, what would be the best way to deploy it it as
  well? Azure works well with SQL updates and stuff like that… does a
  similar technology exist in WebDeploy on a VPS host?

It depends upon your web host, if you are provided Windows VPS with necessary web deployment tools, you can deploy your websites through web deploy method.


text:
Q: GOLANG: Walk Directory Tree and Process Files -- err = 'no such file or directory I'm writing a routine to walk a directory tree and create a digital signature (salted-hash) for each file I find.  When testing it I get this weird behavior - if I give the program a root path "above" the directory, the program can walk the tree and print out the file names, but if I try and open the file to read it's bytes, I get the error message "no such file or directory" on the file that the routines found - not sure what gives here.  How can the Walk() routine "see" the file, but ioutil.ReadFile() not be able to find it?
Sample Code:
// start with path higher up the tree, say $HOME
func doHashWalk(dirPath string) {
    err := filepath.Walk(dirPath, walkFn)
    // Check err here
}

func walkFn(path string, fi os.FileInfo, err error) (e error) {

    if !fi.IsDir() {
        // if the first character is a ".", then skip it as it's a hidden file

        if strings.HasPrefix(fi.Name(), ".") {
            return nil
        }

        // read in the file bytes -> get the absolute path
        fullPath, err := filepath.Abs(fi.Name())
        if err != nil {
            log.Printf("Abs Err: %s", err)
        }

        // THIS ALWAYS FAILED WITH ERROR
        bytes, err := ioutil.ReadFile(fullPath) // <-- (fi.Name() also doesn't work)
        if err != nil {
            log.Printf("Err: %s, Bytes: %d", err, len(bytes))
        }

        // create the salted hash
        ...
    }
    return nil
}

A: Try logging the values of path vs. fullPath inside of walkFn.
Using filepath.Abs() inside of walkFn does not give the result you want: it's resolving a filename relative to the current working directory, instead of the original dirPath.
One option is to resolve the target directory to an absolute path up-front in doHashWalk:
func doHashWalk(dirPath string) {
    fullPath, err := filepath.Abs(dirPath)

    if err != nil {
        log.Println("path error:", err)

        return
    }

    err = filepath.Walk(fullPath, walkFn)

    // check err here
}

With that change, the walkFn callback will always receive a fully-qualified path argument; no need to call filepath.Abs() again:
func walkFn(path string, fi os.FileInfo, err error) (e error) {
    // ...

    bytes, err := ioutil.ReadFile(path)

    // ...
}

If it's important for your application to see the path of each file relative to the original dirPath root, you can sneak that path into the walkFn callback via a closure:
func doHashWalk(dirPath string) error {

    fullPath, err := filepath.Abs(dirPath)

    if err != nil {
        return err
    }

    callback := func(path string, fi os.FileInfo, err error) error {
        return hashFile(fullPath, path, fi, err)
    }

    return filepath.Walk(fullPath, callback)
}

func hashFile(root string, path string, fi os.FileInfo, err error) error {
    if fi.IsDir() {
        return nil
    }

    rel, err := filepath.Rel(root, path)

    if err != nil {
        return err
    }

    log.Println("hash rel:", rel, "abs:", path)

    return nil
}

A: The problems is that you're not using the filepath.Walk exactly the way it's intended.
You allready get the path to the file from the path parameter.
The docs might not exactly be abundantly clear but they do say this for filepath.Walk:

Walk walks the file tree rooted at root, calling walkFn for each file or directory in the tree, including root.

So you could shorten walkFn to something like this:
func walkFn(path string, fi os.FileInfo, err error) (e error) {
    if !fi.IsDir() {
        bytes, err := ioutil.ReadFile(path) // path is the path to the file.
        if err != nil {
            fmt.Println("Fail")
        }
    }
    return nil
}

Walk will take care of not walking up the file-tree via .. there's no need for you to check for that. Considering the absolute path part I don't really think you need that either, but I make no promises ;)