text:
Q: Is $(A_1,A_2,\dots ,A_n, \dots)$ where $n \in ℕ^*$ a legit sequence? the comments on this post says

$\mathbb N$ is not a sequence

I guess it is because set $\mathbb N$ does hot have an order with its element.
so, if I put an order on each element of that, to construct this
$(A_1,A_2,\dots ,A_n, \dots)$
$A_1 = 1, A_2 = 2, ..., A_n = n, ...$ where $n \in ℕ^*$ (positive integers)
Is $(A_1,A_2,\dots ,A_n, \dots)$ a legit sequence?

A: From what I understand, they mean $\mathbb{Z}$ and $\mathbb{N}$ aren't sequences, because they're just sets of some elements, and sequences are functions from naturals to a set. So, while formally the set $\{1,2,3,...\}$ is not a sequence, $(1,2,3,...)$ (or $a_n=n$, or formally $\{(1,1),(2,2),(3,3),...\}$) is.
I see that comment as just nitpicking, formally $\mathbb{N}$ is not a sequence, because it's just a (unordered) set of distinct elements with no structure on them, but it becomes a sequence if we order, or number them.

A: By definition set doesn't have order. That means that $\{1,2,3\}=\{2,1,3\}$
So $\{0,1,2,3,4\dots\}=\{2,1,0,3,4,5,6...\}=\mathbb N$
However you can use another thing: ordered group - the set and a relation on it.  $<A,\prec>$, Where A - is a set, and $\prec$ is some relation. [< is a private example of $\prec$]
This relation must be an order relation. That means $a\nprec a$ and $a\prec b \land b\prec c\rightarrow a\prec c$
Your suggestion is nothing nut $<\mathbb N, \prec >$ where $\prec$ is <.
It's a good idea, but it is not a simple $\mathbb N$ set.


text:
Q: how to package a standalone xulrunner application I was wondering what I need to do to create an executable (.exe) file that will run my XUL application?
I'm trying to create an application using Mozilla's XUL format.

A: Here are the steps:

*

*Compress your application folder tree using WinZip.

*Rename the .zip file to have a .xpi extension. (i.e., myApp.xpi).

*Assuming you have xulrunner in your PATH, execute: xulrunner --install-app myApp.xpi.

On Windows, this installs your app to
c:\Program Files\<Vendor>\<Application Name>\<Application Name>.exe

Where  and  match exactly with what is in your application.ini file.
On Linux, the process is similar. On OS X, though, things are quite a bit different. I haven't completed mastered the OS X process yet.
See also Deploying XULRunner.

A: It is too bad that xulrunner can not run a zipped .xpi or .xulapp directly, but it is possible to package most of your .js, .xul, .css and .png files into a jar and wrap everything up with a private copy of xulrunner, without having to run --install-app
These are the steps I went through to package our XUL application.
The first step is to put all your files (except application.ini, chrome.manifest, and prefs.js) into a .jar file like this (all of this was carried out under Windows, make appropriate adjustments for Linux and OSX)
zip -r d:\download\space\akenispace.jar * -i *.js *.css *.png *.xul *.dtd

Then in d:\download\space, layout your files as follows:
D:\download\space\akenispace.jar
D:\download\space\application.ini
D:\download\space\chrome.manifest
D:\download\space\defaults
D:\download\space\defaults\preferences
D:\download\space\defaults\preferences\prefs.js

The content of the files are as follows. All three files need to be adjusted to reflect your own application.
application.ini
[App]
Vendor=Akeni.Technologies
Name=Akeni.Space
Version=1.2.3
BuildID=20150125
Copyright=Copyright (c) 2015
ID=space@akeni.com

[Gecko]
MinVersion=1.8
MaxVersion=35

chrome.manifest
content     akenispace             jar:akenispace.jar!/chrome/content/
skin        akenispace    default  jar:akenispace.jar!/chrome/skin/
locale      akenispace    en-US    jar:akenispace.jar!/chrome/locale/en-US/
resource    akenispace             jar:akenispace.jar!/chrome/resource/

prefs.js
pref("toolkit.defaultChromeURI", "chrome://akenispace/content/space.xul");

Now you can put these files into your .wxs for WiX and produce a MSI file for Wndows.
Of course you need to include all the files for XULRunner as well.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Semaphore value in function inside thread function inconsistent I've been learning how to use pthreads and mutexes, and am confused about the output of the following C code:
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>

void *TestThread(void *);
void TestFunc();

sem_t mutex;

int main(int argc, char *argv[]) {
    pthread_t tid;
    sem_init(&mutex, 1, 0);
    pthread_create(&tid, NULL, TestThread, NULL);
    pthread_join(tid, NULL);
}

void *TestThread(void *arg) {
    int val;
    sem_getvalue(&mutex, &val);
    printf("value of mutex in Thread function: %d\n", val);
    TestFunc();
    pthread_exit(NULL);
}

void TestFunc() {
    int val;
    sem_getvalue(&mutex, &val);
    printf("value of mutex in function in Thread function: %d\n", val);
}

I'm then compiling this like g++ -lpthread mutexTest.c -o mutexTest and running with ./mutexText, which gives and output like
value of mutex in Thread function: 0
value of mutex in function in Thread function: 1754151134

Why is the mutex value changing in the function that I call within the thread? Did I lose the reference to the mutex somehow?

A: I do not know why your code fails. Unfortunately for our present purpose, your code succeeds on my machine.
Until someone else posts a proper answer, if you would like to try a few debugging ideas with me, at your option, we can try the following.
1.
Try the suggestion of @AndrewHenle: "What is sem_getvalue() returning in both cases? If it's returning non-zero, what is errno?"
For information, on my machine (Debian GNU/Linux 9, GCC 6.3, Pthreads 2.24), it returns zero and errno is also zero.
2.
Try changing
sem_t mutex;

to
volatile unsigned char buffer_before_mutex[0x1000];
sem_t mutex;
volatile unsigned char buffer_after_mutex[0x1000];

Reason: if something is overwriting your mutex on the stack, this might give it some empty space to overwrite instead of trashing the mutex. Even if this works (and I suspect that it won't), it will not be right; but it might afford a clue as to what is going wrong with your code.
3.
(My answer may have been overtaken by comments. I leave the answer here in case part of it proves useful nevertheless.)


text:
Q: In custom gallery, On scrolling images repalcing I have create a custom gallery for selecting multiple photos in android . I am using AsynTask to set bitmap. When i am scrolling my screen, images replacing with next images and the setting to previous location.

A: public class CustomGallery extends Activity implements View.OnClickListener{
/**
 * Created by Ramesh on 04-Jan-16.
 */
private ImageAdapter imageAdapter;
private String[] arrPath;
private boolean[] thumbnailsSelection;
private int ids[];
private int count;
String imgDecode;
ArrayList<String> imageIdList = new ArrayList<String>();
final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.custom_gallery);

    System.out.println("MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE-->" + MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

    if (Integer.valueOf(Build.VERSION.SDK_INT)>=23) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {

            // Show an expanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.
            Log.i("Permission Log", " Permission Granted----> if cond");
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

        } else {

            // No explanation needed, we can request the permission.
            Log.i("Permission Log", " Permission Granted----> else cond");
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    }

    else{

        final String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID};
    Log.i( MediaStore.Images.Media.DATA, "Media Store Images.Media.Data");
    Log.i(MediaStore.Images.Media._ID, "Media Store Images.Media_id" );
    final String orderBy = MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC" ;

    Cursor imageCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null,
            orderBy );

    final int image_column_index = imageCursor.getColumnIndex(MediaStore.Images.Media._ID);
    imgDecode = imageCursor.getColumnName(image_column_index);
    this.count = imageCursor.getCount();
    this.arrPath = new String[this.count];
    ids = new int[count];
    this.thumbnailsSelection = new boolean[this.count];

    for (int i = 0; i < this.count; i++) {
        imageCursor.moveToPosition(i);
        ids[i] = imageCursor.getInt(image_column_index);
        int dataColumnIndex = imageCursor.getColumnIndex(MediaStore.Images.Media.DATA);
        arrPath[i] = imageCursor.getString(dataColumnIndex);
    }

    GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
    imageAdapter = new ImageAdapter();
    imagegrid.setAdapter(imageAdapter);
    imageCursor.close();

    final Button selectBtn = (Button) findViewById(R.id.selectBtn);
    selectBtn.setOnClickListener(this);

    Button cancelBtn = (Button) findViewById(R.id.cancelBtn);
    cancelBtn.setOnClickListener(this);

    }

}

@Override
public void onBackPressed() {
    super.onBackPressed();
    setResult(Activity.RESULT_CANCELED);

}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                Log.i(" Permission Log", " Permission Granted");
                final String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID};
                Log.i( MediaStore.Images.Media.DATA, "Media Store Images.Media.Data");
                Log.i(MediaStore.Images.Media._ID, "Media Store Images.Media_id" );
                final String orderBy = MediaStore.Images.Media._ID;

    Cursor imageCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy);
    //final int image_column_index = imageCursor.getColumnIndex(MediaStore.Images.Media._ID);
    final int image_column_index = imageCursor.getColumnIndex(MediaStore.Images.Media._ID );

    imgDecode = imageCursor.getColumnName(image_column_index);
    this.count = imageCursor.getCount();
    this.arrPath = new String[this.count];
    ids = new int[count];
    this.thumbnailsSelection = new boolean[this.count];

    for (int i = 0; i < this.count; i++) {
        imageCursor.moveToPosition(i);
        ids[i] = imageCursor.getInt(image_column_index);
        int dataColumnIndex = imageCursor.getColumnIndex(MediaStore.Images.Media.DATA);
        arrPath[i] = imageCursor.getString(dataColumnIndex);
    }

    GridView image_grid = (GridView) findViewById(R.id.PhoneImageGrid);
    imageAdapter = new ImageAdapter();
    image_grid.setAdapter(imageAdapter);
    imageCursor.close();

    final Button selectBtn = (Button) findViewById(R.id.selectBtn);
    selectBtn.setOnClickListener(this);

    Button cancelBtn = (Button) findViewById(R.id.cancelBtn);
    cancelBtn.setOnClickListener(this);

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Log.i("Permission Log", " else cond");
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

private void setBitmap(final ImageView iv, final int id) {

    new AsyncTask<Void, Void, Bitmap>() {

        @Override
        protected Bitmap doInBackground(Void... params) {
            return MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(), id,
                    MediaStore.Images.Thumbnails.MINI_KIND, null);
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            iv.setImageBitmap(result);
        }
    }.execute();
}

@Override
public void onClick(View v) {
    switch (v.getId()) {

        case R.id.selectBtn:
            final int len = thumbnailsSelection.length;

            String selectImages = "";
            int cnt = 0;
            for (int i = 0; i < len; i++) {
                if (thumbnailsSelection[i]) {
                    cnt++;
                    Log.i("Custom Gallery", "Inside for loop----->");

                    selectImages = selectImages + arrPath[i];
                    System.out.println("Array Path--" + arrPath[i]);
                    imageIdList.add(arrPath[i]);

                }

            }

            if (cnt == 0) {

                Toast.makeText(getApplicationContext(), "Please select at least one image", Toast.LENGTH_LONG).show();
            } else if (cnt > 5) {

                Toast.makeText(getApplicationContext(), "You can select only 5 images", Toast.LENGTH_LONG).show();

            } else {

               // System.out.println("My ListItem -->>" + imageIdList);
               /* Bundle bundel = new Bundle();
                bundel.putStringArrayList("key", imageIdList);
                Intent intent = new Intent(getApplicationContext(), AddVehicle.class);
                intent.putExtras(bundel);
                startActivity(intent);
                finish();*/

                Intent returnIntent = new Intent();
                returnIntent.putStringArrayListExtra("image-list", imageIdList);
                setResult(Activity.RESULT_OK, returnIntent);
                finish();

            }
            break;

        case R.id.cancelBtn:
            onBackPressed();
            break;

    }
}

public class ImageAdapter extends BaseAdapter {
    private LayoutInflater mInflater;

    public ImageAdapter() {
        mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
        return count;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;

        /*if (convertView == null) {*/

            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.gallery_item, null);
            holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
            holder.checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);

            convertView.setTag(holder);
       /* } else {

            holder = (ViewHolder) convertView.getTag();
        } */

        holder.checkbox.setId(position);
        holder.imageview.setId(position);
        holder.checkbox.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                CheckBox cb = (CheckBox) v;

                int id = cb.getId();
                if (thumbnailsSelection[id]) {
                    cb.setChecked(false);
                    System.out.println("if thumbnail selection");
                    thumbnailsSelection[id] = false;
                } else {
                    System.out.println("else thumbnail selection");
                    cb.setChecked(true);
                    thumbnailsSelection[id] = true;
                }
            }
        });

        holder.imageview.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                int id = holder.checkbox.getId();
                if (thumbnailsSelection[id]) {
                    Log.i("Custom Gallery", "if image click----->");

                    holder.checkbox.setChecked(false);
                    thumbnailsSelection[id] = false;
                } else {
                    Log.i("Custom Gallery", "if image not clicked----->");

                    holder.checkbox.setChecked(true);
                    thumbnailsSelection[id] = true;

                }
            }
        });

        try {

            setBitmap(holder.imageview, ids[position]);

        } catch (Throwable e) {
            Log.i(e.getMessage(), "Exception:");
        }
        holder.checkbox.setChecked(thumbnailsSelection[position]);
        holder.id = position;

        return convertView;
    }
}

class ViewHolder {
    ImageView imageview;
    CheckBox checkbox;
    int id;
}

}


text:
Q: Scrape number of tweets for certain Twitter accounts I need to scrape the exact number of tweets that are generated under certain Twitter accounts on a daily basis. As well as the number of followers.
As far as I know Twitter's streaming API is not complete.
Does anyone know a suitable source - not necessarily from Twitter. I am already scraping from Topsy but I could not figure out yet how to limit the displayed tweets to only a single account. I do not even need the content but only the number of generated tweets and the number of followers.
Thank you!!!

A: There are several python modules that can be used.
Here is how you could go about getting a list of followers with Twython
(from: How to get twitter followers using Twython?)
from twython import Twython

twitter = Twython()
followers = twitter.get_followers_ids(screen_name = "ryanmcgrath")

for follower_id in followers:
    print "User with ID %d is following ryanmcgrath" % follower_id


text:
Q: phantomjs - page.onError - trace is always an empty object? In the documentation of phantomjs they say the following:
Error Handling
To easily catch an error occured in a web page, whether it is a syntax error or other thrown exception, an onError handler for the WebPage object has been added. An example on such a handler is:
page.onError = function (msg, trace) {
    console.log(msg);
    trace.forEach(function(item) {
        console.log('  ', item.file, ':', item.line);
    })
}

Now if the page opens a site with some JavaScript exceptions, a detailed information (including the stack trace) will be printed out.
Well, I have created a few 'broken' pages (pages where the javascript causes an exception) and I get
the error that gets thrown but nothing in the trace
Can somebody help ?
Here is an example of a case I had:
html:
<!docType>

script: broken.js
1. // this script is broken at line 5.
2. //
3. var i=20;
4.
5. i = somethingThatDontExist
6.
7. // we will never be here...
8.

A: You probably missed something in your test settings but everything works fine. You maybe forgot that phantomJS calls are asynchronous.
Here is my test settings:
test.html
<!docType>

broken.js
var i = 20;
i = somethingThatDontExist;

testError.js
var page = require('webpage').create();
page.onError = function (msg, trace) {
  console.log(msg);
  trace.forEach(function(item) {
    console.log(' ', item.file, ':', item.line);
  })
}
page.open('test.html',function(){phantom.exit()});

A: This is an old question but still an issue (I ran into this recently).  The OP was probably using an older version.
A few things to check...
1) The API for console.log has changed between phantomjs 2.1.1 and 2.5.0.  In 2.5.0 console.log only prints the first argument (in 2.1.1 it would print all).
To be safe try building a string first and logging that as a single argument just to make sure this isn't just a logging issue.  ie console.log(concatenatedString) not console.log(var1, var2, var3,...)
Use JSON.stringify(object) if you want to concatenate your objects and arrays.
2) In my experience phantomjs is inconsistent about how it captures errors in the page context.
For instance if (in the page) a javascript catchblock does a console.log('message', error), the phantomjs page.onConsoleMessage callback will get a string for the message and a string "[object Object]"...so any data about the error contained within that object is lost between the page context and phantomjs.
(console.error might have different behaviour than console.log, but I didn't test it.)
3) page.onError is broken in phantomjs 2.5.0 at the moment.  It never gets called, instead errors show up in page.onConsoleMessage but miss the error object (see #2).
Use phantomjs 2.1.1 for now if you really need to know if there is a javascript error on page.
See the below bug for repro code that illustrates the differences between 2.1.1 and 2.5.0 when it comes to page.onError, page.onResourceError and page.onConsoleMessage.
https://github.com/ariya/phantomjs/issues/14776


text:
Q: Adding a datetime column in pandas dataframe from minute values I have a data frame where there is time columns having minutes from 0-1339  meaning 1440 minutes of a day. I want to add a column datetime representing the day 2021-3-21 including hh amd mm like this 1980-03-01 11:00 I tried following code
from datetime import datetime, timedelta
date = datetime.date(2021, 3, 21)
days = date - datetime.date(1900, 1, 1)
df['datetime'] = pd.to_datetime(df['time'],format='%H:%M:%S:%f') +  pd.to_timedelta(days, unit='d')

But the error seems like descriptor 'date' requires a 'datetime.datetime' object but received a 'int'
Is there any other way to solve this problem or fixing this code? Please help to figure this out.
>>df
time
0
1
2
3
..
1339

I want to convert this minutes to particular format 1980-03-01 11:00 where I will use the date 2021-3-21 and convert the minutes tohhmm part. The dataframe will look like.
>df
datetime               time
2021-3-21 00:00         0
2021-3-21 00:01         1
2021-3-21 00:02         2
...

How can I format my data in this way?

A: Let's try with pd.to_timedelta instead to get the duration in minutes from time then add a TimeStamp:
df['datetime'] = (
        pd.Timestamp('2021-3-21') + pd.to_timedelta(df['time'], unit='m')
)

df.head():
      time            datetime
0        0 2021-03-21 00:00:00
1        1 2021-03-21 00:01:00
2        2 2021-03-21 00:02:00
3        3 2021-03-21 00:03:00
4        4 2021-03-21 00:04:00

Complete Working Example with Sample Data:
import numpy as np
import pandas as pd

df = pd.DataFrame({'time': np.arange(0, 1440)})

df['datetime'] = (
        pd.Timestamp('2021-3-21') + pd.to_timedelta(df['time'], unit='m')
)
print(df)


text:
Q: 1004 Read-Only Error when Opening Closed Workbooks in VBA To give context to the problem that I'm facing - keep in mind I'm a relative novice - I am attempting to write a code that will open and then close a series of workbooks all contained within a folder, ultimately in order to update a number of VLookups on the master data sheet (since to update them, I believe the dependents need to be open).
Right now, I'm simply attempting to do this for one of the files which I can then go through and do for the rest of the folder. When I do attempt to open the file though, I get the "Run-Time Error 1004" with the message "Excel cannot access 'FolderName'. The document may be read-only or encrypted"
The code I'm using is:
sub openevery_v2()
' openevery_v2 Macro
' Keyboard Shortcut: Ctrl+Shift+O

' Dim diaFolder As FileDialog <-- Ideally the user would use a dialog box to select the folder
' Dim Fname As String
' Dim originalWB As Workbook
' Set originalWB = ThisWorkbook
' originalWB.Save
' Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
' diaFolder.AllowMultiSelect = False
' diaFolder.Show
' Fname = diaFolder.SelectedItems(1)

Fname = "C:\FolderPath"
Openr = Dir(Fname + "Filename.xlsm")
Workbooks.Open (Fname)

End Sub

I've tried to change the settings of the folder from non-read only, but I don't think that is the issue at hand.
Has anyone run through a similar issue or can think of a solution to this particular issue? Alternatively, if there is a better way to think through this challenge, that would be much appreciated.

A: Your code is trying to open a file named c:\FolderPathFilename.xlsm. Unless that file exists in the root of your C: drive, you'll get errors.
This may be more of what you're after:
Fname = "C:\FolderPath\"
Openr = Dir(Fname & "Filename.xlsm")
Workbooks.Open (Fname)

Notice:

*

*the \ added to the end of Fname.

*The + is replaced with a &. VBA uses & for concatenation.

Of course, your code sample does seem to be a very cut-down version of what you're really executing, so that may not be the problem in your real code.


text:
Q: How to replace a row in file (if statment) I want to create a file that if a statment is true then give to the line the value '1', if not the value '0'.At the start I'm giving vaue 0 and then if true i have to replace with '1'. This must be inside a for loop and every time check the statment as the code below.
     import java.io.BufferedReader;
     import java.io.File;
     import java.io.FileReader;
     import java.io.FileWriter;
     import java.io.IOException;
     import java.io.PrintWriter;
     import java.util.logging.Level;
     import java.util.logging.Logger;

     public class Main {
            public static void main(String[] args) {
            File F=new File("D:\\File.txt");
        try {
        F.createNewFile();
        BufferedReader br = new BufferedReader(new FileReader(F));
        PrintWriter pw = new PrintWriter(new FileWriter(F));
        for (int i=0;i<5;i++){
            pw.println(0);
            for ( int j=0;j<10;j++){
               if(i==2)     {   //sample if statment
                   pw.write("1");
                   pw.flush();    }
               if(j==3&&i==3)     {   //sample if statment
                   pw.write("1");
                   pw.flush();    }
                         }
                  pw.write("\n");
                   }
           pw.close();
           br.close();
           } catch (IOException ex) {
          Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                        }

Here i have 2 if statments that are true. So the file have to be like that:
              0   //0 because i != 2 or i!=3 & j!=3
              0   //0 because i != 2 or i!=3 & j!=3
              1   //1 because i == 2
              1   //1 because i==3  & j==3
              0   //0 because i != 2 or i!=3 & j1=3

Now this that I'm getting from my code is:
              0
              0
              0
              11111111110
              10

A: When i==2, it prints a 0 and a new line (like hitting Enter).
Then it enters the inner loop by j, which execute 10 times. Every time because i is 2, it prints 1 on the same line. That's why you have the 10 1's.
Then it loops around to get to i==3, and prints another 0 and a new line.
Then when the inner loop gets to j==3 it prints that 1.
[Edit]
The debugger is your friend!

A: *

*why do you execute pw.println(0); with every iteration of your outer loop?

*what is the difference between pw.println(0); and pw.write("1");?


text:
Q: Regular Expressions find all values inside asterisk i need to find all values that resides between two asterisk symbol *data1* *data2* *data3* *data4* *data5*how do i set Regular Expression in java for this particular string.
i tried indexof ..but it ain't  work

A: this works fine...
String pattern = "\*([^*^\s*$]+)\*";
Pattern pt = Pattern.compile(pattern);
Matcher mat = pt.matcher(data);

A: To find only the values (without the asterisks). (Not find values completely blank):
(?<=\*)(\s*[^*\s]+\s*)


text:
Q: Proximal operator inequality under strong convexity assumption Define the prox operator associated to a closed, convex, proper function $f$, $\operatorname{prox}_f(x)$ to be
$$\operatorname{prox}_f(x) = \arg\min\limits_{u}\left\{f(u) + \frac{1}{2}\|x-u\|^2\right\}$$
We have the following inequality given $y = \operatorname{prox}(x)$, for each $u$,
$$f(y) - f(u) +\frac{1}{2}\|y-u\|^2 + \frac{1}{2}\|y-x\|^2\leq \frac{1}{2}\|u-x\|^2$$
This can be derived using the definition of the prox operator and the fact that $f(\cdot) + \frac{1}{2}\|\cdot-x\|^2$ is strongly convex with respect to $\frac{1}{2}\|\cdot-x\|^2$. What if $f$ itself is strongly convex with respect to $\frac{1}{2}\|\cdot\|^2$? How does the inequality improve?
To prove the inequality above we do the following. Let $y=prox(x)$, then
$$0\in \partial\left(f(\cdot) + \frac{1}{2}\|\cdot-x\|^2\right)(y)$$
We have that $g(u) = f(u) + \frac{1}{2}\|u-x\|^2$ is strongly convex w.r.t. $\frac{1}{2}\|u-x\|^2$ since $f(u) + \frac{1}{2}\|u-x\|^2 - \frac{1}{2}\|u-x\|^2 = f(u)$ is convex. By this strong convexity of $g(u)$ we have
$$g(u) - g(u^*) \geq \frac{1}{2}\|u-u^*\|^2$$
where $u^*$ is the minimizer of $g$. Since $y$ is exactly $u^*$, we get, for any u
$$g(u) - g(y) \geq \frac{1}{2}\|u-y\|^2\\ f(u) + \frac{1}{2}\|x-u\|^2 - f(y) - \frac{1}{2}\|y-x\|^2 \geq \frac{1}{2}\|u-y\|^2\\ \implies f(y) - f(u) +\frac{1}{2}\|u-y\|^2 + \frac{1}{2}\|y-x\|^2\leq \frac{1}{2}\|x-u\|^2$$

A: Based on the comment of gerw, here is the final result. Let $\lambda > 0$, assume that $f(\cdot)-\frac{m}{2}\|\cdot\|^2$ is convex, and let $y=prox_{\lambda f}(x)$, then for all $u$ it holds
$$f(y) - f(u) +\frac{m + \lambda^{-1}}{2}\|u-y\|^2 + \frac{\lambda^{-1}}{2}\|y-x\|^2\leq \frac{\lambda^{-1}}{2}\|u-x\|^2.$$
To see it, denote $g(u) := \lambda f(u) + \frac{1}{2}\|u-x\|^2$ and notice by definition of the prox that
$$0\in \partial g(y).$$
We have that $g(u)$ is $(\lambda m+1)$-strongly convex w.r.t. $\frac{1}{2}\|u-x\|^2$. By this strong convexity of $g(u)$ we have
$$g(u) - g(y) \geq \frac{\lambda m + 1}{2}\|u-y\|^2$$
where we have used the fact that $0\in\partial g(y)$ to eliminate a linear term. Substituting the definition of $g$ we get, for any u,
$$g(u) - g(y) \geq \frac{\lambda m + 1}{2}\|u-y\|^2\\ \lambda f(u) + \frac{1}{2}\|u-x\|^2 - \lambda f(y) - \frac{1}{2}\|y-x\|^2 \geq \frac{\lambda m + 1}{2}\|u-y\|^2\\ \implies f(y) - f(u) +\frac{m + \lambda^{-1}}{2}\|u-y\|^2 + \frac{\lambda^{-1}}{2}\|y-x\|^2\leq \frac{\lambda^{-1}}{2}\|u-x\|^2.$$
And so there is an additional $\frac{m}{2}\|u-y\|^2$ term on the left hand side that pops up when $f$ is $m$-strongly convex with respect to $\frac{1}{2}\|\cdot\|^2$.


text:
Q: Are there any command line utilities that can capture joystick button presses? Here's my situation: I have a Raspberry Pi with Raspbian installed on it. I also have RetroArch installed and a simple USB gamepad hooked up. Everything works fine, but I wanted to set it up so that pressing a key combination (ex L1+L2+R1+R2) would gracefully exit the emulator so that I don't have to keep a keyboard around. RetroArch's default key to gracefully exit is ESC, and I can't remap it to a key combination due to a limitation in RetroArch (I could, however, remap it to a single gamepad key).
So I was wondering if there were any utilities out there that could listen to the gamepad's key presses and, when a certain combination is pressed, performs an action (sending the ESC key to the emulator). Or is there an easier way to achieve what I want and I'm just being silly?
EDIT:  Now that I think about it, it would also be nice if I could have a different key combination execute a bash script that starts the emulator so that I could start it without a keyboard as well.

A: Give jstest a try. This article discusses its use, titled: flightgear.org - Input device. Appears to be installed by default in most distros. Also, here's a link to the jstest man page.
Basically you have to determine what device the joystick is being assigned. Look in the dmesg log file after you plug it in to get this info. Might be something like /dev/input0.
$ dmesg | grep Joystick
input0: USB HID v1.00 Joystick [SAITEK CYBORG 3D USB] on usb2:3.0

Then run this command:
$ jstest /dev/input0

A: This looks like a common problem with RetroPie/Emulation station.
They address it in the RetroPie-Setup Wiki:
https://github.com/petrockblog/RetroPie-Setup/wiki/EmulationStation#my-emulator-wont-close-through-my-gamepad
It should just require editing your RetroArch config file to add a line:
input_exit_emulator_btn = "6″

Where "6" is the gamepad button identifier.

If you want to make it work with a key combination, you can instead add the following lines: (from http://forum.themaister.net/viewtopic.php?pid=1065#p1065)
input_enable_hotkey_btn = 1
input_exit_emulator_btn = 2

This makes it so that you need to press button 1 to "unlock" hotkeys, and press 2 at the same time to quit.

A: Put this in you .rc file (.bashrc if you are a bash user, then source .bashrc).
joyst () {
    js='/dev/input/js0'
    jscal  $js
    jstest $js
}


text:
Q: How to start from the smallest digit? I was self studying on my Arithmetic and I encounter a problem. My goal is to find the least number not the greatest. I'm quite confused.
Example output
Enter n: 42123647
Smallest digit = 7

Program
#include<stdio.h>

int main(){
    int num1, num2, num3=0;
    printf("Enter n: ");
        scanf("%d", &num1);
        while(num1>0){
            num2 = num1 % 10;
            if(num3<num2){
                num3=num2;
            }
            num1 = num1 * 10;
        }
        printf("Smallest digit = %d",num3);

  return 0;
}

A: On systems where sizeof (int) is 4, the statement
num1 = num1 * 10;

will quickly (within two iterations) cause signed integer overflow when the input is 42123647, as INT_MAX is 2147483647
The behaviour of this program is undefined when this occurs.

After retrieving the least significant digit with % 10, try dividing your input by 10.
Additionally, you want to check that your current digit is less than your current minimum value, and initialize your minimum value to a value greater than or equal to the maximum possible value.
#include <stdio.h>

int main(void) {
    int input;
    int min = 10;

    printf("Enter n: ");

    if (1 != scanf("%d", &input)) {
        fprintf(stderr, "Invalid input.\n");
        return 1;
    }

    while (input > 0) {
        int digit = input % 10;

        if (digit < min)
            min = digit;

        input /= 10;
    }

    printf("Smallest digit = %d\n", min);
}

A: As already mentioned you want to use division (instead of multiplication) to move to the next digit.
Also use a bottom-tested loop so that the case of just entering a zero as the number works correctly. A bottom-tested loop guarantees at least one pass through the loop.
The following code works as long as a proper number is entered. The %d format specifier, used with scanf, will essentially ignore a leading zero (i.e. if 0123 is entered then the smallest digit will be 1 instead of 0).
/* find a number's smallest digit

*/

#include <stdio.h>

int main (void)
{
    printf("\n");
    printf("enter n: ");
    int number;
    scanf("%d", &number);

    int smallestDigit = 9;
    do {
        int currentDigit = number % 10;
        if (currentDigit < smallestDigit) {
            smallestDigit = currentDigit;
        }
        number /= 10;
    } while (number > 0);
    printf("\n");
    printf("smallest digit = %d\n", smallestDigit);

    return 0;
}

A: A char array (string) based solution in case your input is too large and overflows the variable as mentioned in other answers.
#include <stdio.h>
#include <ctype.h>

int isNumeric(char *str);

int main(void) {
    char *input;
    int min = 9;
    int digit;

    printf("Enter n: ");
    input = inputString(stdin,10); // explained later in answer
    if( isNumeric(input) == 0 ) {
        printf("Not a number.\n");
        return 0;
    }

    for( int i = 0; input[i] != '\0'; i++) {
        digit = input[i] - '0'; // ascii values
        if (digit < min)
            min = digit;
    }

    printf("Smallest digit = %d\n", min);
}

int isNumeric(char *str) {
    if( str[0] == '\0' )
        return 0;
    for( int i = 0; str[i] != '\0'; i++) {
        if( !isdigit(str[i]) )
            return 0;
    }
    return 1;
}

Important
inputString(stdin,10) is a function call from a function implementation that exist in this stack overflow question C-read-variable-length-input.


text:
Q: Git files in Qt creator Sooo, I've been trying to use Qt creator and QGroundControl Open source repository and while trying to build my qgroundcontrol.pro file, the "Issues" bar shows this weird message:

unknown option: -
usage: git [-v | --version] [-h | --help] [-C <path>] [-c <name>=<value>]
           [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
           [-p | --paginate | -P | --no-pager] [--no-replace-objects] [--bare]
           [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
           [--super-prefix=<path>] [--config-env=<name>=<envvar>]
           <command> [<args>]

Basicaly I think this is about not beeing able no read git files and it messing up the build.
Has this happen to anyone or am I just this lucky ? (:
I´ve tried searching for help and see the documentation for both Qt creator and QGroundControl and none have anything about this


text:
Q: Why is this formula valid in PDL In the book modal logic for open minds by johan van benthem there is on page 161 a statement that the sentence $\langle (R\lor S)^* \rangle \phi$ is equivalent to the sentence $\langle (R^* ; S^*)^* \rangle \phi$
(* means iteration and ; means composition here)
So:
$\langle (R\lor S)^* \rangle \phi \equiv \langle (R^* ; S^*)^* \rangle \phi$
Why is this equivalent to each other?

A: Suppose that for some arbitrary $M_w$ it holds that $M_w \models \langle (r \cup s)^\ast \rangle \varphi$. By the semantics this means that $\exists v \in W^M$ such that $M_{w,v} \models (r \cup s)^\ast$ and $M_v \models \varphi$. Now let us consider $M_{w,v} \models (r \cup s)^\ast$. According to the semantics, there is an $r \cup s$ path (which may be empty) between $w$ and $v$. Expression $r \cup s$ means that every step of the path may be either an $r$-step or an $s$-step. Examples of such paths are the empty path, $r$, $s,s$, $r,s,r,s,s,r$ and so on. Now we notice that the same paths can be described by the regular expression $(r^\ast;s^\ast)^\ast$. Moreover, we could construct automata for recognising $(r \cup s)^\ast$ and $(r^\ast;s^\ast)^\ast$, and see that they are equivalent. Therefore, we have that $M_{w,v} \models (r^\ast;s^\ast)^\ast$ and $M_v \models \varphi$, and hence $M_w \models \langle (r^\ast;s^\ast)^\ast \rangle \varphi$.


text:
Q: Save to a custom photo folder IOS 7.1 Is there a way to disable the "Saved Photos" folder when saving an image?
NSData *data1 = UIImagePNGRepresentation(imageToCrop.image);
        UIImage *tehnewimage = [UIImage imageWithData: data1];
        [self.library saveImage:tehnewimage toAlbum:@"Databender Edits"     withCompletionBlock:^(NSError *error) {
            if (error!=nil) {
                NSLog(@"eRrOr: %@", [error description]);
            }
        }];

A: If you are using ALAssetsLibrary to manage your apps photos, then they will always show under saved photos. According to the Apple Docs the purpose of ALAssetsLibrary is
You use it to retrieve the list of all asset groups and to save images and videos into the Saved Photos album.

If you only need your images accessible inside your app you can handle the reading writing, and presenting of them yourself. This would prevent them from showing up in the camera role or saved photos.
 //WRITING TO APP DIRECTORY
 NSString *directory = [NSHomeDirectory() stringByAppendingPathComponent:@"Photos/"];

if (![[NSFileManager defaultManager] fileExistsAtPath:directory]){
    NSError* error;
    [[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:&error];
}
NSData *imgData = UIImagePNGRepresentation(imageToCrop.image);
NSString *imgName = @"example.png";
NSString  *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:imgName];
[imgData writeToFile:pngPath atomically:YES];

//READING FROM APP DIRECTORY
NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"/Photos/"] error:NULL];
for (int i = 0; i < (int)[directoryContent count]; i++)
{
    NSURL *url = [NSURL URLWithString:[NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/Photos/%@",[directoryContent objectAtIndex:i]]]];
    UIImage *image = [UIImage imageWithContentsOfFile:[url absoluteString]];
    //ADD IMAGE TO TABLE VIEW OR HANDLE HOW YOU WOULD LIKE
}


text:
Q: std::string, difference between string val and string val = "" I am trying to pass an std::string as a default argument to a function.
I'm trying like follows
void string_fun(int i, string val = "", int j = 10)
// void string_fun(int i, string val, int j = 10) // <-- error since no default value
{
    cout << "values " << endl;
    cout << "i: " << i << endl;
    cout << "val: " << val << endl;
    cout << "j: " << j << endl;
}

void ret_fun()
{
    string fun;
    cout << "values " << endl;
    cout << "fun: " << fun << endl;
}

int main()
{
    string_fun(3);
    ret_fun();
    return 0;
}

I heard that the default constructor of a string will initialize the string, if that is correct what will be the value of that? See here if I'm using only string val as the argument to the function, I'll  get compilation error. But when I print the string both val and fun I'm getting the same output. My question is what make the two string different in case of their values, since string val = "" also creates a blank string.

A: You are looking at an argument list for a function, the rules are therefore different. It doesn't matter that std::string has a default constructor.
The point is that the language's rules for argument lists make sure that you allow or disallow a caller to omit parameters from the call. When a default value is given, the caller may omit the parameter and the default values is used instead. Without a default value, the caller must supply an appropriate parameter.
If you leave out the default value of the second parameter, your call
string_fun(3);

does not compile as it requires at least two parameters. You could even use the default constructor in the call:
string_fun(3, string());


text:
Q: C++: Trying to encapsulate std::enable_if in class I was just using SFINAE to select function templates when I had the glorious idea to encapsulate std::enable_if in a struct like this
template<typename T, typename U>
struct EnableWhenEqual
{
    typedef typename std::enable_if<std::is_same<T, U>::value>::type type;
};

and then use it, for example, like this
template<typename T, typename U, typename Enable = EnableWhenEqual<T,U>::type >
void foo(T&& t, U&& u)
{
    if (std::is_same<T,U>::value)
        std::cout << "OK, overload allowed." << std::endl;
    else
        std::cout << "Bad. Should not compile!" << std::endl;
}

However, this doesn't work, as one sees by invoking
foo(1,1);     //prints "OK, overload allowed"
foo(1,2.0);   //prints "Bad, should not compile", but obviously does

On the other hand, by trying to create
EnableWhenEqual<int,int>();      //compiles
EnableWhenEqual<int,double>();   //does not compile because type does not exist

one obtains a compiler error ("type is not a member of std::enable_if").
What is the reason for this behaviour? I'm asking because from my little SFINAE knowledge I would have thought that an error in the type-deduction leads to exclusion of the overload ... ?

For completeness, the above problem can be solved using template aliasing
template <typename T, typename U>
using EnableWhenEqual = typename std::enable_if<std::is_same<T,U>::value>::type;

Is there also an alternative using a struct instead of a template alias?
EDIT: Here I mean an implementation which solves the general problem. For example, this here
template<typename T, typename U, bool B, typename C=void>
struct EnableWhenEqual {};

template<typename T, typename U, typename C>
struct EnableWhenEqual<T,U,std::is_same<T,U>::value>
{
    typedef typename C type;
};

don't works for me because the partial specialization needs a simple identifier. If it would, one could replace std::is_same by general structs Condition<T,U>. Any alternatives?

A: This should do the trick:
template<typename T, typename U>
struct EnableWhenEqual : std::enable_if<std::is_same<T, U>::value>
{
};

http://coliru.stacked-crooked.com/a/650202ba3d42d34b

A: A different kind of encapsulation:
template<class T, class U>
using EnableWhenEqual_t = typename std::enable_if< std::is_same<T,U>::value >::type;

template<typename T, typename U, typename Enable = EnableWhenEqual_t<T,U> >
void foo(T&& t, U&& u) {
  if (std::is_same<T,U>::value)
    std::cout << "OK, overload allowed." << std::endl;
  else
    std::cout << "Bad. Should not compile!" << std::endl;
}

note when you are asking questions about VS treatment of templates, please include the exact visual studio version.  VS template support is extremely quirky.


text:
Q: Cannot convert html content of a data frame in to text I have a column with HTML values in a data frame like below.
print(df['Body'])

0    <html><head>\r\n<meta http-equiv="Content-Type...
1    <html xmlns:v="urn:schemas-microsoft-com:vml" ...
2    <html>\r\n<head>\r\n<meta http-equiv="Content-...
3    <meta http-equiv="Content-Type" content="text/...
Name: Body, dtype: object

But when I going to convert them in to a plain text like below.
from selectolax.parser import HTMLParser
from bs4 import BeautifulSoup

soup = BeautifulSoup(df['Body'])
print(soup.get_text())

But I am ending up with below error.How should I improve this code to get the converted plain text of whole column?
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-44-4c34d2bd9f1f> in <module>
----> 1 soup = BeautifulSoup(df['Body'])
      2 print(soup.get_text())

~\anaconda3\lib\site-packages\bs4\__init__.py in __init__(self, markup, features, builder, parse_only, from_encoding, exclude_encodings, element_classes, **kwargs)
    251         if builder is None:
    252             builder = builder_class(**kwargs)
--> 253             if not original_builder and not (
    254                     original_features == builder.NAME or
    255                     original_features in builder.ALTERNATE_NAMES

~\anaconda3\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
   1440     @final
   1441     def __nonzero__(self):
-> 1442         raise ValueError(
   1443             f"The truth value of a {type(self).__name__} is ambiguous. "
   1444             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

A: You need to use Series.apply to apply your parsing on each cell of the column. Here's an example, use your own logic in parse_cell method
from bs4 import BeautifulSoup

def parse_cell(content):
    return BeautifulSoup(content, features="html.parser").get_text()

df['plain'] = df['Body'].apply(parse_cell)
print(df)


text:
Q: Updating GFortran on Scientific Linux 7? I have a software application that requires updating GFortran to a newer version before making the program.  I updated gcc, but GFortran did not update.  This is on Scientific Linux 7.
$ gcc --version
gcc (GCC) 7.3.0

$ gfortran --version
GNU Fortran (GCC) 4.8.5 20150623 (Red Hat 4.8.5-11)

How do I get GFortran to update?  Even if it is just for this application?  I'm using yum.
Edit:  Searching for gfortran packages give the following:
$ sudo yum search all gfortran
Loaded plugins: langpacks
============================== Matched: gfortran ===============================
gcc-gfortran.x86_64 : Fortran support
compat-gcc-44-gfortran.x86_64 : Fortran support for compatibility compiler
compat-libgfortran-41.i686 : Compatibility Fortran 95 runtime library version
                           : 4.1.2
compat-libgfortran-41.x86_64 : Compatibility Fortran 95 runtime library version
                             : 4.1.2
libgfortran.i686 : Fortran runtime
libgfortran.x86_64 : Fortran runtime
libgfortran-static.i686 : Static Fortran libraries
libgfortran-static.x86_64 : Static Fortran libraries
mingw32-gcc-gfortran.x86_64 : MinGW Windows cross-compiler for FORTRAN for the
                            : win32 target
mingw64-gcc-gfortran.x86_64 : MinGW Windows cross-compiler for FORTRAN for the
                            : win64 target
When I try to install gcc-gfortran.x86_64, I get
$ yum install gcc-gfortran.x86_64
Loaded plugins: langpacks
Package gcc-gfortran-4.8.5-11.el7.x86_64 already installed and latest version
Nothing to do
It's stuck on the old version.
Edit 2:  Okay.  In order to get something newer to show up, I tried to install devtoolset-7.  It didn't show up in yum search, but the way to get the package available in Scientific Linux is this:
yum install yum-conf-repos
yum install yum-conf-softwarecollections
Now, devtoolset-7 shows up in yum search, but I get this output when trying to install:
$ sudo yum install devtoolset-7
...
--> Finished Dependency Resolution
Error: Package: devtoolset-7-gcc-gfortran-7.2.1-1.el7.sc1.x86_64 (softwarecollections)
           Requires: libgfortran4 >= 7.1.1-2
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest
But,
$ sudo yum search libgfortran4
Loaded plugins: langpacks
Warning: No matches found for: libgfortran4
No matches found

A: If the package manager installed is yum (I noticed it in your question's tags), you can use the following to update GNU Fortran to the latest version available:
$ yum update gcc-gfortran

A: Please edit as necessary.  And thank you Knud Larson for the reference repo packages.
In order for my version of to SL7 to even see a more recent version of GFortran to download, I attempted to install devtoolset-7.  In order to access devtoolset-7, I needed to use these SL7 commands
# yum install yum-conf-repos
# yum install yum-conf-softwarecollections
Then devtoolset-7 was available to install.  However, when attempting to install the package, libgfortran4 was not available.  In order to get everything to install, I downloaded the repo packages suggested by Knud Larson plus libgfortran from CentOS and installed the libgfortran4
# yum install ./libgfortran4-7.1.1-2.2.1.el7.x86_64.rpm
Then devtoolset-7 installed
# yum install devtoolset-7-gcc-gfortran.x86_64
And now it's working.  Thanks everyone.


text:
Q: Mocking behaviour resets after each test with PowerMock I'm writing unit tests using PowerMock, mocking behaviour of some util classes. Defining behaviour once for test class (by @BeforeClass annotation) causes:

*

*first test invocation to return mocked value

*second test invocation to return real method return value

Sample code:
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest( {A.class, B.class})
public class TestMockedMethods {

private static B b;

@BeforeClass
public static void setUp() {
    PowerMockito.mockStatic(A.class);
    PowerMockito.when(A.getVal()).thenReturn("X");

    b = PowerMockito.mock(B.class);
    PowerMockito.when(b.getVal()).thenReturn("Y");
}

@Test
public void test1() { // PASS
    Assert.assertEquals("X", A.getVal());
    Assert.assertEquals("Y", b.getVal());
}

@Test
public void test2() { // FAIL
    Assert.assertEquals("X", A.getVal()); // actual="A"
    Assert.assertEquals("Y", b.getVal()); // actual="B"
}

}
class A {
  static String getVal() {
    return "A";
  }
}
class B {
  String getVal() {
    return "B";
  }
}

Any ideas why second test is failing?

A: The method PowerMockito.mockStatic(...) invokes MockCreator.mock(...). This method regsiters a Runnable that will be executed after each test :
MockRepository.addAfterMethodRunner(new MockitoStateCleaner());

This runnable cleans the internal state of Mockito :
private static class MockitoStateCleaner implements Runnable {
    public void run() {
        clearMockProgress();
        clearConfiguration();
    }

    private void clearMockProgress() {
        clearThreadLocalIn(ThreadSafeMockingProgress.class);
    }

    private void clearConfiguration() {
        clearThreadLocalIn(GlobalConfiguration.class);
    }

    private void clearThreadLocalIn(Class<?> cls) {
        Whitebox.getInternalState(cls, ThreadLocal.class).set(null);
        final Class<?> clazz = ClassLoaderUtil.loadClass(cls, ClassLoader.getSystemClassLoader());
        Whitebox.getInternalState(clazz, ThreadLocal.class).set(null);
    }
}

So you should execute your setUp before each test.
@Before
public void setUp() {
    PowerMockito.mockStatic(A.class);
    PowerMockito.when(A.getVal()).thenReturn("X");

    b = PowerMockito.mock(B.class);
    PowerMockito.when(b.getVal()).thenReturn("Y");
}


text:
Q: What is $\overline{\partial} 1/z^2$? it is all in the title : what is $\overline{\partial} \frac{1}{z^2}$ in the sense of distributions ? I remember that $\overline{\partial} \frac{1}{z}$ is a dirac at 0, but I can't seem to find a way to deduce the result for $1/z^2$ from that. I also know that the support of $\overline{\partial} \frac{1}{z^2}$ is included in $\{0 \}$ so it's a dirac or a derivative of dirac. I was unable to find the proof.
EDIT : as pointed out, the question doesn't make sense since $1/z^2$ is not a distribution.


text:
Q: A Python Segmentation Fault? This generates a Segmentation Fault: 11 and I have no clue why.
Before I get into it, here's the code:
import numpy.random as nprnd
import heapq
import sys

sys.setrecursionlimit(10**6)

def rlist(size, limit_low, limit_high):
    for _ in xrange(size):
        yield nprnd.randint(limit_low, limit_high)

def iterator_mergesort(iterator, size):
    return heapq.merge(
         iterator_mergesort(
           (iterator.__next__ for _ in xrange(size/2)), size/2),
         iterator_mergesort(
            iterator, size - (size/2))
       )

def test():
    size = 10**3
    randomiterator = rlist(size, 0, size)
    sortediterator = iterator_mergesort(randomiterator, size)
    assert sortediterator == sorted(randomiterator)

if __name__ == '__main__':
    test()

Basically, it's just a mergesort that works on iterators and generator expressions instead of working on lists so as to minimize the memory footprint at any one time. It's nothing special, and uses the heapq.merge() built-in method for merging iterators, so I was quite surprised when everything breaks.
Running the code quickly gives Segmentation Fault: 11 and an error window telling me python has crashed. I have no idea where to look or how to debug this one, so any help would be much appreciated.

A: Segmentation Faults in python happen for one of two reasons:
You run out of memory
Bug in a C module
Here, the seg fault belongs to the first. You (I) have a boundless recursion because there is no base case in iterator_mergesort(), it'll keep calling itself on itself forever and ever.
Normally, python throws an exception for this and it will terminate before causing a segfault. However, the recursion limit has been set extremely high so python runs out of memory and breaks before it recognizes it should throw an exception for an unbounded recursion.
Add a base case like so:
...
def iterator_mergesort(iterator, size):
return heapq.merge(
         iterator_mergesort(
           (iterator.next() for _ in xrange(size/2)), size/2),
         iterator_mergesort(
            iterator, size - (size/2))
       ) if size >= 2 else iterator #<-- Specifically this

Now it passes the test() function and sorts, albeit rather slowly.


text:
Q: iPhone application to show nearby business offices into table view I want to make iPhone application that use GPS to show nearby places (particular business offices) into table view starting nearest office at top of the table.
Location coordinates will come using location manager but i want my application do above tasks
Any suggestion how to implement all these things or any tutorial.
Thank you in advance i really appreciate any sort of help.

A: Search the SDK documentation either from XCode or developer.apple.com and you'll find a bunch of white papers and samples relating to your questions.
Edited  to include samples...
http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/LocationAwarenessPG/Introduction/Introduction.html
http://developer.apple.com/library/ios/#documentation/CoreLocation/Reference/CLLocationManager_Class/CLLocationManager/CLLocationManager.html
http://developer.apple.com/library/ios/#documentation/CoreLocation/Reference/CLLocationManagerDelegate_Protocol/CLLocationManagerDelegate/CLLocationManagerDelegate.html
http://developer.apple.com/library/ios/#samplecode/LocateMe/Introduction/Intro.html%23//apple_ref/doc/uid/DTS40007801
http://developer.apple.com/library/ios/#samplecode/Locations/Introduction/Intro.html%23//apple_ref/doc/uid/DTS40008406
http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MapKit_Framework_Reference/_index.html
All found with a simple search in the apple developer website, can't imagine what else you might need at this stage.


text:
Q: Specman / E "UML like" took tool to generate a Class diagram. Do you know? I am looking for a tool that can generate Class diagram (UML style) of specman / E programming language.
I search in the web and couldn't find any.
Does anyhow have some insight on this matter?
Thanks

A: As far as I know, "eDoc" is the Specman documentation extraction tool.  If it doesn't have UML class diagrams, then no one does.  eDoc is using the javadoc tool to automatically document the code, so if someone can generate UML class diagrams from javadoc input, then perhaps you can intercept the javadoc source and manipulate it to generate UML class diagrams.  Ask Cadence.
If you want to run eDoc for your entire testbench, then run the following lin on the Specman CLI after loading your entire testbench:
write doc -detail -no_source_links -overwrite -dir=./testbench_edoc @*

There is a "tree" view of the class hierarchy which is reachable from the main page generated by the above command.  It shows you the class inheritance tree, but it doesn't give you a UML class diagram.
The documentation for eDocs is in section "Generating and Using eDoc Reports" of sn_usage.pdf.  I believe the javadoc version of eDocs was introduced in Specman 8.2


text:
Q: Burned cable while trying UPS transformer with no load I have this big transformer taken from an old UPS. I wanted to use it to build a linear high current 12V power supply, so I was testing if it was suitable for the task. Unfortunately it has no ratings, but I assume it would be capable of delivering at least 10A.
Here are a couple of pictures of the transformer: https://imgur.com/a/PEsIrfS
These are the resistance of the windings:

*

*grey-violet 1.61 ohm

*brown-blue 5.22 ohm

*black-red(right) 0.15 ohm

*white-red(left) 0.15 ohm

I connected brown-blue to the mains (230V) using a regular PC cable (rated 2.5A 250V) and took some measurements. In this configuration, both black and white with the respective reds were 13,8VAC, but grey-violet was out of range with my multimeter (UT61E).
Then I tried to connect grey-violet to the mains, and this is where the PC cable immediately burned.
My question is, why there was this big current absorption if there was no load connected (just my multimeter)? And why only when I connected grey and violet? Is this transformer still safe to use, provided that the resistance measurements remained the same and its cable show no signs of burning (maybe the 2.5A cable acted as a fuse)?

A:
My question is, why there was this big current absorption if there was no load connected

Because you connected a low voltage winding to 230V. It's not the resistance of a winding on a core that stops excessive current but its inductance. Overvoltage saturates the core before a half-period is over and before the core gets demagnetized again by the negative voltage half-period. So the inductance for all the additional voltage-time in an AC half-period drops to nearly zero and the only thing that limits current is the winding resistance.


text:
Q: I am trying to use ionic icons in my HTML pages but icons are not displaying I am trying to use ionic icons in my HTML pages. But icons are not displaying.
I am linking <link src="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" src_type="url" rel="stylesheet" type="text/css"/> into my page.
And using icon:
I am very new to programming. So, any help?

A: if you use ionic it will works as usage of
<ion-icon name="something"></ion-icon>

in a list, grid, col, and html tags. First check package.json         "ionicons": "3.0.0", is exist or not .. If not please put this value in package.json file.

A: If you want to use more icons addition to Ionic Icons you can add font awesome library. To install this library in your project document is very useful and simple.

A: Use below you will get the star icon.

You can also use star icon in button in the way of
<button class="button button-icon button-clear ion-star">Shopping Cart</button>

Just try with it.

A: I have faced a similar issue, here is how I got around it:
I went over to the https://github.com/ionic-team/ionicons
 and downloaded the docs folder.
It contains these folders:

*

*css

*fonts

*Ionicons/svg

I downloaded it and placed it in a folder in the root directory of my development environment.
I now linked the style sheet in the folder I downloaded in my head section

in this case I placed everything I downloaded in the "Ionicons" folder
from now you can use Ionicons anywhere in your page
by using an inline element


text:
Q: Почему не срабатывает столкновение текстур двух объектов? Здравствуйте! Имеется код для столкновения двух объектов и текстуры 16х16. Реализация такая, нужно что бы игрок прыгая на врага сверху убивал его, а по координате x враг убивал игрока...
С помощью класса Rectangle делаю проверку на столкновение затем внутри пишу такие условия.
Это условие для гибели игрока:
if((rectPlayer.x + rectPlayer.width < arrayEnemy.get(num).getRect().x + arrayEnemy.get(num).getRect().width
|| rectPlayer.x + rectPlayer.width > arrayEnemy.get(num).getRect().x + arrayEnemy.get(num).getRect().width)
&& rectPlayer.y < arrayEnemy.get(num).getRect().y + arrayEnemy.get(num).getRect().height
.... тут какой либо код...
}

Это условие для удара игроком сверху по врагу:
if((rectPlayer.x + rectPlayer.width < arrayEnemy.get(num).getRect().x + arrayEnemy.get(num).getRect().width
|| rectPlayer.x + rectPlayer.width > arrayEnemy.get(num).getRect().x + arrayEnemy.get(num).getRect().width)
&& rectPlayer.y > arrayEnemy.get(num).getRect().y + arrayEnemy.get(num).getRect().height
.... тут какой либо код...
}

Мой код по x координате работает... но стоит подключить этот то игрок его не может убить врага сверху... и игрок умирает почему то... либо наоборот, если убрать условие x то игрок прыгает на врага без проблем.... в чем моя ошибка?

A: Здравствуйте. Честно говоря, я никогда бы не понял по коду, что Вы хотите сделать. Вот моё предложение по реализации необходимых Вам экшенов:
if (rectPlayer.overlaps(arrayEnemy.get(num).getRect())) {
if (rectPlayer.y + rectPlayer.height > (arrayEnemy.get(num).getRect().y +
          arrayEnemy.get(num).getRect().height)) {
    // Код для убийства существа
} else {
    // Код для убийства Player
}

}
Задумка такова, что идёт проверка на столкновение объектов, затем на сторону, откуда пришёл герой. Код не проверял, надеюсь, P.S.: В Вашем примере, скорее всего, спутаны координаты, а так же условия с ИЛИ следовало бы заключить в скобки.


text:
Q: Does Oracle have rights to my code? I'm about to write some software for an academic research project.  I'm hoping to write it in Java, but the group I'm working with raised some concerns about licensing.  I originally though these were silly questions, but I'm having trouble finding definitive answers:
If I write software in Java, am I free to release that software and its source code?  Are there restrictions on how I can license it?  Does Oracle have any rights to it?

A:
If I write software in Java, am I free to release that software and its source code?

Absolutely.

Are there restrictions on how I can license it?

None whatsoever.  (Or at least, not based on the fact that it is written in Java.)

Does Oracle have any rights to it?

No.
The only (possibly) relevant rights Oracle have are to do with your distributing modified versions of the Java platform ... or using the Java trademarks inappropriately.

... but the group I'm working with raised some concerns about licensing.

It is safe to say that the people who raised those concerns haven't got a clue.

A: No Oracle does not have rights to your code. It will be your software.

A: I'm not a lawyer; I'd recommend that you get one to be sure.
With that said, I think the concern is overblown.    Everyone who writes a Java application is not obligated to turn over source to Oracle or anyone else.
It makes no sense - how could Java have been so widely adopted if that were the case?


text:
Q: Structured streaming : watermark vs. exactly-once semantics The programming guide says that structured streaming guarantees end-to-end exactly once semantics using appropriate sources/sinks.
However I'm not understanding how this works when the job crashes and we have a watermark applied.
Below is an example of how I currently imagine it working, please correct me on any points that I'm misunderstanding. Thanks in advance!
Example:
Spark Job: Count # events in each 1 hour window, with a 1 hour Watermark.
Messages:

*

*A - timestamp 10am

*B - timestamp 10:10am

*C - timestamp 10:20am

*X - timestamp 12pm

*Y - timestamp 12:50pm

*Z - timestamp 8pm

We start the job, read A, B, C from the Source and the job crashes at 10:30am before we've written them out to our Sink.
At 6pm the job comes back up and knows to re-process A, B, C using the saved checkpoint/WAL. The final count is 3 for the 10-11am window.
Next, it reads the new messages from Kafka, X, Y, Z in parallel since they belong to different partitions. Z is processed first, so the max event timestamp gets set to 8pm. When the job reads X and Y, they are now behind the watermark (8pm - 1 hour = 7pm), so they are discarded as old data. The final count is 1 for 8-9pm, and the job does not report anything for the 12-1pm window. We've lost data for X and Y.
---End example---
Is this scenario accurate?
If so, the 1 hour watermark may be sufficient to handle late/out-of-order data when flowing normally from Kafka-Sspark, but not when the spark job goes down/Kafka connection is lost for a long period of time. Would the only option to avoid data loss be to use a watermark longer than you expect the job to ever go down for?

A: The watermark is a fixed value during the minibatch. In your example, since X, Y and Z are processed in the same minibatch, watermark used for this records would be 9:20am. After completion of that minibatch watermark would be updated to 7pm.
Below the quote from the design doc for the feature SPARK-18124 which implements watermarking functionality:

To calculate the drop boundary in our trigger based execution, we have to do the following.

*

*In every trigger, while aggregate the data, we also scan for the max value of event time in the trigger data

*After trigger completes, compute watermark = MAX(event time before trigger, max event time in trigger) - threshold

Probably simulation would be more description:
import org.apache.hadoop.fs.Path
import java.sql.Timestamp
import org.apache.spark.sql.types._
import org.apache.spark.sql.streaming.ProcessingTime

val dir = new Path("/tmp/test-structured-streaming")
val fs = dir.getFileSystem(sc.hadoopConfiguration)
fs.mkdirs(dir)

val schema = StructType(StructField("vilue", StringType) ::
                        StructField("timestamp", TimestampType) ::
                        Nil)

val eventStream = spark
  .readStream
  .option("sep", ";")
  .option("header", "false")
  .schema(schema)
  .csv(dir.toString)

// Watermarked aggregation
val eventsCount = eventStream
  .withWatermark("timestamp", "1 hour")
  .groupBy(window($"timestamp", "1 hour"))
  .count

def writeFile(path: Path, data: String) {
  val file = fs.create(path)
  file.writeUTF(data)
  file.close()
}

// Debug query
val query = eventsCount.writeStream
  .format("console")
  .outputMode("complete")
  .option("truncate", "false")
  .trigger(ProcessingTime("5 seconds"))
  .start()

writeFile(new Path(dir, "file1"), """
  |A;2017-08-09 10:00:00
  |B;2017-08-09 10:10:00
  |C;2017-08-09 10:20:00""".stripMargin)

query.processAllAvailable()
val lp1 = query.lastProgress

// -------------------------------------------
// Batch: 0
// -------------------------------------------
// +---------------------------------------------+-----+
// |window                                       |count|
// +---------------------------------------------+-----+
// |[2017-08-09 10:00:00.0,2017-08-09 11:00:00.0]|3    |
// +---------------------------------------------+-----+

// lp1: org.apache.spark.sql.streaming.StreamingQueryProgress =
// {
//   ...
//   "numInputRows" : 3,
//   "eventTime" : {
//     "avg" : "2017-08-09T10:10:00.000Z",
//     "max" : "2017-08-09T10:20:00.000Z",
//     "min" : "2017-08-09T10:00:00.000Z",
//     "watermark" : "1970-01-01T00:00:00.000Z"
//   },
//   ...
// }

writeFile(new Path(dir, "file2"), """
  |Z;2017-08-09 20:00:00
  |X;2017-08-09 12:00:00
  |Y;2017-08-09 12:50:00""".stripMargin)

query.processAllAvailable()
val lp2 = query.lastProgress

// -------------------------------------------
// Batch: 1
// -------------------------------------------
// +---------------------------------------------+-----+
// |window                                       |count|
// +---------------------------------------------+-----+
// |[2017-08-09 10:00:00.0,2017-08-09 11:00:00.0]|3    |
// |[2017-08-09 12:00:00.0,2017-08-09 13:00:00.0]|2    |
// |[2017-08-09 20:00:00.0,2017-08-09 21:00:00.0]|1    |
// +---------------------------------------------+-----+

// lp2: org.apache.spark.sql.streaming.StreamingQueryProgress =
// {
//   ...
//   "numInputRows" : 3,
//   "eventTime" : {
//     "avg" : "2017-08-09T14:56:40.000Z",
//     "max" : "2017-08-09T20:00:00.000Z",
//     "min" : "2017-08-09T12:00:00.000Z",
//     "watermark" : "2017-08-09T09:20:00.000Z"
//   },
//   "stateOperators" : [ {
//     "numRowsTotal" : 3,
//     "numRowsUpdated" : 2
//   } ],
//   ...
// }

writeFile(new Path(dir, "file3"), "")

query.processAllAvailable()
val lp3 = query.lastProgress

// -------------------------------------------
// Batch: 2
// -------------------------------------------
// +---------------------------------------------+-----+
// |window                                       |count|
// +---------------------------------------------+-----+
// |[2017-08-09 10:00:00.0,2017-08-09 11:00:00.0]|3    |
// |[2017-08-09 12:00:00.0,2017-08-09 13:00:00.0]|2    |
// |[2017-08-09 20:00:00.0,2017-08-09 21:00:00.0]|1    |
// +---------------------------------------------+-----+

// lp3: org.apache.spark.sql.streaming.StreamingQueryProgress =
// {
//   ...
//   "numInputRows" : 0,
//   "eventTime" : {
//     "watermark" : "2017-08-09T19:00:00.000Z"
//   },
//   "stateOperators" : [ ],
//   ...
// }

query.stop()
fs.delete(dir, true)

Notice how Batch 0 started with watermark 1970-01-01 00:00:00 while Batch 1 started with watermark 2017-08-09 09:20:00 (max event time of Batch 0 minus 1 hour). Batch 2, while empty, used watermark 2017-08-09 19:00:00.

A:
Z is processed first, so the max event timestamp gets set to 8pm.

That's correct. Even though Z may be computed first, the watermark is subtracted from the maximum timestamp in the current query iteration. This means that 08:00 PM will be set as the time in which we subtract the watermark time from, meaning 12:00 and 12:50 will be discarded.
From the documentation:

For a specific window starting at time T, the engine will maintain state and allow late data to update the state until (max event time seen by the engine - late threshold > T)

Would the only option to avoid data loss be to use a watermark longer than you expect the job to ever go down for

Not necessarily. Lets assume you set a maximum amount of data to be read per Kafka querying to 100 items. If you read small batches, and you're reading serially from each partition, each maximum timestamp for each batch may not be the maximum time of the latest message in the broker, meaning you won't lose these messages.


text:
Q: Is $(0,0)$ a local minima,local maxima or the saddle point? $f(x,y)=5x^2+xy^3-3x^2y$
Is $(0,0)$ a local minima,local maxima or the saddle point?
My attempt:I calculated
$$f_{xx}(0,0)=10, \hspace{0.3cm}f_{xy}(0,0)=0, \hspace{0.3cm}f_{yy}(0,0)=0$$
So $$f_{xx}(0,0)f_{yy}(0,0)-(f_{xy}(0,0))^2=0$$
I concluded nothing from this test.I do not know other method to solve this problem.Please help me.
Thanks.

A: It is true that $\nabla f(0,0)=(0,0)$ and that the Hessian $d^2f(0,0).(X,Y)=10X^2$ is positive semidefinite. The latter implies that the second derivative test is inconclusive in this example.
Fact is that our $f$ has an  intricate zero at $(0,0)$. Writing $f$ in the form
$$f(x,y)=(5-3y)\>x\left(x+{y^3\over5-3y}\right)$$
shows that near the origin we have $f(x,y)=0$ along two curves having the $y$-axis as common tangent, namely $x=0$ and $$x=-{y^3\over 5-3y}\ ,$$
the latter resembling the cubic parabola $x=-{y^3\over5}$ near the origin. Crossing either of these two curves changes the sign of $f$.
This shows that $f$ assumes as well negative as positive values near  $(0,0)$. It follows that we don't have a local extremum of $f$ at $(0,0)$.


text:
Q: Passing javascript variable to php file I can't find the best way to pass a JavaScript variable to use in a PHP file.
I found this function wp_localize_script(), but it does exactly the contrary.
Is there a way to pass a JavaScript variable to PHP?

A: You could use cookies - set in JS, and read from PHP.
Another way can be using an AJAX request to get the variable value.


text:
Q: Image tag not is showing the images in the first load rails I'm trying to create a carrousel in rails with bootstrap and I'm using active storage to save the images.
My problem is when I load the page for the first time not is loading the images stored in the s3 bucket, but when I reload the page, the images appear.
I confirm that in the variable img is the image attached.
This is my code:
_carrousel.html.erb
<div id="carouselExampleControls<%=property.id%>" class="carousel slide" data-bs-interval="false">

      <% count = 0%>
      <% property.property_image.images.each do  |img| %>
        <div class="carousel-item <%= 'active' if count == 0 %> background-covr">
          <%= image_tag(img, class: "card-img-top d-block background-covr") %>
          <% count += 1 %>

      <% end %>

  <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls<%=property.id%>" data-bs-slide="prev">

    Previous
  </button>
  <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls<%=property.id%>" data-bs-slide="next">

    Next
  </button>

Can someone give me a hand or an explanation?

A: I was able to fix this issue. The problem was turbolinks.
I removed turbolink of application.js and add this library:
gem 'jquery-turbolinks'
that's fixed the issue and continue working with the velocity of turbolink.


text:
Q: Is It possible to install or run dotnetredist.exe (or any arbitrary EXE) as part of an .MSI? Suppose I have an MSI, that has .NET Framework as a pre-requisite.
I know the MSI generated from VS2008 setup project will detect when that pre-req is missing and will direct the user to install it.
Q1. Is it possible, technically, to call out to dotnetredist.exe (or, I guess, any arbitrary EXE) during the run of an MSI, to handle this pre-req, and then continue installing? I mean, I think it is not, if I confine myself to a VS2008-generated setup, but what if I used WIX?  What if I was willing to write a custom action?  What if I could manually edit the MSI table with Orca or via script?  Is it possible?
Q2.  Is it legal?  Is it allowed by the license?

A: The technical restriction is that one windows installer session cannot launch another one. For example, one MSI file cannot install another MSI file.
Launching executables or scripts from an MSI file is possible, as long as they don't start any windows installer sessions. This is called a custom action.
The .NET installer exe definitely cannot be launched from an MSI because it uses windows installer sessions. Instead, you must create a bootstrapper setup.exe which first installs .NET and then launches your MSI. The wix documentation has a topic which covers how to generate such a bootstrapper with msbuild. This is not really wix specific; you can use the bootstrapper generator task with any MSI file.
As for the legal aspect, I don't see a need to worry. It is called a redistributable after all.

A:
Q1. ... or, I guess, any arbitrary EXE ...
Q2. Is it legal? Is it allowed by the license?

The legality of redistributing any arbitrary EXE is governed by the EXE's license.  'dotnetredist' is specifically licensed for redistribution, so no problem there.
MSI 4.5 will allow installer chaining, within limits.

A: Installing .Net may require a reboot. I don't know how you are going to handle it. Abort the install? Suppress the reboot? Terminate the install? I don't think MSI transaction works across reboots.
You must have a copy of either Visual Studio, or the freely available Windows SDK that include .Net SDK/ standalone .Net Frameword SDK and agree the license and terms in the EULA to publish dotnetredist.exe with your app.


text:
Q: How to change date format to German? I use the \today comment, then it produces 26th February. However in my context, I want 26ten Februar. How can I change that?

A: Try with the datetime package, by defining a new date format:
\newdateformat{myformat}{\THEDAY{ten }\monthname[\THEMONTH], \THEYEAR}

MWE:
\documentclass{article}

\usepackage[ngerman]{babel}
\usepackage{datetime}

\newdateformat{myformat}{\THEDAY{ten }\monthname[\THEMONTH], \THEYEAR}

\begin{document}

\myformat\today

\end{document}

Output:

EDIT
If you can't load babel with the language ngerman, you can however load datetime as
\usepackage[ngerman]{datetime}

and define the date format as
\newdateformat{myformat}{\THEDAY{ten }\monthnamengerman[\THEMONTH], \THEYEAR}

MWE:
\documentclass{article}

\usepackage[english]{babel}
\usepackage[ngerman]{datetime}

\newdateformat{myformat}{\THEDAY{ten }\monthnamengerman[\THEMONTH], \THEYEAR}

\begin{document}

\myformat\today

\end{document}

Output:


text:
Q: Page numbers on first page and no logo on second page in newlfm I am trying to write a cover letter with a header and footer on the first page, but no header on the consecutive pages. I also am having trouble adding a page number to the first page. Any help would be much appreciated.
\documentclass[10pt,stdletter, times, addrfromright]{newlfm}
\usepackage{charter}
\pagenumbering{arabic}

\usepackage{csquotes}
\widowpenalty=1000
\clubpenalty=1000

\unprbottom{1cm}
\newsavebox{\Luiuc}
\sbox{\Luiuc}{%
    \parbox[b]{1.75in}{%
        \vspace{0.5in}%
        \includegraphics[scale=.15]
        {RSCAS}%
    }%
}%
\makeletterhead{Uiuc}{\Lheader{\usebox{\Luiuc}}}
\makeatletter
\let\ps@othhead\ps@fancy

\makeatother

\rfoot{ \thepage}

\Cfooter{\tiny Robert Schuman Center for Advanced Studies
 \\ European University Institute, Via dei Roccettini 9, I-50014 San Domenico di Fiesole (FI) Italy}
\newlfmP{headermarginskip=20pt}
\newlfmP{sigsize=50pt}
\newlfmP{dateskipafter=-70pt}

\newlfmP{addrfromemail}
\PhrEmail{Email}

\lthUiuc
\namefrom{John D'Attoma \\
Postdoctoral Research Fellow \\
Robert Schuman Centre for Advanced Studies \\
European University Institute}

\addrfrom{
    John D'Attoma\\
    Postdoctoral Research Fellow\\
    Robert Schuman Centre for Advanced Studies
}
\emailfrom{john.dattoma@eui.eu}

\addrto{%
The New School for Social Research\\
Department of Politics\\
66 West 12th Street \\
New York, NY 10011}

\greetto{Dear Members of the Search Committee:}
\closeline{Best Regards,}
\begin{document}
\begin{newlfm}

A: I'd forego newlfm and choose something less restrictive. Here's a replica of your document under good ol' article:
\documentclass[10pt]{article}
\usepackage{charter,fancyhdr,geometry,graphicx}
\usepackage{lipsum}% For this example

\geometry{paper=letterpaper,
  hmargin=1in,
  vmargin=.5in,
  includefoot
}

\pagestyle{fancy}
\fancyhf{}% Clear header/footer
\renewcommand{\headrulewidth}{0pt}% No header rule
\renewcommand{\footrulewidth}{1pt}% 1pt footer rule
\fancyfoot[C]{%
  \tiny
  \begin{tabular}{c}
    Robert Schuman Center for Advanced Studies \\
    European University Institute, Via dei Roccettini 9, I-50014 San Domenico di Fiesole (FI) Italy
  \end{tabular}}
\fancyfoot[R]{\thepage}

\setlength{\parindent}{0pt}% No paragraph indent
\setlength{\parskip}{.5\baselineskip}

\begin{document}

\includegraphics[scale=.15]{example-image} \\% Your logo here
\rule{\textwidth}{1pt}

\hfill
\begin{tabular}{l@{}}
  John D'Attoma \\
  Postdoctoral Research Fellow \\
  Robert Schuman Centre for Advanced Studies \\
  Email: john.dattoma@eui.eu
\end{tabular}

\bigskip\bigskip

\begin{tabular}[t]{@{}l}
  The New School for Social Research\\
  Department of Politics\\
  66 West 12th Street \\
  New York, NY 10011
\end{tabular}
\hfill
\today

\bigskip

Dear Members of the Search Committee:

\bigskip

\lipsum[1-7]

\bigskip

\hfill
\begin{tabular}{l@{}}
  Best Regards, \\[50pt]
  John D'Attoma \\
  Postdoctoral Research Fellow \\
  Robert Schuman Centre for Advanced Studies \\
  European University Institute
\end{tabular}

\end{document}

Output before switching away from your class:

Output using the above code:


text:
Q: Is there a registry key change that will by-pass the Windows Domain Join Welcome page? I'm scripting some Windows Server 2008 R2 builds using Power Shell.  Some software needs to be installed after the server has joined the domain.  Since I want to automate everything, I'm looking to by-pass the domain controllers Welcome page using a registry hack script.  I work for a large company and the Active Directory people are unwilling to change group policy.  I figure if it's a registry key I can script the change, install the software, replace the key and reboot as the final step.  Is there a registry key change that will by-pass the Domain Join Welcome page?

A: Embed some AutoIT script code to automatically click whatever buttons you need to.
http://trevorsullivan.net/2012/05/25/powershell-integrate-invocation-of-autoit-scripts/


text:
Q: Vuetify justify-end for v-col I'm trying to fit two v-cols inside of a v-row, one being 2 cols wide and the other 10. The for-loop (or default behavior) of v-cols seems to be causing the v-cards after the first 2 to stick to the left side of the screen, when I'd want to them to keep in the same alignment as the top two cards. The first set of v-cols is a side component, while the second v-col is for a grid.
Is there a way I can make all the v-cards in the grid justify to the right side so that they wouldn't revert back to the left side once the side component ends?
<template>

    <TopNavbar />
    <v-app id="bigGrid">

        <v-container>
          <v-row class="grey" align-md="right">
            <v-col cols="12" sm="12" md="12" lg="2" xl="2">
              <v-card class="pa-8" style="height: 30vh" outlined title>
                Side Stuff
              </v-card>
            </v-col>
            <v-col
              justify="end"
              v-for="n in 6"
              :key="n"
              cols="12"
              md="5"
              lg="5"
              xl="5"
            >
              <v-card style="height:25vh" class="pa-8" outlined title>
                <v-card-title> Category Name</v-card-title></v-card
              >
            </v-col>
          </v-row>

          ></v-container
        >

</v-app
    >

</template>

Codepen Link:

A: My updated code is as follows

  <v-app id="bigGrid">

      <v-container>
        <v-row class="grey" align-md="right">
          <v-col cols="12" lg="2">
            <v-card class="pa-8" style="height: 30vh" outlined title>
              Side Stuff
            </v-card>
          </v-col>
          <v-col cols="12" lg="10">
            <v-row>
              <v-col
                v-for="n in 6"
                :key="n"
                cols="12"
                md="5"
              >
                <v-card style="height:25vh" class="pa-8" outlined title>
                  <v-card-title> Category Name</v-card-title></v-card
                >
              </v-col>
            </v-row>
          </v-col>
        </v-row>
      </v-container>

  </v-app>

*

*Main page should be wrapped into another <v-col> component and grid components can go inside it(<v-row> in this case)

*justify="end" is applied to  component

*<v-col cols="12" sm="12" md="12" lg="2" xl="2"> can be minimized to <v-col cols="12" lg="2">. And the samething for <v-col justify="end" v-for="n in 6" :key="n" cols="12" md="5" lg="5" xl="5">


text:
Q: Firebase duplicates a node instead of deleteing it when removeValue is called I have Firebase database tree like this:

I am trying to delete the entire node -Ka4ytRxQIrzXRR7eSti from iOS app and here is what I do in code:
private let usersDatabase = FIRDatabase.database().reference().child("users")

func deleteNode() {
    guard let userID = FIRAuth.auth()?.currentUser?.uid else {
        assertionFailure("No user logged in when deleting a node")
        return
    }
    usersDatabase.child(userID).child("-Ka4ytRxQIrzXRR7eSti").removeValue()
}

Instead of deleting the node this duplicates it! The new auto id is generated for the duplicated node and all the data from the original node -Ka4ytRxQIrzXRR7eSti are copied (keys and values) to the duplicated node. Where is the catch?


text:
Q: Custom permission return always true, django Sorry for my english. Now i learning django rest and i try create custom permisssion for user. Fox example permission: "big" and "small".
My user model
class User(AbstractUser):
    is_active = models.BooleanField(default=False)
    email = models.EmailField(blank=False, unique=True)
    avatar = models.ImageField(upload_to='avatar/users', blank=True)

    class Meta:
        permissions = (
            ("big", "this is big boy"),
            ("small", "this is small"),
        )

then i added permission to user something like this:
permission = Permission.objects.get(name='big')
        user.user_permissions.add(permission)
        user.save()

created custom class, it class check permission:
class IsBigBoy(permissions.BasePermission):

    def has_permission(self, request, view):
        return request.user.has_perm('users.big')

and in view i create test class for check my custom permission
class MySuperTestRequest(generics.CreateAPIView):
    permission_classes = (permissions.IsAuthenticated, custom_permissions.IsBigBoy)
    serializer_class = CreateSomethingSerializer

    def post(self,
        return Response({"detail": "good"}, status.HTTP_200_OK)

Problem:
return request.user.has_perm('users.big')

it code always return true

A: may be you need user has_perms() for your logic, and don't forget if user is_superuser he has all permissions.


text:
Q: Swift How to change button label outside IBaction? I have this IBAction button with title change functionality. How can I set the initial title from outside of IBAction?
@IBAction func startButton(_ sender: UIButton) {

if sender.currentTitle == "Start" {
        sender.setTitle("Stop", for: .normal)
        start()
    } else {
        sender.setTitle("Start", for: .normal)
        stop()
    }
}

A: You need to create a reference to the button:
@IBOutlet weak var myButton: UIButton!

Then you can simply set the title in e.g. viewDidLoad() or wherever and whenever you want:
override func viewDidLoad() {
   super.viewDidLoad()
   myButton.setTitle("Stop", for: .normal)
}


text:
Q: CUDA MPI performance bottleneck I want to clarify the following issue. I have access to a single node containing a Nvidia K40 GPU and Intel Xeon E5 processor.The processor details got using the lscpu command are as follows:
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                32
On-line CPU(s) list:   0-31
Thread(s) per core:    1
Core(s) per socket:    8
Socket(s):             4
NUMA node(s):          4
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 62
Stepping:              4
CPU MHz:               2300.201
BogoMIPS:              4599.40
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              16384K
NUMA node0 CPU(s):     0-7
NUMA node1 CPU(s):     8-15
NUMA node2 CPU(s):     16-23
NUMA node3 CPU(s):     24-31

I am running an MPI program which  distributes the work across the 32 cores of the processor. Each core then offloads some portion to the GPU. On running the code, the performance decreases (increase in execution time) rather than decrease? Is it because the the access to the GPU by the cores is getting serialized? I would just like clarity regarding this concept hence I have not posted any code. I have read about CUDA aware MPI ,but I think It is not much useful in this case as it is more applicable for multi node situations. Please correct me If I am wrong. What are the possible ways to improve performance in situations like these?

A:
Is it because the the access to the GPU by the cores is getting serialized?

It's possible that serialization on the GPU may be contributing in some way to what you are observing, unless you are taking special steps.  MPI creates a number of processes.  A common strategy is to create one process per CPU core.  CUDA activity from separate processes (that targets a single GPU)  will normally be serialized on that GPU.

What are the possible ways to improve performance in situations like these?

CUDA MPS was designed specifically for this situation.  It allows GPU activity emanating from separate processes to behave as if they were all coming from the same process. This can have several types of efficiency advantages (e.g. no context switching on the GPU, the possibility to run some GPU kernels concurrently, etc.), but I don't want to oversell the feature.  Whether and how much it helps in your case can only be determined by trying it.
If you are throwing lots of work at the GPU (per MPI rank) it's unreasonable of course to expect arbitrary linear scaling.  Once the GPU is saturated with work, things won't get any faster if the GPU is the bottleneck, and the additional overhead of additional MPI rank servicing may actually slow things down also.
This presentation, starting around slide 40, gives lots of useful information about MPS in this scenario.
Note that I'm focusing mainly on the GPU aspects here.  In general, MPI codes may not show linear scaling (and may even slow down, due to MPI overhead, and other factors) as you scale the MPI rank count from 1 to the total number of "processors" on your system.  There can be many reasons for this that have nothing to do with the GPU:

*

*Process placement/affinity

*Saturating the memory bandwidth of the CPU

*Use of "hyperthreaded" cores in HPC codes often shows no benefit or negative effects.

And I'm sure there are many other possibilities as well.  So it's entirely possible that your performance slowdown actually has nothing to do with the GPU (if it turns out to be not the bottleneck) and is due to some other factor.  You can get some initial idea of this using profiling tools, and the above linked presentation offers some ideas there.


text:
Q: Installing a php extension (xdiff) from pecl on Linux I was getting this error on my php script:
Fatal error:  Call to undefined function xdiff_file_diff()
I realised that I didn't had the xdiff extension installed. When I tried to install it using the install pecl xdiff command, I got this errors (among other lines):

configure: WARNING: You will need re2c
  0.13.4 or later if you want to regenerate PHP
      configure: error: Please reinstall the libxdiff distribution

Then I installed re2c and libxdiff:
wget http://www.compdigitec.com/labs/files/re2c_0135_redhat.rpm
wget ftp://ftp.task.gda.pl/vol/vol1/ftp.pld-linux.org/dists/2.0/PLD/i386/PLD/RPMS/libxdiff-0.7-1.i386.rpm
rpm -ivh re2c_0135_redhat.rpm
rpm -ivh libxdiff-0.7-1.i386

But after that I still get the same errors.
PS: I've Googled a LOT and I found a couple of people with this problem but they didn't get an answer either :(

A: This can occur if your are using wrong parameters or installation is file is corrupted.
You can refer to the following URL for more details regarding function xdiff_file_diff():

*

*http://php.net/manual/en/function.xdiff-file-diff.php

*http://php.net/manual/en/ref.xdiff.php


text:
Q: NFS Mount not showing in Windows Explorer Ok. After several hours of searching Google, I can not find exactly what I need.
After mounting an Ubuntu NFS share in Windows 7 via command line, it says it mounts successively. I know it was successful because I can (in cmd) cd to the drive letter I chose (in this case W), and then dir just fine. Lists all the files as it should.
The issue comes in with explorer. For some reason it will not show the new drive letter (again, W), and it does not show up in disk management.
Any suggestions on what needs to change?

A: I stumbled upon this question just now, because I experienced the exact same problem - and managed to solve it! Although probably uninteresting for OP after several month, others may benefit.
If you mount NFS shares from an elevated command prompt (Run as administrator), the mount will not show up in the explorer running with normal user privileges.
The solution is to unmount the share and remount it, either from explorer or from an ordinary command prompt. Admin privileges are not required for NFS mounts.


text:
Q: String interpolation in form inputs In Rails, I'm trying to create video uploader forms for multiple video types.
I ended with code like this:
= semantic_form_for element, url: form_url, method: form_method, remote: true do |f|
  // there will be some form should return once
  - ['webm', 'mp4', 'ogv'].each do |ext|
    .video-item-uploader
      = f.input :"#{ext}", hint: [ f.object."#{ext}"? ? "#{I18n.t('uploaded')}" : '' ].join.html_safe
      = f.input :"#{ext + '_cache'}", as: :hidden

      = f.input :_destroy, as: :boolean, label: "#{I18n.t('do_delete')}"

With code like that, I got syntax errors. It works if I replace "#{ext}" with any text (without quotes) from array.
Is there any possibility to insert a variable inside a form input like that?

A: = semantic_form_for element, url: form_url, method: form_method, remote: true do |f|
  // there will be some form should return once
  - %w(webm mp4 ogv).each do |ext|
    .video-item-uploader
      = f.input :"#{ext}", hint: [ f.object.send("#{ext}?")? ? "#{I18n.t('uploaded')}" : '' ].join.html_safe
      = f.input :"#{ext + '_cache'}", as: :hidden

      = f.input :_destroy, as: :boolean, label: "#{I18n.t('do_delete')}"

try this


text:
Q: Prevent JWPlayer from loading JWPLAYER.SWF multiple times for multiple instances I am using the JW Embedder with JWPlayer to embed 3 videos on a page. (I'm pretty sure the sitatuion would be the same if using SWFObject to do the embedding.
To my horror (!) when looking in Fiddler I saw 3 downloads (HTTP Status 200) for jwplayer.swf which is an unnecessary 200kb.
Obviously what's happening is that the javascript for the embedder just spews out the code to instantiate the flash object and then the browser initiates 3 requests for the 100kb jwplayer.swf file.
It isn't clever enough to wait for jwplayer.swf to load and then use it for the 2 other players.
How can I make sure that jwplayer.swf is only loaded once.

A: It is up to the browser to decide how to deal with multiple requests for the same objects. Most browsers will save the assets in a cache and either skip the subsequent requests and serve directly from the cache, or they send a different type of request which checks to see if the content has changed on the server.
Either way, there's no way for the player itself to control this behavior. That said....
If you're down with HTML5, you can try making a cache manifest for the swf.
This script looks promising: http://blog.sebastian-martens.de/2010/05/preload-assets-with-javascript-load-complete-callback-for-single-assets-include-swfflash/ You can preload the first player and then the next two as a post-load callback (See comment 9).