text:
Q: Formatting TimeSpan to show only the relevant time unit My application shows an estimated time for completion (ETA).
I don't want to give users a fully formatted TimeSpan, but showing only the most relevant unit. Users don't want to see 0:00:39,766.
For instance, if the TimeSpan is

*

*12 days, 5 hours, 42 minutes, 15 seconds

I would like to be formatted as "12 days"
If the TimeSpan is

*

*5 hours and 3 minutes

it should only show "5 hours", because the amount of hours, compared to the minutes, makes the amount of minutes irrelevant.
The same for minutes. 15 minutes and 15 minutes and 3 seconds should be formatted the same way.
Is there an standardized way to do this?

A: There's no standard way but you can implement an extension method:
 public static partial class TimeSpanExtensions {
   public static string ToMyFormat(this TimeSpan ts) {
     return ts.Days != 0 ? $"{ts.Days} days"
          : ts.Hours != 0 ? $"{ts.Hours} hours"
          : ts.Minutes != 0 ? $"{ts.Minutes} minutes"
          : ts.Seconds != 0 ? $"{ts.Seconds} seconds"
          : $"{ts.Milliseconds} milliseconds";
   }
 }

And then use it:
 TimeSpan test = new TimeSpan(0, 415, 48, 44, 452);

 // 17 days (415 = 17 * 24 + 7 - 17 days 7 hours)
 Console.Write(ts.ToMyFormat());


text:
Q: VSCode Python debugger throwing ImportError ModuleNotFound I'm running tests for my project which contains several modules:
├── compute_metrics_service
│   ├── tests
│   │   ├── integration
        │   ├── test_app.py
        │   └── __init__.py
│   │   └── unit
│   └── utils
├── data_quality
│   ├── helpers
│   └── tests
│       ├── integration
│       └── unit
└── fetch_data_metrics
    ├── helpers
    └── tests
        ├── integration
        └── unit

For example, I'm trying to debug a test inside of compute_metrics_service/tests/integration with VSCode, but I'm getting the following error:
ImportError: 'test_app' module incorrectly imported from '/Users/xxxx/Documents/SOC/data-quality-tool/data_quality/tests/integration'. Expected '/Users/xxxx/Documents/SOC/data-quality-tool/compute_metrics_service/tests/integration'. Is this module globally installed?

I've set my PYTHONPATH the following way:
export PYTHONPATH="$PWD/data_quality:$PWD/compute_metrics_service:$PWD/fetch_data_metrics"

test_app.py is simply a TestCase, similar to the following:
import unittest
import os
import logging
from datetime import datetime
from unittest import mock
from unittest.mock import MagicMock, patch, mock_open
from compute_metrics_service import app
from compute_metrics_service.utils import Helpers

class TestMainCompleteness(unittest.TestCase):
 ...

What am I missing?
TIA!

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to put users' private data on separate partition in Windows 7 I am going to install Windows 7 on a machine in some days time. I wanted to know if it is easy to separate the OS data from users' data (/users in Windows 7, I believe) on separate partition during or after installation.
I hope it will be as seamless as with "/home" on Unix or Linux, but I have never tried it with Windows before.
My main motivation is to be able to do re-installs of the OS without having to worry too much about recovering the users' data from backups (saves some hours). Also, I have personally favor this separation, coming from Linux background.
All inputs and experiences regarding this are welcome.
Thanks.

A: Similar thread at What's the best way to move c:\users to d:\users under vista/W7

A: Using sysprep is the easiest way to create user profiles in a different location. All the other, unofficial ways, such as messing around with junctions and copying or moving files around, gave me "The User Profile Service failed the logon. User profile cannot be loaded." profile error.

*

*Windows 8:

*

*How to Relocate User Profiles to another Partition or Disk in Windows 8:
http://www.eightforums.com/tutorials/4275-user-profiles-relocate-another-partition-disk.html

*Windows 7:

*

*How to Create User Accounts on another Partition or Disk During Windows 7 Installation:
http://www.sevenforums.com/tutorials/124198-user-profiles-create-move-during-windows-7-installation.html


text:
Q: Convert MySQL Month/Year to Datetime or Unixtime I have a MySQL column in the following format, but how can I convert it to datetime or unixtime format.
Existing format
February 2015

Required format
2015-02-01 00:00:00

Any idea how this can be done using MySQL?

A: You can use str_to_date and date_format for this
 mysql> select date_format(str_to_date('February 2015','%M %Y'),'%Y-%m-01 %H:%i:%s') as date;
+---------------------+
| date                |
+---------------------+
| 2015-02-01 00:00:00 |
+---------------------+
1 row in set (0.00 sec)


text:
Q: on touch of image, image view to fullscreen and zoom should work I'm loading Image from server to imageview. I'm using Picasso to load the image from server to imageview.
On touch of that image, i want it to appear fullscreen and even zoom/tap should work.
I don't know what to do for this, Please help me with suggestions or some examples.
I found few examples, but there was more than 1000 lines code, I couldn't find it helpful and I didn't understand what to do with it.
Thanks.
this is my code.
image = (ImageView) findViewById(R.id.image);
image.setOnClickListener(this);

Picasso.with(this).load("http://Imageurl").into(image);

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.image:

            //what to do here ?

             break;
   }
}

A: You can use following cusome class for implment zooming functionality in your layout which will work for me better.
public class TouchOrZoomImageView extends ImageView
{
    Matrix mMatrix = new Matrix();

    // We can be in one of these 3 states
    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;
    int mode = NONE;

    // Remember some things for zooming
    PointF last = new PointF();
    PointF start = new PointF();
    float minScale = 1f;
    float maxScale = 3f;
    float[] m;

    float redundantXSpace, redundantYSpace;

    float width, height;
    static final int CLICK = 3;
    float saveScale = 1f;
    float right, bottom, origWidth, origHeight, bmWidth, bmHeight;

    ScaleGestureDetector mScaleDetector;

    Context context;

    public TouchOrZoomImageView(Context context)
    {
        super(context);
        sharedConstructing(context);
    }

    public TouchOrZoomImageView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        sharedConstructing(context);
    }

    private void sharedConstructing(Context context)
    {
        super.setClickable(true);
        this.context = context;
        mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
        mMatrix.setTranslate(1f, 1f);
        m = new float[9];
        setImageMatrix(mMatrix);
        setScaleType(ScaleType.MATRIX);

        setOnTouchListener(new OnTouchListener()
        {
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                mScaleDetector.onTouchEvent(event);

                mMatrix.getValues(m);
                float x = m[Matrix.MTRANS_X];
                float y = m[Matrix.MTRANS_Y];
                PointF curr = new PointF(event.getX(), event.getY());

                switch (event.getAction())
                {
                    case MotionEvent.ACTION_DOWN:
                        last.set(event.getX(), event.getY());
                        start.set(last);
                        mode = DRAG;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (mode == DRAG)
                        {
                            float deltaX = curr.x - last.x;
                            float deltaY = curr.y - last.y;
                            float scaleWidth = Math.round(origWidth * saveScale);
                            float scaleHeight = Math.round(origHeight * saveScale);
                            if (scaleWidth < width)
                            {
                                deltaX = 0;
                                if (y + deltaY > 0)
                                    deltaY = -y;
                                else if (y + deltaY < -bottom)
                                    deltaY = -(y + bottom);
                            }
                            else if (scaleHeight < height)
                            {
                                deltaY = 0;
                                if (x + deltaX > 0)
                                    deltaX = -x;
                                else if (x + deltaX < -right)
                                    deltaX = -(x + right);
                            }
                            else
                            {
                                if (x + deltaX > 0)
                                    deltaX = -x;
                                else if (x + deltaX < -right)
                                    deltaX = -(x + right);

                                if (y + deltaY > 0)
                                    deltaY = -y;
                                else if (y + deltaY < -bottom)
                                    deltaY = -(y + bottom);
                            }
                            mMatrix.postTranslate(deltaX, deltaY);
                            last.set(curr.x, curr.y);
                        }
                        break;

                    case MotionEvent.ACTION_UP:
                        mode = NONE;
                        int xDiff = (int) Math.abs(curr.x - start.x);
                        int yDiff = (int) Math.abs(curr.y - start.y);
                        if (xDiff < CLICK && yDiff < CLICK)
                            performClick();
                        break;

                    case MotionEvent.ACTION_POINTER_UP:
                        mode = NONE;
                        break;
                }
                setImageMatrix(mMatrix);
                invalidate();
                return true; // indicate event was handled
            }
        });
    }

    @Override
    public void setImageBitmap(Bitmap bm)
    {
        super.setImageBitmap(bm);
        if (bm != null)
        {
            bmWidth = bm.getWidth();
            bmHeight = bm.getHeight();
        }
    }

    public void setMaxZoom(float x)
    {
        maxScale = x;
    }

    private class ScaleListener extends
            ScaleGestureDetector.SimpleOnScaleGestureListener
    {
        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector)
        {
            mode = ZOOM;
            return true;
        }

        @Override
        public boolean onScale(ScaleGestureDetector detector)
        {
            float mScaleFactor = (float) Math.min(
                    Math.max(.95f, detector.getScaleFactor()), 1.05);
            float origScale = saveScale;
            saveScale *= mScaleFactor;
            if (saveScale > maxScale)
            {
                saveScale = maxScale;
                mScaleFactor = maxScale / origScale;
            }
            else if (saveScale < minScale)
            {
                saveScale = minScale;
                mScaleFactor = minScale / origScale;
            }
            right = width * saveScale - width - (2 * redundantXSpace * saveScale);
            bottom = height * saveScale - height
                    - (2 * redundantYSpace * saveScale);
            if (origWidth * saveScale <= width || origHeight * saveScale <= height)
            {
                mMatrix.postScale(mScaleFactor, mScaleFactor, width / 2, height / 2);
                if (mScaleFactor < 1)
                {
                    mMatrix.getValues(m);
                    float x = m[Matrix.MTRANS_X];
                    float y = m[Matrix.MTRANS_Y];
                    if (mScaleFactor < 1)
                    {
                        if (Math.round(origWidth * saveScale) < width)
                        {
                            if (y < -bottom)
                                mMatrix.postTranslate(0, -(y + bottom));
                            else if (y > 0)
                                mMatrix.postTranslate(0, -y);
                        }
                        else
                        {
                            if (x < -right)
                                mMatrix.postTranslate(-(x + right), 0);
                            else if (x > 0)
                                mMatrix.postTranslate(-x, 0);
                        }
                    }
                }
            }
            else
            {
                mMatrix.postScale(mScaleFactor, mScaleFactor, detector.getFocusX(),
                        detector.getFocusY());
                mMatrix.getValues(m);
                float x = m[Matrix.MTRANS_X];
                float y = m[Matrix.MTRANS_Y];
                if (mScaleFactor < 1)
                {
                    if (x < -right)
                        mMatrix.postTranslate(-(x + right), 0);
                    else if (x > 0)
                        mMatrix.postTranslate(-x, 0);
                    if (y < -bottom)
                        mMatrix.postTranslate(0, -(y + bottom));
                    else if (y > 0)
                        mMatrix.postTranslate(0, -y);
                }
            }
            return true;
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width = MeasureSpec.getSize(widthMeasureSpec);
        height = MeasureSpec.getSize(heightMeasureSpec);
        // Fit to screen.
        float scale;
        float scaleX = (float) width / (float) bmWidth;
        float scaleY = (float) height / (float) bmHeight;
        scale = Math.min(scaleX, scaleY);
        mMatrix.setScale(scale, scale);
        setImageMatrix(mMatrix);
        saveScale = 1f;

        // Center the image
        redundantYSpace = (float) height - (scale * (float) bmHeight);
        redundantXSpace = (float) width - (scale * (float) bmWidth);
        redundantYSpace /= (float) 2;
        redundantXSpace /= (float) 2;

        mMatrix.postTranslate(redundantXSpace, redundantYSpace);

        origWidth = width - 2 * redundantXSpace;
        origHeight = height - 2 * redundantYSpace;
        right = width * saveScale - width - (2 * redundantXSpace * saveScale);
        bottom = height * saveScale - height - (2 * redundantYSpace * saveScale);
        setImageMatrix(mMatrix);
    }
}

Now put after this class as view in your layout whereyou want to show like bellow is the example
<com.yourpackagename.TouchOrZoomImageView
    android:id="@+id/bottomImage"
    android:src="@drawable/nature_2"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_weight="1" />

Then after you can load data or set src same as you are setting in ImageView, This class inherit ImageView class so you can set all property which is using image use.

A: There are some simple steps you should follow.

*

*Create one full-screen Activitywith ImageView only.

*You need to implement library for Pinch to Zoom In/Zoom Out Images. Through which you can zoom In/Out your Imageview.

*By Clicking on Imageview Start that Activity and Finish on onBackPress()
There are some of the examples of library you can use.

https://github.com/martinwithaar/PinchToZoom
https://github.com/jsibbold/zoomage


text:
Q: Generic quicksort not working I'm trying to make a generic quicksort function, and I fail to understand what's wrong with what I'm doing, because it's not working properly.
Here is my code:
typedef bool (*CmpFunction)(void*, void*);

void swap(void *c1, void *c2)
{
    assert(c1 && c2);
  int c = *(int*)c1;
  *(int*)c1 = *(int*)c2;
  *(int*)c2 = c;
}

void quick_sort(void* a, int n, CmpFunction swap)
{
   int p, b = 1, t = n - 1;
   if (n < 2)
      return;
   swap((char*)a, (char*)a+n/2);
   p = *(int*)a;
   while(b <= t) {
      while(t >= b && (char*)a + t >= p )
         t--;
      while(b <= t && (char*)a + b < p)
         b++;
      if ( b < t)
         swap((char*)a+(b++), (char*)a+(t--));
   }
   swap((char*)a, (char*)a+t);
   quick_sort(a, t, swap);
   n=n-t-1;
   quick_sort(a + t + 1, n, swap);
}

While the original quicksort function, without me trying to make it generic is:
void quick_sort(int a[], int n)
{
   int p, b = 1, t = n - 1;
   if (n < 2)
      return;
   swap(&a[0], &a[n/2]);
   p = a[0];
   while(b <= t) {
      while(t >= b && a[t] >= p )
         t--;
      while(b <= t && a[b] < p)
         b++;
      if ( b < t)
         swap(&a[b++], &a[t--]);
   }
   swap(&a[0], &a[t]);
   quick_sort(a, t);
   n=n-t-1;
   quick_sort(a + t + 1, n);
}

void swap(int *c1, int *c2)
    {
      int c = *c1;
      *c1 = *c2;
      *c2 = c;
    }

I'm using this main():
int main(){

    char b[] = {'a','t','b','c','y','s'};
    int c[] = {1,4,6,3,5,7};
    quick_sort(c, 6, &swap);

    for (int i=0;i<6;i++)
        printf("%d | ", c[i]);

    return 0;
}

Now we all agree that the output should be:
1, 3, 4, 5, 6, 7

which is indeed what I get when running the NOT generic function.
When I run my generic(upper) function I get basically trash.
You all have any ideas where I'm wrong? :)

A: The most obvious issue: Your input data is an int array, typecasted into a void * pointer, then forced into a char * pointer:
swap((char*)a, (char*)a+n/2);

Here you force that into a char * pointer, and jumping n/2 into it.
char * is an array of 1 byte size elements
int * is an array of 2, 4 or 8 byte size elements depending on compiler/OS/CPU.
So char *a +1, void give you the second byte of the first element of the initial array.

A: qsort is a generic sorting function. You give it an array, the size of the elements in the array, the number of elements, and a comparison function.
typedef int(*compare)(const void*, const void*);

void quicksort(void *base, size_t num_elements, size_t width, compare *cmp);

To move through the array the sorting function needs to know the width of each element so it can do the pointer arithmetic correctly. An array of char will be 1 byte per element. An array of int is probably 4 bytes. double will be 8. base[4] of a char array is base + 4*1, but it's base + 4*4 for an int array. Ultimately base[n] is base + (n * width).
To avoid making assumptions about the data in the elements, or how you want them sorted, the compare is used to compare elements for sorting. It returns < 0 if a < b, 0 if a == b and > 0 if a > b. This allows it to be as simple as return a - b for most numbers.
An example function for comparing integers:
int cmp_int(const void* _a, const void* _b) {
    /* Do the casting separately for clarity */
    int *a = (int *)_a;
    int *b = (int *)_b;

    return *a - *b;
}

There's no need to pass in a swap function. So long as you know the size of the elements a single swap function will serve. The one from @HonzaRemeš' answer works.
void swap(void * a, void * b, size_t size) {
    /* Temp buffer large enough to contain an element */
    char tmp[size];

    memcpy(tmp, a, size);
    memcpy(a, b, size);
    memcpy(b, tmp, size);
}

With all this in mind, your function is not being given the element size (ie. width) so it cannot correctly move through the array. It's also unnecessarily passing in a swap function, but there's no need for this if you know the size of the elements. And you're lacking a proper comparison function to compare elements. Not much of a generic sort function if it can't compare things to sort them.

A: You are trying to do something the C language is not very appropriate for. If you want to do it, you need some background knowledge about pointer arithmetics.
Specifically, for a T *, where T is a type with size N (sizeof(T) == N),
T * ptr;
ptr = (T *) 0x0100;
ptr = ptr + 1;
// ptr now has value 0x100 + N

That means you can't have a generic function which will operate on data arrays without knowing the size of the array element.
So I suggest you rewrite your quick_sort and swap functions to incorporate size parameters. You then cast your pointers to char * and use the size parameter to make the functions work correctly. Example swap function follows.
void swap(void * c1, void * c2, size_t size) {
    char tmp[size]; // temporary buffer big enough to contain c1 data
    memcpy(tmp, c1, size);
    memcpy(c1, c2, size);
    memcpy(c2, tmp, size);
}

Modifying quick_sort is left as an exercise :). Remember though that when you don't know the size of your data, you must use memcpy(dst, src, size) instead of dst = src, you must use memcmp(a1, a2, size) >= 0 instead of a1 >= a2 and that your pointer access must be multiplied by size (exerpt from quick_sort follows):
EDIT: @Schwern points out in the comments why using memcmp() may not work. Comparing values of unknown size and format (endianness, float X int) would probably require a generic comparison function (which would likely be next to impossible to write). That takes us back to C's ill-suitedness for this task.
void quick_sort(void *a, int n, size_t size) {
    char[size] p;
    int b = 1, t = n - 1;
    if(n < 2)
        return;
    // Using new swap with 'size' parameter
    swap(&a[0], &((char *)a)[n / 2 * size], size);
    // or swap((char *)a + 0, (char*)a + (n / 2 * size), size);
    memcpy(p, a, size);
    while(b <= t) {
        while(t >= b && memcmp((char *)a[t * size], p, size) >= 0) {
    ...
}

You can then write wrapper macros to pass the size parameter to the quick_sort function.
#define QSORT(arr, n) quick_sort((arr), (n), sizeof((arr)[0]))


text:
Q: Poorly worded, but Simple Probability Question I'm having a discussion with my professor about the following probability problem:

Suppose that the probability that a driver is a male, and has at least one motor
  vehicles accident during a one-year period, is 0.12. Suppose that the corresponding
  probability for a female is 0.06. What is the probability of a randomly selected
  driver having at least one accident during the next 12 months?

My professor is insisting that the answer is 0.09, as the book "implies" that the sample space of the population is half male, and half female, and you would just take the average of the two probabilities.
I however, am attempting to argue that the probability is instead 0.18.  Following the probability axiom: P(A) = P(AB) + P(ABC), I propose that if you define A to to be the probability of being in a motor vehicle accident, and B to be the probability that the subject is a male, that the above formula should be applied to the problem to get the answer of 0.18.
I believe the difference comes down to wording.  If the problem had said "GIVEN that the driver was a male, the probability of having at least one motor vehicle accident is 0.12", I would agree with my professor's assessment.  But I would think that the wording of the problem clearly does not state that, but rather stating that P(AB)=0.12, and P(ABC)=0.06, giving my answer.
Can somebody help shed some light onto this?  Sorry if it seemed like I am rambling.

A: To elaborate on both my comment and in general, I realize that in your interpretation, the probabilities I gave in my comment are impossible. The reason for this is that in your interpretation, you start out by picking a random driver.
This driver is male and has had a recent accident with probability 0.12, or the driver is female and has had a recent accident with probability 0.06.
Of course both of these probabilities cannot be larger that 0.5, because they are non-overlapping events.
Also, I agree that this is what the problem states, if you take it literally, and in this case, your answer is correct. If the problem was intended differently, then it should have been made more precise.
As a fun follow-up question, given this interpretation, you can ask: What is the probability of him having had a recent accident, if you choose a male driver? I get
$P(A|B) = P(AB)/P(B) = 0.12/0.5 = 0.24,$
which is of course a huge and not very realistic probability for this particular problem.
For the other interpretation, that for the set of male drivers, 12 % of them have had recent accidents, and likewise 6 % for female drivers, the problem of an arbitrary driver having had an accident is
$P(A) = P(A|B)P(B) + P(A|B^c)P(B^c)=0.12\cdot 0.5 + 0.06\cdot 0.5 = 0.09.$
I'm sure that your professor chooses this interpretation of the problem, because he believes (through experience) that this is how the problem was intended, despite the poor wording.


text:
Q: WorkManager does not initialize on demand I read these instructions: https://developer.android.com/topic/libraries/architecture/workmanager/advanced/custom-configuration#on-demand
Now I have a MyApplication class, but I can't understand how to use it and I can't find clear instruction anywhere
When requesting WorkManager.getInstance, an error is naturally generated because the MyApplication class is not used anywhere. I could not understand how to activate this class for WorkManager.
AndroidManifest.xml:
<provider
  android:name="androidx.work.impl.WorkManagerInitializer"
  android:authorities="${applicationId}.workmanager-init"
  tools:node="remove"
  android:exported="false" />

MyApplication.java:
public class MyApplication extends Application implements Configuration.Provider {
    @NonNull
    @Override
    public Configuration getWorkManagerConfiguration() {
        return new Configuration.Builder().
        setExecutor(Executors.newFixedThreadPool(5)).build();
    }
}

I need to solve this problem exactly, so I will be grateful for the good help. How to make on-demand initialization work?

A: WorkManager v2.1 introduced on-demand initialization. This means that you don't need to call WorkManager.initialize() when you have a custom configuration, calling getInstance(Context) is enough.
What is not enough is to call the, now deprecated, getInstance() (without the Context argument). This is stated in the documentation you linked to.
I also covered it at droidcon Berlin 2019 in my talk "Embracing WorkManager". You can find the slides here and the video recording here.


text:
Q: How can I give Linear gradient to my entire flutter app? Here's the code,
The problem is that there is a gap of black colour around the rounded corners due to theme data being black. I can't fill it with gradient present in the above container. image has been attached. any solution?
 class _TrackListState extends State<TrackList> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Expanded(
              child: Container(
                height: double.infinity,
                //child: Text('hello'),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                      colors: [Color(0xFF04DCB6), Color(0xFF6DE079)]),
                ),
                child: Column(
                  children: <Widget>[],
                ),
              ),
            ),
            Expanded(
              flex: 3,
              child: Container(
                //padding: EdgeInsets.symmetric(horizontal: 20),
                foregroundDecoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(30),
                    topRight: Radius.circular(30),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

The image where I am having the problem

A: I tested it on DartPad. Give it a try. Using stack, you can fill the background and draw on top of it.
      @override
      Widget build(BuildContext context) {
        return Stack(
          fit: StackFit.expand,
          children: <Widget>[
            Container(
              decoration: BoxDecoration(
                gradient:
                    LinearGradient(colors: [Color(0xFF04DCB6), Color(0xFF6DE079)]),
              ),
            ),
            Positioned.fill(
              top: 80,
              child: Container(
                foregroundDecoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(30),
                    topRight: Radius.circular(30),
                  ),
                ),
              ),
            ),
          ],
        );
      }


text:
Q: assetic:dump and error 404 JS files not found I've been using assetic:dump for a while. However, since we changed the server of our application we have been experiencing strange errors. Actually, the JS files generated by assetic:dump cannot be found (404). And what is strange is that this bug depends on the server I'm using. On the production server, the JS are available on app.php but not on app_dev.php. On the tests server, the JS are available on both app.php and app_dev.php. On the development server, the JS are neither available on app.php nor on app_dev.php. It's for sur an environment issue. However, I cannot find where the problem is.
My configuration:
assetic:
    debug:          "%kernel.debug%"
    use_controller: false
    bundles:
        - MyBundle
    ruby: %path_ruby%
    node: %path_node%
    filters:
        cssrewrite: ~
        sass:
            bin: %path_sass%
            apply_to: "\.scss$"
        lessphp:
            file: "%kernel.root_dir%/../vendor/oyejorge/less.php/lessc.inc.php"
            apply_to: "\.less$"
        uglifyjs2:
            bin: %path_uglifyjs2%
        assets:
            back_js:
            inputs:
            - "%kernel.root_dir%/../vendor/jquery/jquery/jquery-1.11.0.js"
            - "%kernel.root_dir%/../vendor/twbs/bootstrap/js/transition.js"
            - "%kernel.root_dir%/../vendor/twbs/bootstrap/js/alert.js"
            - "%kernel.root_dir%/../vendor/twbs/bootstrap/js/button.js"
            - "%kernel.root_dir%/../vendor/twbs/bootstrap/js/carousel.js"
            - "%kernel.root_dir%/../vendor/twbs/bootstrap/js/collapse.js"
            - "%kernel.root_dir%/../vendor/twbs/bootstrap/js/dropdown.js"
            - "%kernel.root_dir%/../vendor/twbs/bootstrap/js/modal.js"
            - "%kernel.root_dir%/../vendor/twbs/bootstrap/js/tooltip.js"
            - "%kernel.root_dir%/../vendor/twbs/bootstrap/js/popover.js"
            - "%kernel.root_dir%/../vendor/twbs/bootstrap/js/scrollspy.js"
            - "%kernel.root_dir%/../vendor/twbs/bootstrap/js/tab.js"
            - "%kernel.root_dir%/../vendor/twbs/bootstrap/js/affix.js"
            - "%kernel.root_dir%/../vendor/braincrafted/bootstrap-bundle/Braincrafted/Bundle/BootstrapBundle/Resources/js/bc-bootstrap-collection.js"
            - "%kernel.root_dir%/Resources/js/plugins.js"
            - "%kernel.root_dir%/Resources/js/modernizr-2.6.2-respond-1.1.0.min.js"
            - "%kernel.root_dir%/Resources/js/jquery.mousewheel-3.0.6.pack.js"
            - "%kernel.root_dir%/Resources/js/jquery.minicolors.js"
            - "%kernel.root_dir%/Resources/js/jquery.minicolors.min.js"
            - "@MyBundle/Resources/public/js/jquery.countTo.js"
            - "@MyBundle/Resources/public/js/backend.js"
        output: js/headooback.js

After app/console assetic:dump and app/console assetic:dump --env=prod, I have:
On the html/app_dev.php a link like this
<script src="http://bugs.com/js/505da13_back_1.js?2"></script>

On the html/app_dev.php a link like this
<script src="http://bugs.com/js/505da13_1.js?2"></script>

And on my web folder
js/back.js

I have already tried to uninstall nodejs and uglifyjs and then to reinstall both of them. I'm sure that the path for their bin are correct. I also disabled the javascript-common.conf of Apache in case it was searching the js in the wrong folder. What else can I check? Or what else can influence the generation of the js ? I have no errors.
Thank you.

A: Did you do a "app/console as:in" (assetic:install)?

A: This often happens with assetic if you don't clear cache after changing its settings. Try doing that: rm -r app/cache/* and then run the dump again. This could also explain difference between servers.


text:
Q: make-frame does not set the right font size If I open up a new frame in emacs (v24.3.1), the font is set to a different size. All other settings are correct but the fontsize. (On the screenshot, the window in the back opens up a new frame with make-frame, the window in the front is the new window, with the wrong font size.

In my init.el, I have the following code:
 (set-face-font 'default "-misc-fixed-medium-r-semicondensed--13-120-75-75-c-60-iso8859-1")

A: Check your init file (and any code it loads) for something that changes default-frame-alist, specifically with respect to parameter font or font-parameter. Check the definition of face default.
You can customize option default-frame-alist or face default, to control this. (But you still might want to figure out what code you are using already changes this.)
 M-x customize-face default
 M-x customize-option default-frame-alist

Always, for something like this, please report whether the behavior you observe happens also when you start from emacs -Q, that is, without your init file.
If it does not, then recursively bisect your init file (by commenting-out 1/2, then 3/4, then 7/8,... until you find the culprit code that is causing the problem. This is a binary search, so it is very quick (though it does not seem so at the outset).
(Your screenshot indicates that you have Projectile loaded, for example. We cannot help you debug something if it is just a giant sack of stuff, all or most of which is unknown to us. You need to narrow things down, to identify what is causing the problem - by bisecting your init file.)


text:
Q: NoSuchMethodError for Scala Seq line in Spark I am having an error when trying to run plain Scala code in Spark similar to these posts: this and this
Their problem was that they were using the wrong Scala version to compile their Spark project. However, mine is the correct version.
I have Spark 1.6.0 installed on an AWS EMR cluster to run the program. The project is compiled on my local machine with Scala 2.11 installed and 2.11 listed in all dependencies and build files without any references to 2.10.
This is the exact line that throws the error:
var fieldsSeq: Seq[StructField] = Seq()

And this is the exact error:
Exception in thread "main" java.lang.NoSuchMethodError: scala.runtime.ObjectRef.create(Ljava/lang/Object;)Lscala/runtime/ObjectRef;
at com.myproject.MyJob$.main(MyJob.scala:39)
at com.myproject.MyJob.main(MyJob.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:731)
at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:181)
at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:206)
at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:121)
at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

A: Spark 1.6 on EMR is still built with Scala 2.10, so yes, you are having the same issue as in the posts you linked. In order to use Spark on EMR, you currently must compile your application with Scala 2.10.
Spark has upgraded their default Scala version to 2.11 as of Spark 2.0 (to be released within the next several months), so once EMR supports Spark 2.0, we will likely follow this new default and compile Spark with Scala 2.11.


text:
Q: ASP.NET MVC3 dropdown JQuery change event wire up gone wrong I am trying to wire up and change event jQuery handler for a dropdown list I have to populate a div "payment" with html returned from my controller action as soon as user changes a value in the dropdown.
Here is what I have so far and I have no idea why it's not working or on how to chase this further.  No errors or response from changing the dropdown value.  Any help very much appreciated!
cshtml:

@using (Html.BeginForm())
{

   @Html.Label("Select payment method")

   <select id="PaymentType" name="PaymentType">
     <option value="CreditCard">Credit Card</option>
     <option value="Cash">Cash</option>
     <option value="Check">Check</option>
   </select>

 }

OrderController.cs
    public JsonResult PaymentChanged(string paymentType)
    {
        return Json(new { agent = "sample html" }, JsonRequestBehavior.AllowGet);
    }

Standard, largely unchanged _Layout.cshtml file with all jQuery src including src="/Scripts/jquery-1.5.1.min.js"

A: Code looks fine to me so I'll answer "how to chase this further"

*

*Use Chrome's debugger or Firebug to see the status of your XHR.

*Run your MVC app in Debug mode (from Visual Studio) and put a break point inside your controller to see if it's actually being called and if paymentType is being sent properly (the former is more likely given your code looks fine).


text:
Q: Need to capture the return value of global class using tooling api I am calling global function defined in my salesforce org using the tooling api /services/data/v35.0/tooling/executeAnonymous/?anonymousBody= in python and that global class is actually returning a list of values which i need to capture in python. Is there a way to capture the value.
Regards,
Balaji.

A: I've covered a similar requirement before in Adding Eval() support to Apex. Essentially, you want to execute anonymous Apex and read a response.
There are two main ways to achieve this.

*

*Enable Debug logging when the anonymous Apex is executing. Then write out any return value to the log so it can be parsed out at a latter stage.

*Deliberately make a failed assertion call or throw an Exception. This method was first proposed by Kevin Poorman in his blog post EVAL() in Apex. Secure dynamic code evaluation on the Salesforce1 platform.
Both methods have their pros and cons. In your case you may find throwing an intentional exception and parsing the response to be an easier approach.


text:
Q: UWP ValueConverter from byte[] to BitmapImage I have this ValueConverter to convert a byte[] into a BitmapImage:
  public class ByteArrayToImageConverter : IValueConverter
  {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var bitmapImage = new BitmapImage();
            var buffer = (byte[])value;
            var str = new MemoryStream(buffer).AsRandomAccessStream();
            bitmapImage.SetSource(str);
            return bitmapImage;
        }

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

Strangely enough, when I run the code, the application hangs (deadlocks) in the in the line with SetSource.
Why is this happening? Am I doing something wrong?

A: I try use the code below that can convert.
var bytes = (byte[])value;

var image = bytes.AsBuffer().AsStream().AsRandomAccessStream();

// decode image
var decoder = await BitmapDecoder.CreateAsync(image);
image.Seek(0);

// create bitmap
var output = new WriteableBitmap((int)decoder.PixelHeight, (int)decoder.PixelWidth);
await output.SetSourceAsync(image);
return output;


text:
Q: Apache PIG - Get only date from TimeStamp I've the following code:
Data = load '/user/cloudera/' using PigStorage('\t')
as
(   ID:chararray,
    Time_Interval:chararray,
    Code:chararray);

transf = foreach Source_Data generate  (int) ID,
                                   ToString( ToDate((long) Time_Interval), 'yyyy-MM-dd hh:ss:mm') as TimeStamp,
                        (int) Code;

SPLIT transf INTO       Src25 IF (ToString(TimeStamp, 'yyyy-MM-dd')=='2016-07-25'),
                        Src26 IF (ToString(TimeStamp, 'yyyy-MM-dd')=='2016-07-26');

STORE Src25 INTO '/user/cloudera/2016-07-25' using PigStorage('\t');
STORE Src26 INTO '/user/cloudera/2016-07-26' using PigStorage('\t');

I want to split the files by date and the rules that I'm putting in Split statement it gives me error...
How can I transform TimeStamp (used on transf statement) in Date to make the comparasion?
Many thanks!

A: After you get the datetime object from ToDate, use GetYear(),GetMonth(),GetDay() on the datetime object and use CONCAT to construct only the date.
transf = foreach Source_Data generate
                   (int) ID,
                   ToString( ToDate((long) Time_Interval), 'yyyy-MM-dd hh:ss:mm') as TimeStamp,
                   (int) Code;

transf_new = foreach transf generate
                     ID,
                     TimeStamp,
                     CONCAT(CONCAT(CONCAT(GetYear(TimeStamp),'-')),(CONCAT(GetMonth(TimeStamp),'-')),GetDay(TimeStamp)) AS Day,-- Note:Brackets might be slightly off but it should be like 'yyyy-MM-dd' format
                     Code;

-- Now use the new Day column to split the data
SPLIT transf_new INTO       Src25 IF (Day =='2016-07-25'),
                            Src26 IF (Day =='2016-07-26');


text:
Q: draw color scale in grid plot in r I want to plot color scale with grid package. Something like heat.plot (10).

I am trying something like this:
require(grid)
legendViewport <- viewport(height=0.3, width=0.8)
pushViewport(legendViewport)
grid.rect(gp = gpar(col = "gray90"))

Let's say I want to divide 0 to 1, into 10 and fill heat.colors (10). Is there a simple way to do it.

A: If you just want colors,
grid.raster(t(heat.colors (10)),
   width=unit(1,"npc"),
   height=unit(1,"npc"), int=FALSE)


text:
Q: What is a clean interface to set class variables in a mixin module? In a Ruby project I'm working on, I add ActiveRecord-style, MVC functionality to model classes with a mixin architecture similar to the following:
module Model

  # Classes that mixin this module gain ActiveRecord-style class methods
  # like Model.all, Model.first, Model.last et al.
  #
  # Throughout this module, @@database_bridge will contain a reference to a
  # database ORM bridge, that does the dirty implementation of these methods.

  def all
    # Implementation stuff here, using @@database_bridge as appropriate
  end

  def first
    ...
  end

  # et al

end

class ExampleModel

  extend Model

  # Model-specific implementation goes here...

end

Calling e = ExampleModel.first would assign the first ExampleModel in the database to e.
I want to use dependency injection to set @@database_bridge at runtime, such that every class containing extend Model uses the same, specified ORM object.
How can I do this?
If I could write some kind of helper method to set up that class variable on demand, that would be great.

A: This isn't the answer, but is a potential solution: you can call class_variable_set on a module, by calling Module.class_variable_set.
Thus, you could create a helper method, in an appropriate namespace somewhere, that calls Module.class_variable_set :@@class_var, "new value".
For the example above, my helper function would like this:
def set_database_bridge(new_bridge)
  Model.class_variable_set :@@database_bridge, new_bridge
end

This solution creates a degree of coupling between the helper function and the implementation of the Model mixin, as if the name of @@database_bridge were to change, the helper function would break.
If anyone has an idea for a more loosely coupled/more encapsulated solution (where we perhaps encapsulate the helper function within Model somewhere), that would be awesome!

A: I've found a better solution than the previous, and it's much simpler than I thought (d'oh!): by prefixing a method with self. in a mixin module, a public interface to that method via Module.method becomes available.
Thus, we simply add a setter to our module, using a self.attribute_set statement.
In the above example, the above approach would yield the following code:
module Model

  # Classes that mixin this module gain ActiveRecord-style class methods
  # like Model.all, Model.first, Model.last et al.
  #
  # Throughout this module, @@database_bridge will contain a reference to a
  # database ORM bridge, that does the dirty implementation of these methods.

  def all
    # Implementation stuff here, using @@database_bridge as appropriate
  end

  def first
    ...
  end

  def self.set_database_bridge(ref_to_new_bridge)
    @@database_bridge = ref_to_new_bridge
    ## any additional intialisation/sanitisation logic goes here
  end

  # et al

end

class ExampleModel

  extend Model

  # Model-specific implementation goes here...

end

Calling Model.set_database_bridge would allow us to pass in a new database bridge.
If we don't actually need any initialisation or sanitisation logic in our helper function, there is another, more elegant approach - add an attr_accessor within a class << self block, thus:
module Model

  # ...

  class << self
    attr_accessor :database_bridge
  end

end

This way, we can call Ruby's standard setter method: Model.database_bridge = the_new_bridge.
Sweet.


text:
Q: QtSpim Assembler: Error on stack operation with double i'm writing a program for class. It takes x and epsilon from the console and should retrieve an sin(x) approximation. When i run it in QtSpim i get the error:

Unknown instruction type: 0

The error occurs here:
 floatsin:    addi    $sp, $sp, -64   # Frame
              sw      $ra, 64($ra)
              sw      $fp, 60($sp)
              s.d     $f0, 56($sp)
              s.d     $f4, 48($sp)
              s.d     $f20, 40($sp)
              s.d     $f8, 32($sp)
              s.d     $f10, 24($sp)
              s.d     $f14, 16($sp)
              s.d     $f18, 8($sp)        # ERROR HERE
              addi    $fp, $sp, 64

What could be the reason? I'm confused because till s.d $f18 everything runs normal. Thanks for any hints!
Below the full programm:
.data
xinput:      .asciiz "\nPlease enter x\n"
epsinput:    .asciiz "\nPlease enter epsilon\n"
sinxoutput:  .asciiz "\nsin(x) is: "

.text

main: la    $a0, xinput
      li    $v0, 4
      syscall
      li    $v0, 7
      syscall
      mov.d $f2, $f12
      la $a0, epsinput
      li $v0, 4
      syscall
      li    $v0, 7
      syscall
      mov.d $f0, $f12
      jal   floatsin
      la    $a0, sinxoutput
      li    $v0, 4
      syscall
      li    $v0, 3
      syscall
      li    $v0, 10
      syscall

floatsin:     addi    $sp, $sp, -64   # Frame
              sw      $ra, 64($ra)
              sw      $fp, 60($sp)
              s.d     $f0, 56($sp)
              s.d     $f4, 48($sp)
              s.d     $f20, 40($sp)
              s.d     $f8, 32($sp)
              s.d     $f10, 24($sp)
              s.d     $f14, 16($sp)
              s.d     $f18, 8($sp)
              addi    $fp, $sp, 64

              li.d    $f8,  0.0   # Initialize
              li.d    $f14, 1.0
              mov.d   $f16, $f0
              li.d    $f18, 0.0

              jal     loop_p1

main_loop:    add.d   $f18, $f18, $f4
              c.lt.d  $f2, $f4
              bc1f    exit_fsin
              jal     loop_p1
              sub.d   $f18, $f18, $f4
              c.lt.d  $f2, $f4
              bc1f    exit_fsin
              jal     loop_p1
              j       main_loop

loop_p1:      add.d   $f8, $f8, $f14
              li.d    $f10, 1.0       #for (j < 2i-1)
              mov.d   $f4,  $f16
              li.d    $f20, 0.0
              add.d   $f20, $f8, $f8
              sub.d   $f20, $f20, $f14
for:          c.lt.d  $f10, $f20
              bc1f    loop_p2
              mul.d   $f4, $f4, $f16 # (x*x)
              add.d   $f10, $f10, $f14
              j       for

loop_p2:      mov.d   $f0, $f20
              move    $t0, $ra
              jal     floatfac
              div.d   $f4, $f4, $f12
              jr      $t0

exit_fsin:    mov.d   $f12, $f18     # Write in target register
              l.d     $f18, 8($sp)   # rewrite values
              l.d     $f14, 16($sp)
              l.d     $f10, 24($sp)
              l.d     $f8,  32($sp)
              l.d     $f20, 40($sp)
              l.d     $f4,  48($sp)
              l.d     $f0,  56($sp)
              lw      $fp,  60($sp)
              lw      $ra,  64($sp)
              addi    $sp, $sp, 64
              jr      $ra           # back to caller

floatfac:     addi    $sp, $sp, -28   # Frame
              sw      $fp, 28($sp)
              s.d     $f4, 24($sp)
              s.d     $f2, 16($sp)
              s.d     $f0,  8($sp)
              addi    $fp, $sp, 28

              li.d    $f4, 0.0
              c.le.d  $f0, $f4
              bc1t    negative
              li.d    $f12, 1.0
              li.d    $f2, 1.0

while:        c.le.d  $f0, $f2       # Break condition
              bc1t    exit_floatfact
              mul.d  $f12, $f12, $f0
              sub.d   $f0, $f0, $f2
              j       while

negative:     li.d     $f12, 0.0

exit_floatfact: l.d      $f0,  8($sp)   # rewrite values
                l.d      $f2, 16($sp)
                l.d      $f4, 24($sp)
                lw       $fp, 28($sp)
                addi     $sp, $sp, 28
                jr       $ra

A: This is incorrect: sw $ra, 64($ra)
What's happening here is that you're storing the current value of $ra (0x40005c) at 64($ra), i.e. (0x40009c), thereby overwriting the instruction s.d $f14, 16($sp).
What you should be doing instead is sw $ra, 64($sp)


text:
Q: Opengl macos fail I have problem. I wrote the code on clear opengl and c++ without any libraries(glut, glew...) but it doesnt work.
Function displayCB display polygon with
glColor3f(1.0f, 0.0f, 0.0f);
   glBegin(GL_POLYGON);
     glVertex2f(-0.5f, -0.5f);
     glVertex2f( 0.5f, -0.5f);
     glVertex2f( 0.5f,  0.5f);
     glVertex2f(-0.5f,  0.5f);
   glEnd();

and dont display two polygone with
glColor3f(1.0f, 0.0f, 0.0f);
     glLoadIdentity();                                  // Reset The Current Modelview Matrix
        glTranslatef(-1.5f,0.0f,-6.0f);                     // Move Left 1.5 Units And Into The Screen 6.0
        glBegin(GL_TRIANGLES);                              // Drawing Using Triangles
            glVertex3f( 0.0f, 1.0f, 0.0f);                  // Top
            glVertex3f(-1.0f,-1.0f, 0.0f);                  // Bottom Left
            glVertex3f( 1.0f,-1.0f, 0.0f);                  // Bottom Right
        glEnd();                                            // Finished Drawing The Triangle
        glTranslatef(3.0f,0.0f,0.0f);                       // Move Right 3 Units
        glBegin(GL_QUADS);                                  // Draw A Quad
            glVertex3f(-1.0f, 1.0f, 0.0f);                  // Top Left
            glVertex3f( 1.0f, 1.0f, 0.0f);                  // Top Right
            glVertex3f( 1.0f,-1.0f, 0.0f);                  // Bottom Right
            glVertex3f(-1.0f,-1.0f, 0.0f);                  // Bottom Left
        glEnd();

Can you help me?
COMPILE WITH:       g++ -g -o opengl1 opengl1.cxx -lGLU -lGL -lX11
    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    #include <sys/time.h>
    #define GL_GLEXT_PROTOTYPES
    #define GLX_GLXEXT_PROTOTYPES
    #include <GL/gl.h>
    #include <GL/glu.h>
    #include <GL/glx.h>

    struct MyWin
    {
      Display  *display;
      Window    win;
      bool      displayed;
      int       width;
      int       height;
    };

    const int   WIN_XPOS    = 256;
    const int   WIN_YPOS    = 64;
    const int   WIN_XRES    = 600;
    const int   WIN_YRES    = 600;
    const int   NUM_SAMPLES = 4;

    MyWin        Win;

    double elapsedMsec( const struct timeval &start, const struct timeval &stop )
    {
      return ( ( stop.tv_sec  - start.tv_sec  ) * 1000.0 +
               ( stop.tv_usec - start.tv_usec ) / 1000.0 );
    }

    double elapsedUsec( const struct timeval &start, const struct timeval &stop )
    {
      return ( ( stop.tv_sec  - start.tv_sec  ) * 1000000.0 +
           ( stop.tv_usec - start.tv_usec ) );
    }

    /// check() - Check for GL errors, and report any queued

    void check( const char hdr[] = "" )
{
  int err;

  while ( ( err = glGetError() ) != GL_NO_ERROR )
    fprintf( stderr, "OpenGL Error at %s: %s\n", hdr, gluErrorString(err) );
}

void displayCB()
{
  glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

  //---------------------------------------------------
  // FIXME: Insert GL draw code here
  //---------------------------------------------------
  glColor3f(1.0f, 0.0f, 0.0f);
  glLoadIdentity();                                 // Reset The Current Modelview Matrix
    glTranslatef(-1.5f,0.0f,-6.0f);                     // Move Left 1.5 Units And Into The Screen 6.0
    glBegin(GL_TRIANGLES);                              // Drawing Using Triangles
        glVertex3f( 0.0f, 1.0f, 0.0f);                  // Top
        glVertex3f(-1.0f,-1.0f, 0.0f);                  // Bottom Left
        glVertex3f( 1.0f,-1.0f, 0.0f);                  // Bottom Right
    glEnd();                                            // Finished Drawing The Triangle
    glTranslatef(3.0f,0.0f,0.0f);                       // Move Right 3 Units
    glBegin(GL_QUADS);                                  // Draw A Quad
        glVertex3f(-1.0f, 1.0f, 0.0f);                  // Top Left
        glVertex3f( 1.0f, 1.0f, 0.0f);                  // Top Right
        glVertex3f( 1.0f,-1.0f, 0.0f);                  // Bottom Right
        glVertex3f(-1.0f,-1.0f, 0.0f);                  // Bottom Left
    glEnd();
  // glBegin(GL_POLYGON);
  //   glVertex2f(-0.5f, -0.5f);
  //   glVertex2f( 0.5f, -0.5f);
  //   glVertex2f( 0.5f,  0.5f);
  //   glVertex2f(-0.5f,  0.5f);
  // glEnd();
  // Display it
  glXSwapBuffers( Win.display, Win.win );

  check( "displayCB()" );
}

//----------------------------------------------------------------------------

void keyboardCB( KeySym sym, unsigned char key, int x, int y,
                 bool &setting_change )
{
  switch ( tolower( key ) )
  {
    case 27:
      // ESCape - We're done!
      exit (0);
      break;

    case 'k':
      printf( "You hit the 'k' key\n" );
      break;

    case 0:
      switch ( sym )
      {
        case XK_Left  :
          printf( "You hit the Left Arrow key\n" );
          break;

        case XK_Right :
          printf( "You hit the Right Arrow key\n" );
          break;
      }
      break;
  }
}

//----------------------------------------------------------------------------

void reshapeCB( int width, int height )
{
  Win.width = width;
  Win.height = height;
}

//----------------------------------------------------------------------------

XVisualInfo *chooseVisual( Display *display )
{
  int attribs [ 100 ] ;
  int n = 0 ;

  // Request 24-bit color with alpha
  attribs [n++] = GLX_RGBA ;
  attribs [n++] = GLX_RED_SIZE   ; attribs [n++] = 8 ;
  attribs [n++] = GLX_GREEN_SIZE ; attribs [n++] = 8 ;
  attribs [n++] = GLX_BLUE_SIZE  ; attribs [n++] = 8 ;

  // Request 24-bit depth buffer
  attribs [n++] = GLX_DEPTH_SIZE ; attribs [n++] = 24 ;

  // Request 4 multisamples per pixel
  attribs [n++] = GLX_SAMPLE_BUFFERS ; attribs [n++] = 1 ;
  attribs [n++] = GLX_SAMPLES        ; attribs [n++] = NUM_SAMPLES ;

  // Request double-buffering
  attribs [n++] = GLX_DOUBLEBUFFER ;
  attribs [n++] = None ;

  return glXChooseVisual( display, DefaultScreen( display ), attribs );
}

//----------------------------------------------------------------------------

void createWindow()
{
  // Init X and GLX
  Win.displayed = false;
  Display *display = Win.display = XOpenDisplay( ":0.0" );
  if ( !display )
    printf( "Cannot open X display\n" );

  int    screen   = DefaultScreen( display );
  Window root_win = RootWindow( display, screen );

  if ( !glXQueryExtension( display, 0, 0 ) )
    printf( "X Server doesn't support GLX extension\n" );

  // Pick a visual
  XVisualInfo *visinfo = chooseVisual( display );
  if ( visinfo == 0 )
    printf( "glXChooseVisual failed\n" );

  // Describe the visual
  printf( "Window Visual 0x%.2x\n", unsigned( visinfo->visualid ) );

  // Create the X window
  XSetWindowAttributes winAttr ;

  winAttr.event_mask = StructureNotifyMask | KeyPressMask ;
  winAttr.background_pixmap = None ;
  winAttr.background_pixel  = 0    ;
  winAttr.border_pixel      = 0    ;

  winAttr.colormap = XCreateColormap( display, root_win,
                                      visinfo->visual, AllocNone );

  unsigned int mask = CWBackPixmap | CWBorderPixel | CWColormap | CWEventMask;

  Window win = Win.win = XCreateWindow ( display, root_win,
                                         WIN_XPOS, WIN_YPOS,
                                         WIN_XRES, WIN_YRES, 0,
                                         visinfo->depth, InputOutput,
                                         visinfo->visual, mask, &winAttr ) ;

  XStoreName( Win.display, win, "My GLX Window");

  // Create an OpenGL context and attach it to our X window
  GLXContext context = glXCreateContext( display, visinfo, NULL, 1 ) ;

  if ( ! glXMakeCurrent( display, win, context ) )
    printf( "glXMakeCurrent failed.\n" );

  if ( ! glXIsDirect ( display, glXGetCurrentContext() ) )
    printf( "Indirect GLX rendering context obtained\n" );

  // Display the window
  XMapWindow( display, win );

  if ( ! glXMakeCurrent( display, win, context ) )
    printf( "glXMakeCurrent failed.\n" );

  check( "createWindow()" );

  printf( "Window Size    = %d x %d\n", WIN_XRES, WIN_YRES );
  printf( "Window Samples = %d\n", NUM_SAMPLES );
}

//----------------------------------------------------------------------------

void processXEvents( Atom wm_protocols, Atom wm_delete_window )
{
  bool setting_change = false;

  while ( XEventsQueued( Win.display, QueuedAfterFlush ) )
  {
    XEvent    event;

    XNextEvent( Win.display, &event );

    if( event.xany.window != Win.win )
      continue;

    switch ( event.type )
    {
      case MapNotify:
        {
          Win.displayed = true;
          break;
        }
      case ConfigureNotify:
        {
          XConfigureEvent &cevent = event.xconfigure;
          reshapeCB( cevent.width, cevent.height );
          break;
        }
      case KeyPress:
        {
          char      chr;
          KeySym    symbol;
          XComposeStatus status;

          XLookupString( &event.xkey, &chr, 1, &symbol, &status );

          keyboardCB( symbol, chr, event.xkey.x, event.xkey.y,
                      setting_change );
          break;
        }
      case ClientMessage:
        {
          if ( event.xclient.message_type      == wm_protocols &&
               Atom( event.xclient.data.l[0] ) == wm_delete_window )
          {
            //printf( "Received WM_DELETE_WINDOW\n" );
            exit(0);
          }
          break;
        }
    }
  }
}

//----------------------------------------------------------------------------

void mainLoop()
{
  // Register to receive window close events (the "X" window manager button)
  Atom wm_protocols     = XInternAtom( Win.display, "WM_PROTOCOLS"    , False);
  Atom wm_delete_window = XInternAtom( Win.display, "WM_DELETE_WINDOW", False);
  XSetWMProtocols( Win.display, Win.win, &wm_delete_window, True );

  while (1)
  {
    // Redraw window (after it's mapped)
    if ( Win.displayed )
      displayCB();

    // Update frame rate
    static timeval last_xcheck   = {0,0};
    struct timeval now;
    gettimeofday( &now, 0 );

    // Check X events every 1/10 second
    if ( elapsedMsec( last_xcheck, now ) > 100 )
    {
      processXEvents( wm_protocols, wm_delete_window );
      last_xcheck = now;
    }
  }
}

//----------------------------------------------------------------------------

int main( int argc, char *argv[] )
{
  // Init globals
  Win.width = WIN_XRES, Win.height = WIN_YRES;

  // Create context and window
  createWindow();

  // Init OpenGL
  glViewport  ( 0, 0, Win.width, Win.height );
  glColorMask ( 1,1,1,1 );
  glClearColor( 0,0,1,1 );
  glClear     ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

  // Go
  printf( "Valid keys: Left, Right, k, ESC\n" );
  printf( "Press ESC to quit\n" );

  mainLoop();

  return 0;
}

A: There are three problems here.
First: you haven't set up a GL viewport (e.g, using glFrustum() or gluPerspective()), so the perspective matrix isn't set up appropriately to do 3D graphics. As such, trying to draw a model in 3D won't work properly.
Second: The code that you've got here is written against the X11 windowing system, not Mac OS X. While it'll compile and sort-of-run on Mac OS, it will not run natively, nor will it perform particularly well. You will really want to use some interface which allows you to interface with the native Mac OS X GL implementation, such as SDL, GLUT/GLEW, or AGL.
(Keep in mind that there is no such thing as using GL "without libraries". OpenGL is itself a library, as is libX11; there's nothing at all wrong with using extra utility libraries to cut out some of the OS-specific setup and make your application easier to port.)
Third: You are currently learning how to use OpenGL immediate mode, which was used prior to OpenGL 3.0. Modern OpenGL — that is, OpenGL 3.0 or later, as well as OpenGL ES — uses a significantly different API which has very little in common with immediate mode. I'd strongly recommend that you skip immediate mode entirely; it's a dead technology at this point. There are a number of good tutorials out there for OpenGL 3+, including:

*

*http://www.opengl-tutorial.org/

*http://www.arcsynthesis.org/gltut/

*https://open.gl/


text:
Q: How can I generate a seed for np.random.uniform? I am trying to create 50 different cities with their latitudes and longitudes however each time I run I want the coordinates to be same.
lat = np.random.uniform(low=-90, high=90, size=50)
long = np.random.uniform(low=-180, high=180, size=50)

How can I provide a seed?

A: You can do as follow:
np.random.seed(42)
lat = np.random.uniform(low=-90, high=90, size=50)
long = np.random.uniform(low=-180, high=180, size=50)


text:
Q: Designing pipeline system Background
I have set of tools\solution that can be combined together into a one single data processing\action flow.
Each unit on my flow do a calculation or do an action.
Example: Solve equation -> send email
In this example, the Solve equation unit is a type of calculation unit. While the send email unit is action.
The point that I have 100 different units that can be combined together on a different order.
The Question
In order to solve this problem, I planning to create a data flow for my application. Each flow will implement this interface:
public interface IFlow
{
    public IUnit[] UnitsChain{get;}

    public void Start(string input);
}

While my unit will implement this interface:
public interface IUnit
{
    public string /*output*/ Process(string input);
}

Everything in this design sound doable, but also sounds like I "inventing the wheel" instead of using an existing solution that allow those option.
Looking to better solution to implement this kind of custom pipeline processing.
Thanks!

A: "Everything in this design sound doable, but also sounds like I "inventing the wheel" instead of using an existing solution that allow those option"
Microsoft's own DataFlow basically provides this functionality with very convenient options to parallelize steps etc.
Let's break it down:
Solve an equation
That sounds like a job for a TransformBlock.
You set it up to use a transformation method that will take an (let's call it) TInput type and produces TOutput (Result of Equation).
Send an Email
I'd break this up into two more Blocks:

*

*Transform TOutput to an Email

*Send Email

So you have one more Transformblock<TOutput , Email>and one ActionBlock<Email>
(I am using "Email" like a type here. It's just a placeholder. The exact type of course depends on Email Framework in use.)
Put it all together
You then build your pipeline by "linking" TransformBlock<TInput, TOutput> => TransformBlock<TOutput, Email> => ActionBlock<Email>.
Having done that, you have set up a complete Pipeline to wich you can submit TInputs and the framework will take care of the rest. Each block can be conveniently configured to for example process several TInput in parallel etc.
It also let's you decide if you want to use synchronous or asynchronous (Task/await) API.


text:
Q: Passing on a return value from one function to another in TypeScript I am new to TS so please be patient. I am trying to pass on the return value from one function into another. As a parameter and also call it from outside the function.
I have tried declaring the variable as public but that is no use as all the function inside the class unless defined otherwise are treated as public. Hence I am not sure where to go with this.
class generateXML{
    controlPrefix: string;
    constructor(name: string){
        this.controlPrefix = name;
        console.log('<Group>' + name + 'Control' + '</Group>')
    }

    controlCategoryName(uniqueName : string){
        let controlDisplayName: string = this.controlPrefix + ' ' + uniqueName;
        let controlName: string = controlDisplayName.replace(/\s/g, "");

        console.log(`<DisplayName>${controlDisplayName}</DisplayName>`);
        console.log(`<Name>${controlName}</Name>`);
        return uniqueName;
    }

    controlXMLPropertyGenerator(propertyName: string){
        let propertyXML: string = propertyName.toLowerCase();
        let propertyFriendlyName: string = propertyName;
        console.log(`<Prop ID="${propertyName}" friendlyname="${propertyFriendlyName}" category="${uniqueName}"`);
    }

    controlXMLPropertyGeneratorFriendlyName(uniqueName){

    }
}

let genXML = new generateXML('Control Name');
genXML.controlCategoryName('Control Category Name');
genXML.controlXMLPropertyGenerator('Control Property Name');

In the function controlXMLPropertyGenerator, I would like to log the value of "uniqueName" which is a parameter from the controlCategoryName function.
Also, I would like to pass "uniqueName" as parameter for controlXMLPropertyGeneratorFriendlyName function.


text:
Q: check why iPhone restarted Is there a way to check why iPhone restarted? My iPhone restarted once during the day, not being connected to power, so I believe that wasn't update. It happened just once today, so I'm curious what was a reason to restart.

A: I had the problem of my iPhone 6s randomly restarting. It might not be the same problem you're having, but it will give you something to check.
For me, the restarting problem occurred several times in the months leading up to the phone dying. Well, let me be more specific: about a month after experiencing the random restarting problem, I began to notice the phone wasn't holding a charge. So I called Apple support and they had me check Settings-->Battery-->Battery Health.
In that section it showed I had "Maximum Capacity 87%" but then below that in the "Peak Performance Capability" section it had a message indicating there had been a problem (I can't remember, but the message was something like performance monitoring had been turned off because the battery couldn't supply enough power).
After that I took the phone in to an Apple service center to get the battery replaced, but was told that it wasn't that easy: there was a problem with the power supply which meant a hefty repair. That's when I changed phones.
So, I'd check the above settings, keep an eye on your battery performance, and perhaps call Apple if things go downhill.


text:
Q: How to capture an Android Camera image without saving a file to the phone/sdcard? I would like to capture an image with the Android Camera but because the image may contain sensitive data I dont want the image saved to the phone or sd card.  Instead I would like a base64 string (compressed) which would be sent to the server immediately
In PhoneGap it seems files are saved to various places automatically.
Natively I was never able to get the image stream - in onJpegPictureTaken() the byte[] parameter was always null.
can anyone suggest a way?

A: See Camera.onPreviewFrame() and the YuvImage.compresstoJpeg() to be able to get a byte array you can convert into a bitmap.
Note that YuvImage.compressToJpeg() is only available in SDK 8 or later, I think. For earlier versions you'll need to implement your own YUV decoder. There are several examples around or, I could provide you an example.
Those two methods will allow you to get a camera picture in memory and never persist it to SD. Beware that bitmaps of most camera preview sizes will chew up memory pretty quickly and you'll need to be very careful to recycle the bitmaps and probably also have to scale them down a bit to do much with them and still fit inside the native heap restrictions on most devices.
Good luck!


text:
Q: is it possible to use a thread consumer / producer at same of time? I have a set of questions regard consumer/ producer problem..

*

*is it possible to make a thread consumer and producer at the same time ?

*what is the best block queue type for sending/receiving data between threads?

*is it possible to limit the transmission between threads to set of instances of threads ? and how ?
Thanks.
For question NO 1. I think BlockingDeque is the solution.
Here is some explanation:http://tutorials.jenkov.com/java-util-concurrent/blockingdeque.html

A: *

*Yes. Usually if a thread is both consumer and producer, it consumes different "products" than produces, but it also can consume its own product.

*Depends on the characteristics of the messages and transfer rate. But usually benefits are negligible.

*Yes - just pass the queue to the interested parties only.

A: To add to Alexei's answer:

*

*While it's possible, note that such thread will have to split it's CPU time between consuming and producing activities, so they can't be run concurrently. But it's perfectly viable, e.g., if your thread accepts some data (takes it from it's consumer-side queue), quickly transforms it somehow and offloads it to the next queue;

*While LinkedBlockingQueue minimizes blocking on producer's side, it's usage may lead to memory exhaustion if consumer works much slower than producer (e.g., consumer do some long-running calculations on producer's input). So, you may want ArrayBlockingQueue, which is bounded and, therefore, wouldn't lead to OutOfMemory error.


text:
Q: median in each subgroup I have a csv file having city name and price. Need to find the median of price for each group of city.
Input: from a csv file
London, 10
London, 25
London, 30
Brasov, 50
Brasov, 60

Expected:
London, 25
Brasov, 55

Solution using Pandas:
import pandas as pd

costs = []
with open("path","r") as f:
    for line in f:
        costs.append(line.split(","))

# with above , data looks like below. We can store in any format.
#costs = [["London",10] , ["London",25], ["London",30],
#         ["Brasov",50], ["Brasov",60]]

df = pd.DataFrame(costs,columns=["city","price"])

res = df.groupby("city")["price"].median()
print(res)

I have tried using Pandas above and works fine. Is there any other approach in Python without using Pandas? I'm trying to tweak below approach to get results per each city group, but could not find a way to fit to groups. Please advice.
mid = len(data) // 2

if len(data) % 2 != 0:  # if odd number
    return data[mid]
else:                   # if even number
    return (data[mid] + data [mid-1]) / 2

A: The following code should work:
path = 'your/path/to/file'
with open(path, 'r') as f:
    data = {}
    for line in f:
        split_line = line.split(",")
        # Check if city is a key already if not initialize it
        if split_line[0] not in data:
            data[split_line[0]] = []
        data[split_line[0]].append(split_line[1])

# Data wourld look like this
# {'city1': ['value1', 'value2', 'value3'], 'city2': ['value1', 'value2', 'value3']}
def median(values: list) -> float:
    values.sort()
    if len(values) % 2 == 0:
        return (values[len(values) // 2] + values[len(values) // 2 - 1]) / 2
    else:
        return values[len(values) // 2]

for city, values in data.items():
    print(city, median(values))

Hope it´s clear and helpful.


text:
Q: Elementary proof of this easy number-theoretic statement? We have the following very elementary statement:
Let $p$ be a prime number. Let $k \in \mathbb{Z}$ be an integer number and $d \in \mathbb{N}$ be a positive integer. Then there exists a positive integer $e \in \mathbb{N}$ and integers $n, m \in \mathbb{Z}$ with $0 \leq m < p^e$ and $0 \leq n < p^d$ such that
$$k = (p^d -1)m - p^e n.$$
The only proof I know of this is the following: consider the rational number $\alpha = \frac{k}{p^d-1}$. Because $\alpha \in \mathbb{Z}_{(p)}$ we can consider its $p$-adic expansion:
$$\alpha = \alpha_0 + p \alpha_1 + p^2 \alpha_2 + \cdots$$
Because $\alpha$ is rational with $(p^d -1) \alpha \in \mathbb{Z}$ this expansion is eventually repeating with period $d$ (see e.g. Konrad's notes here, where it is only proven that the expansion is eventually repeating, but I believe it follows from the proof that $d$ is an eventual period for the expansion).
We can thus "chop-off" the expansion to obtain $\alpha = m + p^e \gamma$ where $0 \leq m < p^e$ is an integer and $\gamma \in \mathbb{Z}_p$ has a (purely) periodic expansion with period $d$. But on Konrad's notes (or just by observing) we also see that the periodicity of the expansion of $\gamma$ implies that $(p^d - 1)\gamma \in \mathbb{Z}$ and $-1 \leq \gamma \leq 0$ so $\gamma = -n/(p^d -1)$ for some integer $n$ with $0 \leq n < p^d -1$. Multiplying the equality by $\alpha = m + p^e \gamma$  by $(p^d -1)$ we obtain the required result.
My question is: is there an elementary proof of this that does not use $p$-adic integers?
The natural first attempt is to use the coprimality of $(p^d -1)$ and $p^e$ to write $k$ as $k = (p^d -1)a - p^e b$ for some $a,b$. We would want to pick $e$ such that $-p^e \leq k \leq (p^e-1)(p^d-1)$ ($\ast$) since this would follow it we could find the desired expression. Then use the fact that we can replace $a$ by $a + p^e$ and $b$ with $b + (p^d -1)$ in the expression above. But I could not get this to work: in fact, for the example $p = 2, d = 3, k = -19$ one needs to pick $e \geq 5$ so the inequality ($\ast$) is not enough.

A: Let $k$ be a positive integer and let $e$ be such that $p^e>k$. The integers $p^d-1$ and $p^e$ are coprime, so there exist integers $a$ and $b$ such that
$$(p^d-1)a-p^eb=k.$$
Then for every integer $c$ we also have
$$(p^d-1)(a+p^ec)-p^e(b+(p^d-1)c)=k,\tag{1}$$
and there exists a unique integer $c_0$ such that $0\leq a+p^ec_0<p^e$. Define
$$m:=a+p^ec_0\qquad\text{ and }\qquad n:=b+(p^d-1)c_0,$$
so that $k=(p^d-1)m-p^en$ and $0\leq m<p^e$. Then it follows from $(1)$ that
$$n=b+(p^d-1)c_0=\frac{(p^d-1)(a+p^ec_0)-k}{p^e}<p^d-1-\frac{k}{p^e}<p^d,$$
and clearly $n\geq0$ as otherwise
$$k=(p^d-1)m-p^en\geq p^e>k,$$
a contradiction. The proof for negative $k$ is similar, and for $k=0$ we can take $m=n=0$.


text:
Q: How can I reloaded URL link, that it stay the same after I click on submit button I have simple form:

    <form action="" name="formular" id="formular" method="GET">
    From: <input name="actual_position" type="text" maxlength="512" id="actual_position" class="searchField"
                                        <?php if(!empty($actual_position)){  ?>
                                                  value="<?php echo $_GET['actual_position']?>"
                                                <?php
                                                }else {
                                                  ?> value = ""; <?php
                                                      }  ?>/>

    To: <input name="final_position" type="text" maxlength="512" id="final_position" class="searchField"     <?php if(!empty($final_position)){  ?>
                                                  value="<?php echo $_GET['final_position']?>"
                                                <?php
                                                }else {
                                                  ?> value = ""; <?php
                                                      }  ?>/>
<input type="submit" value="Find path" />

And another multiselect in form who gets values form url link and compere with database and get som results. Here is a code:

Waypoints:

<select style="float:center; margin-left:5px" multiple id="waypoints">

        if(!empty($urls)){
            foreach($urls as $url){
                if($result = $conn->query("SELECT * FROM $table where $ID = '$url' "));
                    $atraction = $result->fetch_array();  ?>
                        <option value="<?php echo  $atraction['lat']. "," . $atraction['lon']; ?>"
                        > <?php  echo  "".$atrction['City']. ", " . $atraction['Name'];?> </option>
    <?php
            }
        }
    ?>
                      </select>

</form>

And getting ID-s from url code:
if(!empty($_GET[$ID])){
$urls = $_GET[$ID];
  foreach($urls as $url){
 //  echo $url;
  }
}

... and after submit, it Post to URL some variables like this:
http://127.0.0.1/responsiveweb/travel.php?actual_position=Paris&final_position=Praha&ID[]=23&ID[]=15&ID[]=55
... very important for me are ID-s values ... but when I change for example actual position and then submit I lost my ID-s and I get something like this: http://127.0.0.1/responsiveweb/travel.php?actual_position=Berlin&final_position=Praha
Can you help me how to get after clicking on submit button full url link? Thanks

A: I had some trouble understanding your question OP, but I think I understood somehow what you ment, so I decided to try giving you a answer.
I have re-written your code, and tried to make somehow better code-structure. I have also used form method POST in my example, so you can see how you can change the get data on the redirection url.
See my code example here: http://pastebin.com/wQ7QCBmt
I also decided to use the form method POST instead of GET, so you can easily do back-end tasks, and extend your link if neccessary. You could also add more data to the link even when using GET. You could add an hidden input inside your form, example:
<input type="hidden" name="more_data" value="a_value" />


text:
Q: how to retrieve hierarchical data retrieved as a collection I have implemented the following hierarchical data using MySQL
1
 |----- 2
 |----- 3

4
 |----- 5
 |----- 6
        |----- 7

id     |    path     |    level   |    parent_id   |    content  |
-------------------------------------------------------------------
1             1             1           NULL            xxx
2            1:2            2           1               yyy
3            1:3            2           1               abc
4             4             1           NULL            zzz
5            4:5            2           4               yyy
6            4:6            2           4               abc
7            4:6:7          3           6               abc

Assuming I have only these records,
how do I retrieve them in a tree structure and yet within a single collection starting with the last tree?
What I expected from the query or stored procedure is to return me the following in exactly this order
id
-----

4
5
6
7
1
2
3

How do I do the same but starting with the first tree?
id
-----
1
2
3
4
5
6
7

A: try including order by desc
 ORDER by path desc,id asc

A: To cope with parents / children possibly something like this:-
SELECT PathTable.*, SUM(OrderVal) AS OrderCalc
FROM
(
    SELECT id,
            POW(100, MaxDepth-i-1) * SUBSTRING_INDEX(SUBSTRING_INDEX(path, ':', (i+1)), ':', -1) AS OrderVal
    FROM PathTable
    CROSS JOIN (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) Sub1
    CROSS JOIN (SELECT MAX(LENGTH(path) - LENGTH(REPLACE(path, ':', ''))) + 1 AS MaxDepth FROM PathTable) Sub2
    WHERE i <= (LENGTH(path) - LENGTH(REPLACE(path, ':', '')))
) Sub1
INNER JOIN PathTable
ON Sub1.id = PathTable.id
GROUP BY PathTable.id
ORDER BY OrderCalc

This is splitting up the path field and calculating an order value based on 100 to the power of the level of the bit of path, taking into account the max number of bits of path, times that bit of path (so 4:6:7 lands up as 7 + 6 * 100^1 + 4 * 100^2), then ordering by that.
100 chosen just as it is bigger than the largest single value in the path.


text:
Q: How can I programmatically add a websocket endpoint in embedded tomcat? I've been trying for weeks to get websockets working with embedded tomcat. I've tried emulating the examples in the tomcat unit tests to no avail. This is the first time I've tried to use websockets so I'm likely making a foolish mistake. Does anyone have any simple "Echo" examples for embedded tomcat websockets?
public void run() {

    if(!new File(consoleAppBase).isDirectory())
    {
         consoleAppBase = Paths.get("").toAbsolutePath().toString() + File.separatorChar + "wepapp";
    }

    tomcat = new Tomcat();

    tomcat.getService().removeConnector(tomcat.getConnector()); // remove default
    tomcat.getService().addConnector(createSslConnector(ConfigManager.getWeb_securePort())); // add secure option

    StandardServer server = (StandardServer) tomcat.getServer();
    AprLifecycleListener listener = new AprLifecycleListener();
    server.addLifecycleListener(listener);

    try {
        SecurityConstraint constraint = new SecurityConstraint();
        constraint.setDisplayName("SSL Redirect Constraint");
        constraint.setAuthConstraint(true);
        SecurityCollection collection = new SecurityCollection();
        collection.addPattern("/*");
        constraint.addAuthRole("administrator");
        constraint.addCollection(collection);

        //create the console webapp.
        consoleContext = tomcat.addWebapp(consoleContextPath, consoleAppBase);
        consoleContext.addConstraint(constraint);

        //this allows that little login popup for the console webapp.
        LoginConfig loginConfig = new LoginConfig();
        loginConfig.setAuthMethod("BASIC");
        consoleContext.setLoginConfig(loginConfig);
        consoleContext.addSecurityRole("administrator");

        //this creates a valid user.
        tomcat.addUser(ConfigManager.getWeb_username(), Encryptor.decrypt(ConfigManager.getWeb_passwordEncrypted()));
        tomcat.addRole("admin", "administrator");

    } catch (ServletException e) {
        LogMaster.getWebServerLogger().error("Error launching Web Application. Stopping Web Server.");
        LogMaster.getErrorLogger().error("Error launching Web Application. Stopping Web Server.", e);
        return;
    }

    addServlets(); // this is where I usually call a convenience method to add servlets

    // How can I add websocket endpoints instead?

}

A: For programmatic (non-annotated) endpoints, you have to provide a class that implements Endpoint to act as the server end, and then either:

*

*Deploy a class that implements ServerApplicationConfig in your WAR file, that supplies EndpointConfig information about some or all of the non-annotated Endpoint instances that were found in the WAR file, or

*Call ServerContainer.addEndpoint() during the deployment phase of your webapp.

See the Java™ API for WebSocket, JSR 356.

A: As far as I know, configuring a websocket is the same as configuring a servlet (or a servlet filter). In web.xml you must include <async-supported>true</async-supported>.
I assume there's a similar flag in the java config.

A: I was using WebSocket in such way:
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
//...

@ServerEndpoint("/move")
public class TestWebSocketEndPoint {//@OnMessage
public void onMessage(Session session, String message) {}
private static final Queue<Session> QUEUE = new ConcurrentLinkedQueue<Session>();

@OnOpen
public void open(Session session) {
    QUEUE.add(session);
}

@OnError
public void error(Session session, Throwable t) {
    StaticLogger.log(TestWebSocketEndPoint.class, t);
    QUEUE.remove(session);
}

@OnClose
public void closedConnection(Session session) {
    QUEUE.remove(session);
}

public static void sendToAll(String message) throws IOException {
    ArrayList<Session> closedSessions = new ArrayList<Session>();
    for (Session session : QUEUE) {
        if (!session.isOpen()) {
            closedSessions.add(session);
        } else {
            session.getBasicRemote().sendText(message);
        }
    }
    QUEUE.removeAll(closedSessions);
}
}

And JS call:
var webSocket;
webSocket = new WebSocket("ws://localhost:8585/test/move");
webSocket.onmessage = function () {
    alert('test');
}

Java call:
  TestWebSocketEndPoint.sendToAll(result);


text:
Q: receive data from php:mysql to android using json I am developing an Android app which sends and receive simple fname,Lname from my database. I am Using php and mysql for webservice. I am using this tutorial
In JSONParser class which is as following
public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "talha");
        }
        Log.i("Buffer Error", "Baby Baby! Yes Mama! ");

        is.close();
        json = sb.toString();
        Log.i("Buffer Error", "Eating suger! NO Mama! "+ json);

    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("MyJSON", "Error parsing data "+ e.toString());
    }

    // return JSON String
    return jObj;

}
}

When i am trying to parse string to json object
try {
     jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("MyJSON", "Error parsing data "+ e.toString());
    }

I am getting exception JSONArray cannot be converted to JSONObject. Please help since in every other tutorial, similar procedure is described.

A: Yes, you will get that problem if you will directly create that.Add one line after json = b.toString();
json = sb.toString();
json = "{json_parse" + "[" + json + "]" + "}";


text:
Q: How to combine only specific items in a data frame in the python I want make dataframe like this
Hi I have data frame like the image above.
and I want to create a new dataframe that depends on a specific number (iter_no)
Which code can I create a new dataframe like above?
Thank you. (For reference, there are dozens of items in my_list each) \
can use dataframe easily


text:
Q: IdentityServer3 integration with Ping Identity. Is it possible? We are currently using IdentityServer3 for authentication and authorization with our asp.net MVC(angular.js) and webapi clients.  We are about to bring on a new customer that uses PingIdentity for their Single Sign On(SSO).  The customer would like to be able to integrate their SSO into our application.
Is this possible with IdentityServer3?
Thanks in advance!

A: You should be able to leverage the WS-Federation capabilities that both products have to integrate them. IdentityServer3 playing the Service Provider (or: RP) role, the customer playing the Identity Provider (or: IP) role.

A: Have you looked into KentorIT Authservices?  It's a SAML plugin for IdentityServer3.  I was able to add OneLogin SAML authentication with this plugin.
-Scott


text:
Q: MongoException no documents given I am using MongoDB in my symfony project. For communication to the database, i am using either Document Manager and MongoClient.
What i intend to do is to batch insert an array directly into the database. I've made attempt of creating array and fill it. However when i execute batchInsert(), i get this exception
[MongoException]
 no documents given

Very confusing because according to the manual, the exception thrown if the inserted array is empty. I've made sure and just tried many times that the array i was inserting is not empty. This is my piece of code:
$dm = $this->getContainer()->get('doctrine_mongodb');

            echo "initiating... \n";

        $data = $dm->getRepository("KahviDocumentBundle:Suppliers")->findAll();

        $children = array();

        echo "fetched\n";

        echo "\n".count($data)."\n";

        $items = array();
        foreach ($data as $row) {
            foreach ($row->getValue()->getConsigneeName() as $consignee) {

                    $items[] = array(
                        'id' => Util\Util::slugify($consignee),
                        'name' => $consignee,
                        'data' => array(
                            'band' => $row->getValue()->getShipperName(),
                            'relation' => 'Buyer of band'
                        )
                    );

            }
            // echo $row->getValue()->getShipperName()."\n";
        }
        echo "items collected\n".count($items)."\n";

        foreach ($items as &$item) {
            $parent = $item['data'];
            $children[Util\Util::slugify($parent['band'])][] = &$item;
        }

        unset($item);

        foreach ($items as &$item) {
            if (isset($children[$item['id']])) {
                $item['children'] = $children[$item['id']];
            }

        }
        unset($item);

        // die();
        echo "start deleting\n";
        $mongo = new \MongoClient('mongodb://192.168.125.17:27017');

        $db = $mongo->selectDB('dbname');
        // print_r($db);
        $collection = $db->the_collection;
        // print_r($collection);
        $response = $collection->drop();

        echo "finished\n";
        print_r($response);
        // die();

        echo "starting recording\n";

        $newCollection = $db->createCollection(
            "the_collection",
            array(
                'capped' => true,
                'size' => 1024*1024,
                'max' => 10
            )
        );

        echo "children count ".count($children)."\n";

        $trees = array();
        foreach ($children as $key => $child) {

            $test = array(
                'id' => $key,
                'name' => $key,
                'children' => is_array($child) ? $child : array()
            );
            $serialized = serialize($test);
            $trees[] = $serialized;
            // echo $serialized."\n";
        }
        // die();
        var_dump($trees);
        $newCollection->batchInsert($trees);

        // $dm->getManager()->flush();

        echo "finished\n";

A: You have inserted an array of string, while the expected type is array of an array which the inside array is a set of column (field)
And also, you dont' need to recreate the same collection you have dropped it.
So it should be like this.
$db = $mongo->selectDB('dbname');
        $collection = $db->the_collection;
        $collection->drop();

$trees = array();
            foreach ($children as $key => $child) {
            $test = array(
                'id' => $key,
                'name' => $key,
                'children' => is_array($child) ? $child : array()
            );
            // echo print_r($test);
            // echo "\n";
            $serialized = serialize($test);
            $trees[] = array('column1' => $serialized, 'column2'=> $key);
        }

        $collection->batchInsert($trees);


text:
Q: how can store executed statement (not fetched from a table) in a variable or table Dear Friends I want to store executed statement's value into a variable or table but right now  I am stuck and not able to get the solution, hoping I will get solution here.
my stored procedure:
DELIMITER $$

USE `test`$$

DROP PROCEDURE IF EXISTS `sp_grants`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_grants`(_user VARCHAR(50))
BEGIN
        DECLARE done INT(1) DEFAULT 0;
        DECLARE _grant TEXT DEFAULT '';

        DECLARE cur1 CURSOR FOR SELECT CONCAT('\'', USER ,'\'@\'', HOST,'\'') FROM mysql.user WHERE USER=_user;

        DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;
-- open cursor1
OPEN cur1;
BEGIN
REPEAT
FETCH cur1 INTO _grant;

IF _grant='' THEN
    SET done = 1;
END IF;

            IF (done<>1) THEN
    SET @str1=CONCAT('show grants for ',_grant);
                 PREPARE stmt1 FROM @str1;
                 EXECUTE stmt1;
                 DEALLOCATE PREPARE stmt1;

            END IF;

UNTIL done
END REPEAT;
END;
     CLOSE cur1;
-- close cursor1

     SELECT 'done';

END$$

DELIMITER ;

Getting below results
CALL sp_grants('zafar');
GRANT USAGE ON *.* TO 'zafar'@'%' IDENTIFIED BY PASSWORD '*20F283F208C26099783173695D6F7BBF24E2346B';
GRANT ALL PRIVILEGES ON `test`.* TO 'zafar'@'%'

I want to store above 2 rows in a variable or table.
Please help me, i will be very thankful.
Note: I know if i was preparing statements from any table data then i can store these statements col1 into @var1 but how can I do here.


text:
Q: Why are the the elements of the stress-energy tensor not all symmetrical, and the units are not all the same? PI know questions related to the stress-energy-momentum tensor's units have been asked many times before, but I have a question about the elements of this tensor not all having the same units, nor the elements all being symmetrical.
It is said that the stress-energy-momentum tensor's units are "energy density" or "momentum flux density" :
Energy = $kg~m^2/s^2$ --> density $= /m^3$ --> energy density : $kg /m~s^2$
Momentum = $kg~m/s$ --> flux = $/ (s~m^2)$ --> momentum flux (technically not "density") : $kg/m~s^2$
So far, so good, the units agree.
The definition of $T_{\mu\nu}$ is "the rate of flow of the $\mu$ component of four-momentum across a surface [of unit area] of constant $\nu$."  Since the four-momentum's terms are ($E/c$, $p_x$, $p_y$, $p_z$), by this definition, this creates the following matrix :

Which can be reduced to a shorthand units notation of (note : $mc = E/c$ = momentum) :

And doing a units analysis on this results in :

The 3 right columns all have the correct units, because of the $\Delta$t in their denominator in the second matrix.  But the left column's denominators are all spatial, so the units are not an energy density or momentum flux.
So my questions are :
Are the left column's units actually different than all the other column's units, or have I missed something?
Also, why is the tensor claimed to be symmetrical, when the left column's units are different than the top row's units? Even if I have the left column wrong, the shear forces (see table below) are also not symmetrical.
P.S. – since pressure's units are : $kg/m~s^2$ and shear force's units are : $kg~m/s^2~m^2 = kg / m~s^2$, the first matrix can be re-written (using the dimensions of the second matrix as a guide) as :

Which is the best description I've seen for this tensor.

A: The weird dimensions in your tensor seem to come from working with the coordinate $\lbrace t,x,y,z\rbrace$, which have different dimensions. Usually one works with $\lbrace ct,x,y,z\rbrace$, in which all of the components have the same dimensions. (Remark: the original version of this answer claimed all components of a tensor should have the same dimension but, as mike stone pointed out in the comments, this only holds if the coordinates all have the same dimension).
Hence, from your matrix, the problem seems to be simply that you're writing $\Delta t$ when you really should be writing $c \Delta t$.
I find it somewhat complicated to define the stress-energy tensor in terms of its interpretation. It is cleaner to define it mathematically (for example, using the expressions on Wikipedia) and interpret it later. This will clear the difficulties with the manipulation of $c$'s and make it clear which entries in your tensor should be divided or multiplied by $c$.


text:
Q: Query to get names of databases, count of tables, count of indexes, size of the database and owner of database Is there a query to get names of databases, count of tables, count of indexes, size of the DB and owner of DB on MSSQL? I looked at many solutions but could not find any, where I could get the count of indexes on the DB as well.

A: Tables in database
    sp_MSForEachTable 'DECLARE @t AS VARCHAR(MAX);
    SELECT @t = CAST(COUNT(1) as VARCHAR(MAX))
    + CHAR(9) + CHAR(9) + ''?'' FROM ? ; PRINT @t'

A: Yes.  You can do all of these things from SQL like so:
Get the database name:
select DB_NAME()

Get the number of tables:
select count(*) from sys.tables

Get the number of indexes:
select count(*) from sys.indexes

Get the amount of space used:
exec sp_spaceused

Get the user name of the database owner:
select distinct suser_sname( owner_sid ) from sys.databases

A: I'd tend to use Powershell for something like this. Here's my swing at it:
push-location;
import-module sqlps -disablenamechecking;
pop-location;

$s = new-object microsoft.sqlserver.management.smo.server 'yourServer';

foreach ($db in $s.Databases | where {$_.IsAccessible -eq $true} ) {
    $r = @{TableCount = 0;
        IndexCount = 0;
        Name = $db.Name;
        Size = $db.Size
    }
    $table_count = 0;
    $index_count = 0;
    foreach ($table in $db.Tables) {
        $r.TableCount += 1;
        $r.IndexCount += $table.Indexes.Count
    }
    $r | select-object @{name='name';expression={$_.name}},
        @{name='size';expression={$_.size}},
        @{name='TableCount';expression={$_.TableCount}},
        @{name='IndexCount';expression={$_.IndexCount}};
}