text:
Q: Implement simple Photo Gallery like iPhone's 'Photos' with UIScrollView and UIImageView I have an UIScrollView which populated with UIImageView. I'd like to have each UIImageView to be able to zoom & pan, and flick to the next page, just like iPhone's Photos app. I have searched around and what I have so far is this:
NSArray *pages = [self loadImages];

_pageScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
NSUInteger pageCount = [pages count]; // Adjustable
for (int i = 0; i < pageCount; i++) {

    CGFloat x = i * self.view.frame.size.width;

    // Page Settings
    UIImageView *pageView = [[UIImageView alloc] initWithFrame:CGRectMake(x, 0, self.view.frame.size.width, self.view.frame.size.height)];

    pageView.backgroundColor = [UIColor greenColor];
    pageView.image = [pages objectAtIndex:i];
    pageView.userInteractionEnabled = YES;
    pageView.tag = i;

    UIScrollView *pageScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    pageScroll.maximumZoomScale = 2.0f;
    pageScroll.minimumZoomScale = 1.0f;
    pageScroll.zoomScale = 1.0f;
    pageScroll.bouncesZoom = YES;
    pageScroll.contentSize = CGSizeMake(pageView.frame.size.width, pageView.frame.size.height);
    pageScroll.pagingEnabled = NO;
    pageScroll.delegate = self;
    [pageScroll addSubview:pageView];

    // Gesture Reocgnisers
    UIPinchGestureRecognizer *pinchGr = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchImage:)];
    pinchGr.delegate = self;
    [pageView addGestureRecognizer:pinchGr];

    UIPanGestureRecognizer *panGr = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panImage:)];
    [pageView addGestureRecognizer:panGr];

    [_pageScrollView addSubview:pageView];

}
_pageScrollView.contentSize = CGSizeMake(self.view.frame.size.width * pageCount, self.view.frame.size.height);

_pageScrollView.pagingEnabled = YES;

_pageScrollView.delegate = self;

[self.view addSubview:_pageScrollView];

They just work fine for just paging (horizontal scrolling). However, I'm stack at how to implement UIGestures for each UIImageView. And with the help from various good questions & answers here in stackoverflow, I have implemented Zoom & Pan like this:
- (void) pinchImage:(UIPinchGestureRecognizer*)pgr {

  [self adjustAnchorPointForGestureRecognizer:pgr];

  if ([pgr state] == UIGestureRecognizerStateBegan || [pgr state] == UIGestureRecognizerStateChanged) {

    CGFloat currentScale = pgr.view.frame.size.width / pgr.view.bounds.size.width;
    CGFloat newScale = currentScale * pgr.scale;

    if (newScale < 1.01f) {
        newScale = 1.01f;
    }
    if (newScale > 3.0f) {
        newScale = 3.0f;
    }

    CGAffineTransform transform = CGAffineTransformMakeScale(newScale, newScale);
    pgr.view.transform = transform;
    pgr.scale = 1;
  }
}

- (void) panImage:(UIPanGestureRecognizer*)panGr {

  if ([panGr state] == UIGestureRecognizerStateBegan || [panGr state] == UIGestureRecognizerStateChanged) {

    CGPoint p = [panGr translationInView:self.view];
    NSLog(@"[PAMPHLET PAGE]: Point: %@", NSStringFromCGPoint(p));
    CGPoint movedPoint = CGPointMake(panGr.view.center.x + p.x, panGr.view.center.y + p.y);

    if (panGr.view.frame.size.width > panGr.view.center.x + p.x &&
        panGr.view.frame.size.height > panGr.view.center.y + p.y) {
        panGr.view.center = movedPoint;
        NSLog(@"Current: %f / %f", panGr.view.center.x, panGr.view.center.y);
    }

    [panGr setTranslation:CGPointZero inView:self.view];
  }
}

This works almost there, but has several problems. Both Zoom & Pan is not limited to the scale of UIImageView, and when zoomed out or pan out to the outside of bounds, the image exceeds to the next view and everything gone wrong. I'm still figuring out this but don't know where should I start this.
How can I 'limit' those gesture's effective area, or should I try another method? Is this even the right approach to achieve this? I just wanted to make simple photo gallery like Photos app...
Please, any help would be appreciated.
Thank you.

A: If you use MWPhotoBrowser from here, it will take care of downloading remote images too in addition to functionalities you are expecting.


text:
Q: c# make UI calls when TCPClient receives data async I have a Forms app and a Console server app connected with TCPClient. The Forms app opens up a dialog for user authentication, when user clicks the Login button, a request is sent to the server. The server then responds if the login credentials were valid or not. The Forms app receives the response asynchronously and gives out an error message or closes the authentication window and continues.
After reading this post about SynchronizationContext I have created a working solution which calls functions on the UI thread from the thread that handles the server response. My question is, is there a better way to do this in C#?
I read quite a bit on async/await but haven't found a way to await for a particular server response. The Client handles the responses using stream.BeginRead() from a buffer.
Capturing UI Context:
public static SynchronizationContext uiContext;

public MainForm(string[] args)
{
    InitializeComponent();
}

private void MainForm_Load(object sender, EventArgs e)
{
    uiContext = SynchronizationContext.Current;
    //etc
}

Calling functions on the LoginForm when Client receives particular server response for authentication through stream.BeginRead():
private void UserAuthenticationAnswerReceived(byte[] _data)
{
    SynchronizationContext uiContext = MainForm.uiContext;
    //if auth was unsuccessful, the data will be only 1 int in length
    if (_data.Length <= sizeof(int))
    {
        Debug.WriteLine("Authentication failed.");
        uiContext.Post(UserLogin.userLoginFrm.AuthUnsuccessfulAsync, null);
    }
    else
    {
        Debug.WriteLine("Authentication successful.");
        uiContext.Post(UserLogin.userLoginFrm.AuthSuccessfulAsync, user);
    }
}

I am quite new to networking and may be missing a more fundamental concept about client/server model and how to manage responses asynchronously.

A:
My question is, is there a better way to do this in C#?

Generally, it's easier to use Task-based APIs such as ReadAsync instead of old-style IAsyncResult-based APIs such as BeginRead.
But for the general solution of notifying the UI from a background thread, the best solution is to capture the SynchronizationContext.
However, if you have a command/response protocol, with the client only receiving responses for commands it has sent, then you can get a much simpler solution using async/await.

I am quite new to networking and may be missing a more fundamental concept about client/server model and how to manage responses asynchronously.

The first thing I'd recommend is to self-host an ASP.NET Core WebApi. Then you can use an off-the-shelf HttpClient to handle the commands and responses. Custom network protocols are extremely complex to get right, and they're even more complex if you're not familiar with asynchronous code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to specify the type signature to find a specific method with InteractiveUtils.edit in Julia? In order to quickly find the implementation of some methods I would like to use InteractiveUtils.edit.
E.g. if I wanted to see the implementation of methodswith I should be able to write something like edit(methodswith). However, as the methodswith function has multiple methods I get:
ERROR: function has multiple methods; please specify a type signature

How do I specify the type signature? I know that I can find out which methods there are with methods(methodswith), giving signatures like this:
[1] methodswith(t::Type; supertypes) in InteractiveUtils at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.0/InteractiveUtils/src/InteractiveUtils.jl:169

How can I plug this into a call of edit?
I know that there is @edit which I could use with some exemplary function call. However, sometimes it would be more straightforward to just specify the types, because constructing the objects for an exemplary call of the method also involves some investigation for valid constructors.
TL;DR:
How to find a specific method of a function with InteractiveUtils.edit in Julia?

A: Just pass argument types as a tuple in the second positional argument to edit.
For example edit(sin, (Int,)) will open you the definition of sin that is used with one argument of type Int.
Note that this might fail if you want to edit a function from stdlib (for functions from Base or non-standard libraries edit will work properly).
In such a case you have to use methods function and locate the file manually. For example:
julia> using Statistics

julia> edit(mean, (Vector{Int},)) # this might not work as expected

julia> methods(mean, (Vector{Int},))
# 1 method for generic function "mean":
[1] mean(A::AbstractArray; dims) in Statistics at C:\cygwin\home\Administrator\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.1\Statistics\src\Statistics.jl:132

Now you have a file name and a line number where the method is located, but the path may be wrong, so you have to find the file yourself in the Julia installation folder.
Here is how you can retrieve this information programatically (assuming you have specified the args correctly and only one method matches). First define a function:
function edit_stdlib(fun, args)
    m = methods(fun, args)
    @assert length(m.ms) == 1 # assume we have an exact match
    p = joinpath(Sys.STDLIB, splitpath(string(m.ms[1].file))[end-2:end]...)
    l = m.ms[1].line
    edit(p, l)
end

and now you can write e.g. edit_stdlib(mean, (Vector{Int},)) to get what you want.


text:
Q: Java reflection to compare 2 objects for each variable class I have a class that has some member variables one or more being another class also with member variables.
I can get the variables by calling: getDeclaredFields(); And the values of the Foo Object by calling field.get(obj) then iterating of them again to get the sub class variables.
My actual goal is to compare 2 Foo objects to know if there have the same values or not. My actual problem is to access to variable of the 2nd object
Thanks in advance
First Object:
public class Foo {
    public Foo(){}
    private Integer someInt = 123;
    private Long someLong = 987654321L;
    private String someString = "qwertyuiop";
    private Bar bar = new Bar();
}

Second Object:
public class Bar {
    public Bar(){}
    private Double someDouble = 123.456;
    private String innerString = "another String";
}

main method and getting variables and values:
public class MyTest {
    public static void main(String[] args) throws Exception {
        Foo foo = new Foo();
        Foo foo2 = new Foo();
        getMemberFields(foo, foo2);
    }

    private static boolean getMemberFields(Object obj1, Object obj2) throws IllegalAccessException, NoSuchFieldException {

        Class<?> objClass1 = obj1.getClass();
        Class<?> objClass2 = obj2.getClass();

        Field[] fields1 = objClass1.getDeclaredFields();
        Field[] fields2 = objClass2.getDeclaredFields();

        int id = 0;

        for(Field field1 : fields1)
        {
            field1.setAccessible(true);
            fields2[id].setAccessible(true);

            if (!field1.getType().isPrimitive() && !field1.getType().getName().contains("java.lang")) // if not int String char Long short...
            {
                getMemberFields(field1.get(obj1), fields2[id].get(obj2));
            } else {
                System.out.println("id : " + id);
                System.out.println("Field: " + field1.getName() + " value: " + field1.get(obj1));
                System.out.println("Field: " + fields2[id].getName()+ " value: " + fields2[id].get(obj2));

                if (field1.get(obj1) != fields2[id].get(obj2)) return false; // if different return false
            }
            id+=1;
        }
        return true;
    }
}

Actually i have this bad result :
id : 0 Field: someInt value: 123

Exception in thread "main" java.lang.IllegalAccessException: class xxx.open.api.test.myTest.MyTest cannot access a member of class xxx.open.api.test.myTest.Foo with modifiers "private"
at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:361)
at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:591)
at java.base/java.lang.reflect.Field.checkAccess(Field.java:1075)
at java.base/java.lang.reflect.Field.get(Field.java:416)
at xxx.open.api.test.myTest.MyTest.getMemberFields(MyTest.java:31)
at xxx.open.api.test.myTest.MyTest.main(MyTest.java:9)

A: I can not reproduce your result with the current version of your question. Since you edited the code in a way that the problem disappeared, I have to emphasize that this is not the way, Stackoverflow works. Your question about a specific problem is supposed to contain the code necessary to reproduce the problem. The Answers section is dedicated to contain solutions.
Besides the original problem of not calling setAccessible on the second Field instance, it's not clear why you are using a second Field object in the first place.
There are two possible scenarios.

*

*You assume both objects to have the same type. Then, there is no reason to operate with two arrays of Field objects. You can just use one array to access both objects.

*You assume that the objects may have different types. Then it is entirely unreasonable to assume that the two arrays of Field objects of different classes correspond in any way.
In fact, the documentation of getDeclaredFields() specifies

The elements in the returned array are not sorted and are not in any particular order.

and does not even state that calling getDeclaredFields() twice on the same Class object will return fields in the same order.
You should use your approach only for objects of the same type and just use one array of fields. When descending to objects contained in fields, use equals where appropriate, as certain types (e.g. collections) have equality rules for objects of different implementation classes.
For example
static boolean equalByMemberFields(Object obj1, Object obj2)
                                                throws ReflectiveOperationException {

    if(obj1 == obj2) return true;
    else if(obj1 == null || obj2 == null) return false;

    Class<?> objClass1 = obj1.getClass();
    if(obj2.getClass() != objClass1) return false;

    Field[] fields = objClass1.getDeclaredFields();
    AccessibleObject.setAccessible(fields, true); // on all at once

    for(Field field : fields) {
        Object value1 = field.get(obj1), value2 = field.get(obj2);
        if(shouldDescend(field.getType())) {
            if( ! equalByMemberFields(value1, value2)) return false;
        } else {
            System.out.println("Field: " + field.getName()
                + ", value1: " + value1 + ", value2: " + value2);

            if(!Objects.equals(value1, value2)) return false;
        }
    }
    return true;
}

private static boolean shouldDescend(Class<?> type) throws NoSuchMethodException {

    if(type.isPrimitive() || type.isEnum()) return false;

    if(type.getClassLoader() == null) return false; // don't peek into core classes

    if(type.getMethod("equals", Object.class).getDeclaringClass() != Object.class)
        return false; // has overridden equals method

    return true;
}


text:
Q: How to preserve view memory when dismissing dialog? In my android app activity, I create a global variable for a LinearLayout. Then I create a dialog box and add the LinearLayout to this dialog box. Then when I dismiss the dialog box, I believe what happens is that the LinearLayout variable gets deleted, as in its value becomes null or something.
What I want is that the LinearLayout data not get deleted when the dialog box gets dismissed. This is because if I want to open the dialog box window again, I would be adding the LinearLayout view again, and I do this so that it would remember the states of the views inside that LinearLayout, such as radio groups and checkboxes.
Is this possible to do?
Thanks.

A: If you safe the reference to the LinearLayout in some variable and don't set it to null yourself, it won't be null after dismissing the dialog.
However, I think you can not attach a View to a parent twice.
The best way to persist state is:

*

*As config changes and other things will pause your app, store the state some where else, persist it across activity restarts with onSaveInstanceState() and onCreate(). There is a Bundle passed to both methods, where you can save your state.

*Restore your state when creating the new layout.

*Optional: Save a reference to the dialog.


text:
Q: How to display selected features in a map to exporte as PDF I've already managed to select feature by ID in a layer and zoom to it using pyqgis. The canvas considered this changes but the map that I exported as PDF do not consider this changes, any idea to solve this problem. This is my code:
xpr = QgsExpression("\"ID_PARCELL\"=1440")
it = vlayer.getFeatures(QgsFeatureRequest(expr))
ids = [i.id() for i in it]
vlayer.setSelectedFeatures(ids)
box = vlayer.boundingBoxOfSelected()
iface.mapCanvas().setExtent(box)
canvas = qgis.utils.iface.mapCanvas() ###
canvas.zoomToSelected(vlayer)
iface.mapCanvas().refresh()


text:
Q: Push Notification not getting sound when app closed or minimized I am using fcm for getting push notifications in my android app. I am getting notifications well when app is opened and closed or minimised state also.But the problem is I am not getting notification sound when app in minimised or closed state.
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

@Override
public void onTokenRefresh() {
   String refrehedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d("refreshedtoken",refrehedToken+"");
    PrefUtils.saveToPrefs(getApplicationContext(),PrefUtils.DEVICETOKEN,refrehedToken);
    sendRegistrationToServer(refrehedToken);

}

private void sendRegistrationToServer(String refrehedToken) {

}

}

///////////////////////////////////////////////////////////////////
public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    if(remoteMessage.getData().size()>0){
        Log.d(TAG,"From:"+remoteMessage.getData()+"");
        Gson gson = new Gson();
        String json = gson.toJson(remoteMessage.getData());
        Log.d("jsonresponce",json+",,,");
        try {
            JSONObject object = new JSONObject(json);
            String title   = object.getString("title");
            String message = object.getString("message");
            Log.d("firebasenotification",title+",,"+message);
            sendNotificatin(title,message);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }else if(remoteMessage.getNotification()!=null){
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getTitle());
        sendNotificatin(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());

    }
}

private void sendNotificatin(String title, String message) {
    Intent intent = new Intent(this,SplashScreen.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent, PendingIntent.FLAG_ONE_SHOT);
    Uri defaultsoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.app_ic)
            .setContentTitle(title)
            .setContentText(message)
            .setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_SOUND)
            .setContentIntent(pendingIntent);
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Random random = new Random();
    int num = random.nextInt(99999-1000)+1000;
    notificationManager.notify(num,notificationBuilder.build());

}
}

////////////////////////////////////////////////////////
   <service android:name=".Fcm.MyFirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>
    <service
        android:name=".Fcm.MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@mipmap/app_ic" />

A: I haven't enough reputation to add a comment so, I am doing this for you, but I know this is inappropriate.
The reason is when app minimized, or in the background, the notification delivered to Android notification delivered to Android notification tray. There are two payloads one is "data payload" and another one is "notification payload." Just remove "notification payload" then it will work fine.

A: I have edited my code, you forgot to add .setSound. I have also added in some other stuff that you may want in the future.
private void sendNotificatin(String title, String message) {

private void sendNotificatin(String title, String message) {
    Intent intent = new Intent(this,SplashScreen.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent, PendingIntent.FLAG_ONE_SHOT);
     Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.app_ic)
            .setContentTitle(title)
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(sound) // changed from SET_DEFAULTS
            .setContentIntent(pendingIntent);
            /* Begin other added stuff */
            .setLights(0xffff0000, 500, 250);
            .setWhen(System.currentTimeMillis())
            /* End other added stuff */
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Random random = new Random();
    int num = random.nextInt(99999-1000)+1000;
    notificationManager.notify(num,notificationBuilder.build());

    }


text:
Q: JNA: java.lang.Error: Invalid memory access I'm using JNA to access some dll function from Java, this dll Native Function is declared as the following:
// it returns (long)
H264_Login (char *sIP, unsigned short wPort, char *sUserName, char *sPassword, LP_DEVICEINFO lpDeviceInfo, int *error); // where LP_DEVICEINFO is a struct

and so, I declared it inside library interface as the following:
long H264_Login(String sIP, short wPort, String sUserName, String sPassword,
                    Structure DeviceDate, int error);

and then I call it the following way:
simpleDLL INSTANCE = (simpleDLL) Native.loadLibrary(
                ("NetSdk"), simpleDLL.class);
DeviceDate dev = new DeviceDate() // where DeviceDate is a static class inherits com.sun.jna.Structure
int err = (int) INSTANCE.H264_GetLastError();
long result = INSTANCE.H264_DVR_Login("255.255.255.255", (short) 33333, "admin", "admin", dev, err);

but I'm getting the following Exception:
Exception in thread "main" java.lang.Error: Invalid memory access
    at com.sun.jna.Native.invokeLong(Native Method)
    at com.sun.jna.Function.invoke(Function.java:386)
    at com.sun.jna.Function.invoke(Function.java:315)
    at com.sun.jna.Library$Handler.invoke(Library.java:212)
    at com.sun.proxy.$Proxy0.H264_DVR_Login(Unknown Source)
    at Test.main(Test.java:47)

It's strange since there is no long variables inside the method parameters, only the returning type is long which I think it has nothing to do with that Exception. Also I tried some of other methods
which return long and it works perfectly.

A: Your return type needs to be NativeLong.
Your final argument needs to be either IntByReference or int[1].
Unless DeviceDate is compatible with LP_DEVICEINFO, you need to make sure those structure types match.
EDIT
What are the native definitions of DeviceDate and LP_DEVICEINFO?
If LP_DEVICEINFO is just a generic pointer where you can substitute a device-specific structure, then this should be fine, for example:
typedef void *LP_DEVICEINFO;
typedef struct _DeviceData { /* anything you want in here */ } DeviceData, *pDeviceData;

But if it's got any specific definition, the contents of that structure must be compatible with DeviceDate, for example:
typedef struct _LP_DEVICEINFO {
    int type;
    // Fill in with device-specific information
} DEVICEINFO, *LP_DEVICEINFO;

typedef struct _DeviceDate {
    int type; // Example "common" field
    int timestamp; // device-specific information
} DeviceDate;


text:
Q: Unable to drop a column that I used to explode an array To preface, I am using pyspark==2.4.5.
When reading from a json file, which can be found here: https://filebin.net/53rhhigep2zpqdga, I need to explode the data, I also have no need for data after exploding and I have no need of statistics as well.
spark= SparkSession.builder.master('local[2]').appName("createDataframe")\
        .getOrCreate()
json_data = spark.read.option('multiline', True).json(file_name)
json_data = json_data.withColumn("data_values", F.explode_outer("data"))\
        .drop("data", "statistics")

Below you will see the schema and the top 5 rows of json_data
root
 |-- data_values: struct (nullable = true)
 |    |-- date: string (nullable = true)
 |    |-- events: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- active: long (nullable = true)
 |    |    |    |-- index: long (nullable = true)
 |    |    |    |-- mode: long (nullable = true)
 |    |    |    |-- rate: long (nullable = true)
 |    |    |    |-- timestamp: string (nullable = true)

+----------------------------------------------------------------------------------------------------------------------------------------------------------+
|data_values                                                                                |
+----------------------------------------------------------------------------------------------------------------------------------------------------------+
|[2019-02-20, [[0, 0, 1, 0, 2019-02-20T00:00:00], [0, 1, 1, 0, 2019-02-20T00:01:00], [0, 2, 1, 0, 2019-02-20T00:02:00]]]                                   |
|[2019-02-21, [[1, 0, 1, 0, 2019-02-21T00:03:00], [0, 1, 1, 0, 2019-02-21T00:04:00], [1, 2, 1, 1, 2019-02-21T00:05:00], [1, 3, 1, 1, 2019-02-21T00:06:00]]]|
|[2019-02-22, [[1, 0, 1, 0, 2019-02-22T00:03:00], [0, 1, 1, 0, 2019-02-22T00:04:00], [1, 2, 1, 1, 2019-02-22T00:05:00], [1, 3, 1, 1, 2019-02-22T00:06:00]]]|
|[2019-02-23, [[1, 3, 1, 1, 2019-02-23T00:16:00]]]                                                                                |
|[2019-02-24, [[1, 0, 1, 1, 2019-02-24T00:03:00], [1, 1, 1, 0, 2019-02-24T00:04:00]]]                                                                      |
+----------------------------------------------------------------------------------------------------------------------------------------------------------+

Now to get the data as I desire, I perform the queries below.
newData = json_data\
   .withColumn("events", F.explode(json_data.data_values.events))\
   .withColumn("date", json_data.data_values.date)
newData.printSchema()
newData.show(3)
finalData = newData.drop("data_values")
finalData.show(6)

Above you see that I am creating a column called data_values that explodes my incoming json data. Then I create columns to extract the events and date from data_values. Below you will see how the schema looks, as well as the top 5 rows.
root
 |-- data_values: struct (nullable = true)
 |    |-- date: string (nullable = true)
 |    |-- events: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- active: long (nullable = true)
 |    |    |    |-- index: long (nullable = true)
 |    |    |    |-- mode: long (nullable = true)
 |    |    |    |-- rate: long (nullable = true)
 |    |    |    |-- timestamp: string (nullable = true)
 |-- events: struct (nullable = true)
 |    |-- active: long (nullable = true)
 |    |-- index: long (nullable = true)
 |    |-- mode: long (nullable = true)
 |    |-- rate: long (nullable = true)
 |    |-- timestamp: string (nullable = true)
 |-- date: string (nullable = true)

+----------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------------------+----------+
|data_values                                                                                |events                           |date      |
+----------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------------------+----------+
|[2019-02-20, [[0, 0, 1, 0, 2019-02-20T00:00:00], [0, 1, 1, 0, 2019-02-20T00:01:00], [0, 2, 1, 0, 2019-02-20T00:02:00]]]                                   |[0, 0, 1, 0, 2019-02-20T00:00:00]|2019-02-20|
|[2019-02-20, [[0, 0, 1, 0, 2019-02-20T00:00:00], [0, 1, 1, 0, 2019-02-20T00:01:00], [0, 2, 1, 0, 2019-02-20T00:02:00]]]                                   |[0, 1, 1, 0, 2019-02-20T00:01:00]|2019-02-20|
|[2019-02-20, [[0, 0, 1, 0, 2019-02-20T00:00:00], [0, 1, 1, 0, 2019-02-20T00:01:00], [0, 2, 1, 0, 2019-02-20T00:02:00]]]                                   |[0, 2, 1, 0, 2019-02-20T00:02:00]|2019-02-20|
|[2019-02-21, [[1, 0, 1, 0, 2019-02-21T00:03:00], [0, 1, 1, 0, 2019-02-21T00:04:00], [1, 2, 1, 1, 2019-02-21T00:05:00], [1, 3, 1, 1, 2019-02-21T00:06:00]]]|[1, 0, 1, 0, 2019-02-21T00:03:00]|2019-02-21|
|[2019-02-21, [[1, 0, 1, 0, 2019-02-21T00:03:00], [0, 1, 1, 0, 2019-02-21T00:04:00], [1, 2, 1, 1, 2019-02-21T00:05:00], [1, 3, 1, 1, 2019-02-21T00:06:00]]]|[0, 1, 1, 0, 2019-02-21T00:04:00]|2019-02-21|
+----------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------------------+----------+

When I have the dataframe that I desire I then try to drop data_values but I get this error:
py4j.protocol.Py4JJavaError: An error occurred while calling o58.showString.
: org.apache.spark.sql.catalyst.errors.package$TreeNodeException: Binding attribute, tree: _gen_alias_25#25
        at org.apache.spark.sql.catalyst.errors.package$.attachTree(package.scala:56)
        at org.apache.spark.sql.catalyst.expressions.BindReferences$$anonfun$bindReference$1.applyOrElse(BoundAttribute.scala:75)
        at org.apache.spark.sql.catalyst.expressions.BindReferences$$anonfun$bindReference$1.applyOrElse(BoundAttribute.scala:74)
        at org.apache.spark.sql.catalyst.trees.TreeNode.$anonfun$transformDown$1(TreeNode.scala:286)
        at org.apache.spark.sql.catalyst.trees.CurrentOrigin$.withOrigin(TreeNode.scala:72)
        at org.apache.spark.sql.catalyst.trees.TreeNode.transformDown(TreeNode.scala:286)
        at org.apache.spark.sql.catalyst.trees.TreeNode.$anonfun$transformDown$3(TreeNode.scala:291)
        at org.apache.spark.sql.catalyst.trees.TreeNode.$anonfun$mapChildren$1(TreeNode.scala:376)
        at org.apache.spark.sql.catalyst.trees.TreeNode.mapProductIterator(TreeNode.scala:214)
        at org.apache.spark.sql.catalyst.trees.TreeNode.mapChildren(TreeNode.scala:374)
        at org.apache.spark.sql.catalyst.trees.TreeNode.mapChildren(TreeNode.scala:327)
        at org.apache.spark.sql.catalyst.trees.TreeNode.transformDown(TreeNode.scala:291)
        at org.apache.spark.sql.catalyst.trees.TreeNode.transform(TreeNode.scala:275)
        at org.apache.spark.sql.catalyst.expressions.BindReferences$.bindReference(BoundAttribute.scala:74)
        at org.apache.spark.sql.catalyst.expressions.BindReferences$.$anonfun$bindReferences$1(BoundAttribute.scala:96)
        at scala.collection.TraversableLike.$anonfun$map$1(TraversableLike.scala:238)
        at scala.collection.immutable.List.foreach(List.scala:392)
        at scala.collection.TraversableLike.map(TraversableLike.scala:238)
        at scala.collection.TraversableLike.map$(TraversableLike.scala:231)
        at scala.collection.immutable.List.map(List.scala:298)
        at org.apache.spark.sql.catalyst.expressions.BindReferences$.bindReferences(BoundAttribute.scala:96)
        at org.apache.spark.sql.execution.ProjectExec.doConsume(basicPhysicalOperators.scala:63)
        at org.apache.spark.sql.execution.CodegenSupport.consume(WholeStageCodegenExec.scala:193)
        at org.apache.spark.sql.execution.CodegenSupport.consume$(WholeStageCodegenExec.scala:148)
        at org.apache.spark.sql.execution.InputAdapter.consume(WholeStageCodegenExec.scala:495)
        at org.apache.spark.sql.execution.InputRDDCodegen.doProduce(WholeStageCodegenExec.scala:482)
        at org.apache.spark.sql.execution.InputRDDCodegen.doProduce$(WholeStageCodegenExec.scala:455)
        at org.apache.spark.sql.execution.InputAdapter.doProduce(WholeStageCodegenExec.scala:495)
        at org.apache.spark.sql.execution.CodegenSupport.$anonfun$produce$1(WholeStageCodegenExec.scala:94)
        at org.apache.spark.sql.execution.SparkPlan.$anonfun$executeQuery$1(SparkPlan.scala:211)
        at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
        at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:208)
        at org.apache.spark.sql.execution.CodegenSupport.produce(WholeStageCodegenExec.scala:89)
        at org.apache.spark.sql.execution.CodegenSupport.produce$(WholeStageCodegenExec.scala:89)
        at org.apache.spark.sql.execution.InputAdapter.produce(WholeStageCodegenExec.scala:495)
        at org.apache.spark.sql.execution.ProjectExec.doProduce(basicPhysicalOperators.scala:49)
        at org.apache.spark.sql.execution.CodegenSupport.$anonfun$produce$1(WholeStageCodegenExec.scala:94)
        at org.apache.spark.sql.execution.SparkPlan.$anonfun$executeQuery$1(SparkPlan.scala:211)
        at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
        at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:208)
        at org.apache.spark.sql.execution.CodegenSupport.produce(WholeStageCodegenExec.scala:89)
        at org.apache.spark.sql.execution.CodegenSupport.produce$(WholeStageCodegenExec.scala:89)
        at org.apache.spark.sql.execution.ProjectExec.produce(basicPhysicalOperators.scala:39)
        at org.apache.spark.sql.execution.WholeStageCodegenExec.doCodeGen(WholeStageCodegenExec.scala:629)
        at org.apache.spark.sql.execution.WholeStageCodegenExec.doExecute(WholeStageCodegenExec.scala:689)
        at org.apache.spark.sql.execution.SparkPlan.$anonfun$execute$1(SparkPlan.scala:173)
        at org.apache.spark.sql.execution.SparkPlan.$anonfun$executeQuery$1(SparkPlan.scala:211)
        at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
        at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:208)
        at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:169)
        at org.apache.spark.sql.execution.TakeOrderedAndProjectExec.executeCollect(limit.scala:161)
        at org.apache.spark.sql.Dataset.collectFromPlan(Dataset.scala:3482)
        at org.apache.spark.sql.Dataset.$anonfun$head$1(Dataset.scala:2581)
        at org.apache.spark.sql.Dataset.$anonfun$withAction$1(Dataset.scala:3472)
        at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$4(SQLExecution.scala:100)
        at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:160)
        at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:87)
        at org.apache.spark.sql.Dataset.withAction(Dataset.scala:3468)
        at org.apache.spark.sql.Dataset.head(Dataset.scala:2581)
        at org.apache.spark.sql.Dataset.take(Dataset.scala:2788)
        at org.apache.spark.sql.Dataset.getRows(Dataset.scala:297)
        at org.apache.spark.sql.Dataset.showString(Dataset.scala:334)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:282)
        at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
        at py4j.commands.CallCommand.execute(CallCommand.java:79)
        at py4j.GatewayConnection.run(GatewayConnection.java:238)
        at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.RuntimeException: Couldn't find _gen_alias_25#25 in [data_values#5]
        at scala.sys.package$.error(package.scala:30)
        at org.apache.spark.sql.catalyst.expressions.BindReferences$$anonfun$bindReference$1.$anonfun$applyOrElse$1(BoundAttribute.scala:81)
        at org.apache.spark.sql.catalyst.errors.package$.attachTree(package.scala:52)

The schema of newData has the fields that I want, but executing newData.show(3) results in the error above.
root
 |-- events: struct (nullable = true)
 |    |-- active: long (nullable = true)
 |    |-- rate: long (nullable = true)
 |    |-- index: long (nullable = true)
 |    |-- mode: long (nullable = true)
 |    |-- timestamp: string (nullable = true)
 |-- date: string (nullable = true)

I have tried creating a new dataframe after dropping data_values and then running .show() but I still get the same issue. I'm guessing that for some reason, the new columns I created are still referencing data_values so maybe the way I am creating these columns is wrong?
I have tried finding people who have the same issue online but it seems as if this is not a common issue. As there is not much info on the gen_alias error.

A: Here I am using spark 2.4.3
point 1: update path
>>> from pyspark.sql import functions as F
>>> json_data = spark.read.option('multiline', True).json("/home/maheshpersonal/stack.json")
>>> json_data.show(truncate=False)
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|data                                                                                |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|[[2019-02-20, [[0, 0, 1, 0, 2019-02-20T00:00:00], [0, 1, 1, 0, 2019-02-20T00:01:00], [0, 2, 1, 0, 2019-02-20T00:02:00]]], [2019-02-21, [[1, 0, 1, 0, 2019-02-21T00:03:00], [0, 1, 1, 0, 2019-02-21T00:04:00], [1, 2, 1, 1, 2019-02-21T00:05:00], [1, 3, 1, 1, 2019-02-21T00:06:00]]], [2019-02-22, [[1, 0, 1, 0, 2019-02-22T00:03:00], [0, 1, 1, 0, 2019-02-22T00:04:00], [1, 2, 1, 1, 2019-02-22T00:05:00], [1, 3, 1, 1, 2019-02-22T00:06:00]]], [2019-02-23, [[1, 3, 1, 1, 2019-02-23T00:16:00]]], [2019-02-24, [[1, 0, 1, 1, 2019-02-24T00:03:00], [1, 1, 1, 0, 2019-02-24T00:04:00]]]]|
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

Point:2 check the schema
>>> json_data.printSchema()
root
 |-- data: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- date: string (nullable = true)
 |    |    |-- events: array (nullable = true)
 |    |    |    |-- element: struct (containsNull = true)
 |    |    |    |    |-- active: long (nullable = true)
 |    |    |    |    |-- index: long (nullable = true)
 |    |    |    |    |-- mode: long (nullable = true)
 |    |    |    |    |-- rate: long (nullable = true)
 |    |    |    |    |-- timestamp: string (nullable = true)

Point3: exploding the data columns
>>> json_data_1 = json_data.withColumn("data_values", F.explode_outer("data"))
>>> json_data_1.printSchema ()
root
 |-- data: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- date: string (nullable = true)
 |    |    |-- events: array (nullable = true)
 |    |    |    |-- element: struct (containsNull = true)
 |    |    |    |    |-- active: long (nullable = true)
 |    |    |    |    |-- index: long (nullable = true)
 |    |    |    |    |-- mode: long (nullable = true)
 |    |    |    |    |-- rate: long (nullable = true)
 |    |    |    |    |-- timestamp: string (nullable = true)
 |-- data_values: struct (nullable = true)
 |    |-- date: string (nullable = true)
 |    |-- events: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- active: long (nullable = true)
 |    |    |    |-- index: long (nullable = true)
 |    |    |    |-- mode: long (nullable = true)
 |    |    |    |-- rate: long (nullable = true)
 |    |    |    |-- timestamp: string (nullable = true)

Point4: selecting the column as per requirement
 >>> newData = json_data_1.withColumn("events", json_data_1.data_values.events).withColumn("date", json_data_1.data_values.date)

 >>> newData.show()
    +--------------------+--------------------+--------------------+----------+
    |                data|         data_values|              events|      date|
    +--------------------+--------------------+--------------------+----------+
    |[[2019-02-20, [[0...|[2019-02-20, [[0,...|[[0, 0, 1, 0, 201...|2019-02-20|
    |[[2019-02-20, [[0...|[2019-02-21, [[1,...|[[1, 0, 1, 0, 201...|2019-02-21|
    |[[2019-02-20, [[0...|[2019-02-22, [[1,...|[[1, 0, 1, 0, 201...|2019-02-22|
    |[[2019-02-20, [[0...|[2019-02-23, [[1,...|[[1, 3, 1, 1, 201...|2019-02-23|
    |[[2019-02-20, [[0...|[2019-02-24, [[1,...|[[1, 0, 1, 1, 201...|2019-02-24|
    +--------------------+--------------------+--------------------+----------+

point5 : dropping the data column from dataframe
>>> newData_v1 = newData.drop(newData.data)
>>> newData_v1.show()
+--------------------+--------------------+----------+
|         data_values|              events|      date|
+--------------------+--------------------+----------+
|[2019-02-20, [[0,...|[[0, 0, 1, 0, 201...|2019-02-20|
|[2019-02-21, [[1,...|[[1, 0, 1, 0, 201...|2019-02-21|
|[2019-02-22, [[1,...|[[1, 0, 1, 0, 201...|2019-02-22|
|[2019-02-23, [[1,...|[[1, 3, 1, 1, 201...|2019-02-23|
|[2019-02-24, [[1,...|[[1, 0, 1, 1, 201...|2019-02-24|
+--------------------+--------------------+----------+

Point6: drop data_values column from newData_v1
>>> finalDataframe = newData_v1.drop(newData_v1.data_values)
>>> finalDataframe.show(truncate = False)
+--------------------------------------------------------------------------------------------------------------------------------------------+----------+
|events                                                                                |date      |
+--------------------------------------------------------------------------------------------------------------------------------------------+----------+
|[[0, 0, 1, 0, 2019-02-20T00:00:00], [0, 1, 1, 0, 2019-02-20T00:01:00], [0, 2, 1, 0, 2019-02-20T00:02:00]]                                   |2019-02-20|
|[[1, 0, 1, 0, 2019-02-21T00:03:00], [0, 1, 1, 0, 2019-02-21T00:04:00], [1, 2, 1, 1, 2019-02-21T00:05:00], [1, 3, 1, 1, 2019-02-21T00:06:00]]|2019-02-21|
|[[1, 0, 1, 0, 2019-02-22T00:03:00], [0, 1, 1, 0, 2019-02-22T00:04:00], [1, 2, 1, 1, 2019-02-22T00:05:00], [1, 3, 1, 1, 2019-02-22T00:06:00]]|2019-02-22|
|[[1, 3, 1, 1, 2019-02-23T00:16:00]]                                                                                |2019-02-23|
|[[1, 0, 1, 1, 2019-02-24T00:03:00], [1, 1, 1, 0, 2019-02-24T00:04:00]]                                                                      |2019-02-24|
+--------------------------------------------------------------------------------------------------------------------------------------------+----------+

Learning from this is always use a new data frame to store the transformation. please check if it helps you :)


text:
Q: Nestjs how to debug while editing code in VS code I see there is a couple of answers making custom setups for debugging a NestJs application. However, I noted that in the standard package.json there is a script available "start:debug": "nest start --debug --watch",.
I tried to create a launch.json with the following setup.
{
    "type": "node",
    "request": "launch",
    "name": "Debug Program",
    "cwd": "${workspaceFolder}",
    "runtimeExecutable":"npm",
    "runtimeArgs":["run","start:debug"],
    "autoAttachChildProcesses":true
}

This works fine until i start editing the code.
After that breakpoints are completely ignored, even if I remove and add them again.

A: *

*Open Vscode, and enter CTRL+SHIFT+P,  select Toggle auto attach, choose always

*Click the code line you want to debug

*npm run start


text:
Q: I went in, booted as I was. (Is this same as?: I went in though I was booted.) I went in, booted as I was. (Is this same as?: I went in though I was booted.)
I think booted as I was is a concessive clause.

A: Yes, here as is a conjunction that means although/though and is used to express concession.

A: I would need more context to know definitely. I can understand the way you've interpreted it, but I'd read

booted as I was

as a simple description, i.e. the person has not changed his shoes before entering.


text:
Q: How do I write a Python program that computes the average from a .dat file? I have this so far but I don't know how to write over the .dat file:
def main():
   fname = input("Enter filename:")
   infile = open(fname, "r")
   data = infile.read()
   print(data)

for line in infile.readlines():
    score = int(line)
    counts[score] = counts[score]+1
    infile.close()

total=0
for c in enumerate(counts):
    total = total + i*c
    average = float(total)/float(sum(counts))
print(average)
main()

Here is my .dat file:
4
3
5
6
7

My statistics professor expects us to learn Python to compute the mean and standard deviation. All I need to know is how to do the mean and then I've got the rest figured out. I want to know how does Python write over each line in a .dat file. Could someone tell me how to fix this code? I've never done programming before.

A: fname = input("Enter filename:")
infile = open(fname, "r")
data = infile.readline() #Reads first line
print(data)
data = infile.readline() #Reads second line
print(data)

You can put this in a loop.
Also, these values will come in as Strings convert them to floats using float(data) each time.
Also, the guys over at StackOverflow are not as bad at math as you think. This could have easily been answered there. (And maybe in a better fashion)

A: To answer your question, as I understand it, in three parts:
How to read the file in
in your example you use

infile.read()

which reads the entire contents of the file into a string and takes you to the end of file. Therefore the following

infile.readlines()

will read nothing more. You should omit the first read().
How to compute the mean
There are many ways to do this in python - more or less elegant - and also I guess it depends on exactly what the problem is. But in the simplest case you can just sum and count the values as you go , then divide sum by count at the end to get the result:
infile = open("d.dat", "r")
total = 0.0
count = 0
for line in infile.readlines():
    print ("reading in line: ",line)
    try:
        line_value = float(line)
        total += line_value
        count += 1
        print ("value = ",line_value, "running total =",total, "valid lines read = ",count)
    except:
        pass #skipping non-numeric lines or characters

infile.close()

The try/except part is just in case you have lines or characters in the file that can't be turned into floats, these will be skipped.
How to write to the .dat file
Finally you seem to be asking how to write the result back out to the d.dat file. Not sure whether you really need to do this, it should be acceptable to just display the result as in the above code. However if you do need to write it back to the same file, just close it after reading from it,  reopen it for writing (in 'append' mode so output goes to the end of the file), and output the result using write().
outfile = open("d.dat","a")
outfile.write("\naverage = final total / number of data points = " + str(total/count)+"\n")
outfile.close()


text:
Q: How do I fire from a  CTRL+V and CTRL+Z to a targeted ? I want to fire from a button Ctrl+V and Ctrl+Z to a targeted textarea. If it is possibility to have this as an onclick button instead of id button that would be perfect. How do I do that?

NOTE: Please do not misunderstand this post with detecting or alert keypress. I do NOT want that. I want to have a button that executes this keypress onto the textarea.

My JavaScript:

<script type="text/javascript">
var t = document.getElementById('mytextarea'),
    bcsv = document.getElementById('bcv'),
    bsz = document.getElementById('bcz'),
    cv = document.createEvent('KeyboardEvents'),
    cz = document.createEvent('KeyboardEvents');

cv.initKeyboardEvent(
           'keydown',
           true,     // key down events bubble
           true,     // and they can be cancelled
           document.defaultView,  // Use the default view
           true,        // ctrl
           false,       // alt
           false,        //shift
           false,       //meta key
           86,          // keycode
           0
          );
cz.initKeyboardEvent(
           'keydown',
           true,     // key down events bubble
           true,     // and they can be cancelled
           document.defaultView,  // Use the default view
           true,        // ctrl
           false,       // alt
           false,        //shift
           false,       //meta key
           90,          // keycode
           0
          );

bcz.addEventListener('click', function(){
  t.dispatchEvent(cz);
}, false);

bcsz.addEventListener('click', function(){
  t.dispatchEvent(csz);
}, false);
</script>

My HTML:

<input type="button" value="CTRL+V" id="bcv" />
<input type="button" value="CTRL+Z" id="bcz" />
<textarea id="mytextarea" rows="5" cols="10"></textarea>

Question: I never managed to make this work. So how do I make it work? Or is it another way to make this work?
How do I make two buttons to act as if I would push Ctrl+V and Ctrl+Z on the keyboard on a targeted textarea? But without using the keyboard.


text:
Q: Does anyone know if there is a performance benefit to fullscreen opengl vs windowed opengl in OSX? The client for the MMO I work on uses two contexts, one for a window view and one fullscreen. I'm wondering if I just use a window sized to the display I can simply resize it if the user wants a smaller window so they can access their desktop.
Is their a performance penalty for running opengl in a window vs fullscreen assuming the same dimensions etc?
The client shell is written in cocoa; the game code itself is cross-platform.
We only support OSX 10.5 and 10.6 for the next release.

A: Before 10.6, if your context did not have the full screen flag in it's creation, then you had a small performance difference. Now, with 10.6, this has changed.
Have a look at:
http://lists.apple.com/archives/Cocoa-dev/2009/Sep/msg01054.html

A: if there is a cost associated with clipping each frame, then yes.


text:
Q: Here Map instead of map tiles update store the map at once Here Map folks, How to load the HERE Map for one time to particular state instead while travel map tiles update. Any Suggestion or Example.

A: If you are using the Premium version of the SDK, it sounds like you want to use the MapLoader API. In particular, MapLoader#getMapPackages() and MapLoader#installMapPackages(List<Integer> packageIdList). More detailed API reference can be found here.
If you are using the Starter version of the SDK, you are out of luck. Offline caching of map data is not supported in the Starter version.
For more details on the usage of the MapLoader API you can see this answer: https://stackoverflow.com/a/35333711/275524


text:
Q: Looping through csv files and outputting calculations to one consolidated csv file I am trying to loop through a specified folder, containing a bunch of .csv files. The purpose is to gather three metrics listed in each file, add them up, and output that to a row in a consolidated, soon-to-be-produced-by-python csv file.
This is my code:
import pandas as pd
import os

results_output = pd.DataFrame(index = None, columns=["gross_revenue","impressions","bid_requests"])
filenames = os.listdir("Z:/some/folder/path")

count = 0

for file in filenames:
    file_path = "Z:/some/folder/path/" + file
    data = pd.read_csv(file_path,skiprows=[0])
    data.columns = ["product1_gross_revenue","product2_gross_revenue","product3_gross_revenue"]
    gross_revenue = (data.product1_gross_revenue[0] + data.product2_gross_revenue[0] + data.product3_gross_revenue[0])
    if gross_revenue > 0:
        count += 1
        results_output.gross_revenue[1+count] = [gross_revenue]
        results_output.to_csv("data.csv",index=False,header=False)

This is the error:
Traceback (most recent call last):
  File "test.py", line 16, in <module>
    results_output.gross_revenue[1+count] = [gross_revenue]
  File "C:\Python27\lib\site-packages\pandas-0.14.1-py2.7-win3
, in __setitem__
    values[key] = value
IndexError: index 2 is out of bounds for axis 0 with size 0

I can print out all the revenue items on the console so I know it is calculating correctly through each file, and a "data.csv" file is generated, but it remains at 0kb, with nothing ever being written to it, so I suspect this is where I am making a mistake.
This is what I want my "data.csv" file to look like:
0 gross_revenue[file1]
1 gross_revenue[file2]
2 gross_revenue[file3]
3 gross_revenue[file4]
4 gross_revenue[file5]
5 gross_revenue[file6]
6 gross_revenue[file7]

Hopefully I have supplied all useful bits of information, happy to provide anything else.
Thanks in advance!

A: When you create the results_output dataframe, you are creating it with zero elements in the index. That's why (I think) it throws you an error when you try to access it.
Try creating it with an index equal to the number of files.
I also changed the way you used count 'cause I think it was off by 2.
I haven't tested the code below, but give it a try and report back if you find an issue
import pandas as pd
import os

filenames = os.listdir("Z:/some/folder/path")
n_files = len(filenames)
results_output = pd.DataFrame(index = range(n_files), columns=["gross_revenue","impressions","bid_requests"])

count = 0

for file in filenames:
    file_path = "Z:/some/folder/path/" + file
    data = pd.read_csv(file_path,skiprows=[0])
    data.columns = ["product1_gross_revenue","product2_gross_revenue","product3_gross_revenue"]
    gross_revenue = (data.product1_gross_revenue[0] + data.product2_gross_revenue[0] + data.product3_gross_revenue[0])
    if gross_revenue > 0:
        results_output.gross_revenue[count] = [gross_revenue]
        results_output.to_csv("data.csv",index=False,header=False)
        count += 1

(Slightly more pythonic, if you wanna keep the order of files: drop the count variable outside and do for count, file in enumerate(filenames) )


text:
Q: Javascript array variable scoping issue I am trying to solve a scoping issue with the webapp i'm building.
the array called paths are being filled with coordinates from a XML file. I create the array before the functions, so that it will be a global variable. I'm able to console.log the whole array after its being filled with coordinates, but i can't run it through jQuery each loop og a javascript for loop. It's important that i can run it through a loop afterwards because i need to calculate the distances between the points with google.maps.geometry.spherical.computeDistanceBetween().
Thanks in advance! :)
My code is below:
    $(document).ready(function() {
        var newLatLng = new google.maps.LatLng(17.74033553, 83.25067267);
        MYMAP.init('#map-img', newLatLng, 3);
        MYMAP.placeMarkers('xml/coordinats.xml');
    });

    var MYMAP = {
        map: null,
        bounds: null
    };

    MYMAP.init = function(selector, latLng, zoom) {
        var myOptions = {
            zoom: zoom,
            center: latLng,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableDefaultUI: true, // a way to quickly hide all controls
            mapTypeControl: false,
            scaleControl: true,
            zoomControl: false,
            zoomControlOptions: {
                style: google.maps.ZoomControlStyle.LARGE
            },
            minZoom: 3
        };
        this.map = new google.maps.Map($(selector)[0], myOptions);
        this.bounds = new google.maps.LatLngBounds();
    };

    var currentRouteId = <?php echo json_encode($route_id)?>;

    var paths = new Array;
    var i = 0;

    MYMAP.placeMarkers = function(filename) {
        $.get(filename, function(xml) {
            $(xml).find("koordinator").each(function() {
                var routeId = $(this).find('rute_id').text();
                var routeIdInt = parseInt(routeId);

                var lat = $(this).find('lat').text();
                var lng = $(this).find('lng').text();
                var point = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));

                var markerXML = $(this).find('marker').text();

                var markerImg = "images/" + markerXML;

                if (routeIdInt === currentRouteId) {

                    paths.push(point);

                    // extend the bounds to include the new point
                    MYMAP.bounds.extend(point);

                    var marker = new google.maps.Marker({
                        position: point,
                        map: MYMAP.map,
                        clickable: false,
                        options: {icon: new google.maps.MarkerImage(markerImg)}
                    });

                    MYMAP.map.fitBounds(MYMAP.bounds);
                }
            });
        });
    };

    console.log(paths);


text:
Q: Notifications not showing on lock screen I want to show notifications on lock screen, but I'm unable to get it to work.
This is my code that I have;
                  .setSmallIcon(R.drawable.deleteaccounticon)
                  .setContentTitle("My notification")
                  .setContentText("Much longer text that cannot fit one line...")
                  .setStyle(new NotificationCompat.BigTextStyle()
                          .bigText("Much longer text that cannot fit one line..."))
                  .setPriority(NotificationCompat.PRIORITY_HIGH);

          builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);

          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
              CharSequence name = "channel1";
              String description = "test";
              int importance = NotificationManager.IMPORTANCE_HIGH;
              NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
              channel.setDescription(description);
              // Register the channel with the system; you can't change the importance
              // or other notification behaviors after this

              NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
              notificationManager.createNotificationChannel(channel);
              notificationManager.notify(1,builder.build());
              channel.setLockscreenVisibility(VISIBILITY_PUBLIC);
      }

The notifications is not showing on the lock screen. The settings for the app allows to show notifications on lock screen.
Any advice?

A: builder.setOngoing(true)
makes the notification shown on the lock screen.


text:
Q: Drupal 6 catch form fails on validation in template file How can I know in my template file: node-object.tpl.php that form falis on validation.
I want to use this because form is in hidden div and when I know that validation fails I can pre-open that div.
Thx.

A: You can use jquery on the client side to check  for validation and you can use a module to get server side validation done.
Jquery will be fast and user friendly and server side validation will make sure the submission is safe and no cross side scripting hacks are done.
Further research to get your work done:
1) Search for hook_form_validate() function in d7. This is a simple function which will do the validation for you.
2) Check out http://drupal.org/project/clientside_validation for  client side validation.
If you still need more help then pls revert.


text:
Q: Magento 2 Leverage Browser Caching for Images, CSS and JS not any effect As in Magento 1 to increase the page speed score and Y-slow score we have used
Leverage Browser Caching for Images, CSS and JS  code in .htaccess file but same script in Magento2 is not working.
below is the code of browser cache:
# Leverage browser caching using mod_expires #
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/pdf "access plus 1 month"
    ExpiresByType text/x-javascript "access plus 1 month"
    ExpiresByType application/x-shockwave-flash "access plus 1 month"
    ExpiresByType image/x-icon "access plus 1 year"
    ExpiresDefault "access plus 2 days"
</IfModule>
# End of Leverage browser caching using mod_expires #

Why Magento 2 is not considering this code.?
If anything is wrong in code please share the code so we can optimize the code.

A: I had also faced the similar issue, even after updating .htaccess caching was not applied to files. Enable mode expires module and restart apache2, fixed issue.
sudo a2enmod expires
sudo service apache2 restart

A: Add the following at the following:
root > .htaccess file
# Leverage browser caching using mod_expires #
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/pdf "access plus 1 month"
    ExpiresByType text/x-javascript "access plus 1 month"
    ExpiresByType application/x-shockwave-flash "access plus 1 month"
    ExpiresByType image/x-icon "access plus 1 year"
    ExpiresDefault "access plus 2 days"
</IfModule>
# End of Leverage browser caching using mod_expires #

It will be clear the Leverage browser aching issue.


text:
Q: The certificate is not trusted because no issuer chain was provided Could anyone explain the meaning of this error message in plain English?
Should I add an exception or I should not continue on this website?
Technical details: the URL is here, the browser is Firefox 14.0.1 on Ubuntu 12.04 LTS.
Konqueror 4.8.2 says for the same link:
The certificate authority's certificate is invalid
The root certificate authority's certificate is not trusted for this purpose

UPDATE: I did not do anything with my browser and now it magically works, no error message. A mystery.

A: Some secure web-sites with certificates from trusted authorities have incorrect configuration such that they don't include a chain of intermediate certificates of trust when serving their own certificate.
If you have a system/browser that has seen its share of valid certificates, such intermediaries may already be cached, and you won't be getting any error messages, even if their web-server configuration is still wrong as above.
However, if you're using a freshly installed browser on a fresh system, and such intermediaries weren't cached yet, and the certificate presented by the web-server is missing an appropriate chain of intermediaries, then you get an error message.
Here's an official explanation by a Mozilla developer in a Mozilla.org mailing list:
http://www.mail-archive.com/dev-security@lists.mozilla.org/msg02155.html
Bottom line: it is the fault of the web-site, even if it only happens in your freshly installed browser, and works fine elsewhere.

How they've fixed it in plain English:

They bought their certificate from a reseller of trust, and their web-server must have only been serving one certificate — their own — which your browser doesn't trust directly, since they bought it from a reseller you've never heard of.
Now, instead of serving just one certificate, they serve two right at the same time — their own ("*.upc.biz") and that of some certificate reseller ("AlphaSSL CA - G2"), and the certificate of such reseller completes the trust, since you now see that someone whom you trust ("GlobalSign Root CA") has vouched for such reseller of trust.
You can see more details about exact names involved here:
http://www.digicert.com/help/?host=web.upc.biz
Some other web-sites buy their certificates directly from a trusted authority, and not from a reseller, so, they only need to serve their own certificate, and everything will still be tip-top.
For example, linode.com bought their certificate directly from Equifax, which Mozilla trusts directly, so there's no need for Linode to include any copies of any certificates other than their own.

A: It looks like you are missing an intermediate CA (Certificate Authority).
Certificates are only trusted because they are signed by a trusted certificate authority (the issuer), which is in turn signed by another trusted CA, up to those listed as explicitly trusted by whatever is verifying them (a root CA). Browsers (and OSes) come with a list of root CAs. See here for more details. Wikipedia also has a very nice explanation of just about every aspect.
The website certificate appears to specify AlphaSSL as its issuer, which in turn specifies GlobalSign Root CA. So that's the chain - the website's certificate does not mention GlobalSign Root CA anywhere so if either of the two in the chain is missing, Firefox will complain.

Could you verify GlobalSign/AlphaSSL exists in your Firefox certificate authorities list?

*

*Open the Certificate Manager (Tools => Options => Advanced => Encryption => View Certificates)

*Check on the Authorities tab for the AlphaSSL CA - G2. It should be under GlobalSign nv-sa.
Also check for GlobalSign Root CA.

*Select GlobalSign Root CA, click Edit Trust, and verify that it is allowed to identify websites. At least for me, AlphaSSL did not have that permission.

If the root CAs is missing, try resetting your certificate store. Basically, delete (or rename) cert8.db, secmode.db and cert_override.txt from your profile folder.
If the intermediate certificate is missing, well, it's the responsibility of the server operator to serve the intermediate certificate along with the root. You should contact them and let them know. If you want, you can grab the intermediate certificate elsewhere - these sites sometimes works for some people because they have a cached intermediate that's already trusted.

You might also want to try clearing your cache in Firefox.

This might also be an issue with the CA being missing from your system stores, which would explain why Konqueror is also affected. I know that, at least on Windows, Firefox ignores the system's certificate store. I'm not familiar with how Ubuntu (or Firefox on Ubuntu) manages certificates, but the issue is the same: you appear to be missing a CA. You'll need to add it.
Alternatively, you could add the site's certificate to the exceptions list. Since you are missing a CA, there's a chance other sites will display a similar error - the only reason not to add the CA is if you don't trust them. This site's certificate seems to be valid, at least according to my system (though CAs can revoke certificates). Of course, unless you can somehow verify a certificate as valid, do not add an exception.

A:
Could anyone explain the meaning of this error message in plain English?

upc.biz wants you to type in personal details
To reassure you that upc.biz is a website being run by UPC, upc.biz has presented you with a certificate saying "you can trust upc.biz, I vouch for them" signed Joe Smith.
You have no idea who Joe Smith is. You have a list of signatures of people that Microsoft The Mozilla project say you can probably trust to introduce you to other people who are probably who they say they are, Joe smith isn't in that list of signatures (Certifying Authorities).
The certificate is therefore worthless

You can test this by cutting your full upc.biz URL and pasting it in to the certificate tester at http://www.digicert.com/help/ - though that is aimed at people who set up certificates in sites like upc.biz, not at people who access those sites.

Also, http://www.schneier.com/blog/archives/2010/09/uae_man-in-the-.html is a good read.


text:
Q: Passing an object into a Cypress cy.setcookie() Command I have a cookie with several objects, namely path, secure status, and httponly status, that I need to set alongside the actual value of the cookie. While the Cypress guide does specifically state that such objects can be passed in, there is no example of a command with passed in objects for a novice like me to follow.
Can someone provide an example?
Already tried...
cy.setcookie('cookieName', 'value', 'path=/', 'Httponly=true', 'Secure=true')
cy.setcookie('cookieName', 'value', path='/', Httponly=true, Secure=true)

A: The third parameter should be an options object, just a normal plain old Javascript object. That would look like this in your example:
cy.setcookie('cookieName', 'value', {
    path: '/',
    httpOnly: true,
    secure: true
})


text:
Q: To prove $(0,0)$ is a saddle point of $f(x,y)=x^2-2xy+y^2+x^3-y^3+x^5$ Investigate maxima and minima of $$f(x,y)=x^2-2xy+y^2+x^3-y^3+x^5$$
My attempt:
$$f_x=2x-2y+3x^3+5x^4=0$$
$$f_y=-2x+2y-3y^2=0$$
Solving,I got $(0,0)$ as a stationary point.
The second derivative test fails in this case
The solution is $(0,0)$ is a saddle point but I can't figure out how

A: Let us construct the Hessian
$$H(x,y) = \left[\begin{array}{cc}
f_{xx} & f_{xy} \\
f_{yx} & f_{yy}
\end{array}\right]$$
$$= \left[\begin{array}{cc}
2+6x+20x^3 & -2 \\
-2 & 2-6y
\end{array}\right] $$
$$\implies |H|(0,0) = \left|\begin{array}{cc}
2 & -2 \\
-2 & 2
\end{array}\right| = 0 $$
Hence, we must proceed with definition of maxima/minima saddle point. At the point $(0,0)$, we see function value is $0$. Now in an $\epsilon$-neighbourhood of the point, if the function values are all bigger then maxima, else if all smaller then minima. If there are some above and below, no matter how small epsilon, then it's a saddle point.
Just look at $f(\epsilon,\epsilon) = \epsilon^5$, this will change sign about $(0,0)$, hence saddle point


text:
Q: Make axios request one at a time I want to implement an upload file function and thus need to do an Axios post request, which requires a token for the user, to the server and after each upload is completed the token for the user is changed. So when the same is implemented for uploading multiple files the token gets changed after the first file upload is complete and thus the request for the second file gives an error as it already sent a request with the previous token.
I need to implement Axios requests for the upload function one at a time and store the requests in a queue and send them to the server one by one. How to implement this?
Edit: I don't need the entire code. I will be able to write the code but I want to know how can we implement it. I searched on google and the closest I could find something was of concurrency in promises. And I tried to fetch in a for loop and the same error appeared because I need to wait for the first fetch statement to complete and then get the new token and then request using that token. If I use the synchronous method then the UI will be stuck causing a bad user experience
 axios({
      method: "post",
      url: `url`,
      headers: {
        "Content-type": "multipart/form-data",
        token: localStorage.getItem("token"),
      },
      data: formData,}).then(response=>{localStorage.setItem("token", response.data.newtoken);})

I need to send this new token with the file being uploaded next.


text:
Q: The Type or Namespace "MyServiceClient" Could not be Found I've just completed this wcf duplex tutorial, but upon going over my code I encountered this error:
Severity    Code    Description   Line
Error   CS0246  The type or namespace name 'MyServiceClient' could not be found (are you missing a using directive or an assembly reference?) ClientSide 15

My usings all seem to be in order, and I've googled this error numerous times with no luck.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;

namespace ClientSide
{
    class Program
    {
        static void Main(string[] args)
        {
            InstanceContext callback = new InstanceContext(new ClientCallback());
            MyServiceClient client = new MyServiceClient(callback);
            client.Open();
            client.Register();
            Console.WriteLine("Press a key to exit");
            Console.ReadKey();
            client.Close();
        }
    }
}

Is MyServiceClient a type or a namespace?
Any help would be much appreciated, I'm using Visual Studio 2015.

A: In this case MyServiceClient should be the name of the client class generated when you did "Add Service Reference".
To verify the name of the generated class, in windows explorer navigate to the directory containing your service references (typically e.g. <ProjectName>\Service References\<ServiceReferenceName>, and open the file Reference.cs
Inside of Reference.cs, look for a class that inherits from System.ServiceModel.ClientBase.  The derived class is the your service client class that you should use to interact with the web service.
So, for example, if Reference.cs contained
public partial class BlahServiceSoapClient : System.ServiceModel.ClientBase<global::MyProject.MyService.BlahServiceSoap>, global::MyProject.MyService.BlahServiceSoap

Note, that depending on the reference, it could be a different subclass of System.ServiceModel.ClientBase that you see in the Reference.cs file.  Since this question is specifically about the duplex client, you would see System.ServiceModel.DuplexClientBase
Then your service class would be BlahServiceSoapClient, so you would do
BlahServiceSoapClient client = new BlahServiceSoapClient(callback);


text:
Q: How do I draw an image in Canvas, when I press a key with setOnKeyPressed? I want to draw an image in canvas when I press RIGHT, but I don't know exactly how I should do it.
First I create two variables for later on, then I create my canvas. Then I get the Image I want to draw. I tried getting the key with getCode().equals(KeyCode.Right), but it doesn't work. Please Help.
public class Controller implements Initializable {

    @FXML
    private Canvas canvas;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        double v1 = 0;
        double v2 = 0;

        GraphicsContext gc = canvas.getGraphicsContext2D();
        Image pm = new Image("sample/pacman.png", 20, 20, true, true);

        canvas.setOnKeyPressed(keyEvent -> {
            if (keyEvent.getCode().equals(KeyCode.RIGHT)) {
                gc.drawImage(pm, v1, v2);
            }

        });
    }

}

I expect the image to appear, but instead it's just an empty program.


text:
Q: How to do a Cube Map Texturing on a Sphere? I am working in QT with OpenGL, and I have a sphere in the project. What I need is to do a Cube Map Texturing on the sphere.
Does anybody have any material or anything that can help me to do this? I am not finding anything like this on the internet that can help me :(. Please if you have anything in that direction, ti would be really helpfull
The Sphere is created by code, by creating triangles and then shading.

A: For a point p on the surface of a sphere centered at c, use normalised(p - c) as the texture coordinate of p.
Conceptually, imagine the cubemap texture centered at the sphere's center. Mapping the texture to a point on the sphere corresponds to casting a ray from the center of the sphere through the surface point, and using the texel hit by that ray. That's precisely what you'll get by using the c->p vector (a.k.a. p - c) as the cubemap texture coordinate.


text:
Q: Nginx default host when not defined How does nginx determine the server to use when there is no default_server defined and it doesn't match server_name?
It was magically matching a server_name of localhost in the default sites-enabled file.

A: http://nginx.org/en/docs/http/request_processing.html

In this configuration nginx tests only the request's header field "Host" to determine which server the request should be routed to. If its value does not match any server name, or the request does not contain this header field at all, then nginx will route the request to the default server for this port. In the configuration above, the default server is the first one — which is nginx's standard default behaviour.


text:
Q: Trying to stretch background to 100% height I am trying to create a full page div (with 100% width & height). But in firefox it is not stretching fully. Here's my code:-
div{
    background:url('image.jpg')no-repeat fixed;
    background-size:cover;
 }

I've tried a lot,but I don't know what's wrong.

A: Actually there's nothing wrong with your CSS as such, but in order for it to work properly you need to(unfortunately) add browser prefix
try adding
 div{
    background:url('image.jpg')no-repeat fixed;
    background-size:cover;
    -moz-background-size:cover;
  }

A: Be sure you set the height of html, body.
By default, the html and body elements do not take up the entire height of the window. You have to explicitly set the height of html, body to force them to span the entire height of the window.
html, body {
    height:100%;
}

By forcing the html, body to take up the entire height of the window and then placing the div { width:100%; height:100%; } as a child of the body element you can ensure that the div will stretch to 100% of the window's width and height.
Here's an example: http://jsfiddle.net/ewF8M/


text:
Q: MySQL datatype to store month and year only I'm writing a PHP application that will store STUDENT data in a MySQL relational database. I'm trying to find the best way / datatype to store a month and year together without the day.
I don't know whether I should just store it as a DATE and use PHP someway to just store the day as the 1-st or use a different datatype that I'm not currently familiar with. Ideally, I do not want to store a day, because the day will not always be the same and would require changing PHP source code if the day changed in the future.
Just for more background info, I'm storing a STUDENT's INTENT_TO_GRAD. The client seems to only want this information as a reference or a visual for a report as opposed to using it for data manipulation. In other words, the only functional requirement for this data is to be displayed in a report.

A: Why bother? Just store it as a complete date (perhaps always using the first as the day)  and use the database functions MONTH() and YEAR() if you only need part of it. This makes using that field much easier as you can still do range queries, etc.

A: It says in the MySQL manual that you can store partial dates
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format

Ranges for the month and day specifiers begin with zero due to the
  fact that MySQL permits the storing of incomplete dates such as
  '2014-00-00'.

This means that to store the year and month only, you can use a DATE column and put 00 instead of the day. e.g 2013-12-00.
Related: Store incomplete date in MySQL date field

A: Consider how you are going to use the data.  If there are any reports you have to create, which way would allow you to retrieve and work with the data more easily?
And you don't have to use a date type field.  You could just have a Year field and a Month field that are both integers.  Then when you actually need to do any kind of expression with it requiring a date it's easy enough to put them together and cast to a date.
And storing as a date with the day number as 1 and just ignoring it is perfectly okay and fairly normal too.  In the end this isn't a decision that's going to matter a whole lot (relatively speaking) so I would just choose the one you like best and get it done.

A: Another solution is to build generated columns from your DATETIME/DATE source.
ALTER TABLE stats
ADD COLUMN year SMALLINT GENERATED ALWAYS AS (YEAR(stat_date)) NOT NULL,
ADD COLUMN month smallint GENERATED ALWAYS AS (MONTH(stat_date)) NOT NULL;

Background
I had a similar problem. After reading this thread, I decided to store incomplete dates (with zeros). It worked on older versions of MySQL, but newer versions produced "Incorrect date" error. As mentioned before, you can turn the error into warning using the NO_ZERO_IN_DATE setting. But the setting itself is deprecated. Hence, in the future, it would only be possible to support zeros in dates by disabling the strict mode, thus, silencing other types of errors.

Because NO_ZERO_IN_DATE is deprecated, it will be removed in a future MySQL release as a separate mode name and its effect included in the effects of strict SQL mode.

My requirement was to build a monthly view of a table. I had to add an index on month. So, computing moth on-the-fly with YEAR() and MONTH() was not an option.
Generated columns served their purpose. The year and month columns weren't part of the primary index, and I could even save space thanks to the VIRTUAL (not STORED) generated columns.
Links

*

*https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_no_zero_in_date

*https://dev.mysql.com/doc/refman/5.7/en/create-table-generated-columns.html

A: I would store the two as two separate columns as integers. It would make validation cake and allow quick and easy sorting and grouping possibilities.

A: SELECT * FROM Users
WHERE
    MONTH(DateTime) = '07'
AND
    YEAR(DateTime) = '2015'
AND
    DAY(DateTime) = '26'

you can filter like above but still if you want to store year/month and day as separate, its useless until you apply indexing and its very big data.

A: As of 5.7 one could make use of generated columns, which lets you enforce year-month uniqueness while also using date functions on another field without breaking data integrity by duplicating:
CREATE TABLE `year_month` (
  `Year` int(11) NOT NULL,
  `Month` enum(
      'January',
      'February',
      'March',
      'April',
      'May',
      'June',
      'July',
      'August',
      'September',
      'October',
      'November',
      'December'
      ) NOT NULL,
  `GENERATED_YearMonth` date
      GENERATED ALWAYS AS
          ((makedate(`Year`,1) + interval (`Month` - 1) month))
      STORED,
  PRIMARY KEY (`Year`,`Month`),
  KEY `year_month_GENERATED_YearMonth_index` (`GENERATED_YearMonth`)
)
;

A: You can use VARCHAR datatype to store month and year only.
For those who use datepicker :-
1)Set VARCHAR datatype in mysql to store month and year.
2)If you are using jquery validation and have jquery plugin date picker then you have to do below code.
For ex:-
<script>

$(document).ready(function (){

$('#monthyear').datepicker({
  autoclose:true,
  format:'mm-yy'
});

//Your form validation code here//

});
</script>


text:
Q: How is pixel data transferred from the GPU to the video memory? I wrote a test animation program that has 500 translucent ellipses floating randomly. The main purpose of this is to test the performance of a software vector graphics library. I get around 170 FPS, which is good enough.
First I draw the whole frame in plain memory. Then I need a way to transfer this data to the video memory that the monitor accesses. It would be nice and simple to memcpy to the video memory directly, but no modern operating system will allow this. I can think of 2 options here.
The first one is to use the system blitting function, such as BitBlt in Windows or XPutImage in Unix systems.
The second is to copy the whole frame to the GPU as an OpenGL texture, and then draw the whole texture to the screen.
I tested both using the equivalent SDL wrappings. The performance in speed is nearly the same, as most of the time is spent on creating the frame to be drawn.
One noticeable difference is that going through the GPU produces a lot more smoother result. I see not 0 but less tearings. One possible reason I can think of is that maybe the moving of pixels from the GPU to the video memory is treated specially for maximum speed, differently from normal memory copying, so that the screen appears more 'instantly'.
So back to the title of this question, how is pixel data transferred from the GPU to the video memory? Is it just like a simple call to memcpy or are there some special treatings applied? If so, what are those?


text:
Q: How to change the activity background from fragment inside it If I have activity that contains fragment, how to change the background color of the parent activity from fragment inside it ??

A: Use like this:
class Main extends FragmentActivity {
    public ImageView imageView;

    @Override
    protected void onCreate(Bundle arg0) {

        super.onCreate(arg0);
        setContentView(R.layout.main);
        imageView = (ImageView)findViewById(R.id.ivMain);
    }
}

class Demo extends Fragment {
    Main main;

    public void onAttach(Activity activity) {
        main = (Main) activity;
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        main.imageView.setBackgroundColor(color);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

}


text:
Q: How to derive FWHM of sinc function So this is probably a simple question, but I am unable to get my head around it. If we have $\operatorname{sinc}(2 \pi v L)$, what is the width of that $\operatorname{sinc}$ in terms of $v$ at half the maximum point.
Normally I'd just say that the maximum is $1$, thus half point is.... $1/2$
$$
\operatorname{sinc}(2\pi v L) = \frac{1}{2}
\\
\frac{ \sin(2 \pi vL) } { 2 \pi v L} =  \frac{1}{2}
\\
\sin(2\pi vL) = \pi v L
$$
EDIT: How can you analytically find this?
Thanks.

A: I cannot resist the pleasure of providing an approximate solution for $Lv \leq 1$. This approximation was made by Mahabhaskariya of Bhaskara I, a seventh-century Indian mathematician. $$\sin(x) \simeq \frac{16 (\pi -x) x}{5 \pi ^2-4 (\pi -x) x}\qquad (0\leq x\leq\pi)$$ So $$\frac{\sin(x)}x\simeq \frac{16 (\pi -x) }{5 \pi ^2-4 (\pi -x) x}$$ and for a value equal to $\frac 12$, the solution is given by $$x=\frac{\pi }{2}+\sqrt{16-(\pi -4) \pi }-4\approx 1.89477$$ while the exact solution would be $\approx 1.89549426$.
Equations which mix polynomial and trigonometric functions do not show explicit solutions and numerical methods (or sophisticated approximations) should be used.
The solution being close to $\frac{3\pi}5$, we can build the simplest Pade approximant of the left hand side and using exact values for the trigonometric function of the angle get $$x=\frac{250 \left(5+\sqrt{5}\right)+3 \pi  \left(100 \sqrt{10-2 \sqrt{5}}-3 \pi
   \left(-55+5 \sqrt{5}+3 \sqrt{2 \left(5+\sqrt{5}\right)} \pi \right)\right)}{500
   \sqrt{5+2 \sqrt{5}}+75 \left(9+\sqrt{5}\right) \pi -45 \sqrt{2
   \left(5+\sqrt{5}\right)} \pi ^2}$$ which is $\approx 1.89549416$
Edit
In a more general manner, if we expand $\frac{\sin(x)}x$ as its simplest approximant at $x=\theta$, the solution of $\frac{\sin(x)}x=\frac 12$ is given by $$x=\frac{-3 \theta ^2-\left(\theta ^2-2\right) \cos (2 \theta )+\theta  \sin (\theta )
   \left(\theta ^2+8 \cos (\theta )\right)-2}{\left(\theta ^2-2\right) \sin (\theta
   )-3 \theta +2 \sin (2 \theta )+2 \theta  \cos (\theta )-\theta  \cos (2 \theta )}$$ $\theta=\frac{29 \pi}{48}$ would have been a very good choice since the values of its trigonometric  functions are known (with many radicals).
Using it, the result would have been $\approx 1.89549427$

A: I don't think there is a closed form solution, so you would be better off finding it numerically. However, if you must, you can estimate it using a Taylor series:
$$
\frac{\sin(\pi L v)}{\pi L v } = a \\
\Rightarrow \pi L v = \arcsin( a \pi L v ) \\
\Rightarrow \pi L v \approx a \pi L v + \frac{1}{6}(a \pi L v)^3 + \frac{3}{40}(a \pi L v)^5 + \frac{5}{112}(a \pi L v)^7 + \cdots \\
\Rightarrow \cdots + \frac{5}{112}a^7( \pi L v)^6 + \frac{3}{40}a^5(\pi L v)^4 + \frac{1}{6}a^3( \pi L v)^2 + (a-1) = 0
$$
You can find the roots of the above polynomial to solve for $v$. All but two of them will be complex and those are the values you want. However, the Taylor series for $\arcsin(x)$ quickly diverges once $\vert x \vert$ moves away from zero and this error will lead to inaccurate estimates.


text:
Q: Use reduce and recursion in javascript to flatten nested array I have found this interesting code example which flattens an array using the recursion and reduce function instead of flat. I get what it does except the following:

*

*acc = acc.concat(flatWithRec(item)); why accumulator is being reassign? how is it possible in reduce function?
and why use concat here?

*return acc; why acc is being returned? is it a new Flat Array each time function is called?

*is there a way to, still, use recursion and make it easier for the reader to understand?
Please clarify

function flatWithRec(arr) {
  const flatArray = arr.reduce((acc, item) => {
    if (Array.isArray(item)) {
      acc = acc.concat(flatWithRec(item));
    } else {
      acc.push(item);
    }
    return acc;
  }, []);
  return flatArray;
}

console.log(flatWithRec([1, [2, 3, [4],
  [5, 6, [7]]
]]))
// output: [1, 2, 3, 4, 5, 6, 7])

A: *

*The accumulator is an array. You reassign it to give it the new array containing the items of the one you have at the beginning of the loop and the items of the array items to add. As said in the comments, acc.concat returns a new array containing the items of the arrays passed in parameter. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

*You need to return the accumulator at the end of each loop for the new value to be taken in account at the next loop.

*Javascript recursive array flattening

A: *

*acc = acc.concat(flatWithRec(item)); why accumulator is being reassign? how is it possible in reduce function? and why use concat here?

The accumulator (acc) is a function argument, and can be re-assigned, although it's not a good practice to do so. Concat combines two items (array or otherwise), and returns a new array, so you need to assign it to the acc as the result of the current loop.

*return acc; why acc is being returned? is it a new Flat Array each time function is called?

The accumulator holds the current state of the reduced items, in your case the current flat array after each loop. You need to return it, so the next loop can continue to accumulate.

*is there a way to, still, use recursion and make it easier for the reader to understand?

My take on flatWithRec - always concat, but if it's an array call flatWithRec on it before concatenating:

function flatWithRec(arr) {
  return arr.reduce((acc, item) =>
    acc.concat(
      Array.isArray(item)
        ? flatWithRec(item)
        : item
    ), []);
}

const result = flatWithRec([1, [2, 3, [4], [5, 6, [7]]]])

console.log(result) // output: [1, 2, 3, 4, 5, 6, 7])

A: So, the callback for the reduce method runs for every item in the array and whatever is returned from iteration x is passed as the first argument to iteration x+1. So, it is essential to make sure that during every iteration the correct state is returned.

acc = acc.concat(flatWithRec(item)) Why accumulator is being reassigned? How is it possible in reduce function? And why use concat here?

So, we are assigning acc the return value of concat because concat does not change the original array, it returns a fresh array. Accumulator is just like any other parameter so you can reassign. Not at all necessary to use concat (see my solution at the end using push and spread).

return acc; Why acc is being returned? Is it a new flat array each time the function is called?

As, already mentioned you need to return the correct state from the callback. And yes, during each iteration a new array is being created (which is not that performant, see my solution at the end)

Is there a way to still use recursion and make it easier for the reader to understand?

Easier for reader I can't tell, but here's my solution using => functions and spread.

const flatWithRec = (arr) =>
  arr.reduce((acc, item) => (
    Array.isArray(item) ? acc.push(...flatWithRec(item)) : acc.push(item), acc
  ), []);

console.log(flatWithRec([1, [2, 3, [4], [5, 6, [7]]]]));

A: Yes, there is a way to use recursion and make it easier to understand:

function f(A, i=0){
  return i == A.length ? [] : (Array.isArray(A[i]) ? f(A[i]) : [A[i]]).concat(f(A, i+1));
}

var A = [1, [2, 3, [4], [5, 6, [7]]]];

console.log(JSON.stringify(A));
console.log(JSON.stringify(f(A)));


text:
Q: Changing ConnectionString authorization method cause migration fail I've created project to read from MSSQL DB and display some data. VS's wizards created connection string like the following:
<add name="SomeContext" connectionString="data source=xxx.xxx.xxx.xxx\_name,port;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"  providerName="System.Data.SqlClient" />

When I tried to deploy application to the real web server I changed connection string to use faceless DB account:
<add name="SomeContext" connectionString="data source=xxx.xxx.xxx.xxx\_name,port;User Id=userid;Password=password; MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />

It looks like EF thinks that there some migration needed and tries to execute a lot of meaningless operations including attempts to execute SQL expressions with schema creating.
I have no write permissions on this DB server and I don't see any reasons to allow EF change DB structure.
So I'm completely lost there. What is the proper way to change authorization methods without changing on DB side?

A: Try to change connection string to production in VS project, then use Update-Database via Package Manager Console.

A: Pretty strange for me but the root of the issue was in default "initial catalog". It was stored somewhere for connection with integrated security but when I changed authorization method default was broken. As soon I defined initial catalog it was fixed.


text:
Q: MYSQL Workbench 5.2 CE, duplicate key error and constraint error in SQL script I keep getting a duplicate key error for trying to reference a primary key from another table, The script is shown below. I am trying to reference a primary key from a table called Session_and_fees_information. The table I am trying to reference from also has its own primary key. The main idea behind trying to include the foreign key is to establish a relationship between the table Arcade Machine Information and the table Session and fees information. The scripts along with the errors can be found below. I have used 4 different versions of workbench but the same error keeps coming up. The latest version, on the day I am writing this post, has also shown me the same problem.
ERROR 1022: Can't write; duplicate key in table 'arcade_machine_information'
SQL Statement:
CREATE  TABLE `retro club`.`Arcade_machine_information` (
  `Machine_number` INT NOT NULL ,
  `Floor` INT NULL ,
  `Info_ID` VARCHAR(5) NULL ,
  `Game` VARCHAR(15) NULL ,
  `Year` YEAR NULL ,
  PRIMARY KEY (`Machine_number`) ,
  INDEX `Info_ID` (`Info_ID` ASC) ,
  CONSTRAINT `Info_ID`
    FOREIGN KEY (`Info_ID` )
    REFERENCES `retro club`.`session_and_fees_info` (`Info_ID` )
    ON DELETE NO ACTION
    ON UPDATE CASCADE)

Is there a method for me to get rid of this error? If there is, please help.