text:
Q: Need of Iterator class in Java? The question might be pretty vague I know. But the reason I ask this is because the class must have been made with some thought in mind.
This question came into my mind while browsing through a few questions here on SO.
Consider the following code:
class A
{

    private int myVar;

    A(int varAsArg)
    {
          myVar = varAsArg;
    }

   public static void main(String args[])
   {

      List<A> myList = new LinkedList<A>();
      myList.add(new A(1));
      myList.add(new A(2));
      myList.add(new A(3));

      //I can iterate manually like this:
      for(A obj : myList)
                 System.out.println(obj.myVar);

      //Or I can use an Iterator as well:
      for(Iterator<A> i = myList.iterator(); i.hasNext();)
      {
         A obj = i.next();
         System.out.println(obj.myVar);
      }
   }
}

So as you can see from the above code, I have a substitute for iterating using a for loop, whereas, I could do the same using the Iterator class' hasNext() and next() method. Similarly there can be an example for the remove() method. And the experienced users had commented on the other answers to use the Iterator class instead of using the for loop to iterate through the List. Why?
What confuses me even more is that the Iterator class has only three methods. And the functionality of those can be achieved with writing a little different code as well.
Some people might argue that the functionality of many classes can be achieved by writing one's own code instead of using the class made for the purpose. Yes,true. But as I said, Iterator class has only three methods. So why go through the hassle of creating an extra class when the same job can be done with a simple block of code which is not way too complicated to understand either.

EDIT:
While I'm at it, since many of the answers say that I can't achieve the remove functionality without using Iterator,I would just like to know if the following is wrong, or will it have some undesirable result.
for(A obj : myList)
{
           if(obj.myVar == 1)
                 myList.remove(obj);
}

Doesn't the above code snippet do the same thing as remove() ?

A: Iterator came long before the for statement that you show in the evolution of Java. So that's why it's there. Also if you want to remove something, using Iterator.remove() is the only way you can do it (you can't use the for statement for that).

A: First of all, the for-each construct actually uses the Iterator interface under the covers. It does not, however, expose the underlying Iterator instance to user code, so you can't call methods on it.
This means that there are some things that require explicit use of the Iterator interface, and cannot be achieved by using a for-each loop.
Removing the current element is one such use case.
For other ideas, see the ListIterator interface. It is a bidirectional iterator that supports inserting elements and changing the element under the cursor. None of this can be done with a for-each loop.

for(A obj : myList)
{
           if(obj.myVar == 1)
                 myList.remove(obj);
}

Doesn't the above code snippet do the same thing as remove() ?

No, it does not. All standard containers that I know of will throw ConcurrentModificationException when you try to do this. Even if it were allowed to work, it is ambiguous (what if obj appears in the list twice?) and inefficient (for linked lists, it would require linear instead of constant time).

A: The foreach construct (for (X x: list)) actually uses Iterator as its implementation internally. You can feed it any Iterable as a source of elements.
And, as others already remarked: Iterator is longer in Java than foreach, and it provides remove().
Also: how else would you implement your own provider class (myList in your example)? You make it Iterable and implement a method that creates an Iterator.

A: For one thing, Iterator was created way before the foreach loop (shown in your code sample above) was introduced into Java. (The former came in Java2, the latter only in Java5).
Since Java5, indeed the foreach loop is the preferred idiom for the most common scenario (when you are iterating through a single Iterable at a time, in the default order, and do not need to remove or index elements). Note though that the foreach uses an iterator in the background for standard collection classes; in other words it is just syntactic sugar.

A: Iterator, listIterator both are used to allow different permission to user, like list iterator have 9 methods but iterator have only 3 methods, but have remove functionality which you can't achieve with for loop. Enumeration is another thing which is also used to give only read permissions.

A: Iterator is an implementation of the classical GoF design pattern. In that way you can achieve clear behaviour separation from the 'technical code' which iterates (the Iterator) and your business code.
Imagine you have to change the 'next' behaviour (say, by getting not the next element but the next EVEN element). If you rely only on for loops you will have to change manually every single for loop, in a way like this
for (int i; i < list.size(); i = i+2)

while if you use an Iterator you can simply override/rewrite the "next()" and "hasNext()" methods and the change will be visible everywhere in your application.

A: I think answer to your question is abstraction. Iterator is written because to abstract iterating over different set of collections.
Every collection has different methods to iterate over their elements. ArrayList has indexed access. Queues has poll and peek methods. Stack has pop and peek.
Usually you only need to iterate over elements so Iterator comes into play. You do not care about which type of Collection you need to iterate. You only call iterator() method and user Iterator object itself to do this.
If you ask why not put same methods on Collection interface and get rid of extra object creation. You need to know your current position in collection so you can not implement next method in Collection because you can not use it on different locations because every time you call next() method it will increment index (simplifying every collection has different implementation) so you will skip some objects if you use same collection at different places. Also if collection support concurrency than you can not write a multi-thread safe next() method in collection.
It is usually not safe to remove an object from collection iterating by other means than iterator. Iterator.remove() method is safest way to do it. For ArrayList example:
    for(int i=0;i


text:
Q: Using Docker Desktop with a Personal Account on a Company PC I'm using a Docker Desktop on my company pc. I'm using it with my Personal Account (free) and for my own personal projects. Nothing to do with the company where I work for or any other commercial goal. Just my own playground.
Recently, my company was asked by Docker to remove my account or to upgrade it to a paid level.
My question:
May I or may I not use Docker Desktop software on my company PC with my free Personal / Community account?

A: Are you using the company address when opening the account with Docker? If yes, then I believe its deemed as a corporate account and according to the Docker Subscription Service Agreement, may require you to have a paid subscription.
The subscription is free for small businesses which has under 250 employees and less than 10mil in annual revenue. See Docker Subscription

redpajama_set_name: RedPajamaStackExchange


text:
Q: Downloading an audio file from server using a 'circular progress' with a particular position I have created a music app with websrvice data. I get all data from a webservice and set it to listview and now I want to download the audio and store it in the sdcard.
I want to click on the download imageview and I want that imagview to change to a progressbar tand the file downloads. After file has downloaded I want the  image to change but it is not.
How do I solve the problem?
public class DownloadTask extends AsyncTask<String, Integer, String>
{
        Context context;

        private static final int MEGABYTE = 1024 * 1024;
        AudioRecyleviewAdapter.DownloadTask downloadTask;
        String Name;
        ProgressDialog mProgressDialog;
        ProgressBar progressBar;
        ImageView imgdowload;
        int position;

        public DownloadTask(Context context) {
            this.context = context;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // mProgressDialog = new ProgressDialog(context);
            mProgressDialog = new ProgressDialog(context);
            mProgressDialog.setMessage("Downloading....");
            mProgressDialog.setIndeterminate(true);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(false);

            mProgressDialog.show();

            mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {

                    String sdcard_path = Environment.getExternalStorageDirectory().getPath();
                    File file = new File(sdcard_path + "/Petli Satsang/" + Name + ".mp3");
                    file.delete();
                    Toast.makeText(context, "Download In Background", Toast.LENGTH_SHORT).show();
                }
            });
        }

        @Override
        protected String doInBackground(String... str) {

            String URL = str[0];
            Name = str[1];
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            try {
                java.net.URL url = new URL(URL);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return "Server returned HTTP " + connection.getResponseCode()
                            + " " + connection.getResponseMessage();
                }
                int fileLength = connection.getContentLength();
                input = connection.getInputStream();
                String sdcard_path = Environment.getExternalStorageDirectory().getPath();
                File PapersDiractory = new File(sdcard_path + "/Petli Satsang/");
                PapersDiractory.mkdirs();
                File outputFile = new File(PapersDiractory, "" + Name);
                output = new FileOutputStream(outputFile);

                byte data[] = new byte[MEGABYTE];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    if (isCancelled()) {
                        input.close();
                        return null;
                    }
                    total += count;
                    if (fileLength > 0) // only if total length is known
                        publishProgress((int) (total * 100 / fileLength));
                    int progress = (int) (total * 100 / fileLength);
                    Log.d("Progress = ", "" + (int) (total * 100 / fileLength));
                    output.write(data, 0, count);
                }
            } catch (Exception e) {
                return e.toString();
            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException ignored) {
                }

                if (connection != null)
                    connection.disconnect();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            // if we get here, length is known, now set indeterminate to false
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.setMax(100);
            mProgressDialog.setProgress(progress[0]);
            //progressBar.setProgress(Integer.parseInt(String.valueOf(progress[0])));

        }

        @Override
        protected void onPostExecute(String result) {
            mProgressDialog.dismiss();
            if (result != null)
                Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
            else {
                int position = 0;
                Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
            }
        }
    }

//code to call function on dowload image cilck
 holder.download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File extStore = Environment.getExternalStorageDirectory();
                final File myFile = new File(extStore.getAbsolutePath() + "/Petli Satsang/" + detail.getTitle() + ".mp3");
                if (!myFile.exists()) {
                    if (isOnline()) {
                        DownloadTask downloadTask = new DownloadTask(context);
                        downloadTask.execute(Constant.ImagePath_audio1 + detail.getPath(), "" + detail.getTitle() + ".mp3");
                    } else {
                        try {
                            AlertDialog alertDialog = new AlertDialog.Builder(context).create();
                            alertDialog.setTitle("Info");
                            alertDialog.setMessage("Internet not available, Cross check your internet connectivity and try again");
                            alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
                            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                }
                            });
                            alertDialog.show();
                        } catch (Exception e) {
                            //Log.d(Constants.TAG, "Show Dialog: " + e.getMessage());
                        }
                    }
                } else {
                    Toast.makeText(context, "File already Exists in " + myFile, Toast.LENGTH_SHORT).show();
                }

A: Pass your view to AsyncTask with setter getter or constructor in AsyncTask
    this.clickedRowView = clickedRowView;
    public DownloadTask(Context context,View clickedRowView) {
        this.context = context;
        this.clickedRowView = clickedRowView;
    }

Call your DownloadTask inside onclick like
//v comes from onClick method which points to holder.download view.
DownloadTask downloadTask = new DownloadTask(context,v);
v.setVisibility(View.INVISIBLE);//make Image View invisible and display progressbar

((RelativeLayout)v.getParent()).findViewById(R.id.progressBar).setVisibility(View.VISIBLE);// make progressbar to visible

Now you hold your view into the asynctask, now you should change your image view after download successes or fails
    @Override
    protected void onPostExecute(String result) {
        mProgressDialog.dismiss();
        clickedImageView.setVisibility(View.VISIBLE);
        ((RelativeLayout)v.getParent()).findViewById(R.id.progressBar).setVisibility(View.INVISIBLE);// make progressbar to invisible **EDIT 1**
        if (result != null)
            Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
        else {
            int position = 0;
            Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
        }
        if(clickedRowView != null){
             //You can reach your holder view in here! if this is image view just set image with ((ImageView)clickedRowView).setImageBitmap(...); etc..
        }
    }

EDIT 1 :
If you want to make your Image View invisible and make Progress Bar visible, you should put them into same ViewGroup and setVisibility to right state.
And change xml file which holds ImageView like this:
<RelativeLayout
  android:id="@+id/imageAndProgressContainer"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="visible"/>
    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="invisible"/>
  </RelativeLayout>


text:
Q: Installing BioPython and Numpy I am working with Python 2.7.11. I've working problems on Rosalind.com from scratch, but I decided to try using tools that are openly available- in order to start familiarizing myself with finding and using said packages and extensions. Good thing too, because I can't figure out how to get any of the third party extensions to python installed.
Let's start with Numpy. Which this PDF I'm following to install Biopyton suggests I use. http://biopython.org/DIST/docs/install/Installation.pdf
I'm going in circles looking for isntruction. Everybody wants to send me to some other app that uses Numpy or Biopython, I installed Anaconda and then took it back off.
I hear talk of using 'the terminal', which I think is just my windows command prompt.
I've downloaded the files from the sources for both programs. Do I need to put the files somewhere special first? Before opening the cammand prompt and issuing a command roughly of the form "python setup install"?
I placed both sets of files in my python folder, but then before trying to command prompt realized they both have setup files.
I was looking for a executable setup file, but double-clicking on the setup files I downloaded doesn't seem to have served that purpose.
Does anyone see what it missing here?

A: So you need to install your modules into your python path. There is some (windows) documentation to that here and here but should be easily addressable from your interpreter. Can't really give you specific instructions without knowing what you're using. But once you set the path anything you put there will be accessible from your interpreter. Which note that all python programs can be treated as modules so if you want to create your own later put them in a similar place or add that path to your python path.


text:
Q: Failed to register a ServiceWorker when PUBLIC_URL is CDN in create-react-app react-scripts: v3.2.0
I want to load my react web application from cdn using service worker and set PUBLIC_URL to my CDN url at build time.
As in this link describe about PUBLIC_URL, It is usefull for hosting app in CDN.

But it's not work for me and service worker doesn't enable in production.
Should I set homepage in package.json to my CDN url? Or it's irrelevant?


text:
Q: Delete a Image from php folder <?php
include ('config.php');

echo '<script>confirm("Are you sure?");</script>';

if(isset($_GET['fileid']))
{
    $fileid = $_GET['fileid'];
    $target_dir = "img/";
    $target_file =  $target_dir .$_GET['fileid'];
    $query = "DELETE FROM file_info WHERE fileid='$fileid'";
    $result = mysqli_query($conn,$query);
    $row = mysqli_fetch_array($result);
    $path = "img/".$row['filename'];

    if($result)
    {
         unlink($path);
         echo'<script>window.location ="table.php";</script>';
     }
    else
    {
         echo'<script>window.location ="table.php";</script>';
    }
 }
 ?>

I don't know why its not working.
This code is updating the database but not deleting file from folder need to delete it.

A: with select query get filename using fileid. then execute delete statement.
<?php
 $path = "img/".$row['filename'];
if( file_exists ( $path ))
    unlink( $path);
else
 echo "file not found";

 ?>

A: print the $result & cross check that whether you are able to reach inside if() block. Also from where you get the value $row['filename'] To get it select the value first using select query.

A: Change delete query to select and Give the absolute Path and fetch associative array for $row['filename']
CODE
$fileid = $_GET['fileid'];
$target_dir = "img/";
$target_file =  $target_dir .$_GET['fileid'];
$query = "SELECT filename FROM file_info WHERE fileid='$fileid'";
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_assoc($result); // And fetch assoc array

$path = "c:\project\img\".$row['filename'];


text:
Q: how can i add contact form 7 in metaslider in wordpress, I want to display different form when image is slide I am using two wordpress plugin
1- Metaslider
2- Contact form7
I want to display CF7 in metaslider, there is two different images and in each images i want to display CF7.
Is it possible or not.
Metaslider is must require
Here is some other link but this link through i cant find actual output.
Link-1
Link-2
Link-3


text:
Q: How to specify format of XML output when writing from a DataTable? In C#, I'm creating an XML file from a DataTable using dataTable.WriteXml(filePath), and get the following:
<?xml version="1.0" encoding="utf-8" ?>
<ExperienceProfiles>
  <ExperienceProfile>
    <Col1>blah</Col1>
    <Col2>4ed397bf-a4d5-4ace-9d44-8c1a5cdb0f34</Col2>
  </ExperienceProfile>
</ExperienceProfiles>

How can I get it to write the XML in the following format?:
<?xml version="1.0" encoding="utf-8" ?>
<ExperienceProfiles>
  <ExperienceProfile Col1="blah"
    Col2="blah" ></ExperienceProfile>
</ExperienceProfiles>

A: What you want is some way to tell the DataSet the expected format of your data.  You're in luck, the DataSet supports just this feature.
You will need to create an XML schema for your data and load it into the DataSet before you write out the XML.  In the schema define Col1 and Col2 as attributes of the ExperienceProfile element and the DataSet will know to format the output document to meet the requirements specified in the schema.
If you are not comfortable with creating a schema you can create a sample of the XML file the way that you want it to be formatted, then take a look at the XmlSchemaInference class in the framework.  This class can be used to automatically generate your schema, you may need to tweak the output a little but it can help if you are not familiar with XSD.

A: you can use the ColumnMapping feature of the datatable column.
.
column.ColumnMapping = MappingType.Attribute

A:
Short answer: you can't, using the
  WriteXml method of a DataTable.
Long answer (which is not very long):
  Just roll your own.

Retract my answer, as per above :)


text:
Q: set ng-Model to string on number input I have a number input that I would like to set the ngModel dynamically based on values in an array
<input type="number" ng-model="{{$scope. + denom.label}}" tabindex="1" />

I realize I can't put the {{ }} in the ng-model and they aren't necessary because already in an angular controller, however,
<input type="number" ng-model="$scope. + denom.label" tabindex="1" />

doesn't work either.  denom.label is a string but "$scope." + denom.label' would evaluate to a number.
<input type="number" ng-model="denom.label" tabindex="1" />

The above doesn't work either. denom.label evaluates as a string and the error says that expects the ngModel to be a number. I need it to evaluate to $scope.pennies for example
How can I accomplish this?

A: Try below markup..
Markup
<input type="number" ng-model="this[denom.label]"/>

A: All you need is the code below to make this work.
<input type="number" ng-model="denom.label" tabindex="1" />


text:
Q: How would I write this C++ input function in Java? I am trying to figure out how to read input from the console in Java that would behave exactly the same as the following C++ code:
while(cin >> input)
I essentially need to keep reading the console one integer at a time, and only stop when the user enters no more integers.I am able to read integers one at a time, but cannot figure out how to get it to stop executing once the user passes an empty line. Thanks!

A:   Scanner scanner = new Scanner(System.in);

  // find the next int token and print it
  // loop for the whole scanner
  while (scanner.hasNext()) {

     // if the next is a int, print found and the int
     if (scanner.hasNextInt()) {
        System.out.println("Found :" + scanner.nextInt());
     }
     // if no int is found, print "Not Found:" and the token
     System.out.println("Not Found :" + scanner.next());
  }

A: You can use the Scanner nextLine() method and check for integers:
import java.util.*;
class TextNum {
public static void main(String[] args) {

    int n;
    String s;

     Scanner in = new Scanner(System.in);
    while (true) {
        s = in.nextLine();
         //Do something with this
        System.out.println("This is :" + s + ":");
        try {
            n = Integer.parseInt(s);
        } catch (Exception e) {
            break;
        }
    }

}

}


text:
Q: jmeter Reading Json data from file using JSR223, converting braces to square bracketconverting I am using jmeter 5.1 in windows 10, in my jmeter test plan i am reading json data from file, after reading, i am using log.info ${sdata} to log the messages, but the output is converted the braces { to square bracket [, could someone tell me what's wrong.
Below is the data which the json file contains
{"name":"Foo Bar","year":"2018","timestamp":"2018-03-08T00:00:00","tags":["person","employee"],"grade":3.14}

{
    "name": "Foo Bar",
    "year": "2018",
    "timestamp": "2018-03-08T00:00:00",
    "tags": [
        "person",
        "employee"
    ],
    "grade": 3.14
}

Below is the line which i have in JSR223 Prepocessor to read the file and log it in info
def sdata = new groovy.json.JsonSlurper().parseText(new File("data.json").text)
log.info "$sdata"

And below is the output of log.info
["name":"Foo Bar","year":"2018","timestamp":"2018-03-08T00:00:00","tags":["person","employee"],"grade":3.14]

[
    "name": "Foo Bar",
    "year": "2018",
    "timestamp": "2018-03-08T00:00:00",
    "tags": [
        "person",
        "employee"
    ],
    "grade": 3.14
]

In the above output, the braces { got replaced to square bracket [
Please help

A: This happens because you're basically printing a textual representation of LazyMap
If you want to see the same JSON as in the input you should create a JsonBuilder class instance and pass the "slurped" object to it.
Change this line:
log.info "$sdata"

to this one:
log.info(new groovy.json.JsonBuilder(sdata).toPrettyString())

More information:

*

*Apache Groovy: Parsing and producing JSON

*Apache Groovy - Why and How You Should Use It


text:
Q: Ghostscript Printing PDF dPDFFitPage Incorrect Sizes Am having issues with printing different sized PDF's using GhostScript (V9.05).
The PDF in question is A3 landscape however when printing using ghost script using the following command line arguments the result is printed in A4 portrait and cuts off half of the content.
Commad line arguments:
"-sDEVICE=mswinpr2 -dPDFFitPage -dPrinted=false -dNoCancel -dBATCH -dNOPAUSE -sOutputFile="\spool\HP LaserJet P2050 Series PCL6 (A4)" "C:\Users\dmeggs\AppData\Local\Temp\iPlan_Printing_k4gjaoip.pdf""
I've tried many combinations of parameters, most seem to have no effect.  Ideally I want the printer to print the PDF based on the PDF properties as this will be used to print A4, A3, portrait and landscape documents.
Thanks
Dan

A: I presume the printer is an A4 printer ? In order for GS to scale the page correctly you need to tell it what the page size is. It can't tell from the printer name. Try setting -sPAPERSIZE=a4 -dFIXEDMEDIA
That sets the media to A4, and tells GS it can't be altered, the -dPDFFITPAGE switch will then fit the PDF media request to the declared media, by scaling.
If that doesn't work, then I'll need to see your PDF file.

A: Adding as a new answer as its too big for a comment.
If the output from pswrite and epswrite work then the printer is a PostScript printer.
Pdfwrite produces PDF files, so presumably you don't want to do that, given the input is a PDF file :-) Some PostScript printers can in fact print PDF files too, but this is comparatively unusual.
Rather than use psweite (or epswrite) I would suggest that you use ps2write (which will produce PostScript language level 2 as output) and send the resulting file to the printer.
In an ideal world your printer would then do media selection based on the media request in the PostScript program), but not all printers manage this. In part because printers don't always know which media is in which tray, if multiple media are available.
However, you can then write reasonably simple PostScript code which you can prepend to the file which will allow you to determine the requested page size. Assuming you know how to control tray/media selection in your printer you can have the PostScritp program do that for you.
Unfortunately I can't give you much detail on how to do this, as it depends a great deal on the specific printer.


text:
Q: Repeat scenarios for different examples I am trying to run some test written in specflow using Scenario Outlines where I have the input and out out parameterised, this is fine, and I can do it.
However I also would like to then repeat all the tests across multiple browsers.
This means having one set of parameters to define the test scenarios and another set to iterate over for all the different variations of environment setup (browser type)
as a simple example of what I am trying to do I have a web page that has links on it, each link is authorized based on ad group membership (web site is an intranet one using windows authentication)  so I have the tests:
Scenario Outline: Only authorised users can click through links on main page
Given a user <name> in domain "ad" with password <password>
And the home page is loaded
When I click the link <link>
Then the page has "title" <title>
Scenarios:
| name    | password  | link                        | title                                              |
| user1 | VMoney123 | "link1" | "You are not authorized to see this section"       |
| user2 | VMoney123 | "link1" | "Success"       |
| user2 | VMoney123 | "link2" | "Success" |

But when I naively try to add Examples to iterate the browser flavours:
Scenario Outline: Only authorised users can click through links on main page
Given a user <name> in domain "ad" with password <password>
And a <browser> browser
And the home page is loaded
When I click the link <link>
Then the page has "title" <title>
Examples:
| browser |
| "chrome"  |
| "ie"      |
Scenarios:
| name    | password  | link                        | title                                              |
| name    | password  | link                        | title                                              |
| user1 | VMoney123 | "link1" | "You are not authorized to see this section"       |
| user2 | VMoney123 | "link1" | "Success"       |
| user2 | VMoney123 | "link2" | "Success" |

and the build gives the error:
CS1029  #error: 'Generation error: The example sets must provide the same parameters.'

Obviously I could do this by having 6 Scenarios (or examples), but if I need to expand this out to another 5 browsers that would mean an extra 15 scenarios, it becomes unweildy quickly, surely there is a way...

A: Your feature is not valid Gherkin. Have a look at the reference of it here: https://cucumber.io/docs/reference
To run the same scenario for different browsers, have a look at this example:
https://github.com/techtalk/SpecFlow.Plus.Examples/tree/master/SeleniumWebTest
It uses the SpecFlow+Runner to achieve the support of different browsers.

Full disclosure: I am on of the developers of SpecFlow and SpecFlow+.


text:
Q: Unity WebGL Compression Formats In Unity, i created only one 3D hexagonal object and trying to build for WebGL.
I figured it out that if i change don't change Player Settings>Publishing Settings>Compression Format Gzip to Disabled, my project won't work on Chrome/Safari & Mozilla. Results are same with Gzip compression format. Why is that happen
Also this zero compression format give me about 15mb-20mb files so it takes too long to open on browsers. I need to reduces this time. I have only 28kb .fbx object in this project and 2 script.
Tested on localhost and these pages :

*

*Web Link (Default-Uncompressed)

*Alternative Web Server Link (itch.io)
Any advice would be nice . Thanks.

A: Solved. As Unity Documentation says, i need to configure web server side. But i don't know that yet so i clicked Decompression Fallback option to let unitygl to set that. I hope it helps others too. Because unity's default compression format is Gzip and Decompression Fallback is untick so it fails after build as default.


text:
Q: Classification using SVM from opencv I have problem with classification using SVM. Let's say that I have 10 classes, digts from 0 to 9. I can train SVM to recognize theese classes, but sometimes I get image which is not digt, but SVM still tries to categorize this image. Is there a way to set threshold for SVM on the output maybe (as I can set it for Neural Networks) to reject bad images? May I ask for code sample (in C++ or Python with opencv)?
Thanks in advance.

A: As a simple approach, you can train an additional classifier to determine if your feature is a digit or not. Use non-digit images as positive examples and the other classes' positives (i.e. images of digits 0-9) as the negative samples of this classifier. You'll need a huge amount of non-digit images to make it work, and also it's recommendable to use strategies as the selection of hard negatives: negative samples classified as "false positives" after the first training stage, which are used to re-train the classifier.
Hope that it helps!


text:
Q: Variable value has wrong value after returning from a DLL call I have a situation that seems odd to me.  I have a WCF Web Service in C# that I have some debugging code I wrote into it that opens a file and writes some lines about the value of the current variables and closes the file.  This is a feature I turn off and on depending if I need to use it to debug something at a customer's location.
For all the reading and writing functions, it is interacting with a DLL that executes COBOL code in the background to access a legacy data storage system.  All the variables are passed in by reference and the returned data is returned through those same referenced variables.  Most of the time the variables are just initialized to the correct size and passed in and return data to me.  The return types of the functions are all statuses of the execution in the COBOL environment that tell you if the program wasn't loaded/initialized ok, if the execution was ok, etc.  All writes return 0 success and -1 failure.
Before and after all of my calls to this DLL I have my debug code so I can see the values before and after.  The debug function just does a write line into a FileStream and returns.  I do pass in the same variables by value to the debug function that  I'm passing to my worker function as references.
When I turn on my debugging switch, the odd stuff starts happening.  After 1-2 calls, the worker function just continues to have the value 0 in the success/failure code.  Of course my logic believes a 0 is a successful write to the data file so I'm falsely reporting back the write worked fine.  Debugging the dll, you can specifically see it returning -1, attempting to inform the web service that the write failed, which in my case is correct because a duplicate key violation occurred.  When the value shows up in the Visual Studio watch, it somehow turned into a 0, indicating success.
The thing that I can't wrap my brain around is that if I turn off my debugging switch.  This turns off my FileStream writer, my passing of the variables by value that is then passed by reference to my worker function, everything works the way it should.  The value from the Dll shows up correctly for success/failures as it should.  It makes no sense to me why the return value would be corrupted.
I haven't tried to copy all the variables to temp holding variables and passing different variables to the debug and worker function yet.  The thing is, I don't understand why that value is being corrupted.  It is being changed, because I initialize the value to -99, but it comes back always as 0, when it should be returning -1 in my test case.
Thanks in advance, hopefully someone can either suggest how to trace the variable between the Dll return and being displayed in the Visual Studio watch, which seems to be the place the value is getting corrupted or knows why my debug operation might be somehow corrupting the returned value.
private UploadStatus SetRecord(int remoteId, string xmlDate, string val1, string val2, int val3, int recSeq, string name, int cat1, int cat, int seq, string val5, double val6)
{
    UploadStatus status = new UploadStatus();
    status.id = remoteId;
    int RtnCode = -99;
    int countRecSeq = Convert.ToInt16(ConfigurationManager.AppSettings["cycle-value"]); // value to cycle through for unique key

     // Pad variables appropriately
     val1 = val1 .PadRight(6, ' ');
     val2 = val2 .PadRight(3, ' ');
     val3 = val3 .PadRight(30, ' ');
     xmlDate = xmlDate.PadRight(25, ' ');
     val5 = val5.PadLeft(2, ' ');

     errorTypes ErrCode;
     try
     {

     if (debug)
     {
         string input = "remoteId: " + remoteId + "||\n" + "xmlDate: " + xmlDate + "||\n" + "val1: " + val1 + "||\n" + "val2: " + val2+ "||\n" + "val3: " + val3 + "||\n" + "recSeq: " + recSeq + "||\n" + "name: " + name + "||\n" + "cat1: " + cat1 + "||\n" + "cat: " + cat + "||\n" + "val4: " + val4 + "||\n" + "val5: " + val5 + "||\n" + "val6: " + val6 + "||\n" + "RtnCode: " + RtnCode + "||\n";
         writeDebug("\n\n*** Start UploadStatus SetRecord(int remoteId, string xmlDate, string val1, string val2, int val3, int recSeq, string name, int cat1, int cat, int val4, string val5, double val6) ***\n" + input);
      }
      ErrCode = COBOL.SET_RECORD(ref xmlDate, ref val1, ref val2, ref val3, ref recSeq, ref name, ref cat1, ref cat, ref val4, ref val5, ref val6, " ", ref RtnCode);
      // Add to recSeq looking for a unique key to insert
      while (ErrCode == errorTypes.CS_OK && recSeq < countRecSeq && RtnCode == -1)
      { ...

private void writeDebug(string input)
{
    string logText = DateTime.Now.ToShortDateString() + " " + DateTime.Now.TimeOfDay.ToString() + ": " + input;
    try
    {
        if (!File.Exists(debugPath))
        {
            using (StreamWriter sw = File.CreateText(debugPath))
            {
                sw.Write(logText);
            }
        }
        else
        {
            using (StreamWriter sw = File.AppendText(debugPath))
            {
                sw.Write(logText);
            }
        }
     }
     catch (Exception ex)
     {
         writeException(ex);
     }
 }

A: Ultimately, I worked around this situation.  Originally the function would return failure if the keys for writing the data matched another key.  Inside that code, we just developed it to increment to the next key instead.  It is possible that the issue still occurs, but since the function will eventually find a key to use, it is always successful.
The vendor has since made improvements to the COBOL and .NET interopt.  In addition, we completely changed they way we were communicating between the languages, which seemed to be more stable.


text:
Q: Using lambda and strftime on dates when there are null values (Pandas) I'm trying to change the format of a datetime column in my Dataframe using lambda and strftime like below
df['Date Column'] = df['Date Column'].map(lambda x: x.strftime('%m/%d/%Y'))

However, since I have null values in some of these fields, this is giving me an error. I cannot drop these null rows because I still need them for the data in the other columns. Is there a way around this error without dropping the nulls.
Perhaps something like
df['Date Column'].map(lambda x: x.strftime('%m/%d/%Y') if x != null else "")

?
The method I've used is to drop the nulls, format the column, then merge it back onto the original dataset, but this seems like a very inefficient method.

A: You should be not checking for nan/nat (un)equality, but .notnull() should work and it does for me:
s = pd.date_range('2000-01-01', periods=5).to_series().reset_index(drop=True)
s[2] = None
s

0   2000-01-01
1   2000-01-02
2          NaT
3   2000-01-04
4   2000-01-05
dtype: datetime64[ns]

s.map(lambda x: x.strftime('%m/%d/%Y') if pd.notnull(x) else '')

0    01/01/2000
1    01/02/2000
2
3    01/04/2000
4    01/05/2000
dtype: object

This returns the same that the answers by @Alexander and @Batman but is more explicit. It may also be slightly slower for large series.
Alternatively you can use the .dt accesor. The null values will be formatted as NaT.
s.dt.strftime('%m/%d/%Y')

0    01/01/2000
1    01/02/2000
2           NaT
3    01/04/2000
4    01/05/2000
dtype: object

A: Personally I'd just define a small function, and then use that.
def to_string(date):
    if date:
        string = date.strftime('%Y%m%d')
    else:
        string = ""

    return string

Then
df['Date Column'].map(to_string)

Otherwise
df['Date Column'].map(lambda x: x.strftime('%Y%m%d') if x else "")

A: You can use a conditional assignment (ternary).
df['Date Column'] = df['Date Column'].map(lambda x: x.strftime('%m/%d/%Y') if x else '')


text:
Q: wxPyhton's StaticLine Constructor doesn't account for style parameter I've recently started to learn wxPython, and I just need to display a vertical line to separate the buttons on my frame, however I tried to use the constructor StaticLine with the parameter "style = wx.LI_VERTICAL", like the documentation suggests, but when I run it displays a horizontal line. Even more strangely, when I check on the element with the method "IsVertical()" it returns True, as like nothing was wrong.
This is the code:
import wx
class Finestra(wx.Frame):

    def __init__ (self, genitore = None, titolo = "Netflix Preferences Carrier", dimensioni = (600, 450)):
        super(Finestra, self).__init__(parent = genitore, title = titolo, size = dimensioni, style = wx.MINIMIZE_BOX | wx.CAPTION | wx.CLOSE_BOX | wx.SYSTEM_MENU | wx.RESIZE_BORDER)
        self.Center()
        self.interfaccia()
        self.Show()

    def interfaccia(self):
        self.pannello =wx.Panel(self)
        self.pannello.SetBackgroundColour("white")
        self.sep = wx.StaticLine(self.pannello, pos = (50,50), size = (450, -1), style = wx.LI_VERTICAL)
        print(self.sep.IsVertical())

app = wx.App()
Finestra()
app.MainLoop()

What can I do to fix this?

A: Do not pass explicitly the "size" parameter, you're telling the line to have a fixed size of 450 pixels horizontally ... how can it be displayed as a vertical line?

A: The answer provided by @infinity77 is spot on.
With a StaticLine where you declare a size

either the height or the width (depending on whether the line if
  horizontal or vertical) is ignored.

Try:
import wx
class Finestra(wx.Frame):

    def __init__ (self, genitore = None, titolo = "Netflix Preferences Carrier", dimensioni = (600, 450)):
        super(Finestra, self).__init__(parent = genitore, title = titolo, size = dimensioni, style = wx.MINIMIZE_BOX | wx.CAPTION | wx.CLOSE_BOX | wx.SYSTEM_MENU | wx.RESIZE_BORDER)
        self.Center()
        self.interfaccia()
        self.Show()

    def interfaccia(self):
        self.pannello =wx.Panel(self)
        self.pannello.SetBackgroundColour("blue")
        self.sep = wx.StaticLine(self.pannello, pos = (50,50), size = (-1, 350), style = wx.LI_VERTICAL)

app = wx.App()
Finestra()
app.MainLoop()


text:
Q: batch cmd exits as I enter the input with space I am writing a batch script for an user interface where you can enter the digits 1 - 10. its pretty much like this example:

@echo OFF
:ask
cls
echo press 1 for test1
echo press 2 for test2
set /p input=
if %input% == 1 goto test1
if %input% == 2 goto test2
if %input% GTR 10 goto ask
goto ask
:test1
shutdown
:test2
net view
pause
goto ask

i have if %input% GTR 10 goto ask, and in the end goto ask in global because if someone types something different it will go back to the question.
Why does it crash me out of the terminal when I type something different?

A: if you enter a string with space(s), if syntax will give you a syntax error. Let's look at:
if hello world == string echo xyz

if syntax is: if <value1> <comparator> <value2> command
So hello is value1, world is the comparator - wait - what? world isn't a comparator - Syntax error.
Enclose your values in quoutes to be safe:
if "hello world" == "string" echo xyz

So "hello world" is value1, == is the comparator, "string" is value2 and echo xyz is the command. All goes well.
You may be interested in the choice command, which does it's own error handling and allows only valid keys.


text:
Q: kendogrid aggregate on dynamic columns I'm using ASP.NET webmethods and KendoGrid for binding the data to Grid. The columns that are generated is dynamic. I need to apply aggregate on each column.  Please let me know how I can achieve this.
I'll not be aware of the column names that is coming from WebMethod. So not sure of how to write the aggregate.  I think once the grid is loaded we can access it and then define the aggregate. Please guide. Googled on this but didn't get any help.
aggregate: [{field: "unknowncolumnnames", aggregate: "sum" }]
 $.ajax({
    url: "Details.aspx/DetailsWebMethod",
    dataType: "json",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    success: function (data) {
         $("#DetailsGrid").kendoGrid({

                dataSource: {
                    type: "json",
                    data: data.Table,
                    pageSize: 10
                },
                sortable: {
                    mode: "single",
                    allowUnsort: false
                },
                pageable: {
                    input: true,
                    pageSizes: true,
                    numeric: false
                },

                selectable: "row",
                filterable: true,
                columnMenu: true,
                navigatable: true,
                reorderable: true,
                resizable: true,
                groupable: false,
                scrollable: false
            });
         }
     });

A:             $.ajax({
            url: "",
            datatype: "JSON",
            type: "GET",
            success: function (result) {
                var items = $.parseJSON(result)[0];
                var arrCol = [];
                var arrAgg = [];
                for (var index in items)
                {
                    arrCol.push({ field: index, format: "{0:0}",  footerTemplate: "#= kendo.toString(sum, '0.00') #" });
                    arrAgg.push({ field: index, aggregate: "sum" });
                }
                console.log(arrAgg);
                if (result.Result.length > 0) {
                    var dataSource = new kendo.data.DataSource({
                        data: $.parseJSON(result.Result),
                        group: { field: "Category" },
                        aggregate: arrAgg
                    });
                    $('#divgrid').html("");
                    $("#divgrid").kendoGrid({
                        dataSource: dataSource,
                        height: "auto",
                        scrollable: false,
                        sortable: true,
                        groupable: false,
                        columns: arrCol
                    });


text:
Q: SQL - Window Count with reset I am using SQL and trying to achieve the following results (running_count).
I tried out window function counting, but I do not know how to achieve the reseting of my counter.
select *,
     count(1) over
(partition by ID, DATE order by DATE rows unbounded preceding) -1 as "run_count"  from table

My (resulttable) should look like this. The count should reset between days, but also when a B occurs in between A.

ID
Date
Flag
Running_Count

1
10/10
A
1

2
10/10
B
0
-> reset

3
10/10
B
0
-> reset

4
10/10
A
1

5
10/10
A
2

6
10/10
A
3

1
11/10
B
0

2
11/10
B
0

3
11/10
A
1

4
11/10
A
2

5
11/10
A
3

6
11/10
A
4

7
11/10
B
0
-> reset

8
11/10
A
1

A: You seem to want to count "A"s separated by "B"s, starting over on each day.
If so, you can define the group as the number of "B"s before each value and then do some calculations:
select t.*,
       (case when flag = 'A' then row_number() over (partition by date, grp, flag order by id)
             else 0
        end) as running_count
from (select t.*, sum(case when flag = 'B' then 1 else 0 end) over (partition by date order by id) as grp
      from t
     ) t;

Here is a rextester (which uses Postgres).

A: Could you please try following SQLScript select statement
It is possible that it might be solved easier. I used subselects to display the solution step by step.
Inner most SELECT checks if there is a change from another value to 'A' using SQL Lag() function
The following SubSelect performs a SQL running-sum solution using SUM() aggregate function with unbounded preceding option
The outer-most SELECT uses Row_Number() function to create the desired count value.
select
    id,
    date,
    flag,
    case when flag = 'A' then
    row_number() over (partition by date, groupid order by id)
    else 0
    end as rn
from (
    select
        id,
        date,
        flag,
        sum(is_change) over (partition by date order by id rows unbounded preceding) groupid -- running sum
    from (
        select
            id,
            date,
            flag,
            case
                when
                    flag = 'A' and
                    (
                        (lag(flag, 1) over (partition by date order by id)) is null or
                        (lag(flag, 1) over (partition by date order by id)) = 'B'
                    ) -- check prev
                then 1
                else 0
            end as is_change
        from TblTest
    ) tbl
) t
order by date, id

I hope it is useful and can be used in your development

A: You can define grouping based on number of B flag occurences and then use Row_number to number rows for each group:
SELECT
    ID,
    date,
    flag,
    CASE WHEN flag = 'B' THEN 0 ELSE ROW_NUMBER() OVER (PARTITION BY date, B_COUNT ORDER BY ID) END AS "RUNNING_COUNT"
FROM
    (
        SELECT
            TA.ID,
            TA.date,
            TA.flag,
            CASE WHEN SUM(TB.COUNT) IS NULL AND flag = 'A' THEN 0 ELSE SUM(TB.COUNT) END AS B_COUNT
        FROM
            table TA
            LEFT JOIN
                        (
                            SELECT
                                ID, date, 1 AS "COUNT"
                            FROM
                                table
                            WHERE
                                flag = 'B'
                        )   TB ON TA.date = TB.date AND TA.ID > TB.ID AND TA.flag = 'A'
        GROUP BY
            TA.ID,
            TA.date,
            TA.flag
    )
ORDER BY
    date, ID, flag;

It will give you expected result.


text:
Q: Re-assembling mdadm RAID1 I was in the process of reinstalling from Mint 18 -> 20.
I have 2x 4TB devices RAID1'ed with mdadm. One of them had degraded/dropped off the array for some reason. (Not sure if this happens for any other reason besides HDD going bad?) Hence I decided to make sure my RAID array is up-to-date before I reinstall and add them to the new system.
I added the spare device to array with
mdadm /dev/md0 --add /dev/sdf

I was actually supposed to use --add /dev/sdf1 as there was partition on the drive. Was this also a mistake, or does it make any difference?
Then I blundered and accidentally rebooted while mdadm was rebuilding, which caused the /dev/md0 to fail. I had to remove /dev/md0 from fstab in order to properly boot.
mdadm --examine /dev/sdc1

Shows
Update Time : Sun Jan  5 03:32:11 2020

which means it should be the spare device.
Likewise /dev/sdb1 has
Update Time : Thu Feb 25 02:38:37 2021

indicating it's the main drive.
How should I proceed to reassemble this back to /dev/md0 so that sdb1, having the latest data, is mirrored to sdc1? I'd assume something like
mdadm --assemble --verbose --run /dev/md0 /dev/sdb1 /dev/sdc1

but I want to make sure it should be ok to run this without risk of losing data.
Or should I perhaps just run the command without /dev/sdc1 and only add the one drive that is up-to-date and known to be working?
Superblock infos:
/dev/sdb1:
          Magic : a92b4efc
        Version : 1.2
    Feature Map : 0x1
     Array UUID : b2c183f1:793b927a:17534194:5f000d8c
           Name : rattletrap:0  (local to host rattletrap)
  Creation Time : Mon Oct 16 07:41:56 2017
     Raid Level : raid1
   Raid Devices : 2

 Avail Dev Size : 7813772943 (3725.90 GiB 4000.65 GB)
     Array Size : 3906886464 (3725.90 GiB 4000.65 GB)
  Used Dev Size : 7813772928 (3725.90 GiB 4000.65 GB)
    Data Offset : 262144 sectors
   Super Offset : 8 sectors
   Unused Space : before=262056 sectors, after=15 sectors
          State : clean
    Device UUID : 69317f2c:1a988f46:26f00a3a:b2d4ba14

Internal Bitmap : 8 sectors from superblock
    Update Time : Thu Feb 25 02:38:37 2021
  Bad Block Log : 512 entries available at offset 72 sectors
       Checksum : 6c26dd58 - correct
         Events : 57352

   Device Role : Active device 0
   Array State : AA ('A' == active, '.' == missing, 'R' == replacing)

/dev/sdc1:
          Magic : a92b4efc
        Version : 1.2
    Feature Map : 0x1
     Array UUID : b2c183f1:793b927a:17534194:5f000d8c
           Name : rattletrap:0  (local to host rattletrap)
  Creation Time : Mon Oct 16 07:41:56 2017
     Raid Level : raid1
   Raid Devices : 2

 Avail Dev Size : 7813772943 (3725.90 GiB 4000.65 GB)
     Array Size : 3906886464 (3725.90 GiB 4000.65 GB)
  Used Dev Size : 7813772928 (3725.90 GiB 4000.65 GB)
    Data Offset : 262144 sectors
   Super Offset : 8 sectors
   Unused Space : before=262056 sectors, after=15 sectors
          State : clean
    Device UUID : f6ccc9b9:0fa3652d:61d1898a:504c2462

Internal Bitmap : 8 sectors from superblock
    Update Time : Sun Jan  5 03:32:11 2020
  Bad Block Log : 512 entries available at offset 72 sectors
       Checksum : 7c0c6339 - correct
         Events : 7041

   Device Role : Active device 1
   Array State : AA ('A' == active, '.' == missing, 'R' == replacing)

A: All went good by

mdadm --stop /dev/md0

And then

mdadm /dev/md0 --assemble /dev/sdb1 /dev/sdc1


text:
Q: C# nullable string error private string? typeOfContract
{
  get { return (string?)ViewState["typeOfContract"]; }
  set { ViewState["typeOfContract"] = value; }
}

Later in the code I use it like this:
typeOfContract = Request.QueryString["type"];

I am getting the following error at the declaration of typeOfContract line stating:

The type 'string' must be a non-nullable value type in order to use
  it as parameter 'T' in the generic type or method
  'System.Nullable<T>'

Any ideas? Basically, I want to make sure that "type" exists in the QueryString before performing an action.

A: For nullable, use ? with all of the C# primitives, except for string.
The following page gives a list of the C# primitives:
http://msdn.microsoft.com/en-us/library/aa711900(v=vs.71).aspx

A: You are making it complicated. string is already nullable. You don't need to make it more nullable. Take out the ? on the property type.

A: System.String is a reference type and already "nullable".
Nullable<T> and the ? suffix are for value types such as Int32, Double, DateTime, etc.

A: string cannot be the parameter to Nullable because string is not a value type. String is a reference type.
string s = null;

is a very valid statement and there is not need to make it nullable.
private string typeOfContract
    {
      get { return ViewState["typeOfContract"] as string; }
      set { ViewState["typeOfContract"] = value; }
    }

should work because of the as keyword.

A: String is a reference type, so you don't need to (and cannot) use Nullable<T> here. Just declare typeOfContract as string and simply check for null after getting it from the query string. Or use String.IsNullOrEmpty if you want to handle empty string values the same as null.


text:
Q: Java Bytecode compilation Using javap I can disassemble a java class into byte code. If I want to run this byte code, or a modified version of it, how do I do it? Please spare me the "don't bother" answers as I am doing this for educational reasons. I've googled and looked at other Stack Overflow questions but couldn't find an answer.

A: You can use a java dis-assembler to produce java code you can compile (perhaps with some fixing of the code by hand)
You can then modify the code and re-compile it.


text:
Q: Calculate the center of mass of a semicircle How I determine the center of mass of a semicircle using the definition of center of mass? I only know solve this using the Pappus theorem. Consider that the semicircle is centered on the origin and a homogeneous mass distribution.

A: You can determine the center of mass of an arbitrary object by integrating over its volume:
$$\mathbf R = \frac 1M \int_V\rho(\mathbf{r}) \mathbf{r} dV.$$
In your case, where mass is distributed homogeneously, $\rho$ is a constant.

A: In the case of a one dimensional object, the center of mass $\vec r_{\text{CM}}$, if given by
$$
M \vec r_{\text{CM}} = \int_{C} \vec r \text{d}m
$$
where $M$ is the total mass (it is given by the linear density multiplied by the length of the semi-circle), $C$ denotes the semi-circle and $\vec r$ is the vector locating a point on $C$. You should first choose appropriate coordinates for you problem, and then express the quantities appearing in the integral in these coordinates. You'll see that the integral is then very easy to compute.
Good luck !


text:
Q: Why these operations calculates group delay? In textbook, group delay is defined as negative derivative of phase (in frequency domain). And in discrete signal, derivative can be approximately calculated as differentiation. But when I browse some source code, it calculates group delay in following approach that I completely don't understand:

*

*Calculate "energy centroid" by:

*

*fetch a frame of input wave;

*FFT to frequency domain (data1);

*multiply each input wave data by their index, FFT to frequency domain (data2)???

*treat data1 and data2 as arrays of 2D vector, not complex number, then dot-multiply them. the result is array of "energy centroid".

*Calculate energy spectrum by FFT input frame to frequency domain, then calculate power of each bin.

*Group delay array is calculated as dividing "energy centroid" with energy spectrum.
It is obvious that these operations are far different from the definition in textbook. Could anybody help to explain why it gives group delay?


text:
Q: How do i get a Id value into my delete function in angular 2 I have an angular app in which I am trying to delete a table row data using the id of that data. But I am unable to pass the id into the delete function. I am getting undefined when I try this.id how do I get the id value into a function in angular. How do i call a Delete function with id in services?
Component :
import { Component } from '@angular/core';
import { Observable} from 'rxjs';
import { FormsModule } from '@angular/forms';

import { Employee } from './employee';
import { EmployeeService} from './employee.service';

@Component({
    selector: 'employee-form',
    templateUrl: './employee-form.component.html',
    styleUrls: ['./employee-form.component.css']
})

export class EmployeeFormComponent{
    employees : Employee[];
    errorMessage : String;
    id : number;
    firstName : String;
    lastName  : String;
    EmployeeType : String;
    employee = new Employee();
    clicked = false;
    constructor(private employeeservice : EmployeeService){}
    ngOnInit(): void{
        this.fetchEmployees();
    }
        fetchEmployees(): void{
            this.employeeservice.getDetailsFromJson()
            .subscribe( employees => this.employees = employees,
                                    error => this.errorMessage = <any>error)
        }

        addEmployee(): void{
            this.employeeservice.addEmployees(this.employee)
            .subscribe(employee => {
                this.fetchEmployees();
                    this.reset();
                    this.firstName = employee.firstname;
                    this.lastName = employee.lastname;
                    this.EmployeeType = employee.employeetype;
                    this.clicked = false;
                    console.log(this.employee.id)
            },
            error => this.errorMessage = <any>error);
        }
        deleteEmp(id): void {
                this.employeeservice.delete(id)
                 if (confirm("Are you sure you want to delete " + this.id + "?")){
                console.log();
            }
        }

        private reset(){
            this.employee.firstname = null;
            this.employee.lastname = null;
            this.employee.employeetype = null;
        }

}

Template :

Employee Details

Id	Firstname	Lastname	EmployeeType	Actions

        {{employee.id}}
        {{employee.firstname}}
        {{employee.lastname}}
        {{employee.employeetype}}
        <button class="btn btn-default" (click)="deleteEmp(employee.id); $event.stopPropagation()">Delete</button>
            <button class="btn btn-default" (click)="updateEmp(); $event.stopPropagation()"> Update</button>

Employee Form

    <form class="form-horizontal" (ngSubmit) = "addEmployee()" #employeeform="ngForm">

        FirstName:

        <input type="text" class="form-control col-md-6" id="firstname" required [(ngModel)]="employee.firstname" name="firstname" >

        LastName:

        <input type="text" class="form-control" id="lastname" required [(ngModel)]="employee.lastname" name="lastname">

      <input type="submit" class="btn btn-success "  [disabled]="!employeeform.form.valid" value="submit">

    </form>

Service :
import { Injectable } from '@angular/core';
import { Http, Response,Headers,RequestOptions} from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import {Employee} from './employee'

@Injectable()
    export class EmployeeService {
            empurl = 'api/employees';
            constructor (private http:Http){}
            getDetailsFromJson():Observable<Employee[]>{
                return this.http.get(this.empurl)
                        .map(this.extractData)
                        .catch(this.HandleErrorObservable);
            }
            addEmployees(employee: Employee): Observable<Employee>{
                let headers = new Headers({'Content-Type': 'application/json'});
                let options = new RequestOptions({headers: headers});
                return this.http.post(this.empurl,employee,options)
                        .map(this.extractData)
                        .catch(this.HandleErrorObservable)
            }
            delete(id : number){
                console.log(id);
    return this.http.delete(`${this.empurl}/${id}}, options`)
        .map(res => res.json())
      .catch(this.HandleErrorObservable);
  }

            private extractData(res: Response){
                let body= res.json();
                return body.data || {}
            }
            private HandleErrorObservable(error : Response | any){
                console.log(error.message || error);
                return Observable.throw( error.message || error);
            }
    }

Is this the right way to call a delete function ??

A: HTML
<button class="btn btn-default" (click)="deleteEmp(employee.id); $event.stopPropagation()">Delete</button>

Component
deleteEmp(id): void {
         if (confirm("Are you sure you want to delete " + id + "?")){
            this.employeeservice.delete(id).subscribe((res) => console.log(res));
         }

        }

Hope it helps !!


text:
Q: Select statement in a variable I have the following for loop
for i in (
select * from employees)

loop
--code
end loop;

Is it possible to assign the select statement in a variable like
sql_stat := 'select * from employees';

and in loop
for i in (
    sql_stat)
loop

When I tried the above I am getting error
"Encountered the symbol loop"
What is the correct way of doing this if I want to assign the select statement in a variable.
Thanks

A: You can use ref cursors to get result you want. Here is an example.
declare
      type t_cursor is ref cursor;
      c_cursor t_cursor;
      l_sql varchar2(123);
      l_var number;
   begin
     l_sql := 'select count(*) from T1';  -- your query goes here
     open c_cursor for l_sql;
     loop
       fetch c_cursor
        into l_var;-- variable(s) of appropriate datatype you want to fetch data into
       exit When c_cursor%notfound;
       -- any work for processing fetched data goes here
     end loop;
  end;

A: Why do you want to store the select statement in a variable? One would only do this if part of the query is variable. For example the table_name.
Usually the query is static and the normal way of accessing the results of a query row for row is to use a cursor for loop such as this:
declare
   cursor c is
     select column1,column2
     from table;
begin
  for r in c loop
     dbms_output.put_line(r.column1||' '||r.column2);
  end loop;
end;


text:
Q: Why are there two different syntaxes for this in jQuery/bootstrap? I found these two examples for these two different events:
$('.datepickerSelect').datepicker().on('changeDate', myFunction );
$(".datepickerSelect").datepicker( 'option' , 'onSelect', myFunction );

Also are they interchangeable like so?
$('.datepickerSelect').datepicker().on('onSelect', myFunction   );
$(".datepickerSelect").datepicker( 'option' , 'changeDate', myFunction );

A: This is the syntax of attaching an event listener to an element. It is used used at all the places in jquery
$('.datepickerSelect').datepicker().on('changeDate', myFunction );

The advantage is that you  can add multiple handlers:
$('.datepickerSelect').datepicker().on('changeDate', otherFunction );
$('.datepickerSelect').datepicker().on('changeDate', yetAnotherFunction);

Another syntax is:
  $('.datepickerSelect').datepicker({'changeDate', myFunction });

This syntax means you provide handler for changeDate during initialization of datepicker as part of configuration object. You can attach only one handler  this way.
It is equivalent to doing this
$('.datepickerSelect').datepicker('option','changeDate', myFunction);

This syntax means you forgot to add changeDate handler in config object during initialization of datepicker, so you are adding it now(or you may want to replace the existing handler added during initialisation).


text:
Q: How to change the column values in pandas based on some condition I want to change the column values in a dataframe to another name when it matches some certain conditions.
I tried apply method on the dataframe but it didnt work.
This is the dataset i have and i want the country column names should be changed on some condition. For example "Republic of Korea" should be change to 'South Korea' and I have similar names that needs to be changed in this column. I tried apply method and i'm not getting any results. Any suggestions would help me. Thank you in advance.
**
df.head()

       Country Energy_Supply Energy_Supply_per_Capita
0      Afghanistan      3.210000e       10.0
1      Albania          1.020000e       35.0
2      Algeria          1.959000e+09    51.0
3      American Samoa   NaN             NaN

A: Why replace did not work? it seems that it is the good way:
df.head()

       Country Energy_Supply Energy_Supply_per_Capita
0      Republic of Korea      3.210000e       10.0
1      Albania          1.020000e       35.0
2      Algeria          1.959000e+09    51.0
3      American Samoa   NaN             NaN

df.replace({'Country': 'Republic of Korea'}, {'Country': 'South Korea'})

       Country Energy_Supply Energy_Supply_per_Capita
0      South Korea      3.210000e       10.0
1      Albania          1.020000e       35.0
2      Algeria          1.959000e+09    51.0
3      American Samoa   NaN             NaN

You can do this things several times. For each replace

A: You can use replace() for your column of interest.
Create a dictionary repl_dict = {"Republic of China": "China", "Republic of Moldova": "Moldova", "Republic of France": "France","Great Britain": "England"} and then pass is to replace function, for more details and parameters check pandas.DataFrame.replace

This method does replace all at once by creating the dictionary with
  all the names of interest, ultimately will standardize your
  dataframe column based on this dictionary and no need to run
  individually for each Country.

import pandas as pd
my_dict = { 'Country' : ["Republic of China", "China", "England", "Republic of Moldova", "Republic of France","Great Britain", "England"],
                   'age' : [20,27, 35, 55, 18, 21, 35],
                   'designation': ["VP", "CEO", "CFO", "VP", "VP", "CEO", "MD"]}

dfnew = pd.DataFrame(my_dict)
print(dfnew)

Country  age designation
0    Republic of China   20          VP
1                China   27         CEO
2              England   35         CFO
3  Republic of Moldova   55          VP
4   Republic of France   18          VP
5        Great Britain   21         CEO
6              England   35          MD

repl_dict = {"Republic of China": "China", "Republic of Moldova": "Moldova", "Republic of France": "France","Great Britain": "England"}
dfnew['Country'] = dfnew['Country'].replace(repl_dict, regex=True)
print()
print('Final dataframe', dfnew)

Final dataframe
Country  age designation
0    China   20          VP
1    China   27         CEO
2  England   35         CFO
3  Moldova   55          VP
4   France   18          VP
5  England   21         CEO
6  England   35          MD

A: I think what you need is the map function:
df['Country']= df['Country'].map(lambda x: 'South Korea' if x == 'Republic of Korea' else x)

The above expression is taking an element from df['Country'] and calling it x. If x == 'Republic of Korea' it is placing 'South Korea' in a new series in the same position otherwise it just copies over x to new series. It then assigns the new series with 'South Korea' back to the Country column.
Hope this helps


text:
Q: Code to Remove a Word from Form Field I have a jQuery form with a text field (Field ID is: 43) for a website URL. When a user inputs either "http://" or "https://" as part of the URL, I need the form to automatically remove the "http://" or "https://" portion before or when the form is submitted.
I cannot seem to get this working. Here is the latest code I have tried (at first, just trying to get it working to remove "http://"
<script type="text/javascript">
               document.getElementById("43").setAttribute("onchange", "deleteValue()");
function deleteValue() {
    var weburl = 'http://';
    var textarea = document.getElementById("43");
    var data = textarea.value;
    textarea.value = textarea.value.replace(weburl.value, "");
}
</script>

Can anyone provide a suggestion as to how I can get this working?

A: You can use the .blur() event to trigger the removal of http:// and https://
Working Example:

$(document).ready(function(){

    $('input').blur(function(){
        var currentText = $(this).val();
        var replacedText = currentText.replace(/^https?\:\/\//i, '');
        $(this).val(replacedText);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
<fieldset>
<legend>Write a url with http:// and click elsewhere</legend>
<input type="text" name="myUrl" />
</fieldset>
</form>


text:
Q: Trying to get character input at specific line I'm working on a program that'll eventually calculate currency transfer but I'm already stuck. I'm getting the "Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
        at java.lang.String.charAt(String.java:658)
        at Currency.main(Currency.java:31)".

So I know it happens at line (31) and I have a somewhat idea of what the problem is. I think it's because I already got the user's input when I'm asking for the exchange rate of Euros, Pounds, and Yen. My teacher kinda just threw this at us without really teaching us character inputs. My question is how do I get the program to read the 4th input from the program to go towards the loop. Thanks in advance!
    import java.io.*;
    import java.util.Scanner;
    public class Currency
    {
     public static void main(String[]args)
     {
        Scanner input = new Scanner(System.in);

        int quitInput = 0;

        System.out.println("How many Euros a dollar will buy?");
        double euros = input.nextDouble();

        System.out.println("How many Pound Sterling a dollar will buy?");
        double pound = input.nextDouble();

        System.out.println("How many Yen a dollar will buy?");
        double yen = input.nextDouble();

        do {
                System.out.println("Enter 'E' to buy Euros, 'P' to buy Pound Sterling, 'Y' to buy yen, or 'Q' to quit");
                String decisionString = input.nextLine();
                char decision = decisionString.charAt(0);

                if (decision == 'E' || decision == 'e')
                {
                 System.out.println("Euros");
                }
                else if (decision == 'P' || decision == 'p')
                {
                 System.out.println("Pound Sterling");
                }
                else if (decision == 'Y' || decision == 'y')
                {
                 System.out.println("Yen");
                }
                else if (decision == 'Q' || decision == 'q')
                {
                 System.out.println("Are you sure you want to quit?");
                 String quit = input.nextLine();
                 char exit = quit.charAt(0);
                 if (exit == 'Y' || exit == 'y')
                 {
                  quitInput = -1;
                 }
                 else
                 {
                  quitInput = 1;
                 }
                }
                else
                {
                 System.out.println("Your input was invalid, please try again \n");
                }
         }      while (quitInput >= 0);

                System.out.println("End");
 }
}

A: problem:
double yen = input.nextDouble();

It will only consume the double not the new line so by the time you call the String decisionString = input.nextLine(); it will then consume the new line thus giving you error.
solution:
call nextLine after nextDouble to consume the newLine
double yen = input.nextDouble();
input.nextLine();

A: You're getting an empty line because nextDouble() just reads the double and not the enter after it. Easiest solution I can think of is calling input.nextLine() after that line.
double yen = input.nextDouble();
input.nextLine();

A: you will need to skip the carriage return of your nextXXX() calls.
nextDouble() does not reads the next line. So you will face error when you will take input for decision (both currency as well as quit character). here is the fix for your program.

Replace nextLine() with next().

import java.io.*;
    import java.util.Scanner;
    public class Currency
    {
     public static void main(String[]args)
     {
        Scanner input = new Scanner(System.in);
    int quitInput = 0;

    System.out.println("How many Euros a dollar will buy?");
    double euros = input.nextDouble();

    System.out.println("How many Pound Sterling a dollar will buy?");
    double pound = input.nextDouble();

    System.out.println("How many Yen a dollar will buy?");
    double yen = input.nextDouble();

    do {
            System.out.println("Enter 'E' to buy Euros, 'P' to buy Pound Sterling, 'Y' to buy yen, or 'Q' to quit");
            String decisionString = input.next();
            char decision = decisionString.charAt(0);

            if (decision == 'E' || decision == 'e')
            {
             System.out.println("Euros");
            }
            else if (decision == 'P' || decision == 'p')
            {
             System.out.println("Pound Sterling");
            }
            else if (decision == 'Y' || decision == 'y')
            {
             System.out.println("Yen");
            }
            else if (decision == 'Q' || decision == 'q')
            {
             System.out.println("Are you sure you want to quit?");
             String quit = input.next();
             char exit = quit.charAt(0);
             if (exit == 'Y' || exit == 'y')
             {
              quitInput = -1;
             }
             else
             {
              quitInput = 1;
             }
            }
            else
            {
             System.out.println("Your input was invalid, please try again \n");
            }
     }      while (quitInput >= 0);

            System.out.println("End");
   }
}


text:
Q: get topic from kafka message in spark In our spark-streaming job we read messages in streaming from kafka.
For this, we use the KafkaUtils.createDirectStream API which returns JavaPairInputDStreamfrom.
The messages are read from kafka (from three topics - test1,test2,test3) in the following way:
private static final String TOPICS = "test1,test2,test3";
HashSet<String> topicsSet = new HashSet<>(Arrays.asList(TOPICS.split(",")));

HashMap<String, String> kafkaParams = new HashMap<>();
kafkaParams.put("metadata.broker.list", BROKERS);

JavaPairInputDStream<String, String> messages =
KafkaUtils.createDirectStream(
                streamingContext,
                String.class,
                String.class,
                StringDecoder.class,
                StringDecoder.class,
                kafkaParams,
                topicsSet
                );

We want to handle messages from each topic in a different way, and in order to achieve this we need to know the topic name for each message.
so we do the following:
JavaDStream<String> lines = messages.map(new SplitToLinesFunction());

and this is the implementation of the SplitToLinesFunction:
public class SplitToLinesFunction implements Function<Tuple2<String, String>, String> {
    @Override
    public String call(Tuple2<String, String> tuple2)
    {
        System.out.println(tuple2._1);
        return tuple2._2();
    }
}

The problem is that the tuple2._1 is null and we assumed that the tuple2._1 will contain some metadata such as the name of the topic/partition from where the message came from.
However, when we print tuple2._1, it's null.
Our question - is there a way to send the topic name in kafka so that in the spark-streaming code, the tuple2._1 will contain it (and not be null)?
Note that we also tried to get the topic names from the DStream as mentioned in the spark-streaming kafka-integration tutorial:
But it returns ALL the topics that were sent to the KafkaUtils.createDirectStream, and not the specific topic from where the messages (that belong to the current RDD) arrived from.
So it didn't help us to identify the name of the topic from where the messages in the RDD were sent from.
EDIT
in response to David's answer - I tried using the MessageAndMetadata like this:
        Map<TopicAndPartition, Long> topicAndPartition = new HashMap();
        topicAndPartition.put(new TopicAndPartition("test1", 0), 1L);
        topicAndPartition.put(new TopicAndPartition("test2", 0), 1L);
        topicAndPartition.put(new TopicAndPartition("test3", 0), 1L);

        class MessageAndMetadataFunction implements Function<MessageAndMetadata<String, String>, String>
        {

            @Override
            public String call(MessageAndMetadata<String, String> v1)
                    throws Exception {
                // nothing is printed here
                System.out.println("topic = " + v1.topic() + ", partition = " + v1.partition());
                return v1.topic();
            }

        }

        JavaInputDStream<String> messages = KafkaUtils.createDirectStream(streamingContext, String.class, String.class, StringDecoder.class, StringDecoder.class, String.class, kafkaParams, topicAndPartition, new MessageAndMetadataFunction());
        messages.foreachRDD(new VoidFunction() {

            @Override
            public void call(Object t) throws Exception {
                JavaRDD<String> rdd = (JavaRDD<String>)t;
                OffsetRange[] offsets = ((HasOffsetRanges) rdd.rdd()).offsetRanges();
                // here all the topics kafka listens to are printed, but that doesn't help
                for (OffsetRange offset : offsets) {
                    System.out.println(offset.topic() + " " + offset.partition() + " " + offset.fromOffset() + " " + offset.untilOffset());
                }
            }
        });

The problem is that nothing was printed in the MessageAndMetadataFunction.call method. what should I fix in order to get the relevant topic for that RDD inside the MessageAndMetadataFunction.call method?

A: Use one of the versions of createDirectStream that takes a messageHandler function as a parameter. Here's what I do:
val messages = KafkaUtils.createDirectStream[Array[Byte], Array[Byte], DefaultDecoder, DefaultDecoder, (String, Array[Byte]](
  ssc,
  kafkaParams,
  getPartitionsAndOffsets(topics).map(t => (t._1, t._2._1).toMap,
  (msg: MessageAndMetadata[Array[Byte],Array[Byte]]) => { (msg.topic, msg.message)}
)

There's stuff there that doesn't mean anything to you -- the relevant part is
(msg: MessageAndMetadata[Array[Byte],Array[Byte]]) => { (msg.topic, msg.message)}

If you are not familiar with Scala, all the function does is return a Tuple2 containing msg.topic and msg.message. Your function needs to return both of these in order for you to use them downstream. You could just return the entire MessageAndMetadata object instead, which gives you a couple of other interesting fields. But if you only wanted the topic and the message, then use the above.

A: At the bottom of the Kafka integration guide, there's an example which extracts the topic from the messages.
The relevant code in Java:
 // Hold a reference to the current offset ranges, so it can be used downstream
 final AtomicReference<OffsetRange[]> offsetRanges = new AtomicReference<>();

 directKafkaStream.transformToPair(
   new Function<JavaPairRDD<String, String>, JavaPairRDD<String, String>>() {
     @Override
     public JavaPairRDD<String, String> call(JavaPairRDD<String, String> rdd) throws Exception {
       OffsetRange[] offsets = ((HasOffsetRanges) rdd.rdd()).offsetRanges();
       offsetRanges.set(offsets);
       return rdd;
     }
   }
 ).map(
   ...
 ).foreachRDD(
   new Function<JavaPairRDD<String, String>, Void>() {
     @Override
     public Void call(JavaPairRDD<String, String> rdd) throws IOException {
       for (OffsetRange o : offsetRanges.get()) {
         System.out.println(
           o.topic() + " " + o.partition() + " " + o.fromOffset() + " " + o.untilOffset()
         );
       }
       ...
       return null;
     }
   }
 );

This can probably be collapsed into something more compact which just asks for the topic and nothing else.


text:
Q: Automating unit tests for asp.net mvc Today I finally started to write some unit tests for my new ASP.net MVC project seriously. Some unit tests, however, kept returning for every action in a each controller:

*

*Perform a test whether the returned ActionResult is not null.

*Perform a test whether the action returns a valid ActionResult if the ModelState is invalid.

*Perform a test if the type of ActionResult matches a certain type (e.g. ViewResult or RedirectResult).

These three tests contained more or less the same code for every action. Since I like to avoid duplicate code, I thought of automating these 'default' kind of tests for every action. I did some quick Googles about it, but couldn't find anything.
So:

*

*Is automating default test a wise thing to do?

*If yes, any scripts available or persons who already did something like this before?

*If no one did something before, any suggestions on how to approach this?

Thanks for any replies!

A: I don think that having similar tests for different controllers is 'duplicate' code. The testing logic should be refactored so that it can be re-used. Re-used test code to test different controllers thus is not duplication.
Have you looked at the TestHelpers within MvcContrib. I would think that alot of the common controller type tests have already been implemented. There are also other aspects that make testing a bit easier. That been said, it can used to set up your tests more easily. Have a look at this answer regarding Unit Testing Overkill.

A: First big tactical question is "what unit testing stack are you using?" Some [mstest] don't support inheritance in tests so doing this sort of thing is tricky.
As for actually doing it, I've generally found that this might make sense but having too much shared code in unit tests can be a bad thing -- what happens when your unit test codes gets so complex that you need unit tests for the test code?


text:
Q: Migration from WebSphere to WebLogic I have an webapplication running on WebSphere using JDK 1.6, Spring 2.5.6 and iceFaces 1.8.2. I need to migrate that webapp to WebLogic. So I updated JDK to 1.8 and Spring to 4.2. The iceFaces framework I dont change because of the number of change on my source code.
When I deploy the application I got the following:
com.sun.faces.config.ConfigurationException: Factory 'javax.faces.lifecycle.ClientWindowFactory' was not configured properly.
        at com.sun.faces.config.processor.FactoryConfigProcessor.verifyFactoriesExist(FactoryConfigProcessor.java:330)
        at com.sun.faces.config.processor.FactoryConfigProcessor.process(FactoryConfigProcessor.java:236)
        at com.sun.faces.config.ConfigManager.initialize(ConfigManager.java:439)
        at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:227)
        at weblogic.servlet.internal.EventsManager$FireContextListenerAction.run(EventsManager.java:705)
        Truncated. see log file for complete stacktrace
Caused By: javax.faces.FacesException: com.sun.faces.lifecycle.ClientWindowFactoryImpl
        at javax.faces.FactoryFinderInstance.getImplGivenPreviousImpl(FactoryFinderInstance.java:409)
        at javax.faces.FactoryFinderInstance.getImplementationInstance(FactoryFinderInstance.java:253)
        at javax.faces.FactoryFinderInstance.getFactory(FactoryFinderInstance.java:549)
        at javax.faces.FactoryFinder.getFactory(FactoryFinder.java:283)
        at com.sun.faces.config.processor.FactoryConfigProcessor.verifyFactoriesExist(FactoryConfigProcessor.java:328)
        Truncated. see log file for complete stacktrace
Caused By: java.lang.UnsupportedOperationException
        at javax.faces.application.Application.subscribeToEvent(Application.java:1797)
        at com.sun.faces.lifecycle.ClientWindowFactoryImpl.<init>(ClientWindowFactoryImpl.java:62)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        Truncated. see log file for complete stacktrace

Are there some way to resolve that or I need to change my iceFaces version?

A: I think i resolved that including jsf 1.2 libs on my war file.
Still getting another errors, soon I update the answer if it worked or not.
UPDATE:
Yes, this solved my problem... Now webapplication is deployed sucessful. (Still getting httpError 500 when open my login page...)


text:
Q: Solving equations in permutation group Given a relation on a permutation group $S_n$, I'm interested in solving for an unknown permutation. For a concrete example, let's say $\sigma_1=(12)\in S_3$ (in cycle notation), and the relation is
$$\sigma_1^2 \sigma_2=\sigma_2\sigma_1$$
How can I find a $\sigma_2$ that solves this? (Note that I might be able to do this particular example by inspection, but I'm interested in a general method.)
The only idea I have is to represent the permutations by matrices. So,
$$\rho((12))=\left(\begin{array}{ccc}0&1&0\\1&0&0\\0&0&1 \end{array}\right),$$
which amounts to a linear solution of 6 equations (since the representation should 3x3 symmetric matrices) to find $\sigma_1$, but this doesn't always work, since I don't think all matrices can be written as permutations matrices. For example, I think I determined the solution here is
$$\rho(\sigma_1)=\left(\begin{array}{ccc}1&1&1\\1&1&1\\1&1&1 \end{array}\right),$$
But I'm not sure that I can actually write that as a product of cycles. Does anyone have a systematic way to solve such relations, or a way to write such representations as cycles? Or am I barking up on of those "uncountable word problem" trees?

A: You have
$$e=\sigma_1^2 =\sigma_2 \sigma_1 \sigma_2^{-1}$$ where $e$ is the identity permutation while $$e=\sigma_2 \sigma_1 \sigma_2^{-1}= (\sigma_2(1) \ \sigma_2(2))$$ and this equation is impossible as it would mean that $\sigma_2(1)=\sigma_2(2)$ and that $\sigma_2$ won't be one-to-one. Hence the equation in $\sigma_2$ has no solution.
Not sure that you can have a general method to solve such equations… despite that you could just in the theorical way use brut force and test all $\sigma_2$


text:
Q: opencv get fps in variable I'm new in developing on Android. I want to make an app with OpenCV.
For my app I want to have the FPS of the preview stored in a variable. I found a class in the OpenCVLibrary folder called FpsMeter, but when I call fpsmeter.init(), my app crashes. I tried different things, like setting
cameraBridgeViewBase.enableFpsMeter();

or
cameraBridgeViewBase.disableFpsMeter();

or
fpsmeter.setResolution(320, 240);

But it crashes every time.
Can someone help me please? Thanks in advance.
package be.anton.OpenCV_test;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.widget.Toast;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.FpsMeter;
import org.opencv.android.JavaCameraView;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;

public class MainActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2 {

    CameraBridgeViewBase cameraBridgeViewBase;
    BaseLoaderCallback baseLoaderCallback;
    FpsMeter fpsMeter;
    Mat mat1;
    private static final String TAG = "MyActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        cameraBridgeViewBase = (JavaCameraView) findViewById(R.id.cam);
        cameraBridgeViewBase.setVisibility(SurfaceView.VISIBLE);
        cameraBridgeViewBase.enableFpsMeter();
        cameraBridgeViewBase.setCvCameraViewListener(this);
        baseLoaderCallback = new BaseLoaderCallback(this) {
            @Override
            public void onManagerConnected(int status) {
                // super.onManagerConnected(status);
                switch (status) {
                    case BaseLoaderCallback.SUCCESS: {
                        cameraBridgeViewBase.enableView();
                        break;
                    }
                    default: {
                        super.onManagerConnected(status);
                        break;
                    }
                }
            }
        };
        fpsMeter.init(); // when I add this line my app crashes

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!OpenCVLoader.initDebug()) {
            Toast.makeText(getApplicationContext(), "OpenCV could not be loaded.", Toast.LENGTH_SHORT).show();
        } else {
            baseLoaderCallback.onManagerConnected(BaseLoaderCallback.SUCCESS);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (cameraBridgeViewBase != null) {
            cameraBridgeViewBase.disableView();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (cameraBridgeViewBase != null) {
            cameraBridgeViewBase.disableView();
        }
    }

    @Override
    public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
        mat1 = inputFrame.rgba();
        return mat1;
    }

    @Override
    public void onCameraViewStopped() {
        mat1.release();
    }

    @Override
    public void onCameraViewStarted(int width, int height) {
        mat1 = new Mat(width, height, CvType.CV_8UC4);
    }

}

A: SOLUTION:
I created my own FPS meter. This is the code:
The variables I use:
Textview txt1;
int mFPS;
long startTime = 0;
long currentTime = 1000;

Set this in onCreate():
runOnUiThread(new Runnable() {
     @Override
     public void run() {
     txt1 = (TextView) findViewById(R.id.txt1);
     }
});

And this is my onCameraFrame():
@Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
    mat1 = inputFrame.rgba();
    //Log.i(TAG, mat1.get(128, 128).toString());

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (currentTime - startTime >= 1000) {
                txt1.setText("FPS: " + String.valueOf(mFPS));
                mFPS = 0;
                startTime = System.currentTimeMillis();
            }
            currentTime = System.currentTimeMillis();
            mFPS += 1;

        }
    });
    return mat1;
}


text:
Q: UpdateAysnc throws "Field 'id' is not recognied" error I have the following code, written in C# using a .NET Core 2.0 console app. I've used these same variables for an adding function and all works fine.
The GetAsync works and pulls back the list item. When the UpdateAsync is called I get an error return from Microsoft Graph:
Messsage: Field 'id' is not recognied
HResult: -2146233088
request-id: 0682cf9f-c828-43f1-bc9e-acb21631a58e
date: 01/11/2017 7:28:38 Ticks 636450912000000000

note that "recognied" is the actual spelling returned
This is the code I'm using:
var listItemId = SharePointIdToInSiteMapping.GetValueOrDefault(siteRecord.InSiteID);
var graphClient = GetGraphClient();

var listItem = await graphClient.Sites[siteId].Lists[listId].Items[listItemId].Request()
    .Expand(i = > i.Fields)
    .GetAsync();

listItem.Fields.AdditionalData["Title"] = siteRecord.Title;

try
{
    var request = graphClient.Sites[siteId].Lists[listId].Items[listItemId].Request();
    var result = await request.UpdateAsync(listItem);
    Console.WriteLine($"Updated List Item at {result.WebUrl}");
}
catch (Exception e)
{
    Console.WriteLine($"Error updating {siteRecord.Title}");
    Console.WriteLine(e);
}

UPDATED CODE THAT WORKS FOR THOSE THAT ARE INTERESTED
var result = await graphClient.Sites[siteId].Lists[listId].Items[listItemId].Request().UpdateAsync(
  new ListItem(){
    Fields = new FieldValueSet{
      AdditionalData = new Dictionary<string, object>{
        {"Title", "A change title"}
      }
     }
   }
  );

A: The reason for this error is that you're passing the entire ListItem object to UpdateAsync. Since the id property is read-only, it is returning an error.
In order to send an update to the ListItem you should pass in a new ListItem object with only the properties you wish to change:
var result = await graphClient
    .Sites["siteId"]
    .Lists["listId"]
    .Items["listItemId"]
    .Request()
    .UpdateAsync(new ListItem()
    {
        // Properties you wish to change
    });


text:
Q: MSChart - How can i add an on click event to my title? so i have my title:
    Chart = CreateChartTemplate();
    Title area1Title = new Title(chartTitle, Docking.Top, new Font("Verdana", 12),      Color.Black);
    area1Title.IsDockedInsideChartArea = false;
    area1Title.Docking = Docking.Top;
    Chart.Titles.Add(area1Title);

i'd like to add an onclick event to it. I've researched it and googled it but i've found mostly things about datapoints i get quite confused when it comes to using the sender arg. I have used it before but only for buttons, so i could assign it using button.Click+= methodname.
i plan on using the on click event to pop up a dialog box of sorts which will allow a user to change the title.
should probably add that this is not for a web based chart.

A: Unfortunately there are no events for Title class. But you can check where the mouse click has happened and display the user input dialog if the click is on a title.
Subscrible to the chart's MouseDown event.
chart1.MouseDown += new MouseEventHandler(chart1_MouseDown);

In the event handler check whether the click is on the title and show the dialog from user input.
void chart1_MouseDown(object sender, MouseEventArgs e)
{
    HitTestResult result = chart1.HitTest(e.X, e.Y);
    if (result.ChartElementType == ChartElementType.Title)
    {
        Title aTitle = result.Object as Title;
        if (aTitle != null)
        {
            // show dialog for user input.
            aTitle.Text = //user input value
        }
    }
}