text:
Q: Java rectangle 90 array null pointer I cannot figure this one out... so I keep getting an Exception in thread
AWT-EventQueue-0" java.lang.NullPointerException
  at MakeFrame.MovementAndObjects.paint(MovementAndObjects.java:285)

error in my code but there is no nullPointer that I can find! my rectangle []latter array is public and I'm just trying to pass the array simple objects that I cannot reference from it.
void defineObjects(){
       character = new Player("Zander", true, 10, 1, 1, 1, 1, "none", "none");
       charRect = new Rectangle(character.charX, character.charY,character.charWidth,character.charHeight);//y==about 500, x= whatever the x is currently set at
       floor1 = new Rectangle(-1, 660, 1201, 10);
       floor2 = new Rectangle (-1, 550, 1201, 10);
       floor3 = new Rectangle(-1, 440, 1201, 10);
       floor4 = new Rectangle (-1, 330, 1201, 10);
       floor5 = new Rectangle(-1, 220, 1201, 10);
       floor6 = new Rectangle (-1, 110, 1201, 10);
       wallA = new Rectangle(0,660,-700,12);
       wallB = new Rectangle(1182,660,-700,12);
       latter[0]=new Rectangle(1120,560,35,101);
       latter[1]= new Rectangle(100,450,35,101);
       latter[2]=new Rectangle(400,340,35,101);
       latter[3]= new Rectangle(20,340,35,101);
       latter[4]=new Rectangle(800,230,35,101);
       latter[5]= new Rectangle(100,230,35,101);
       latter[6]=new Rectangle(600,450,35,101);
       latter[7]= new Rectangle(500,120,35,101);
       latter[8]=new Rectangle(700,120,35,101);
       objectDefine=true;

       repaint();
}

@Override
 public void paint(Graphics g)
{
    super.paint(g);
    if(objectDefine)
    {

        /*==========
        =THE FLOORS=
        ==========*/
       latter[0]=latter1;
       g.setColor(myBarf);//floor
       g.setColor(myBrown);//floor
       g.fillRect(floor1.x, floor1.y, floor1.width, floor1.height);
       g.fillRect(floor2.x, floor2.y, floor2.width, floor2.height);
       g.fillRect(floor3.x, floor3.y, floor3.width, floor3.height);
       g.fillRect(floor4.x, floor4.y, floor4.width, floor4.height);
       g.fillRect(floor5.x, floor5.y, floor5.width, floor5.height);
       g.fillRect(floor6.x, floor6.y, floor6.width, floor6.height);
        /*==========
        =THE  WALLS=
        ==========*/
       g.setColor(Color.red);
       g.fillRect(wallA.x,wallA.y,wallA.height,wallA.width);
       g.fillRect(wallB.x,wallB.y,wallB.height,wallB.width);
        /*===========
        =THE lATTERS=
        ===========*/
        for(int i=0; i<=latter.length; i++)
        {
            g.setColor(myBrown3);
            g.fillRect(latter[i].x, latter[i].y, latter[i].width, latter[i].height);<---- this is the bad line of code according the the error message
            g.setColor(Color.BLACK);
            System.out.println("D1 complete!!!");
            for(int j=5; j<=80; j+=15)
            {
                g.fillRect(latter[i].x+9 ,latter[i].y+j, latter[i].width/2, latter[i].height/10);
            }
        }

Any thought?
 I have initialized it several different ways, this is the current one that I have tried:
public Rectangle[] latter= {
  new Rectangle(1120,560,35,101),
  new Rectangle(100,450,35,101),
  new Rectangle(400,340,35,101),
  new Rectangle(20,340,35,101),
  new Rectangle(800,230,35,101),
  new Rectangle(100,230,35,101),
  new Rectangle(600,450,35,101),
  new Rectangle(100,230,35,101),
  new Rectangle(700,120,35,101)
};

iv also done the standard rectangle[] latter=new Rectangle[8]; the assigned latter

A: i<=latter.length in the for seems incorrect, it should be i < latter.length (remember that if length is 9 then the elements you can access are from 0 to 8). But that should cause an IndexOutOfBoundsException rather than a NullPointerException.
Be careful with the array dimensions, the correct initialization of latter, for example should be Rectangle[] latter = new Rectangle[9];, so 9 and not 8 as you posted.


text:
Q: Not able to find "File Preview" lightning custom component introduced in winter 18 release As per the winter 18 release , there is document related to create a custom preview component.
Adding screenshot.
Let me know where to find that component.

A: I believe you missed the big disclaimer above the  Release Notes:

Note: This release is in preview. Features described here don't become
  generally available until the latest general availability date that
  Salesforce announces for this release. Before then, and where features
  are noted as beta, pilot, or developer preview, we can't guarantee
  general availability within any particular time frame or at all. Make
  your purchase decisions only on the basis of generally available
  products and features.

That being said, it is normal that the component is not available yet.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Match using predicate function in JavaScript Notice: This is my first question on StackOverflow (although I've answered before). If you think I haven't clarified something, feel free to tell me in the comments.
You may have heard of the String.prototype.match() function in JavaScript, which searches a string for a match against a regular expression, and returns the matches, as an Array object. Here's an example:

var str = "(list 1 2 foo (list nice 3 56 989 asdasdas))"
console.log(str.match(/\d+/g)) //=>["1", "2", "3", "56", "989"]

However, I need a match-like method that inputs a function in JavaScript. This input function would take in a substring of the original string, and output a boolean telling if the substring is a valid match or not. Here's an example of the intended behavior
    function standardFunc(substr) {
       return parseFloat(substr) !== NaN;
    }

    var str = "(list 1 2 foo (list nice 3 56 989 asdasdas))"
    console.log(str.match(standardFunc)) //=>["1", "2", "3", "56", "989"]

Is there an easy way to emulate this behavior in JavaScript?

A: If you can set or somehow identify the boundaries of which sorts of substrings get matched, it's possible. For example, here, every match looks to begin and end at a word boundary:

function standardFunc(str) {
   return !Number.isNaN(parseFloat(str))
}

const str = "(list 1 2 foo (list nice 3 56 989 asdasdas))";
for (const match of str.matchAll(/\b.+?\b/g)) {
  if (standardFunc(match[0])) {
    console.log(match[0]);
  }
}

Note you'll need to use Number.isNaN instead of using !== NaN.
If you're not looking for a general solution, but just a solution to this particular problem, solve this with a regex alone. Match digits followed by an optional decimal point and more digits:

function standardFunc(str) {
   return !Number.isNaN(parseFloat(str))
}

const str = "123.03 (list 1 2 foo (list nice 3 56 989 asdasdas))";
console.log(
  str.match(/\d+(?:\.\d+)?/g)
);

A: I would use the Array.prototype.filter method after converting the string to an array:

var stg = "(list 1 2 foo (list nice 3 56 989 asdasdas))";

var stgAsArray = stg.split(' ');

var numbersFromString = stgAsArray.filter(word => !Number.isNaN(parseFloat(word)));

console.log(numbersFromString)

console.log(numbersFromString.join(' '));


text:
Q: 1-dimensional quadratic placement with distances in [1], Hall shows solution to the following graph optimization problem for a vector of node positions X, given a cost matrix C (normalizing the solution with the constraint $X^TX=1$
$$\text{argmin}_X \sum_i \sum_j (x_i - x_j)^2 \cdot c_{ij}$$
by reducing it to $\text{argmin}_X X^T B X$ where $B$ is a positive semi-definite matrix of rank $n - 1$ (where $n$ is the size of $X$), obtained from $C$ (not important how).
Then he finds the solution as the first but minimal eigenvector of $B$.
I have a similar problem, where instead of forcing the adjacent vectors as close as possible to each other, I'd like to force them to be in the desired distance $d_{ij}$ where $D$ is a skew-symmetric matrix.
$$\text{argmin}_X \sum_i \sum_j (x_i - x_j + d_{ij})^2 \cdot c_{ij}$$
I managed, similarly as in [1] (and hopefully correctly), to reduce the problem into
$$\text{argmin}_X (X^TB + U)X$$
where $B$ is the same as in the original problem and $U$ is a horizontal vector, obtained by adding up columns of a skew-symmetric matrix (for what it's worth).
I wonder if this problem has been investigated before or whether the solution can be elegantly found using eigenvectors, similarly as for the first problem. By the way, I'm not keen on the quadratic metric in the problem definition, an absolute value or something similar is also good.
[1] Hall, Kenneth M. "An r-dimensional quadratic placement algorithm." Management science 17.3 (1970): 219-229.

A: Got it. Guided by the differentiation in this thread and then doing some experimentation, I've found a solution that looks very simple and the results look OK.
To clean up the notation, without loss of generality, I will replace the question's $U$ with $-U^T$ (using $^T$ to show that it's a horizontal vector) and the question's $B$ with $\frac{1}{2}B$. To sum up, we will minimize
$$f(X) = \frac{1}{2}(X^TB - U^T)X = \frac{1}{2}X^TBX - U^TX$$
where X and U are vectors and B is a symmetric matrix (for how it was obtained, see the PS section).
First, I've found the minimum of $f(X)$ by deriving by $X$ and doing some magic with transpositions (we can remove some of them because they are applied on scalars, other ones due to $B$'s symmetry):
$$\partial f(X) = \frac{1}{2}(\partial X)^TBX + \frac{1}{2}X^TB\partial X - U^T\partial X = \partial X(BX - U)$$
We could solve $BX = U$ using $X = B^{-1}U$. Issue here is that $B$, as defined in [1], is singular, which could be expected because the problem is invariant to translation of $X$. To get a solution, I've added parabolic cost on the position of $x_0$ to $f(X)$:
$$f(x) = \frac{1}{2}X^TBX - U^TX + X^TE_0X$$
where $E_0$ is a matrix with all zeroes except the 1 in the left most corner. This way I've actually added $x_0^2$ to $f(x)$ and thus glued the position of $x_0$ to 0. Using the same technique as before, I've got to an equation $(B + E_0)X = U$. The result $X = (B + E_0)^{-1}U$ is now defined.
PS: To map the solution to the original problem
$$\text{argmin}_X \sum_i \sum_j (x_i - x_j + d_{ij})^2 \cdot c_{ij}$$
the matrix $B$ has sums of rows of $C$ on the diagonal and values of $-C$ elsewhere. The vector $U$ is obtained by summing up rows of the pointwise product of $C$ and $-D$.


text:
Q: Confluent: ERROR Failed to run query for table TimestampIncrementingTableQuerier mysql-jdbc I am trying to use mode timestamp with MySQL, with limited rows as my table size is 2.6 GB.
Here are the connector properties that I am using:
{
        "name": "jdbc_source_mysql_registration_query",
        "config": {
                 "connector.class": "io.confluent.connect.jdbc.JdbcSourceConnector",
                 "key.converter": "io.confluent.connect.avro.AvroConverter",
                 "key.converter.schema.registry.url": "http://localhost:8081",
                 "value.converter": "io.confluent.connect.avro.AvroConverter",
                 "value.converter.schema.registry.url": "http://localhost:8081",
                 "connection.url": "jdbc:mysql://localhost:3310/users?zeroDateTimeBehavior=ROUND&useCursorFetch=true&defaultFetchSize=1000&user=kotesh&password=kotesh",
                 "query": "SELECT matriid,DateUpdated  from users.employee WHERE date(DateUpdated)>='2018-11-28' ",
                 "mode": "timestamp",
                 "timestamp.column.name": "DateUpdated",
                 "validate.non.null": "false",
                 "topic.prefix": "mysql-prod-kot-"
        }
}

I getting as below:

INFO TimestampIncrementingTableQuerier{table=null, query='SELECT
  matriid,DateUpdated  from users.employee WHERE
  date(DateUpdated)>='2018-11-28'', topicPrefix='mysql-prod-kot-',
  incrementingColumn='', timestampColumns=[DateUpdated]} prepared SQL
  query: SELECT matriid,DateUpdated  from users.employee WHERE
  date(DateUpdated)>='2018-11-28' WHERE DateUpdated > ? AND
  DateUpdated < ? ORDER BY DateUpdated ASC
  (io.confluent.connect.jdbc.source.TimestampIncrementingTableQuerier:161)
      [2018-11-29 17:29:00,981] ERROR Failed to run query for table TimestampIncrementingTableQuerier{table=null, query='SELECT
  matriid,DateUpdated  from users.employee WHERE
  date(DateUpdated)>='2018-11-28'', topicPrefix='mysql-prod-kot-',
  incrementingColumn='', timestampColumns=[DateUpdated]}: {}
  (io.confluent.connect.jdbc.source.JdbcSourceTask:328)
      java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version
  for the right syntax to use near 'WHERE DateUpdated > '1970-01-01
  00:00:00.0' AND DateUpdated < '2018-11-29 17' at line 1

A: This happens because you are trying to use both "mode": "timestamp" and query. TimestampIncrementingTableQuerier appends a WHERE clause to the query that conflicts with existing WHERE clauses in the query.
JDBC source connector docs is clear on this:

query
If specified, the query to perform to select new or updated rows. Use
  this setting if you want to join tables, select subsets of columns in
  a table, or filter data. If used, this connector will only copy data
  using this query -- whole-table copying will be disabled. Different
  query modes may still be used for incremental updates, but in order to
  properly construct the incremental query, it must be possible to
  append a WHERE clause to this query (i.e. no WHERE clauses may be
  used). If you use a WHERE clause, it must handle incremental queries
  itself.

As a workaround, you can modify your query to (depending on what SQL flavour are you using)
SELECT * FROM ( SELECT * FROM table WHERE ...)

or
WITH a AS
   SELECT * FROM b
    WHERE ...
SELECT * FROM a

For example, in your case the query should be
"query":"SELECT * FROM (SELECT matriid,DateUpdated  from users.employee WHERE date(DateUpdated)>='2018-11-28') o"

A: The error is as shown:
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to use near
'WHERE `DateUpdated` > '1970-01-01 00:00:00.0' AND `DateUpdated` < '2018-11-29 17' at line 1

This is because you're using query but also "mode": "timestamp" and thus the connector tries to append it's own WHERE clause when you have also specified one in the query, which results in the invalid SQL
Per docs for the JDBC source connector:

in order to properly construct the incremental query, it must be possible to append a WHERE clause to this query (i.e. no WHERE clauses may be used). If you use a WHERE clause, it must handle incremental queries itself.


text:
Q: Bind an even to dynamically appended html in ionic 3

I am developing an app with the help of ionic 3
in the application i am generating dynamic html from .ts file and appending in HTML  . Now i want to bind and click event to html

After user done an click event i want to refresh the content present in the dynamically generated html
please help to solve this

    enter code here
my .ts file
with the below code i am generating html and appending to html
 outputHtml = '

My Cart
';
      var innerHTML = '';
      let amount = 0;
      let savings = 0;
      for (let dt in data) {
        amount += data[cart].vv.value;
        savings += data[cart].aa.value;
        innerHTML += '
'
        innerHTML += '
'
        innerHTML +=  '
'
        let img_url=data[cart].product.images ? ConfigurationPage.commonURL+data[dt].aa.images[1].url:'assets/img/place_holder.png'
        innerHTML +=    ''
        innerHTML +=  '
'
        innerHTML +=  '
'
        innerHTML +=    '
' + data[dt].aa.name + '
'
        innerHTML +=    '
'
        innerHTML +=  '
'
        innerHTML +='
'
        innerHTML +=  '
'
        innerHTML +=  '
'
        innerHTML +=    '
-
'
        innerHTML +=    '
'+data[dt].q+'
'
        innerHTML +=    '
+
'///I want an click event here to do some action
       //
        innerHTML +=  '
'
        innerHTML +=  '
'
        innerHTML +=  '
'
        innerHTML +=    '
'
        innerHTML +=      '
'
        if (data[dt].ss.value != 0) {
          innerHTML += '' + this.currency.transform((parseFloat(data[dt].tp.value) + parseFloat(data[dt].ss.value)), 'INR') + ''
        }

        innerHTML += '' + this.currency.transform(data[dt].tp.value, 'INR') + ''
        innerHTML +=    '
'
        if (data[cart].savings.value != 0) {
          innerHTML += '
' + this.currency.transform(data[dt].ss.value, 'INR') + '
'
        }
        innerHTML +=    '
'
        innerHTML +=  '
'
        // innerHTML += '
' + data[dt].qt+ '
'
        innerHTML += '
'
        innerHTML += '
'
        let abc={
          code:data[dt].aa.code,
          data:data[dt]
        }
        clickEventMethod.push(abc);
      }
      this.totalAmount = amount;
      this.totalSaving = savings;
      // outputHtml += '</ion-list>';
      let footerHtml = '
'
      footerHtml += '

Total amount
' + this.currency.transform(this.totalAmount, 'INR') + '
'
      footerHtml += '

Total amount
' + this.currency.transform(this.totalSaving, 'INR') + '
'
      footerHtml += '

Say Checkout to checkout all items

'
      console.log(clickEventMethod,'clickEventMethod')
      outputHtml += innerHTML + footerHtml + '

';

        this.appenData.nativeElement.insertAdjacentHTML('beforeend', outputHtml);//Appending the data at the end of the ion-content      // break;

HTML
<ion-header [ngClass]="!isFromHome ? 'leftPaddingCssTitle':'cssTitle'">

  <ion-navbar color="danger">
    <ion-title>{{headerName}}</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>

To go back , say Go Back

To Go cart , Say Open Cart  or Go to Cart

<ion-content>


text:
Q: Error 13: Invalid or unsupported executable format I installed Ubuntu alongside Windows 10. The Ubuntu setup instructed me to restart the system. After I restarted it automatically boots into Windows. I used easyBCD to add the entry of Ubuntu in boot-loader. Now that when I try to boot in Ubuntu I am getting the grub screen. I don't know what to do now as I am newbie to this. Also I think there is some problem with my hard disk as I am not even able to boot into Windows 10. I checked some online resources where they instructed the steps I performed. The steps are shown here:

to boot back into Ubuntu successfully. It would be of great help if anyone help me out here. Thanks in advance.


text:
Q: How to rotate a JPEG file on Android without losing quality and gaining file size? Background
I need to rotate images taken by the camera so that they will always have a normal orientation.
for this, I use the next code (used this post to get the image orientation)
//<= get the angle of the image , and decode the image from the file
final Matrix matrix = new Matrix();
//<= prepare the matrix based on the EXIF data (based on https://gist.github.com/9re/1990019 )
final Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),matrix,false);
bitmap.recycle();
fileOutputStream = new FileOutputStream(tempFilePath);
rotatedBitmap.compress(CompressFormat.JPEG, 100, fileOutputStream);
rotatedBitmap.recycle();

here the compression rate (AKA "quality" parameter) is 100.
The problem
The code works fine, but the result is larger than the original, much much larger.
The original file is around 600-700 KB, while the resulting file is around 3MB ...
This is even though both the input file and the output file are of the same format (JPEG).
The camera settings are at "super fine" quality. not sure what it means, but I think it has something to do with the compression ratio.
What I've tried
I've tried to set the "filter" parameter to either false or true. both resulted in large files.
Even without the rotation itself (just decode and encode), I get much larger files sizes...
Only when I've set compression ratio to around 85, I get similar files sizes, but I wonder how the quality is affected compared to the original files.
The question
Why does it occur?
Is there a way to get the exact same size and quality of the input file ?
Will using the same compression rate as the original file make it happen? Is it even possible to get the compression rate of the original file?
What does it mean to have a 100% compression rate ?

EDIT: I've found this link talking about rotation of JPEG files without losing the quality and file size , but is there a solution for it on Android ?
Here's another link that says it's possible, but I couldn't find any library that allows rotation of jpeg files without losing their quality

A: I tried two methods but I found out those methods take too long in my case. I still share what I used.
Method 1: LLJTran for Android
Get the LLJTran from here:
https://github.com/bkhall/AndroidMediaUtil
The code:
public static boolean rotateJpegFileBaseOnExifWithLLJTran(File imageFile, File outFile){
    try {

        int operation = 0;
        int degree = getExifRotateDegree(imageFile.getAbsolutePath());
        //int degree = 90;
        switch(degree){
            case 90:operation = LLJTran.ROT_90;break;
            case 180:operation = LLJTran.ROT_180;break;
            case 270:operation = LLJTran.ROT_270;break;
        }
        if (operation == 0){
            Log.d(TAG, "Image orientation is already correct");
            return false;
        }

        OutputStream output = null;
        LLJTran llj = null;
        try {
            // Transform image
            llj = new LLJTran(imageFile);
            llj.read(LLJTran.READ_ALL, false); //don't know why setting second param to true will throw exception...
            llj.transform(operation, LLJTran.OPT_DEFAULTS
                    | LLJTran.OPT_XFORM_ORIENTATION);

            // write out file
            output = new BufferedOutputStream(new FileOutputStream(outFile));
            llj.save(output, LLJTran.OPT_WRITE_ALL);
            return true;
        } catch(Exception e){
            e.printStackTrace();
            return false;
        }finally {
            if(output != null)output.close();
            if(llj != null)llj.freeMemory();
        }
    } catch (Exception e) {
        // Unable to rotate image based on EXIF data
        e.printStackTrace();
        return false;
    }
}

public static int getExifRotateDegree(String imagePath){
    try {
        ExifInterface exif;
        exif = new ExifInterface(imagePath);
        String orientstring = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
        int orientation = orientstring != null ? Integer.parseInt(orientstring) : ExifInterface.ORIENTATION_NORMAL;
        if(orientation == ExifInterface.ORIENTATION_ROTATE_90)
            return 90;
        if(orientation == ExifInterface.ORIENTATION_ROTATE_180)
            return 180;
        if(orientation == ExifInterface.ORIENTATION_ROTATE_270)
            return 270;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return 0;
}

Method 2: Using libjepg-turbo's jpegtran executable
1 Follow the step describe here:
https://stackoverflow.com/a/12296343/1099884
Except that you don't need obj/local/armeabi/libjpeg.a on ndk-build because I only want the jpegtran executable but not mess with JNI with libjepg.a .
2 Place the jpegtran executable on asset folder.
The code:
public static boolean rotateJpegFileBaseOnExifWithJpegTran(Context context, File imageFile, File outFile){
    try {

        int operation = 0;
        int degree = getExifRotateDegree(imageFile.getAbsolutePath());
        //int degree = 90;
        String exe = prepareJpegTranExe(context);
        //chmod ,otherwise  premission denied
        boolean ret = runCommand("chmod 777 "+exe);
        if(ret == false){
            Log.d(TAG, "chmod jpegTran failed");
            return false;
        }
        //rotate the jpeg with jpegtran
        ret = runCommand(exe+
                " -rotate "+degree+" -outfile "+outFile.getAbsolutePath()+" "+imageFile.getAbsolutePath());

        return ret;
    } catch (Exception e) {
        // Unable to rotate image based on EXIF data
        e.printStackTrace();
        return false;
    }
}

public static String prepareJpegTranExe(Context context){
    File exeDir = context.getDir("JpegTran", 0);
    File exe = new File(exeDir, "jpegtran");
    if(!exe.exists()){
        try {
            InputStream is = context.getAssets().open("jpegtran");
            FileOutputStream os = new FileOutputStream(exe);
            int bufferSize = 16384;
            byte[] buffer = new byte[bufferSize];
            int count;
            while ((count=is.read(buffer, 0, bufferSize))!=-1) {
                os.write(buffer, 0, count);
            }
            is.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return exe.getAbsolutePath();
}

public static boolean runCommand(String cmd){
    try{
        Process process = Runtime.getRuntime().exec(cmd);

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()));
        int read;
        char[] buffer = new char[4096];
        StringBuffer output = new StringBuffer();
        while ((read = reader.read(buffer)) > 0) {
            output.append(buffer, 0, read);
        }
        reader.close();

        // Waits for the command to finish.
        process.waitFor();

        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

Unfortunately, both take too long. It is 16 seconds on my Samsung Galaxy S1!!!! But I found out this app (https://play.google.com/store/apps/details?id=com.lunohod.jpegtool) only take 3-4 seconds. There must be some way to do.

A: Once you are done setting you bestPreviewSize You have to now set for bestPictureSize every phone supports different picture sizes so to get Best Picture quality you have to check supported picture sizes and then set best size to camera parameter. You have to set those parameters in surface changed to get the width and height. surfaceChanged will be called in start and thus your new parameters will be set.
 @Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

 Camera.Parameters myParameters = camera.getParameters();

        myPicSize = getBestPictureSize(width, height);

        if (myBestSize != null && myPicSize != null) {

            myParameters.setPictureSize(myPicSize.width, myPicSize.height);

            myParameters.setJpegQuality(100);
            camera.setParameters(myParameters);

            Toast.makeText(getApplicationContext(),
                    "CHANGED:Best PICTURE SIZE:\n" +
                            String.valueOf(myPicSize.width) + " ::: " + String.valueOf(myPicSize.height),
                    Toast.LENGTH_LONG).show();
      }
}

Now the getBestPictureSize ..
 private Camera.Size getBestPictureSize(int width, int height)
    {
    Camera.Size result=null;
    Camera.Parameters p = camera.getParameters();
    for (Camera.Size size : p.getSupportedPictureSizes()) {
        if (size.width>width || size.height>height) {
            if (result==null) {
                result=size;
            } else {
                int resultArea=result.width*result.height;
                int newArea=size.width*size.height;

                if (newArea>resultArea) {
                    result=size;
                }
            }
        }
    }
    return result;

}

A: 100% quality rate probably is a higher quality setting than the setting the files are originally saved with. This results in higher size but (almost) the same image.
I'm not sure how to get exactly the same size, maybe just setting the quality to 85% will do (Quick and Dirty).
However if you just want to rotate the pic in 90°-steps, you could edit just the JPEG-metadata without touching the pixel data itself.
Not sure how it's done in android, but this is how it works.

A: For rotation, try this..
final Matrix matrix = new Matrix();
matrix.setRotate(90):
final Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),matrix,false);

I am using PNG images and it is working fine.... for JPEG images, please check the above code.


text:
Q: How to execute local python scripts in Jenkins UI I am new to Jenkins, recently want to schedule a job to execute a local python script. I do not have a source control yet so I selected "None" in Source Code Management when creating the job in the Jenkins UI.
I did some research about how to execute python scripts in Jenkins UI and I tried using Python Plugin to execute python scripts as build steps. But it failed. (But actually I don't want to use this Plugin since my script takes input arguments so I think I need to select something like "execute shell" in BUILD field -- I tried but also failed) Could anyone help me to find out how to properly run/call a local python script?
PS: I am also not clear about the Jenkins Workspace and how it works? Will appropriate if someone could clarify it for me.
Here is the Console output I got after the fail build:
Started by user Yiming Chen
[EnvInject] - Loading node environment variables.
Building in workspace D:\Application\Jenkins\workspace\downloader
[downloader] $ sh -xe C:\windows\TEMP\hudson3430410121213277597.sh
The system cannot find the file specified
FATAL: command execution failed
java.io.IOException: Cannot run program "sh" (in directory     "D:\Application\Jenkins\workspace\downloader"): CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at hudson.Proc$LocalProc.<init>(Proc.java:245)
at hudson.Proc$LocalProc.<init>(Proc.java:214)
at hudson.Launcher$LocalLauncher.launch(Launcher.java:846)
at hudson.Launcher$ProcStarter.start(Launcher.java:384)
at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:108)
at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:65)
at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:779)
at hudson.model.Build$BuildExecution.build(Build.java:205)
at hudson.model.Build$BuildExecution.doRun(Build.java:162)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:534)
at hudson.model.Run.execute(Run.java:1728)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:98)
at hudson.model.Executor.run(Executor.java:404)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
... 16 more
Build step 'Execute shell' marked build as failure
Finished: FAILURE

A: Another way is creating pipeline and execute sh command, which points to your python script. You also can pass parameters via Jenkins UI as dsaydon mentioned in his answer.
sh command can be as follow (is like you run in command line):
sh 'python.exe myscript.py'

Example pipeline step with creating new virtual environment and run script after installing of all requirements
stage('Running python script'){
sh      '''
        echo "executing python script"
        "'''+python_exec_path+'''" -m venv "'''+venv+'''" && "'''+venv+'''\\Scripts\\python.exe" -m pip install --upgrade pip && "'''+venv+'''\\Scripts\\pip" install -r "'''+pathToScript+'''\\requirements.txt" && "'''+venv+'''\\Scripts\\python.exe" "'''+pathToScript+'''\\my_script.py" --path "'''+PathFromJenkinsUI+'''"
        '''
}

where
sh '''
   your command here
   '''

means multiline shell command (if you really need it)
You also can pass variables from your pipeline (groovy-script) into sh command and, consequently, to your python script as arguments. Use this way '''+argument_value+''' (with three quotes and plus around variable name)
Example: your python script accepts optional argument path and you want to execute it with specific value which you would like to input in your Jenkins UI. Then your shell-command in groovy script should be as follow:
// getting parameter from UI into `pathValue` variable of pipeline script
// and executing shell command with passed `pathValue` variable into it.

pathValue = getProperty('pathValue')
sh '"\\pathTo\\python.exe" "my\\script.py" --path "'''+pathValue+'''"'

A: Create a Jenkins job and run your scripts as shell script from jenkins job.
Like this
#!/bin/sh
python <absolute_path_of_python_script>.py

A: instead of handle local script file on each server, you can actually copy all the python script into the "execute shell" under the Build section.
it has to start with the relevant python shebang. For example:
#!/usr/bin/env python
your script...

you can also add parameters in the job and use environment variables in your python script. for example
parameter1 = os.environ['parameter1']

A: To execute a Python script under BUILD option- select execute windows batch command - type these cammands.
I am passing the pythonpath because jenkins was not able to access the environmental variables because of access issues.
set PYTHONPATH=%PYTHONPATH%;C:\Users\ksaha029\AppData\Local\Programs\Python\Python3
python C:\Users\ksaha029\Documents\Python_scripts\first.py

A: On Mac I just moved the script.py to /Users/Shared/Jenkins/Home/workspace/your_project_name and with chmod 777  /Users/Shared/Jenkins/Home/workspace/your_project_name/script.py I could fix the problem.
Also, I did not need to use :
#!/bin/sh or #!/usr/bin/env python. Just inside jenkins build I used:
python3 /Users/Shared/Jenkins/Home/workspace/your_project_name/script.py
I should mention that, for one day I was trying tu solve this problem, and I have read all the froum related questions. no one really could help :/ .

A: Simplest implementation is checking the inject environment variables into the build process box. Then define two variables one for the python another for the script.
For example PYTHONPATH = C:/python37/python.exe
TEST1SCRIPT = C:/USERS/USERNAME/Documents/test1.py
Executing the windows batch command.
%PYTHONPATH% %TEST1SCRIPT%
This way you can run a number of scripts inside one or multiple execute windows batch command segments. There are also way to customize. You can create a wrapper that would run the scripts under Jenkins, this way, script result output could be formatted, if emailing results of the whole test suite.


text:
Q: How to find the Fourier series of the function $\frac{1}{1+x^2}$from $-\pi$ to $0$ and $\frac{-1}{1+x^2}$from$0$ to $\pi$ I'm stuck in calculating the integration $\int\frac{\sin x}{1+x^2}dx$ while finding the Fourier series of the so-called function.I've tried many exchanging variables but none of the worked.any help would be appreciated.

A: An antiderivative for that integrand will involve Fresnel functions (yuck.)  But for the interval $-\pi$ to $\pi$, the answer will be $0$ because it's an odd function over a symmetric interval.  The integral from $0$ to $\pi$ will be much more of a problem.  Either approximate with Taylor series or do something numerical or dive in with the Fresnel functions.

A: Let $f(x)=\frac{1}{1+x^2}$. The Fourier series for $f(x)$ is $\frac{1}{\pi}[\frac{1}{2}a_0+\sum_{i=1}^\infty(a_i\cos(ix)+b_i\sin(ix))]$, by definition. $f(x)$ is an even function so each $b_i$ will be $0$.
$$\begin{align}
a_0
&=\int_{-\pi}^\pi \frac{1}{1+x^2}\,\mathrm{d}x
\\
&=\left[\tan^{-1}(x)\right]_{-\pi}^\pi
\\
&=2\tan^{-1}(\pi)
\\
\\
a_i&=\int_{-\pi}^\pi \frac{1}{1+x^2}\cos(ix)\,\mathrm{d}x
\\
&=\int_{-\pi}^\pi \frac{1}{1+x^2}\sum_{j=0}^\infty\frac{(-1)^j(ix)^{2j}}{(2j)!}\,\mathrm{d}x
\\
&=\sum_{j=0}^\infty\int_{-\pi}^\pi \frac{(-1)^j(ix)^{2j}}{(1+x^2)(2j)!}\,\mathrm{d}x
\\
&=\sum_{j=0}^\infty\left[\frac{(-1)^j(i x)^{2 j}x\cdot {_2}F_1(1, j+1/2, j+3/2, -x^2)}{(2 j+1) (2 j)!}\right]_{-\pi}^\pi\quad *
\\
&=\scriptsize\sum_{j=0}^\infty\left(\frac{(-1)^j(i \pi)^{2 j}\pi\cdot {_2}F_1(1, j+1/2, j+3/2, -\pi^2)-(-1)^j(-i \pi)^{2 j}(-\pi)\cdot {_2}F_1(1, j+1/2, j+3/2, -(-\pi)^2)}{(2 j+1) (2 j)!}\right)
\\
&=\sum_{j=0}^\infty\frac{(-1)^j{_2}F_1(1, j+1/2, j+3/2, -\pi^2)(i \pi)^{2 j}\pi}{(2 j+1) (2 j)!}\left(1+(-1)^{2j}\right)
\end{align}$$
We can simplify $(1+(-1)^{2j})$ to just $2$.
$$\\a_i=
2\pi\sum_{j=0}^\infty\frac{(-1)^j{_2}F_1(1, j+1/2, j+3/2, -\pi^2)(i \pi)^{2 j}}{(2 j+1) (2 j)!}$$
So we have a final answer and can calculate a few coefficients with WolframAlpha.
$$\begin{align}
f(x)
&=\frac{\tan^{-1}(\pi)}{\pi}
+2\sum_{i=1}^\infty
\sum_{j=0}^\infty
\frac{(-1)^j{_2}F_1(1, j+1/2, j+3/2, -\pi^2)(i \pi)^{2 j}}{(2 j+1) (2 j)!}\cos(ix)
\\
&\approx 0.402+2\left[
0.194\cos(x)+0.064\cos(2x)+0.027\cos(3x)+0.008\cos(4x)
\right]
\end{align}$$
By plotting our approximate coefficients in Geogebra, we can show that with just $4$ terms of the series, we achieve an absolute error less than $0.01$ over the interval $[-\pi,\pi]$ and the curve is fitted very well.

* According to WolframAlpha, where ${_2}F_1(a,b;c;x)$ is the hypergeometric function.


text:
Q: i want result, python selenium filter I want to filter td
HTML:

ABC	13,841

DFG	34,158

HIJ	35,184

KLM	42,501

SUM	125,684

I Try This (failed):
a = soup.select('#list_shop')
for b in a:
    ab = a.select('#list_shop > tr > td')
    print(ab)

I want as result:
ABC 13,841
DFG 34,158
HIJ 35,184
KLM 42,501
SUM 125,684

A: In Selenium I would do this :
CSS_SELCTOR :
tbody#list_shop td

use it like this :
driver.find_elements(By.CSS_SELECTOR, "tbody#list_shop td")

this will give you a list of all td's (WebElement) :
for td in driver.find_elements(By.CSS_SELECTOR, "tbody#list_shop td"):
    print(td.get_attribute('innerHTML'))


text:
Q: How do I solve a system of equations containing a modulus function? I'm trying to solve this system of equations for $a$:
$$\frac{3n+1}{2^{a-1}} \mod 2 = 1$$
$$n \mod 2 = 1$$
for any odd input $n$.
I know that there is only $1$ solution for every possible $n$ value. For example, if $n=9$, then $a=3$, however, I am unable to solve algebraically for $n$. Is it possible to do so?

A: By definition if $x \mod 2 = 1$, then $x$ is odd.
If $n$ is guaranteed odd, then the second equation is guaranteed.
The numerator $3n + 1$ of the first equation is always positive and even. But after dividing by $2^{a-1}$ we want the output to be odd. Thus, this problem is in a way about prime factors. Think of the prime factorization:
$$3n + 1 = 2^{x} \cdot \prod_{i=1}^{b} p^{\, x_i}_{\,i}$$.
$x$ represents the number of $2$'s in the prime factorization of $3n + 1$. By definition of the primes greater than $2$, $p_{\, i}$ must be odd for every $i$. With this, we know
$$ \frac{3n+1}{2^{a-1}} = 2^{x - a + 1} \cdot \prod_{i=1}^{b} p^{\, x_i}_{\,i}$$
and this number can only be odd if $a = x + 1$ (if $a < x + 1$, there would be a $2$ left which makes it even, and if $a > x + 1$, the modulus would be a fraction).
This all being said, I don't think there is an analytical closed-form formula for the number of $2$'s in the prime factorization of a number.

A: Fixed $a$, different solutions can be found for n
if $\quad a=2 \quad $ then $\quad n \equiv 3 \pmod 4 \quad$  are solutions
for $\quad x>0 \quad$
if $\quad a=2 \cdot x +1 \quad $ then $\quad n \equiv \frac{2^{2 \cdot x}-1} {3} \pmod {2^{2 \cdot x+1}}\quad$  are solutions
if $\quad a=2 \cdot x +2\quad $ then $\quad n \equiv \frac{5 \cdot 2^{2 \cdot x+1}-1}{3} \pmod {2^{2 \cdot x+2}}\quad$  are solutions


text:
Q: Dealing with encoding inconsistencies/cleaning hidden characters from webpage I scraped the link below and I want to process the text for further analysis using Python. The segment at issue is "kwa vimada wake". I want to end up with text the corresponds to the way it is intended to display (and does display on my browser), as "kwa vimada wake". However, there are hidden characters around "vimada", which you can see if you copy the text and paste into a program like Notepad++. These mess with my tokenization and NLP processing (POS tagger doesn't recognize the word, for example) and seem not to stay consistent between my script and other programs (after using machine learning and then loading the results in my script, I end up with vimadaÃ, which it can't match with vimada�).
The webpage seems to be using UTF-8 encoding and my files are saved with UTF-8 encoding. If I could solve this issue and eliminate any strange/hidden characters, I would have no issues with consistency across files or using it as input into NLP tools.
My script is using # -- coding: utf-8 --
I would prefer to work with the text I've already downloaded because security changes to the site have made re-scraping it impractical. My database has it saved as "kwa âvimadaâ wake". The begin/end characters display in Notepad++ as three characters each: [â][PAD][SOS] and [â][PAD][SGCI].
I want to remove unicode white space/hidden characters and convert all variants of punctuation like apostrophes, quotation marks, hyphens, etc. into their ASCII equivalents. I would prefer to keep accented characters as is. However, not all accented characters are currently being interpreted correctly. Some are encoded incorrectly, some were changed on the website presumably due to software changes and show up as html code like é. So a simple deletion of a class of characters won't clean the data properly. I'm using python 2.7.
http://www.jamiiforums.com/threads/rais-dhaifu-ccm-uchaguzi-2015.459292/#post-6461865


text:
Q: Access to music folder on different devices I have music download and player application, the problem is that I am getting massive ammount of null pointer exceptions every day because directory path is different on different devices.
How to resolve it?
Here is my path:
final String MEDIA_PATH = new String(Environment.getExternalStorageDirectory().toString() + "/Music");

and here how i'm creating song list (getPlaylist):
public ArrayList<HashMap<String, String>> getPlayList(){
    File home = new File(MEDIA_PATH);

    if (home.listFiles(new FileExtensionFilter()).length > 0) {
        for (File file : home.listFiles(new FileExtensionFilter())) {
            HashMap<String, String> song = new HashMap<String, String>();
            song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
            song.put("songPath", file.getPath());
            songsList.add(song);
        }
    }
    return songsList;
}

Stack trace from crash analytics service:
    Full Stack Trace:
java.lang.NullPointerException
music.download.justin.utils.SongReader.getPlayList(SongReader.java:22)
music.download.justin.Player.player(Player.java:164)
music.download.justin.Player.onViewCreated(Player.java:103)
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:973)
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:490)
android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
android.support.v4.view.ViewPager.populate(ViewPager.java:1105)
android.support.v4.view.ViewPager.populate(ViewPager.java:951)
android.support.v4.view.ViewPager$3.run(ViewPager.java:250)
android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
android.view.Choreographer.doCallbacks(Choreographer.java:579)
android.view.Choreographer.doFrame(Choreographer.java:547)
android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
android.os.Handler.handleCallback(Handler.java:800)
android.os.Handler.dispatchMessage(Handler.java:100)
android.os.Looper.loop(Looper.java:194)
android.app.ActivityThread.main(ActivityThread.java:5371)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:525)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
dalvik.system.NativeStart.main(Native Method)

Mostly affected devices:
Samsung (all models)
Kyocera
HTC

A: I guess this was happening because of the device couldn't able to load the media path from SD card/External storage. you could either use Exception handling/throw some valid error message in else condition to avoid the crash or Exceptions.
Check the android version of those devices, if it exceeded to marshmallow, then you must to specify the permission at the code level.


text:
Q: MVC EF - System.Data.Entity.Infrastructure.DbUpdateException I have two models :
UserProfile
public class UserProfile
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
    public virtual ICollection<UserPost> UserPost { get; set; }
}

UserPost:
public class UserPost
{
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public string Id { get; set; }
   public string PostTitle { get; set; }
   public virtual UserProfile UserProfile { get; set; }
   public string Contents { get; set; }
}

UserProfile has a one-to-one relationship with AspNetUser.
UserProfile has a one-to-many relationship with UserPost.
When I'm adding UserPost to the database in the Create method in my controller I get a System.Data.Entity.Infrastructure.DbUpdateException
    [HttpPost]
    [ValidateAntiForgeryToken]
    [Authorize]
    public ActionResult Create([Bind(Include = "PostTitle, Content")] UserPost post)
    {
        if (ModelState.IsValid)
        {

            UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
            var user = UserManager.FindById(User.Identity.GetUserId());
            post.UserProfile = user.UserProfile;
            db.UserPosts.Add(post);
            db.SaveChanges();//error here
            return RedirectToAction("Index");
        }

        return View(post);
    }

System.Data.Entity.Infrastructure.DbUpdateException occurred
    HResult=0x80131501
    Message=An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.
Inner Exception 1: UpdateException: An error occurred while updating
  the entries. See the inner exception for details.
Inner Exception 2: SqlException: Cannot insert the value NULL into
  column 'Id', table 'aspnet-project12017.dbo.UserPosts'; column does
  not allow nulls. INSERT fails. The statement has been terminated.

A: [DatabaseGenerated(DatabaseGeneratedOption.Identity)] means that the column marked with such attribute expected having auto-generated value from DBMS, and as a general convention that EF treats string & uniqueidentifier (GUID) columns as non auto-incremented, hence those columns value must be assigned in another way (i.e. by constructor assignment).
Common approach to solve null problem for primary key auto-incremented identity column is simply set it to numeric data type (e.g. int):
public class UserPost
{
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public int Id { get; set; } // change to numeric data type
   public string PostTitle { get; set; }
   public virtual UserProfile UserProfile { get; set; }
   public string Contents { get; set; }
}

Then, when performing migrations, do these steps:

*

*Sometimes EF expects by default that you're trying to insert into identity column. If this happens, set StoreGeneratedPattern.None & DatabaseGenerationOption.None to UserPost.Id temporarily:
protected void OnModelCreating(DbModelBuilder modelBuilder)
{
    // other entities

    modelBuilder.Entity<UserPost>()
       .HasKey(p => p.Id)
       .Property(p => p.Id)
       .StoreGeneratedPattern = StoreGeneratedPattern.None;

   // other entities
}

*Ensure that the model has been modified to include actual Id property (try to delete UserPost table in DB when required).

*Run migration through Package Manager Console as this:
Add-Migration "Set Id as Identity Specification"

*In a generated class from DbMigration you will see two methods: Up() and Down(). Modify Up() part to set int datatype there (and re-run migration process when required):
public override void Up()
{
    CreateTable(
          "dbo.UserPost",
          c => new
          {
              Id = c.Int(nullable: false, identity: true),
              PostTitle = c.String(),
              Contents = c.String(),
          })
          .PrimaryKey(t => t.Id);
}

If you still want string Id column as primary key for UserPost, you need to set it as [DatabaseGenerated(DatabaseGeneratedOption.None)] and assign values manually from class constructor (note that generated values must be unique at all or EF will tell you "cannot insert duplicate key in object"):
public class UserPost
{
    public UserPost()
    {
        Id = [[autogenerated value here]];
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string Id { get; set; }

    // other properties
}

Related issues:
MVC5 EF6 Seed Method: Cannot insert NULL into column 'Id' table AspNetUsers
Cannot insert the value NULL into column 'Id' (Database first)
Code first - Cannot insert the value NULL into column 'Id'
Entity Framework Cannot insert the value NULL into column Identity Specification set to No


text:
Q: How can I manually reinitialise jscrollpane? I'm trying to manually reinitialise jscrollpane in my index.php & single.php file after disqus comments have been loaded rather than set autoreinitialise to true when I initialise in my header.php. I'm trying to do so as follows:
<script type="text/javascript">
$(document).ready(function() {
var api = $('.scroll-pane').jScrollPane(settings).data('jsp');
api.reinitialise();
});
</script>

I can't figure out what I am doing wrong. Any help is appreciated!

A: I think the problem is that your diquss height aren't ready when the document is ready, try to use a timeout for the reinit, or if disquss has loadingComplete callback use it to reinitialise after it has finished loading using the same lines you wrote in your question should work.


text:
Q: iOS settings URL changes in iOS 10.0 SDK Now 'prefs:root=general&path=about' doesn't work in iOS 10.0 SDK.
Both methods:
- (BOOL)openURL:(NSURL*)url NS_DEPRECATED_IOS(2_0, 10_0, "Please use openURL:options:completionHandler: instead") NS_EXTENSION_UNAVAILABLE_IOS("");
- (void)openURL:(NSURL*)url options:(NSDictionary<NSString *, id> *)options completionHandler:(void (^ __nullable)(BOOL success))completion NS_AVAILABLE_IOS(10_0) NS_EXTENSION_UNAVAILABLE_IOS("");

are failed.
Does anyone has solutions?


text:
Q: WebLogic Server firewall - Jboss Server (Jasper Server) Environment :

*

*ADF application running on WebLogic Server 11gR1 - JDeveloer 11.1.1.7

*We are doing report generation using Jasper Server deployed on JbossServer. Templates (i.e .JRXML) is present in Jasper Server
Application Requirement :
Report Generation for our ADF application running on WebLogic Server which is firewalled.

*

*To fill the templates present in the jasperServer, dataMap has to be passed from weblogic Server to Jasper server as request through Web-Service.

*Through URL fetching the generated report from JasperServer (i.e running on JBOSS)  into our ADF application I-Frames. As response passing weblogic server firewall.
Help :
How the request from the jasper server can be passed though our WebLogic Server Firewall into our application and reponse to vice versa..
Oracle EM - how can it help here. Is there any other solutions Please suggest...
Thanks in advance..


text:
Q: Serialize binary tree in a stream and reconstruct the tree You have a binary tree (not BST), serialize it in a stream and reconstruct the tree maintaining the format of the tree.
Sending 2 streams InOrder + PreOrder or InOrder + PostOrder is not an option.
Can anyone suggest some solution, using JAVA?

A: If your data structure allows it, you could use Java Serialization API. If your tree objects (and all objects referenced from it) implement java.io.Serializable, you could use the API serialize the whole structure into a stream and then deserialize it at some different place. (The linked page contains an example.) The serialization library handles dependencies between serialized objects, so that they are properly restored when deserailizing.

A: In addition to Petr's answer you might want to have a look here.
Be sure that the object that should be streamed implements the java.io.Serializable interface.


text:
Q: Understanding the TimeSeriesDataSet in pytorch forecasting Here is a code sample taken from one of pytorch forecasting tutorila:
# create dataset and dataloaders
max_encoder_length = 60
max_prediction_length = 20

training_cutoff = data["time_idx"].max() - max_prediction_length

context_length = max_encoder_length
prediction_length = max_prediction_length

training = TimeSeriesDataSet(
    data[lambda x: x.time_idx <= training_cutoff],
    time_idx="time_idx",
    target="value",
    categorical_encoders={"series": NaNLabelEncoder().fit(data.series)},
    group_ids=["series"],
    # only unknown variable is "value" - and N-Beats can also not take any additional variables
    time_varying_unknown_reals=["value"],
    max_encoder_length=context_length,
    max_prediction_length=prediction_length,
)

validation = TimeSeriesDataSet.from_dataset(training, data, min_prediction_idx=training_cutoff + 1)
batch_size = 128
train_dataloader = training.to_dataloader(train=True, batch_size=batch_size, num_workers=0)
val_dataloader = validation.to_dataloader(train=False, batch_size=batch_size, num_workers=0)

I don't really understand how the validation dataset is done with respect to the time index. I also don't understand why there is no test dataset in the tutorial. is it for a specific reason?

A: Concerning validation dataset:
training dataset is all data except the last max_prediction_length data points of each Time series (each time series correspond to datapoints with same group_ids).
Those last datapoints are filtered by the training cutoff (cutoff is the same for each time series because they are of same size)
validation data is the last max_prediction_length data points use as targets for each time series (which mean validation data are the last encoder_length + max_prediction_length of each time series).
This is done by using parameter min_prediction_idx=training_cutoff + 1 which make the dataset taking only data with time_index with value superior to training_cutoff + 1 (minimal decoder index is always >= min_prediction_idx)


text:
Q: Números complexos em C++ Sou novo no C++ e gostaria de saber como usar números complexos sem ser da seguinte forma:
double real[2]={2,5};
double imaginario[2]{7,9};
cout << "Soma: " << real[0]+real[1] << "+" << imaginario[0]+imaginario[1] << "i";

Há alguma library para isto?

A: Há sim:
#include <iostream>
#include <complex>
using namespace std;

int main(){

    complex<double> a={2,7}, b={5,9};
    cout << "Soma: " << a+b;

}


text:
Q: Why the springdoc always show the petshop Swagger UI I am trying to integrete the spring doc into my spring boot project. First, I added the dependencies
api "org.springdoc:springdoc-openapi-ui:1.6.9"
api "org.springdoc:springdoc-openapi-webmvc-core:1.2.32"

then access the swagger ui: http://127.0.0.1:11014/swagger-ui/index.html#/. Now I facing a problem is that no matter how to tweak the  open api swagger config, the swagger ui always show the petshop api. I have tried to add config like this
package misc.config.openapi;

import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OpenApiConfig {

    @Bean
    public OpenAPI openAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("Student Manager API")
                        .description("Student manager server api.API.")
                        .version("appVersion")
                        .license(new License()
                                .name("Apache2.0")
                                .url("http://springdoc.org")))
                .externalDocs(new ExternalDocumentation()
                        .description("Documentation")
                        .url("https://www.jianshu.com/nb/41542276"));
    }

}

Why the spring docs always show the petshop api? how to make the swagger ui show the project api not the demo petshop version?


text:
Q: Is it OK for Scrapy's request_fingerprint method to return None? I'd like to override Scrapy's default RFPDupefilter class as follows:
from scrapy.dupefilters import RFPDupeFilter

class URLDupefilter(RFPDupeFilter):

    def request_fingerprint(self, request):
        if not request.url.endswith('.xml'):
            return request.url

The rationale is that I would like to make the requests.seen 'human-readable' by using the scraped URLs (which are sufficiently unique) rather than a hash. However, I would like to omit URLs ending with .xml (which correspond to sitemap pages).
Like this, the request_fingerprint method will return None if the requests URL ends with .xml. Is this a valid implementation of a dupefilter?

A: If you look into request_seen() method of DupeFilter class you can see how scrapy compares fingerprints:
def request_seen(self, request):
    fp = self.request_fingerprint(request)
    if fp in self.fingerprints:
        return True
    self.fingerprints.add(fp)
    if self.file:
        self.file.write(fp + os.linesep)

fp in self.fingerprints, in your case this would resolve to None in {None}, since your fingerprint is None and self.fingerprints is a set type object. This is valid python and resolves properly.
So yes, you can return None.
Edit: However this will let through first xml response, since the fingerprints set will not have None fingerprint in it yet. Ideally you want to fix request_seen method in your dupefilter as well to simply return False if fingerprint is None.


text:
Q: Outputting a var with a colon in it I get a something from my config in my js:
<script>var r = {{ Config::get('app::r') }}; console.log(r);</script>

The {{}} is laravel, it just echos stuff from php.
The problem is I get an error:
Uncaught SyntaxError: Unexpected token :

The r in config has a : in it. It is:
r => '1:1';

How can I deal with outputting the string?

A: <script>var r = "{{ Config::get('app::r') }}"; console.log(r);</script>

A: Just use the " in the set of r variable and you will get a string.
<script>var r = "{{ Config::get('app::r') }}"; console.log(r);</script>

You also could specify a property and set a object in this property, and get a javascript object, for sample:
<script>var r = { item: { Config::get('app::r') } }; console.log(r);</script>


text:
Q: Prevent kids from "accidentally" making purchases in Steam The kids play with the gaming computer, which has a Steam account always logged in.
I'm worried about them "accidentally" purchasing something in the store, is there way to require a password to complete a purchase in Steam?

A: You can use Family View to restrict what your kids can do with your Steam account, including preventing them from accessing the store. This works by setting a 4-digit PIN that is used to log in as an adult within your account.
You can enable this and configure what parts of your Steam account are off-limits by going to Settings → Family and clicking on Manage Family View.

You'll want to leave the Steam store checkbox unchecked.

A: Another potential option, if none of the above work, is to put the steam client into "Offline" mode. Then they can get online and play those games that are actively downloaded/installed but they can't play uninstalled games, or go to the store and buy any additional games. Family options might be a better idea though.

A: You can't buy things from steam without billing information. So, I would suggest to:

*

*Clear billing information in child's account and stop using it for purchases. (On the top right of the steam window, click the child's username, and choose Account Details. Under Store and Purchase History, find the saved payment method(s) and hit Delete)

*Setup your own steam account.

*Buy games using your own account (buy as a gift) and gift them to your kid.

This will prevent game purchases AND "in-game" purchases.


text:
Q: This Code is giving the wrong output can't figure out where I made a mistake The code should display the number of times maximum number in the array has occurred so for the following input (3,2,1,3) the output should be '2' as '3' is the maximum number and occurs twice. I wanted to use functions, I know there is an easier way to solve it but i just want to know the problem in my code:-
#include<iostream>

using namespace std;

int frequency(int n, int a[]) {
    int j=0,max,count=0;
    max = a[j];
    while(j<n){
        if(a[j+1]> max){
            max = a[j+1];

        }
        j++;
    }
    int seen[n];
    for(int i = 0; i < n; i++)
        seen[i] = 0;

    for(int i = 0; i < n;i++) {
        if(seen[i] == 0) {
            int count = 0;
            for(int j = i; j < n;j++)
                if(a[j] == a[i] && a[j] == max)
                    count += 1;
            seen[j] = 1;

        }
    }
    return count;
}

int main() {
    int i,n;
    cin >> n;
    int a[n];
    for(i = 0; i < n; i++){
        cin >> a[i];
    }
    int result = frequency(n, a);
    cout << result << endl;
    return 0;
}

A: For starters the C++ Standard does not support Variable Length Arrays. So instead of an array you should use some container as for example std::vector<int>.
Moreover the program has undefined behavior because at least in this loop
while(j<n){
    if(a[j+1]> max){
        max = a[j+1];

    }
    j++;
}

there is an attempt to access memory beyond the array in the expression a[j+1].
And at last the function always returns 0 because the variable count in the outermost scope of the function is set to zero and is never changed.
A general approach can be written using iterators.
For example
#include <iostream>
#include <iterator>
#include <vector>

template <typename InputIterator>
size_t count_maximum_value( InputIterator first, InputIterator last )
{
    size_t count = 0;

    if ( first != last )
    {
        ++count;
        typename std::iterator_traits<InputIterator>::value_type max = *first;

        while ( ++first != last )
        {
            if ( max < *first )
            {
                max = *first;
                count = 1;
            }
            else if ( not ( *first < max ) )
            {
                ++count;
            }
        }
    }

    return count;
}

int main()
{
    size_t n = 0;

    std::cout << "Enter the number of integers: ";
    std::cin >> n;

    if ( n )
    {
        std::vector<int> v( n );

        std::cout << "Enter " << n << " integers: ";

        for ( size_t i = 0; i < n; i++ ) std::cin >> v[i];

        std::cout << "The maximum value is encountered "
                  << count_maximum_value( v.begin(), v.end() )
                  << " time(s)"
                  << std::endl;
    }

    return 0;
}

The program output might look the following way
Enter the number of integers: 4
Enter 4 integers: 3 2 1 3
The maximum value is encountered 2 time(s)

A: You are comparing a[j+1] with max. I suggest you use a[j]. You seem to be skipping the first number in your input.

A: Start with count = 1 instead of count = 0 and delete the redeclaration of count in the loop.
You're starting with 0, then you add 1 when you find the second entry that matches it. That's why you're off by one.

A: Check the comments
#include<iostream>

using namespace std;

int frequency(int n, int a[]) {
    int j=0,max,count=0;
    max = a[j];
    while(j<n){
        if(a[j]> max){  // 1. j+1 crosses lenth of array
            max = a[j];

        }
        j++;
    }
    int seen[n];
    for(int i = 0; i < n; i++)
        seen[i] = 0;

    for(int i = 0; i < n;i++) {
        if(seen[i] == 0) {
            //int count = 0;  //2. re declaration and you are not returning this
            //for(int j = i; j < n;j++) //3. No need of extra loop it make count extra because you are starting at j=i
                //if(a[j] == a[i] && a[j] == max)
                        if(a[i] == max)
                    count += 1;
            seen[j] = 1;

        }
    }
    return count;
}

int main() {
    int i,n;
    cin >> n;
    int a[n];
    for(i = 0; i < n; i++){
        cin >> a[i];
    }
    int result = frequency(n, a);
    cout << result << endl;
    return 0;
}


text:
Q: Spring bean registeration programmatically doesnt support transaction my project using template service pattern.
I tried two approach.
One, using @autowired annotation.
Then, set my parameter.
Two, using AutowireCapableBeanFactory. Create ServiceTemplate programmatically then autowireBean.
My service template class is
public class ServiceTemplate<T>{
public ServiceTemplate(){}
public ServiceTmeplate(T clazz, ...){
...}
@Transactional
public Response someMethod(){
 try{
...}
catch{
 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
}

On my controller code is
@Autowired
private AutowireCapableBeanFactory beanfactory

public Resonse getTest(){
final ServiceTemplate<testClass> serviceTemplate = new ServiceTemplate<>(.....)
beanfactory.autowireBean(seviceTemplate)
}

On my first approach, it works. It's rollback all transaction.
But I want to take the second approach. How to make my bean under transaction manager programmatically.

A: Second approach can't work because your ServiceTemplate is self-managed so spring can't proxyfied your bean with transactional concerns. Only the dependencies are managed and autowired by Spring here.
A solution is using programmatic transaction
class ServiceTemplate {

 @Autowired
 private PlatformTransactionManager transactionManager;

 private TransactionTemplate transactionTemplate;

 public Response someMethod() {
     //
     transactionTemplate.execute(status ->
       {
          // the code in this method executes in a transactional context
       }
    });
    //
 }


text:
Q: What happens if I lose all three hearts? Simple question—not sure if I missed it somewhere in the tutorial. I know I can buy hearts back but what happens if I lose all three? Get booted from the level and have to buy at least one back before continuing? Or do they come back automatically? Or do I lose progress? Don't want to find out the hard way.

A: If you die in a level, you will be sent back to the Tavern with 1 heart. You will not lose progress.
You will lose any materials collected during the last level and limited use equipment will stay used, but otherwise there is no punishment for dying. Challenge progress is kept after death. You can simply heal up at the Tavern and try the level again.


text:
Q: autolayout equal width constraints I'm working on implementing a custom graph view.  The design calls for the graph to have a margin of 11 pts on the left and the right, there are 25 blocks of equal width, and the spacing between the blocks is 2.  Not surprisingly this lays out and looks pretty much perfect on iPhone 5s and below. Using autolayout the system correctly finds that each block should be 10x10.

Things break down however when moving to the 6 and 6+.  For instance on the 5 some frames are calculated with a width 12 and 12.5.  This is what I get from the 6.

By manually doing the math and applying the ratio of the new screen sizes the widths don't come out to be integers but what autolayout comes up with is pretty far off.  I have some ideas on how to work around this but I'm not quite sure how to do it.  Here is the code that is laying out my 25 columns:
var columns = Array()
    var lastAddedColumn: UIView?
    for index in 0...numberOfColumns - 1 {
        let column = GraphColumn(frame: CGRectZero)
        column.numberOfRectangles = 10
        column.setTranslatesAutoresizingMaskIntoConstraints(false)
        self.addSubview(column)
        columns.append(column)

        if let lastColumn = lastAddedColumn {
            self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[v1]-2-[v2]", options: NSLayoutFormatOptions.allZeros, metrics: nil, views: dictionaryOfNames(lastColumn,column)))
            self.addConstraint(NSLayoutConstraint(item: column, attribute: .Width, relatedBy: .Equal, toItem: lastColumn, attribute: .Width, multiplier: 1, constant: 0))
        }
        self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[v1]|", options: NSLayoutFormatOptions.allZeros, metrics: nil, views: dictionaryOfNames(column)))

        lastAddedColumn = column
    }

    let firstColumn = columns.first!
    let lastColumn = columns.last!

    self.addConstraint(NSLayoutConstraint(item: firstColumn, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1, constant: 1))
    self.addConstraint(NSLayoutConstraint(item: lastColumn, attribute: .Right, relatedBy: .GreaterThanOrEqual, toItem: self, attribute: .Right, multiplier: 1, constant: -1))

The approach I'm using is to loop from 1-25 creating a column each time.  That column is pinned 2 pts to the right of the column before it and given a width equal to the one before as well.  Finally I pin the first and last to the left and right of the superview.  The superview is added to the scene via the storyboard and is pinned 11 pts to the left and right of the superview.
What I think might work is to have the margins be flexible but I'm unsure of how to accomplish this.  I tried lowering the 11 pt let and right priorities and using less than or equal but that didn't work. Really what I'm trying to get autolayout to do is do the equal width thing and if it's unable to find equal widths then it should push out the margins until can do so.  I think whats holding me up is that the system is reporting that it can satisfy the constraints when in reality it can't.


text:
Q: How to make nested colors in one div background? How I can put multiple nested colors (or 2 colors precisely) to a div in css?
If it's possible to do that, how I can specify the nesting form, as percentage of each color, position, etc?
I mean the gradients, to make a background like this:

A: You can do a 50/50 background if that's what you mean, using gradient, e.g.:
background: -webkit-gradient(linear, left top, right top, color-stop(50%,#000000), color-stop(50%,#333));

Or for a full gradient, e.g.:
-webkit-gradient(linear, left top, left bottom, color-stop(0%,#00b7ea), color-stop(100%,#000ed8));

Which is pretty straight forward, you just have to add the start and finish color. Also, I'm saving space above but you should of course use -o-linear-gradient, -ms-linear-gradient, linear-gradient as well if you want to be supported on all browsers).
There are also tools available to help you out:
http://www.colorzilla.com/gradient-editor/

A: You can use the RGB colors in order to choose one specific color:
background-color:rgb(255,255,255)

and playing with the values.
you can also use color codes:
background-color:#FF0F00

That is how you can reach a specific color (which is combined from two different ones). I don't know of any ways to nest them.
If you would like to read more about the subject you can read about it here:
http://www.w3schools.com/cssref/css_colors.asp
Good luck :)


text:
Q: Can you add an address for an Amazon Cart via API? I cant see it in the Product Advertising API reference but I wonder if it's possible to dynamically / automatically set the delivery billing address (and possibly further options like if the billing should be sent or the product should be wrapped as a gift) for an Amazon cart?
If that would be possible but not via Product Advertising API it would be fine, too (e.g. buying things for yourself with an API).

A: As I understand - no, you can't.
From the Amazon:

Amazon hosts the web pages in the Order Pipeline. Your application plays no role in purchasing the items or order fulfillment. However, your application must use the PurchaseURL returned by Product Advertising API cart operations to add the shopping cart items to the Order Pipeline.

Order Pipeline in docs is

A series of Amazon web pages that guides the customer through the checkout process, which includes adding the customer's name, shipping and billing addresses, payment method, and a purchase confirmation web page, as shown in the following.

That's mean users should fill shipping and billing addresses on Amazon hosted web pages during the checkout process. You can only provider url to finish checkout.
Same thing with your own address. There is no API to change it.


text:
Q: Apache beam python pipeline doesnt proceed after groupbykey() I am doing a GroupByKey in a pipeline, keys are strings and values are dictionaries. I want to group them and do processing on them.
I am able to reach next step if i remove the GroupByKey, but not with it.
(parseout_interim | beam.Map(lambda row: (row['prefix'] + row['report_id'], row))
                                                # | beam.GroupByKey()
                                                | beam.ParDo(ParseSegmentsDoFn()).with_outputs(ParseSegmentsDoFn.OUTPUT_TAG_TRADELINE,
                                                                                main = 'parseout'))

If I comment GroupByKey, data reaches next step.
Am i missing something completely?
Also, on a sidenote - is it advised against spinning up a pipeline inside a ParDo? or it is completely fine? If it is fine, i would get away without having to use groupbykey

A: As you imply in your comment, this must be a Streaming pipeline.
Consider that a streaming pipeline is continuously receiving events. When you want to group events within that pipeline, the system needs to know how long it should wait for events to come in while grouping them. Does that make sense?
Because of that, you need to have a windowing and triggering strategy for your pipeline, otherwise it will wait forever, to group all elements in the stream.


text:
Q: How to read and get Enter Key by Scaner I'm learning Java and at this moment I try simple tasks to get used to with Java synthax.
Today I wrote a simple calculator and one of task goal was to finish program when user press enter key. So this is my problem, my code solution work with other keys, for example 'y'
code with 'y' key(works properly):
import java.util.Scanner;

public class SimpleCalculator {

public static void main(String[] args) {

    System.out.println("Program 'Simple Calculator'");
    boolean log = true;
    Scanner in = new Scanner(System.in);

    while (log == true) {

        double result = 0;
        double a, b = 0;
        System.out.println("Enter the first number");
        a = in.nextDouble();
        char sign;
        String temp;
        boolean log2 = true;

        while (log2 == true) {
            System.out.println("Enter the algebraic operation sign ('+' ,'-' ,'*' or '/' )");
            temp = in.next();
            sign = temp.charAt(0);

            if (sign == '+' || sign == '-' || sign == '*' || sign == '/') {
                log2 = false;
                switch (sign) {
                case '+':
                    System.out.println("Enter the 2nd number ");
                    b = in.nextDouble();
                    result = a + b;
                    break;
                case '-':
                    System.out.println("Enter the 2nd number ");
                    b = in.nextDouble();
                    result = a - b;
                    break;
                case '*':
                    System.out.println("Enter the 2nd number ");
                    b = in.nextDouble();
                    result = a * b;
                    break;
                case '/':
                    while (b == 0) {
                        System.out.println("Enter the 2nd number ");
                        b = in.nextDouble();
                        if (b != 0)
                            result = a / b;
                        else
                            System.out.println("Division by 0 is undefined for real nubers, enter 2nd number again");
                    }
                    break;

                }

            } else {
                System.out.println("wrong operation sign, enter it once again");
            }
            if (log2 == false)
                System.out.println("Result: " + result);

        }
        System.out.println("Press y for exit the program(or any other to use it once again)");

        temp = in.next();
        if (temp.equals("y")) {
            System.out.println("y Key pressed.");
            log = false;
        }

    }
    in.close();
    System.out.println("End of work");

}

}
I tried two variations of last if to end work, when Enter is pressed
temp = in.next();
if (temp.equals("")) {
System.out.println("Enter Key pressed.");
log = false;}

and the second
temp =in.next();
        sign = temp.charAt(0);
        if (sign == 13 )    //carriage return character code
            log = false;

but both are not good in case of enter key. It would be great if somebody tell me why this two variations of if don't work properly with enter key and what is the best way to end program with end key.
Thank You :)


text:
Q: How do I remove and repair the hex file on my Ds2250t-32-16 micro controller Hi I have a circuit board that runs my on board water maker the chip Ds2250t-32-16 is faulty. The manufacturer won't supply the chip or the hex file . They want me to upgrade to a new board cost $3k Aud. I can but the chip for $50 online and a kit to load it from Dallas Microprocessor. My question is can I download the current file and repair it from the chip . I can get hold of 7 different chips all faulty but with different faults . Could these be overlaid on each other to build a correct file. Any help or advice would be appreciated . If I was working I would just pay for a new one but being retired 3k is a lot of cash.
Mike


text:
Q: Getting a pre-populated database into an android app Currently, I have a database called "data_eng.db" in my C: drive. It contains a bunch of quiz questions and other information about them on my quiz app. I created it with "DB Browser for SQLite".
I now want to get this prepopulated database from my computer that I created it on, to always be packaged with the android app in the /data/data/com.example/database/ folder when I run it from Android Studio
I understand that I need to use Room.databaseBuilder and put the path of my database (path of the db from the android device) in either the creatFromAsset or create from file parameter. However, I don't know how to get my database that's on my computer to an emulator or my phone without just copying the file over.
Edit 1 (Addressing comment concerns) :
Here is the code where I build a Room database based on a prepopulated database in the assets folder of my apk on the android device.
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.example.infinityquiz.model.Question

@Database(entities = [Question::class], version = 2, exportSchema = false)
abstract class QuestionDatabase: RoomDatabase() {
    abstract fun questionDao(): QuestionDao

    companion object {
        @Volatile
        private var INSTANCE: QuestionDatabase? = null
        private const val PATH = "database/data_eng.db"
        private const val NAME = "multiple_choice_questions"

        private fun buildDatabase(context: Context) =
            Room.databaseBuilder(context, QuestionDatabase::class.java, "data_eng.db").createFromAsset(PATH).build()

        fun getDatabase(context: Context): QuestionDatabase{
            val tempInstance = INSTANCE
            if(tempInstance != null){
                return tempInstance
            }
            synchronized(this){
                val instance = buildDatabase(context)
                INSTANCE = instance
                return instance
            }
        }
    }
}

Here is my entity class as well:
import android.os.Parcelable
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.android.parcel.Parcelize

@Parcelize
@Entity(tableName = "multiple_choice_questions")//, foreignKeys=[], indices=[])
data class Question (
    @PrimaryKey(autoGenerate = true)
    val id: Int,
    val Question: String,
    val Category: String,
    val Subcategory: String,
    val AnswerOne: String,
    val AnswerTwo: String,
    val AnswerThree: String,
    val AnswerFour: String,
    val CorrectAnswer: Int,
    val WasQuestionSeen: Int,
    val Wikipedia: String
): Parcelable

The database I created has a format similar to the one posted below, so I believe the schemas of the Room and the SQLite database are inline.
Here is the CREATE command for the table in my database:
CREATE TABLE "multiple_choice_questions" (
    "id"    INTEGER,
    "Question"  TEXT,
    "Category"  TEXT,
    "Subcategory"   TEXT,
    "AnswerOne" TEXT,
    "AnswerTwo" TEXT,
    "AnswerThree"   TEXT,
    "AnswerFour"    TEXT,
    "CorrectAnswer" INTEGER,
    "WasQuestionSeen"   INTEGER,
    "Wikipedia" TEXT,
    PRIMARY KEY("id" AUTOINCREMENT)
);

And here is a screenshot of a sample couple lines from the database


text:
Q: Finding base for a set of vectors Given these sets of vectors:
$$
T=\{(2,1,-1),(1,0,-1),(5,1,-4)\}
$$
$$
S=\{(1,2,1),(1,1,2),(3,4,5)\}
$$
1) Find a base for the subspaces: $Sp(S)$, $Sp(T)$, $Sp(S\cup T)$
2) Describe the vectors the belong to $Sp(S)$ and to $Sp(T)$ and find a base for $Sp(S) \cap Sp(T)$
3) Verify that: $dimSp(S\cup T) + dim(Sp(S)\cap Sp(T)) = dimSp(S) + dimSp(T)$
For 1) I did:
$$
S=\begin{pmatrix}
1 & 2 & 1 \\
1 & 1 & 2 \\
3 & 4 & 5 \\
\end{pmatrix}
T=\begin{pmatrix}
2 & 1 & -1 \\
1 & 0 & -1 \\
5 & 1 & -4 \\
\end{pmatrix}
$$
Therefore:
$$
rref(S) = \begin{pmatrix}
1 & 0 & 3 \\
0 & 1 & -1 \\
0 & 0 & 0 \\
\end{pmatrix}
rref(T) = \begin{pmatrix}
1 & 0 & -1 \\
0 & 1 & 1 \\
0 & 0 & 0 \\
\end{pmatrix}
$$
$$Sp(S)=[(1,0,3),(0,1,-1)],Sp(T)=[(1,0,-1),(0,1,1)]$$
$rref(Sp(S)\cap Sp(T)) = \begin{pmatrix}
1 & 0 & 0 \\
0 & 1 & 0 \\
0 & 0 & 1 \\
0 & 0 & 0 \\
\end{pmatrix}$
I could not fully understand how to solve 2 and 3, may I get some help please?
So these are sufficient to represent a base for S and T respectively, right?
Thanks!

A: Hint:
Based on what you found we have $v \in Sp(S) \iff v = (\alpha,\beta,3\alpha - \beta)$
To find $Sp(S) \cap Sp(T)$ think about the vectors in these $2$ subspaces and what properties they must hold in order to belong to both subspaces.
I believe you have an error in $rref(Sp(S)\cap Sp(T))$.. maybe you found $rref(S\cup T)$ instead?


text:
Q: Using Stokes' theorem around a circular loop
I know that I have to use:
$$\oint F\cdot dr = \iint \operatorname{curl}(F)\cdot n \;dS,$$
with $\operatorname{curl}(F)= -x j -yk$ and $n\;dS = dA\; k$
But the dot product of the curl and $dS$ leaves me with
$$\iint -y \; dA$$
but I am unsure how to proceed from here. Do I need to change coordinate systems as I am dealing with a cicle? Any help is appreciated!

A: In order to apply Stoke's Theorem to evaluate $\int_CF\cdot d\vec{r}$ where $C$ is the circular loop $x^2+y^2=a^2$ you need to first establish a surface $S$ whose boundary is $C$ and is equipped with a normal vector $\vec{n}$ that induces the original orientation prescribed to $C$. Let's take $S$ to be the circular disc $$\{x^2+y^2\leq a^2,z=0\}$$ which we'll parameterize by $$\vec{r}(u,v)=(u\cos(v),u\sin(v),0)$$ on the domain $0\leq u\leq a$ and $0\leq v\leq 2\pi$. Clearly the vector $\vec{n}=\big<0,0,1\big>$ is perpendiular to $S$ and induces a counterclockwise orientation on its boundary $C$. (I'm assuming you're prescribing a counterclockwise orientation to $C$.) A little bit of calculation also reveals that $$\text{curl}(F)=\big<0,-1,-1\big>$$ $$\vec{r}_u \times \vec{r}_v=\big<0,0,u\big>$$ $$dS=||\vec{r}_u \times \vec{r}_v||dudv=ududv$$ So with Stoke's Theorem, $$\int_C F \cdot d\vec{r}=\int_{S}\big[\text{curl}(F)\cdot \vec{n}\big]dS=\int_0^{2\pi} \int_0^a -ududv=-\pi a^2$$


text:
Q: can i add a new page in wordpress as like add link html

                                About us

this is my code and about_us.php is fully supported by wordpress but when i click in about us button then say page not found

A: To create a new Page, log in to your WordPress installation with sufficient admin privileges to create new articles. Select the Administration > Pages > Add New option to begin writing a new Page.
For More details refer the below links
http://codex.wordpress.org/Pages
http://codex.wordpress.org/Pages_Add_New_Screen

A: You can add the page in the existing navigation menu.


text:
Q: simple preg_match not returning expected results I went through a few basics on preg match but its quite difficult when your new to it.
What im trying to do is search for this instance in a string
bug1234
it shouldnt be case sensitive so bug1234 or BuG1234 should work
it must be the word bug followed by any 4 numbers
there should be no spaces or anything in between bug1234 so bug-1234 should not be a match
it should ignore things like bug1234z and abug1234 so it must be bug1234 with nothing prefixing it or coming directly after it unless there is a space between then so "there is a problem with bug1234 that i cant solve" would be a match.
Just to clarify it can be any number not 1234 specifically but they must be 4 digits
Heres my lame attempt:
$file_string = $workdetails->text;
$file_string = strtolower($file_string);
$bugkey = "/bug[0-9]{4}/";
$nosey = preg_match($bugkey, $file_string);
if($nosey !== false)
{
echo "We have a match baby!!"
}

That just seemed to return all sorts, empty string,s string with no mention of the word bug

A: Try changing the regex to:
/\bbug[0-9]{4}\b/i

The \b modifier will only match on a word boundary so that makes sure it doesn't match things like abug1234, bug12345 or bug1234was bad.  I also added the i modifier so it is case insensitive.  You no longer need to use strtolower.
Also, preg_match typically returns an integer, and returns (int)0 if there is no match.  It only returns FALSE on failure.  Therefore you should change the match check to be:
if ($nosey > 0) {
// or just
if ($nosey) {

A: Try this: /(?ism)bug(?i-sm)[0-9]{4}/
Tested on the Regular Expression Test Tool
With data:
sdfsfsbUG1234cccs

Cheers!

A: Try it with:
preg_match('/\b(bug\d{4})/i', $file_string, $match);
print_r($match);

The modifier i stands for case insensitive and the \b is for a whole word only (word boundary).


text:
Q: Azure Function data binding error My Azure Function (trigger - Blob, output - data bindung to MS SQL DB) throws error
2017-04-03T17:17:33.475 Exception while executing function: Functions.BlobToDB. System.Net.Http: Response status code does not indicate success: 404 (Execution Failure     inner exception: The specified item 'TestEnt' is not found.).
I have TestEnt in my DB, connection string were verified few times.
Function code:
public static async Task Run(Stream myBlob, string name, IAsyncCollector<TestEnt> outputData, TraceWriter log)
{
        var R = new TestEnt();
        R.TestEntId = Guid.NewGuid();
        R.TestEntName = "Test";
        await outputData.AddAsync(R);
        log.Info($"ok!");
}

public class TestEnt
{
    public Guid TestEntId { get; set; }

    public string TestEntName { get; set; }

}

Thanks for help!

A: I think I found the solution - you need to fill the DB servername with web route (dbservername.database.windows.net not only dbservername)
enter image description here


text:
Q: Rewrite power series I have a series
$$\sum_{n=0}^{\infty} \sum_{k=0}^{n} a^{2n-k} f(k) g(n-k),$$
where $f,g$ are two functions.
Now, I want to rewrite this as a series in terms of powers of $a,$ i.e.
$$\sum_{u=0}^{\infty} a^{u} \cdot{ \text{something}}.$$
Does anybody know whether such an index shift or change of variables is possible ?


text:
Q: Downloading large data sets on overpass-turbo? I'm trying to download historical data from overpass-turbo and I keep getting this error.
Error: runtime error: open64: 0 Success /osm3s_v0.7.54_osm_base Dispatcher_Client::request_read_and_idx::timeout. The server is probably too busy to handle your request.

This is after trying to increase the timeout and maxsize on the query and using the "raw data directly from Overpass API" export function. I need to do this for all of US and Canada.  Breaking it up by state and province is fine or one big download will work as well.  Am I exceeding the limits and need to find another way of doing this?  The files don't seem to be too big.  California is about 10MB and Ohio is about 2MB.  Here are my basic queries.
 [adiff:"2016-10-23T15:00:00Z","2017-10-22T15:00:00Z"];

{{geocodeArea:california}}->.searchArea;
(
  way["highway"="motorway_link"](area.searchArea);
);
out body;
>;
out skel qt;

[adiff:"2016-10-23T15:00:00Z","2017-10-22T15:00:00Z"][timeout:99999][maxsize:10737418240];

{{geocodeArea:california}}->.searchArea;
(
  way["highway"="motorway_link"](area.searchArea);
);
out body;
>;
out skel qt;

A:
Am I exceeding the limits

Given that quoted error includes

Dispatcher_Client::request_read_and_idx::timeout. The server is probably too busy to handle your request.

Yes, you requested more than server is able to provide. Try splitting queries into smaller.
Also, from comments:

Besides, both timeout and maxsize values are both ridiculously large: 99999 seconds is more than 1 day (!), maxsize is >10GB

It is possible that server rejects queries with outrageous maxsize and timeout values.


text:
Q: What is the relationship between Azure and Visual Studio Team Services We have a Visual Studio Team Services instance that is used by the company I work for.
The company has an Azure instance.  As far as I am aware there is no connection to VSTS.
When I was added to VSTS as a Visual Studio Pro level user some months ago we had to use my Microsoft Account as we couldn't use my work identity because my MSDN subscription is linked to my Microsoft Account as we could not link it to my work identity; apparently this was because we use Office365 in the office.
We now have problems adding Basic Users to VSTS.  I enter the users Microsoft Account identity and I am told "No Identities Found".
I looked at VSTS Settings where I can see "This account is backed by the Default Directory Azure Active Directory."
I can also see an "Azure Subscription ID".  When I follow the Subscription ID link I end up at my Microsoft Account Azure instance.
I had other users log in to VSTS and they too are seeing my Azure Subscription ID in VSTS Settings.
Why is this happening?
How do Azure instances/accounts relate to VSTS instances/accounts
Can I break the link between Azure and VSTS

A: You can link your VSTS account to the azure from your azure portal:
Azure - VSTS service
Then, what we do is to add the users to the Azure active directories. As far as I know, these users must be registered in Microsoft.
Once it's done, you can add the users to the VSTS.
Hope it helps you.

A: The Team Services uses an Azure subscription to bill purchases and can control access with Azure AD.
You can unlink your VSTS account from Azure portal. More information, you can refer to this article: Delete or recover Visual Studio Team Services account

A: I am an idiot.
Turns out the company VSTS was linking to the company Azure.
I became confused when clicking the Manage button in VSTS | Azure Subscription ID.
That took me to the Sign in to Azure page and displayed my login, which takes me my Azure.
It was only when we checked the Azure Subscription ID in VSTS against my Azure Subscription ID that it became apparent I was following a red herring.  The ID matched the companies Azure ID. So I can use that to add users and subsequently add them to VSTS.


text:
Q: Trying to delete specific id $('.icn-trash').on('click', function(e) {
    e.preventDefault();
    deleteBookmark($('.del').data('bookmarkid'));
});

function deleteBookmark(bookmarkID) {
    $.ajax({
        url: '/BookmarkApi/delete/' + bookmarkID,
        type: 'POST',
        success: function(response) {
            $('.icn-trash').closest('.del').remove();
            console.log('removed');
        },
        error: function(error) {

        }
    });
}

HTML - it will be generated dynamically for every bookmark folder.

Everytime, I try to delete the specific id of the bookmark folder, multiple folders are removed. It should only remove one specific folder when clicking trash icon. When I clicked trash icon on 6th folder, the 1st, 2nd, 3rd, 4th, 5th folders will disappear and i refreshed again only to find 1st folder actually being removed from database.
I want to have 6th folder disappear and removed from database.
Help appreciated.

A: Try this way
   $(document).on('click', '.icn-trash',function(evt) {
        evt.preventDefault();
        var b_id=$(this).closest('.del').data('bookmarkid')
        $.ajax({
            url: '/BookmarkApi/delete/' + b_id,
            type: 'POST',
            success: function(response) {
                $(this).closest('.del').remove();
                console.log('removed');
            },
            error: function(error) {

            }
        });

});

A: I would bind the event on the a tag:
$('.del').on('click', function(e) {
    e.preventDefault();
    deleteBookmark(this);
});

function deleteBookmark(ele) {
    $.ajax({
        url: '/BookmarkApi/delete/' + $(ele).data('bookmarkid'),
        type: 'POST',
        success: function(response) {
            $(ele).remove();
            console.log('removed');
        },
        error: function(error) {

        }
    });
}

Or if you still want to bind on .icn-trash:
$('.icn-trash').on('click', function(e) {
    e.preventDefault();
    deleteBookmark($(this).closest('.del'));
});

function deleteBookmark(ele) {
    $.ajax({
        url: '/BookmarkApi/delete/' + ele.data('bookmarkid'),
        type: 'POST',
        success: function(response) {
            ele.remove();
            console.log('removed');
        },
        error: function(error) {

        }
    });
}

A: You are removing content using class attribute that return collection of all the links and remove the links.
  $('.icn-trash').on('click', function (e) {
                    debugger
                    event.preventDefault()
                    deleteBookmark(this);
                });

          function deleteBookmark(obj) {
                debugger
                bookmarkID = $('.del').data('bookmarkid');
              $(obj).remove();
                $.ajax({
                    url: '/BookmarkApi/delete ,
 data: { bookmarkID: bookmarkID},
                    type: 'POST',
                    success: function (response) {

                        console.log('removed');
                    },
                    error: function (error) {

                    }
                });
            }

A: From the jQuery Documentation of closest API

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

Now what is happening in the code $('.icn-trash').closest('.del').remove();
$(.icn-trash') is returning the set of all element elements having the class icn-trash. And then you are using this set to find the closest element with class .del which will return a set of all anchor tags (in your html example). Finally you are removing the entire set. Hence multiple bookmarks are getting deleted.
I am assuming you need to delete the anchor tag which has the data-bookmarkid as bookmarkID
$('.icn-trash').on('click', function(e) {
    e.preventDefault();
    deleteBookmark($('.del').data('bookmarkid'));
});

function deleteBookmark(bookmarkID) {
    $.ajax({
        url: '/BookmarkApi/delete/' + bookmarkID,
        type: 'POST',
        success: function(response) {
            // get the element with data-bookmarkid = bookmarkID and remove it
            $("[data-bookmarkid='" + bookmarkID + "']").remove()
            console.log('removed');
        },
        error: function(error) {

        }
    });
}

EDIT: I didn't read the last part of your question

When I clicked trash icon on 6th folder, the 1st, 2nd, 3rd, 4th, 5th folders will disappear and i refreshed again only to find 1st folder actually being removed from database.

Can you make sure that the bookmarkIds are correct in the data-bookmarkid attribute? Since clicking on 6th trash icon is removing the 1st folder from the database, there seems to be a problem either with your server code or the data-bookmarkid attribute is incorrect in the 6th trash icon
EDIT2: Why you are getting the wrong bookmarkId (Didn't investigat enough thoroughly earlier, got involved in  something else)
Again quoting from jQuery documentation for data API

Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.

So analyzing your code deleteBookMark($('.del').data('bookmarkid')): $('.del') will contain all the elements with class name del (in your example all the anchor tags). Calling .data('bookmarkid') with the entire set will return the bookmark id of the first anchor tag. The best way to do this is to first obtain the element which was clicked. This can be done by modifying your code
Again from jQuery Documentation for Event Listener

When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered;...
  To create a jQuery object from the element so that it can be used with jQuery methods, use $( this ).

This means that
$('.icn-trash').on('click', function(e) {
   e.preventDefault();
  deleteBookmark($('.del').data('bookmarkid'));
});

In the listener you have attached, this will refer to the .icn-trash element you clicked on. So now you know which element was clicked, find the closest .del element and then get its data-bookmarkid attribute. i.e.
$('.icn-trash').on('click', function(e) {
   e.preventDefault();
   var curIconTrash = $(this),
       closestAnchor = curIconTrash.closest('.del'),
       bookMarkId = closestAnchor.data('bookmarkid')

   deleteBookmark(bookmarkId);
});

Or taking the advantage of jQuery chaining
$('.icn-trash').on('click', function(e) {
   e.preventDefault();
   deleteBookmark($(this).closest('.del').data('bookmarkid'));
});

Note: This was also suggested by @sreedhar-r
Hope this helps! Cheers :-)