text:
Q: Java compressing try/catch codes exceptions Is there any way to compress the try/catch block codes? Right now, my code has a try/catch code inside a try/catch code.
if(petType.equals("DOG")) {

  try {
    String name = input.next();
    String owner = input.next();
    double weight = input.nextDouble();
    SimpleDateFormat stdDate = new SimpleDateFormat("MM/dd/yy");

    try {
      Date vaccineDate = stdDate.parse(input.next());
      boolean fixed = input.nextBoolean();
      Dog x = new Dog(name,owner,weight,vaccineDate,fixed);
      object.addPet(x);
    }
    catch (ParseException ex) {
      System.out.println("ERROR - Vaccine date " + input.next() + " is not in mm/dd/yy format!");
      input.nextLine();
    }

  }
  catch(NoSuchElementException ex) {
    System.out.println("ERROR - Missing fields. Skipping line " + lineNumber + "...");
    input.nextLine();
  }

}

A: You could do this
if(petType.equals("DOG")) {

  try {
    String name = input.next();
    String owner = input.next();
    double weight = input.nextDouble();
    SimpleDateFormat stdDate = new SimpleDateFormat("MM/dd/yy");
    Date vaccineDate = stdDate.parse(input.next());
    boolean fixed = input.nextBoolean();
    Dog x = new Dog(name,owner,weight,vaccineDate,fixed);
    object.addPet(x);
  }
  catch(NoSuchElementException ex) {
    System.out.println("ERROR - Missing fields. Skipping line " + lineNumber + "...");
    input.nextLine();
  }
  catch (ParseException ex) {
    System.out.println("ERROR - Vaccine date " + input.next() + " is not in mm/dd/yy format!");
    input.nextLine();
  }
}

Or with Java 7
try {
...
} catch(ParseException | NoSuchElementException ex) {
...
}

If that's what you meant by compression.

A: 1st of all, a single try block can be followed by a series of catch blocks:
try {
    throw IOException("msg");
    ...
    throw InterruptedException("msg");
}
catch (IOException ioe){
    ...
 } catch (InterruptedException ie) {
    ...
 }

This is not the best practice, because you might want to narrow your try/catch blocks to handle smaller content of code regarding the Exceptions

A: You can only use one try block, and then use catch(Exception ex) to catch all those exceptions. If you want to react to the specific kind of exception, you have to test for it.

A: You can do it (see below). But you might want to think about the structure of your code, for example, maybe you can restructure so that you don't have to call input.nextLine in each catch block.
if(petType.equals("DOG")) {

  try {
    String name = input.next();
    String owner = input.next();
    double weight = input.nextDouble();
    SimpleDateFormat stdDate = new SimpleDateFormat("MM/dd/yy");

    Date vaccineDate = stdDate.parse(input.next());
    boolean fixed = input.nextBoolean();
    Dog x = new Dog(name,owner,weight,vaccineDate,fixed);
    object.addPet(x);
  }
  catch (ParseException ex) {
    System.out.println("ERROR - Vaccine date " + input.next() + " is not in mm/dd/yy format!");
    input.nextLine();
  }
  catch(NoSuchElementException ex) {
    System.out.println("ERROR - Missing fields. Skipping line " + lineNumber + "...");
    input.nextLine();
  }
}

A: Personally, I don't like nesting try/catch blocks.  I wouldn't write it this way; I'd prefer it more like this:
if(petType.equals("DOG")) {

  String vaccineDateString;
  try {
      String name = input.next();
      String owner = input.next();
      double weight = input.nextDouble();
      DateFormat stdDate = new SimpleDateFormat("MM/dd/yy");
      stdDate.setLenient(false);
      vaccineDateString = input.next();
      Date vaccineDate = stdDate.parse(vaccineDateString);
      boolean fixed = input.nextBoolean();
      Dog x = new Dog(name,owner,weight,vaccineDate,fixed);
      object.addPet(x);
    } catch (ParseException ex) {
        System.out.println("ERROR - Vaccine date " + vaccineDateString + " is not in MM/dd/yy format!");
        input.nextLine();
    } catch(NoSuchElementException ex) {
        System.out.println("ERROR - Missing fields. Skipping line " + lineNumber + "...");
        input.nextLine();
    }
}

I would also look askance at your mingling input with all this other stuff.  I'd find another way.


text:
Q: Breaking a while loop by case in Java I need to issue break a while loop if a case is matched in a switch statement. The case is as follows: if a user enters either a number less than zero or anything greater than five. I have the switch working most of my cost except the two exceptions Ive mentioned. Here is my code:
import java.util.Scanner;
public class Product
{
    public static void main(String args[])
    {
        int cntr = 0;
        int product = 0;
        int units = 0;
        double totalcost = 0;
        Scanner MK = new Scanner(System.in);
        cntr=0;
        while (cntr >= 0 && cntr <=5)
        {
            System.out.println("Enter Product no.(1-5) or -1 to Quit");
            product = MK.nextInt();
            switch(product) {

            case 1:
            {
                System.out.println("Product " + (cntr+1));
                System.out.println("Enter Quantity or -1 to Quit");
                product = MK.nextInt();
                double cost = 2.98;
                totalcost = totalcost + cost*product;
                System.out.println("Current total cost: " + totalcost);
                cntr++;
            }
            break;
            case 2:
            {
                System.out.println("Product " + (cntr+1));
                System.out.println("Enter Quantity or -1 to Quit");
                product = MK.nextInt();
                double cost = 4.50;
                totalcost = totalcost + cost*product;
                System.out.println("Current total cost: " + totalcost);
                cntr++;
            }
            break;
            case 3:
            {
                System.out.println("Product " + (cntr+1));
                System.out.println("Enter Quantity or -1 to Quit");
                product = MK.nextInt();
                double cost = 9.98;
                totalcost = totalcost + cost*product;
                System.out.println("Current total cost: " + totalcost);
                cntr++;
            }
            break;
            case 4:
            {
                System.out.println("Product " + (cntr+1));
                System.out.println("Enter Quantity or -1 to Quit");
                product = MK.nextInt();
                double cost = 4.49;
                totalcost = totalcost + cost*product;
                System.out.println("Current total cost: " + totalcost);
                cntr++;
            }
            break;
            case 5:
            {
                System.out.println("Product " + (cntr+1));
                System.out.println("Enter Quantity or -1 to Quit");
                product = MK.nextInt();
                double cost = 6.87;
                totalcost = totalcost + (cost*product);
                System.out.println("Current total cost: " + totalcost);
                cntr++;
            }
            case 6:
            {
                System.out.println("Product " + (cntr+1));
                System.out.println("Enter Quantity or -1 to Quit");
                //product = MK.nextInt();
                //double cost = 2.98;
                //totalcost = totalcost + cost*product;
                System.out.println("Current total cost: " + totalcost);
                //cntr++;
            }
            break;
            }
            System.out.println("Total cost-->" +totalcost);
        }
    }
}

If anyone can point me in the right direction on how to stop my program when anything less than zero or greater than 5 is entered I would really appreciate it.

A: A couple of options:

*

*Use a flag that you set when you want the loop to end (in your default or -1 clause), or

*Use a labelled statement and a directed break in your default (or -1) clause

*In this specific situation where you said you want the entire program to end, you could use System.exit
Here's more about option 2:
label: while (...) {          // <== Labelled statement
    switch (...) {
        case ...:
            // ...
            break;            // <=== Normal (undirected) break, just exits what
                              //      it's in (switch in this case)
        // ...
        default:
            break label;      // <=== Directed break, exits loop
    }
}

It's also handy for nested loops.

Side note: There's no need for the { and } you have surrounding the statements in your case clauses. The code for case continues until the break. (Yes, it's a bit different from other statements.)

Side note 2: You've said Enter Product no.(1-5) or -1 to Quit in your prompt, but you have cases for the values 1 to 6 (inclusive). You probably meant Enter Product no.(1-**6**) or -1 to Quit.

redpajama_set_name: RedPajamaStackExchange


text:
Q: UserForm.Show within a prior Initial User form causes blank grey un-closeable workbook to open Below is the excerpt of code where the "error(more like an unwanted occurrence)" happens. My code is running in a userform (not userform1) after a command button click. The initial form shows on workbook open. The second userform - UserForm1 in the code below - is a check box that I want to present to the user upon my IF condition. When the program gets there, it opens the UserForm1, but also opens a blank grey excel workbook. The workbook cannot be closed until I close the Userformm1 interface.
Note: the second msgbox does not display until AFTER I close the userform.
I tried searching for this problem, but couldn't find the issue in regards to UserForm stuff. Thanks in advance for any help.
Private Sub CommandButton1_Click()

Dim wbName As String, wb As Workbook, ws As Worksheet
Dim sht As Worksheet
Dim myValue As Variant
Dim counter As Integer
Dim EstNumAttempt As Boolean
EstNumAttemp = False

counter = 0

Dim ThisNum As String
Dim EstNum As String
Dim CopyFromBook As Workbook
Dim CopyToWbk As Workbook
Dim ShToCopy As Worksheet

Set CopyToWbk = ThisWorkbook

Application.ScreenUpdating = False

ThisUserPath = Application.ActiveWorkbook.Path

userDataPath = ThisUserPath & "\SBNBidDataSet01112018.xlsx"

Dim StartDate As String
Dim EndDate As String

StartDate = TextBox1.Value
EndDate = TextBox2.Value
EstNum = TextBox3.Value

Set wb = Workbooks.Open(userDataPath)

Set CopyFromWbk = wb

WSCount = wb.Worksheets.Count

If EstNum <> "" Then

EstNumAttempt = True

For X = 1 To WSCount

Set ws = wb.Sheets(X)
ThisNum = ws.Cells(2, 2)

If ThisNum = EstNum Then

 counter = counter + 1
 Set ShToCopy = CopyFromWbk.Worksheets(X)
 ShToCopy.Copy After:=CopyToWbk.Sheets(CopyToWbk.Sheets.Count)

End If

Next X

If counter = 0 Then

   MsgBox " That's probably not a valid EST# in SmartBidNet"

End If

End If

If IsDate(StartDate) = True And IsDate(EndDate) = True And EstNumAttempt = False Then
MsgBox "h"
wb.Application.Visible = False
UserForm1.Show
wb.Application.Visible = True

MsgBox "h"
'BLANK GREY SHEET HERE

For X = 100 To 101

    Set ws = wb.Sheets(X)

    lastrow = ws.Cells(Rows.Count, 1).End(xlUp).Row

    'future code

Next X

End If

wb.Close
Application.ScreenUpdating = False ' from before also!

End Sub

A: THIS IS NOT A SOLUTION, I tested a piece of your code and here is my feedback below.
I ran just this code in a workbook named testbook.xslm and I created a form (myForm that is just a grey layout, nothing on it):
Private Sub CommandButton1_Click()
Dim wb As Workbook
Dim anotherbook As Workbook
Dim anotherbook2 As Workbook
Dim anotherbook3 As Workbook

Set wb = Workbooks.Add
Set anotherbook = wb
Set anotherbook2 = wb
Set anotherbook3 = wb

MsgBox "h"
wb.Application.Visible = False
myForm.Show
wb.Application.Visible = True

MsgBox "h"

wb.Close
Application.ScreenUpdating = False ' from before also!
End Sub

From the user standpoint:
1) testbook opens
2) click the button -> book# opens on top of testbook
3) msgbox "h" pops up
4) x out of msgbox "h" -> Both workbooks disappear (testbook and book1)
5) my grey user form pops up (its empty)
6) x out of userform
7) testbook shows again on top of the new book created which is behind it
8) msgbox "h" #2 pops up
9) x out of msgbox
10) the book# behind testbook disappears
That's it.  No grey box residue.  How are you closing the userforms (the first one and the second one)?  obviously I used the terminate with the x.  I did not add any code.  So how are you closing your form with no code?
Adding the same behavior occurs if I make multiple workbook references to wb.
So this code area is not your problem . . . .
Second test, still no problems, adding worksheets, running through the number of worksheets, copying them to the testbook.
Option Explicit

Private Sub CommandButton1_Click()
Dim wb As Workbook
Dim wb2 As Workbook
Dim ws As Worksheet
Dim anotherbook As Workbook
Dim anotherbook2 As Workbook
Dim anotherbook3 As Workbook
Dim X As Double
Dim lastrow As Double
Dim thisNum As String

Set wb = Workbooks.Add
Set anotherbook = wb
Set anotherbook2 = wb
Set anotherbook3 = wb
Set wb2 = ThisWorkbook

wb.Worksheets.Add
wb.Worksheets.Add
wb.Worksheets.Add
wb.Worksheets.Add
wb.Worksheets.Add
wb.Worksheets.Add

myForm2.Show

MsgBox "h"
wb.Application.Visible = False
myForm.Show
wb.Application.Visible = True

MsgBox "h"

For X = 1 To wb.Worksheets.Count

    Set ws = wb.Sheets(X)
    thisNum = ws.Cells(2, 2)

    lastrow = ws.Cells(Rows.Count, 1).End(xlUp).Row

    ws.Copy After:=wb2.Worksheets(wb2.Worksheets.Count)

    'future code

Next X

wb.Close
Application.ScreenUpdating = False ' from before also!
End Sub

Perhaps you have a lot of data being acted upon.  Clear the clipboard after the paste?  With:
Application.CutCopyMode = False

Digging - WWC


text:
Q: Looping in a String to find Unicode characters is taking too much time I am creating a custom field where I want to replace some unicode caracters by pictures. Its like doing emoticons for blackberry device. Well I have a problem looping the caracters in the edit field and replacing the unicode caracters by images. When the text becomes too long, the loop takes too much time.
My code is as follows:
String aabb = "";
char[] chara = this.getText().toCharArray();
for (int i = loc; i < chara.length; i ++) {
   Character cc = new Character(chara[i]);
   aabb += cc.toString();
   if (unicodeCaracter) {
       //Get the location
       //draw the image in the appropriate X and Y
   }
}

Well this works fine, and the images are getting in the right place. But the problem is when the text becomes large, the looping is taking too much time, and the input of the text on the device becomes non friendly.
How to find the unicode caracters in a text without having to loop each time for them? Is their another way than this that I missed?
I need help with this issue. Thanks in advance

A: Well you're creating a new Character and a new String in each iteration of the loop, and converting the string to a character array to start with. You're also using string concatenation in a loop rather than using a StringBuffer. All of these will be hurting performance.
It's not obvious what you mean by "Unicode characters" here - all characters in Java are Unicode characters. I suspect you really want something like:
String text = this.getText();
StringBuffer buffer = new StringBuffer(text.length());
for (int i = 0; i < text.length(); i++) {
    char c = text.charAt(i);
    buffer.append(c);
    if (c > 127) { // Or whatever
        // Take some action
    }
}

I'm assuming the "take some action" will be changing the buffer in some respect, otherwise the buffer is pointless of course... but fundamentally that's likely to be the sort of change you want.
The string concatenation in a loop is a particularly bad idea - see my article on it for more details.

A: What takes time is the string concatenation.
Strings are immutable in Java. Each time you do
aabb += cc.toString();

you create a new String object containing all the chars of the previous one, which must be garbage collected, plus the new ones. Use a StringBuilder to build your string:
StringBuilder builder = new StringBuilder(this.getText().length() + 100); // size estimation
char[] chara = this.getText().toCharArray();
for (int i = loc; i < chara.length; i++) {
   builder.append(chara[i]);
   if (unicodeCaracter) {
       //Get the location
       //draw the image in the appropriate X and Y
   }
}
String aabb = builder.toString();

A: Well, besides speeding up your loop, you could also try and minimize the work load.
If the user is appending text you could store the last position you scanned previously time and start from there..
On inserts/deletes you'd need to get the caret position and scan the deleted/inserted part and maybe surrounding characters (if you have character groups instead of single characters that get replaced).
However, fixing loop performance is likely to give you a better improvement in your case, as I doubt you'll have that long strings to make that algorithmic change worthwhile.

A: The most important performance enhancements have already been stated but looping backwards will also help in BlackBerry apps.
Programming Tips: General Coding Tips


text:
Q: Ember.js model- and setupController-hook with nested routes I'm currently evaluating Ember.js and therefore I am building a small sample app. Currently everything went quite smooth so far, but now I don't seem to be able to fix my last little problem.
When I access the app normaly via the route films, everything works as expected. The list of films is displayed. Now when I click onto a film, the details of the film are loaded via setupController hook just below the list of films. That's all just fine.
Here comes my problem: I would like to be able to access the film details directly via url, but somehow in this case another request is fired to grab the film details, with the value of undefinded. As far as I understand that is the model hook.
I can only guess, but I think it is the model hook which is beeing executed.
Can someone point me to the probably obvious mistake I'm making? And on the other hand, is the code i wrote so far "correct"? Or is there a better way of doing this?
(I am aware of the bad way I use to render the film details. I will remove the {{#each}} tag, and change the way I asign the response to the film variable.
Here the link to the sample app: http://jsbin.com/ewiN/1#/films
UPDATE
Ok, now I am getting really confused. I almost have it working, hopefully someone can point it out to me, because it's such a simple task, but it nearly seems impossible to do without knowing ember really well...
When accessing the app via url, it only works when I remove the setupController hook. But I need that hook, to load the FilmDetails on clicking onto the links to properly load the FilmDetails.
http://jsbin.com/ewiN/16#/films/tt0100669
Many thanks for the feedback!
Regards
Reto

A: Instead of use jQuery.getJSON, use Ember.RSVP.Promise, because internally ember use this promise api instead of jquery. I think that using both, can make inconsistencies.
return new Ember.RSVP.Promise(function(resolve, reject) {

  var films = [];

  jQuery.getJSON("http://www.omdbapi.com/?s=" + searchTerm, function (response) {

    $.each(response.Search, function (index, value) {
      films.pushObject(Kitag.Films.create({
        title: value.Title,
        id: value.imdbID
      }));
    });
  }).fail(reject);

  resolve(films);
});

Because we are returning a promise instead of an object, we need to use the model hook, because it is wait until the promise is resolve to render templates.
Kitag.FilmsRoute = Ember.Route.extend({
  model: function() {
    return Kitag.Films.getMovies('spiderman');
  }
});

I have removed the Kitag.FilmRoute, because the expected:
Kitag.FilmRoute = Ember.Route.extend({
    model: function(params) {
        return Kitag.Film.find(params.id)
    },
    serialize: function (model) {
        return { film_id: model.get("id") };
    }
});

is the default.
This is the final result http://jsbin.com/ewiN/15/edit


text:
Q: Exception in property when setting a binary value I have the following method which gives me a stackoverflow exception on setting a value. I can't step into it and debug it application just crashes few seconds later. Here is the code
public byte[] ImageTIFF
{
    get
    {
        try
        {
            string filePath = ImageTIFFDir + ImageId + ".TIFF";

            if (File.Exists(filePath))
            {
                return File.ReadAllBytes(ImageTIFFDir + ImageCollectionId + ".TIFF");
            }
            else
            {
                return null;
            }
        }
        catch (Exception e)
        {
            Logger.log("Can't read TIFF image from file.", e);
            throw;
        }
    }
    set
    {
        try
        {
            ImageTIFF = value;
        }
        catch (Exception e)
        {
            Logger.log("Can't set image TIFF.", e);
            throw;
        }

    }
}

This gets called during an export and it fails on a first call:
someImage.ImageTIFF = File.ReadAllBytes(imageName);

A: Change the code to
private byte[] m_ImageTIFF;
public byte[] ImageTIFF
{
  get{...}
  set { m_ImageTIFF = value;}
}

You need a backing store for the property.

A: This is because , you are setting property itself in the set block
ImageTIFF = value;

make a byte[] array variable and set in the set block and in the get block return this variable.

A: Here you try to set value to the property you are already in.
try
{
    ImageTIFF = value;
}

You need to have class member behind that property. Something like
byte[] _imageTIFF

and set it
set
{
    try
    {
        _imageTIFF = value;
    }
    catch (Exception e)
    {
        Logger.log("Can't set image TIFF.", e);
        throw;
    }
}

A: You're setting the value of Property within setting the value of the property...recursion, my friend:
ImageTIFF = value;

You'll need to create another variable to hole value. Properties are no variables, they're just wrappers.


text:
Q: Dagger2 is not injecting field I have this module:
@Module
public class MainModule {

    private Context context;

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

    @Provides
    @Singleton
    Dao providesDao() {
        return new Dao();
    }

    @Provides
    @Singleton
    FirstController providesFirstController(Dao dao) {
        return new FirstController(dao);
    }

    @Provides
    @Singleton
    SecondController providesSecondController(Dao dao) {
        return new SecondController(dao);
    }

}

and this component:
@Singleton
@Component(modules = MainModule.class)
public interface MainComponent {

    void inject(FirstView view);

    void inject(SecondView view);

}

and, finally, the injector class, that is initialized in App.onCreate() method:
public enum Injector {

    INSTANCE;

    MainComponent mainComponent;

    public void initialize(App app) {
        mainComponent = DaggerMainComponent.builder()
                .mainModule(new MainModule(app))
                .build();
    }

    public MainComponent getMainComponent() {
        return mainComponent;
    }
}

In my FirstView and SecondView (that are Fragments), I have this:
    @Inject
    FirstController controller; //and SecondController for the second view

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Injector.INSTANCE.getMainComponent().inject(this);
    }

In the first fragment, everything is ok, the controller is injected. But in the second view it is not: just returning null.
I have put breakpoints in "provides" module's methods and the providesFirstController is executed but not the providesSecondController.
What am I doing wrong? I'm new in Dagger2 so any advice will be appreciated.

A: If those are Fragments try moving the code connected with injecting:
Injector.INSTANCE.getMainComponent().inject(this);

to the Fragment's public void onCreate(Bundle savedInstanceState) method.
If the views are not visible on the screen at the same time (added by FragmentManager), then the SecondView onAttach method may not be called.

A: Solved! I have change the signature of inject methods to:
@Singleton
@Component(modules = MainModule.class)
public interface MainComponent {

    void inject(FirstFragment view);

    void inject(SecondFragment view);

}

I forget to say that FirstView and SecondView are interfaces, not classes. And inject methods need the concrete class.


text:
Q: LDAP query to retrieve members of a group I know this question has been asked a few times already but I'm still at a loss :(
What I want to do is pass a security group name to an LDAP query and list out all the users who are a memberof. Am I right in understand that all that's required is to pass in the group's distinguished name, as follows? For some reason, the query is returning a blank.
(&(objectCategory=user)(memberOf={group distinguished name}))

A: Thanks for the replies. My query was correct! The reason I wasn't receiving users is that there weren't any in the security group - despite the fact that network admin claimed there were.


text:
Q: Calling a callback method from -drawRewct: using CoreGraphics I have been provided with a method used for styling, called [in / from] the  -drawRect: method of my UIView subclass.  Unfamiliar with lower-level CG syntax I am not sure how to call a method starting with:
void DrawInsetBeveledRoundedRect( CGContextRef context, CGRect rect, CGFloat radius, UIColor *fillColor) {}

from  -drawRect: .
Could anybody please advise and or provide me with a steer?

A: - (void)drawRect:(CGRect)rect {
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    DrawInsetBeveledRoundedRect(ctx, rect, 1234, [UIColor greenColor]);
}


text:
Q: Problema con formato de hora en javascript Estoy enviando una fecha hacia en un campo de texto  y en la caja de texto recibe la fecha sin embargo me llega con formato "Wed Jul 24 2019 12:54:17 GMT-0400 (hora estándar de tu zona)" y necesito recibirla en 'Y-m-d'
$('#datetimepicker').datetimepicker({
            disabledDates: ['2019-07-23'],
            formatDate:'Y-m-d',
            format: 'Y-m-d H:i',
            formatTime: 'H:i',
            step: (60),
            allowBlank: false,
            onSelectDate: function(dateText, inst) {$("input[name='datos']").val(dateText);}
            });

Creo que debo insertar el formato de fecha dentro del function pero no se como hacerlo.

A: Por lo general estas librerías utilizan moment.js para hacer conversiones, en caso contrario podrías incorporar la librería, ya que es demasiado útil para trabajar con fechas, horas y formatos personalizados.
Te dejo un código que debería funcionar:
$('#datetimepicker').datetimepicker({
    disabledDates: ['2019-07-23'],
    formatDate:'Y-m-d',
    format: 'Y-m-d H:i',
    formatTime: 'H:i',
    step: (60),
    allowBlank: false,
    onSelectDate: function(dateText, inst){
        let formatedDate = moment(dateText).format("Y-m-d");
        $("input[name='datos']").val(formatedDate);
    }
};

Espero te sea útil.


text:
Q: Find ratio/algorithm to translate different coordinate systems? So I have two different coordinate systems, one is the incoming data and the other is how i plot points in the app. Is there a formula that, given some aligned up points, will give me an algorithm to calculate future points? Eg:
X = 6.5 & Y = 2  on one system is == X = 3101 & Y = 3441 in the other system.
Another set is 6.45/2.37 = 3211/3414. From these two matchups, how can I calculate a formula to "translate" one system into the other?

A: what you want is called linear interpolation, rule of three, etc

A: You need to solve two equations with two unknowns for X, and then the same for Y.
Let's go through this. First we do X:
3101 = 6.5  * a + b
3211 = 6.45 * a + b

First we isolate b:
3101 - 6.5  * a = b
3211 - 6.45 * a = b

Which gives:
3101 - 6.5 * a = 3211 - 6.45 * a

Now we can solve for a:
3101 - 6.5 * a - 3211 + 6.45 * a = 0
-110 -0.05 * a = 0
-110 = 0.05 * a
-2200 = a

Given this a we can solve for b using either of the original two equations:
3101 - 6.5  * a = b
3101 - 6.5 * -2200 = b
3101 + 14300 = b
17401 = b
b = 17401

So for X we have this formula:
X2 = -2200 * X1 + 17401

Let's try X1 = 6.5 and X1 = 6.45:
X2 = -2200 * 6.5 + 17401
X2 = -14300 + 17401
X2 = 3101

X2 = -2200 * 6.45 + 17401
X2 = -14190 + 17401
X2 = 3211

Doing the exact same math for Y gives me that the relationship follows this formula:
Y2 = Y1 * A + B
3441 = 2 * A + B                 3414 = 2.37 * A + B
3441 - 2 * A = B                 3414 - 2.37 * A = B
3441 - 2 * A = 3414 - 2.37 * A
3441 - 2 * A - 3414 + 2.37 * A = 0
27 + 0.37 * A = 0
     0.37 * A = -27
     0.37 * A = -27
            A = -72.973

3441 = 2 * A + B
3441 = 2 * -72.973 + B
3441 - 2 * -72.973 = B
3441 + 145.946 = B
3586.946 = B
B = 3586.946

Which gives:
Y2 = Y1 * -72.973 + 3586.946

Let's test:
Y2 = 2 * -72.973 + 3586.946
Y2 = -145.946 + 3586.946
Y2 = 3441

Y2 = 2.37 * -72.973 + 3586.946
Y2 = -172.946 + 3586.946
Y2 = 3414

Your translation formulas are this:
X2 = X1 * -2200  + 17401
Y2 = Y1 * 72.973 + 3586.946


text:
Q: Check a password in Javascript with a regular expression i've got an expression checking whether there is at least one number, one lowercase and one uppercase letter and at least 6 characters in a password string.
please see my example:
var myPwd = 'test-123H';
console.log('password to check: ' + myPwd);
//at least one number, one lowercase and one uppercase letter and at least six characters
var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
var validPassword = re.test(myPwd);
console.log(validPassword);

unfortunatly i can't manage it to achieve two more conditions: the password should be checked against a maximum length of 15 characters and there should be at least 2 numbers instead of one. could anyone tell me the trick?

A: You can modify your regex to this:
var re = /^(?=(\D*\d){2})(?=.*?[a-z])(?=.*?[A-Z]).{6,15}$/;

*

*(?=(\D*\d){2}) => will make sure there are at least 2 digits

*.{6,15} makes sure there are min 6 and max 15 character

*^ and $ are line start and line end anchors

Visual Description:


text:
Q: i want to show image instead of showing url

   //

this is my html
<a class="btn btn-primary" onclick="viewList('<?php echo $record->reimId;?>','<?php echo $this->common_model->getEmployeeById($record->empId);  ?>','<?php echo base_url('uploads/reimbrush') . '/' . $record->reimImage; ?>');" name="viewList" id="viewList" data-toggle="modal" data-target="#viewListData">View

how to stop access redirecting URL in Codeigniter
here is my code where url is showing...


text:
Q: Welch's t-test when the smaller sample has a larger variance I have heard that there is no statistical criterion, which would work well in the case when the smaller sample has a larger variance due to the Behrens-Fisher problem, and even Welch's t-test can't be used in this situation.
Is it true? I can't see such limitation in Wikipedia.

A: As far as type I error rate goes, it looks okay to me.
A few quick simulations don't seem to indicate any major difficulty with significance level when the smaller sample has the larger variance.
For example, with the smaller sample having $n_s=10$ and the larger sample with $n_l=100$, and with the smaller population having 25 times the variance of the larger (5 times the sd), the actual significance level when the test is carried out as a 5% test is very close to 0.05 (this is R code):
> sr=5;res=replicate(10000,t.test(rnorm(100),rnorm(10,0,sr))$p.value)
> mean(res<.05)
[1] 0.0501
> sr=5;res=replicate(10000,t.test(rnorm(100),rnorm(10,0,sr))$p.value)
> mean(res<.05)
[1] 0.0499

That seems pretty good. Of course you'd want to try a range of n's and ratios of variances. I tried a few others, but they were all reasonably close to 5% for a 5% test - e.g. a couple of trials of 10000 simulations for a ratio of variances of 9 and a ratio of sample sizes of 100/10 gave the type I error rate at about 5.1%. Four such trials with the ratio of variances changed to 100 gave an average type I error rate of 4.9% -- but the standard error of the estimate is about the same size as the deviation from 5% so we can't actually pick up any deviations from 5% here (there will be some, they're just too small to pick up even with 40000 trials). A much larger trial suggests that it's actually closer to 5% than this.
I'd be quite untroubled by such small deviations in the type I error rate; if you're concerned about some particular $n_s, n_l$ and some range of variance ratios, you could easily simulate to check that case in detail, but I'd suggest that apart from some possible issues at very small sample sizes ($n_s=2$ might might have a few poor ones, say, so you'd probably want to check that more carefully if you had $n$ so low), that pretty much all cases you're likely to encounter in practice will generally be okay.

What about power? It depends on what you compare it to. If the problem is only pairing larger variance with smaller sample, let's look at the effect on asymptotic precision (inverse variance) of swapping the larger variance to the larger sample; this should tell us approximately how much larger a pair of samples we'd need to pick up the same small difference in means.
It certainly will have an effect, since in larger samples, the power is most heavily determined by the smaller of the two precisions of the group means; the case where the bigger variance goes with the smaller sample size will certainly reduce power because of that.
Let the ratio of sample sizes be $n_r=n_l/n_s$ and as before let $V_r$ be the ratio of variances (larger on smaller). Also, for this calculation, let the smaller variance be 1.
In the case you're asking about the precision of the difference in means is proportional to $n_s(1/V_r+n_r)$ and in the case where the larger variance is with the larger sample it's proportional to $n_s(1+n_r/V_r)$
Further, let's look at the simple case where $V_r=n_r$ e.g. consider 9 times the sample size, and 9 times the variance. Then the ratio of the two precisions is 4.55 --- that is, the effective precision will be about 22% of what it would be with the larger variance combined with the larger sample size. Which means to get about the same power at the same ratio of sample sizes you'd need 4.5 times as many data points when the variance is with the smaller group. (Of course if you can control it you can improve things much more quickly by focusing on improving the smaller sample size.)
[Why did I set those ratio to be equal? As they become more different it's the larger of the two ratios that mostly drives the precision of the difference, and hence the asymptotic relative efficiency; the case where they're close to equal is the interesting region, that's where you get the relative impact of swapping the variance between the smaller and the larger sample size to be big]
This doesn't make the test unusable, just relatively less powerful. It's not like there's all that much to be done about that, since there's actually less information about the difference.


text:
Q: Is it possible to read files stored on a computer? I want to access a file in computer(c:\test.bin) and to read it as byte array .Is it possible in Windows phone .
Thanks and Regards
vaysage

A: You cannot access a file via any standard file I/O apis.
You can run a web server on that computer, make the file available via http and include the appropriate client access policy file in the web site.  You can then download the file via WebClient using OpenReadAsync.

A: If you would like to upload something as a project asset, then you should force it to be a "content" from the properties panel and then access it using :
Uri uriMyFile = new Uri("test.bin",UriKind.relative);
StreamReader sr = new StreamReader((Application.GetResourcesStream(
uriMyFile)).Stream);


text:
Q: What is the react-way to handle state that will be impacted by refs So there have been a couple of times now where I have needed to set the state of a component based on properties that are computed at render. As a result, the component is rerendered sometimes. This isn't a huge concern, but it feels hacky and not the "react-way". So I am wondering if someone has a better solution.
So the most recent example is an expandable text component. Similar to the review element on airbnb

This was fairly easy. But the last part was to detect whether there was any overflow and not display the "More" option if it is unnecessary. The solution I came up with was to check if the scrollHeight was greater than the clientHeight and set some state based on that. This is a simplified version of my solution.

import React, { Component, PropTypes } from 'react';
import classNames from 'classnames'

function isOverflowed(element) {
  return element.scrollHeight > element.clientHeight;
}

export default class ExpandableText extends Component {
  static propTypes = {
    content: PropTypes.string,
    maxHeight: PropTypes.number,
  };

  static defaultProps = {
    isOpen: false,
    maxHeight: 10,
  }

  constructor(props) {
    super(props);

    this.handleOpen = this.handleOpen.bind(this);
    this.handleClose = this.handleClose.bind(this);

    this.state = {
      isOpen: props.isOpen,
      isOverFlowed: true,
    };
  }

  componentDidMount() {
    if (!isOverflowed(this.refs.content)) {
      this.setState({ isOpen: true, isOverFlowed: false });
    }
  }

  handleOpen() {
    this.setState({ isOpen: true });
  }

  handleClose() {
    this.setState({ isOpen: false });
  }

  render() {
    const { content, maxHeight } = this.props;
    const { isOpen, isOverFlowed } = this.state;
    const contentClassName = classNames('expandable-text', {
      'expandable-text__content--closed': !isOpen,
      'expandable-text__content--open': isOpen,
    });
    const actionsClassName = classNames('expandable-text__actions', { hide: !isOverFlowed })
    return (

        <div
          ref="content"
          className={contentClassName}
          style={{
            maxHeight: isOpen ? 'none' : `${maxHeight}rem`,
          }}
        >

{content}

          <button onClick={isOpen ? this.handleClose : this.handleOpen}>{isOpen ? 'Close': 'Open'}</button>

    );
  }
}

So there is a decent amount going on, but the important thing is in componentDidMount I am checking the overflow and then setting state (potentially) based on that.
Now I realize that this could probably be accomplished by allowing a limit on number of characters instead of height, or some other solution. But if we assume the solution is similar to this, is there a more react-way to do this? (That doesn't require a rerender)

A: This is fine! You have to render your text before you can detect if it will overflow.
You could do some hacky stuff like counting characters/lines. But font-size can differ greatly per client, so you would just end up with a "good" guess of the overflow size.
Another thing would be to first render the text "off canvas", somehow/somewhere where the user can't see it, into a container which behaves equally to the target container. Then measure the overflow and start rendering to the actual container, knowing that it will/won't overflow.


text:
Q: How to map coordinates in AxesImage to coordinates in saved image file? I use matplotlib to display a matrix of numbers as an image, attach labels along the axes, and save the plot to a PNG file.  For the purpose of creating an HTML image map, I need to know the pixel coordinates in the PNG file for a region in the image being displayed by imshow.
I have found an example of how to do this with a regular plot, but when I try to do the same with imshow, the mapping is not correct.  Here is my code, which saves an image and attempts to print the pixel coordinates of the center of each square on the diagonal:
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axim = ax.imshow(np.random.random((27,27)), interpolation='nearest')
for x, y in  axim.get_transform().transform(zip(range(28), range(28))):
    print int(x), int(fig.get_figheight() * fig.get_dpi() - y)
plt.savefig('foo.png', dpi=fig.get_dpi())

Here is the resulting foo.png, shown as a screenshot in order to include the rulers:

The output of the script starts and ends as follows:
73 55
92 69
111 83
130 97
149 112
…
509 382
528 396
547 410
566 424
585 439

As you see, the y-coordinates are correct, but the x-coordinates are stretched: they range from 73 to 585 instead of the expected 135 to 506, and they are spaced 19 pixels o.c. instead of the expected 14.  What am I doing wrong?

A: This is one of the more confusing parts of trying to get exact pixel values from matplotlib. Matplotlib separates the renderer that handles exact pixel values from the canvas that the figure and axes are drawn on.
Basically, the renderer that exists when the figure is initially created (but not yet displayed) is not necessarily the same as the renderer that is used when displaying the figure or saving it to a file.
What you're doing is correct, but it's using the initial renderer, not the one that's used when the figure is saved.
To illustrate this, here's a slightly simplified version of your code:
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
im = ax.imshow(np.random.random((27,27)), interpolation='nearest')

for i in range(28):
    x, y =  ax.transData.transform_point([i,i])
    print '%i, %i' % (x, fig.bbox.height - y)

fig.savefig('foo.png', dpi=fig.dpi)

This yields similar results to what you have above: (the differences are due to different rendering backends between your machine and mine)
89, 55
107, 69
125, 83
...
548, 410
566, 424
585, 439

However, if we do the exact same thing, but instead draw the figure before displaying the coordinates, we get the correct answer!
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
im = ax.imshow(np.random.random((27,27)), interpolation='nearest')

fig.canvas.draw()

for i in range(28):
    x, y =  ax.transData.transform_point([i,i])
    print '%i, %i' % (x, fig.bbox.height - y)

fig.savefig('foo.png', dpi=fig.dpi)

This yields: (Keep in mind that the edge of the figure is at <-0.5, -0.5> in data coordinates, not <0, 0>. (i.e. the coordinates for the plotted image are pixel-centered) This is why <0, 0> yields 143, 55, and not 135, 48)
143, 55
157, 69
171, 83
...
498, 410
512, 424
527, 439

Of course, drawing the figure just to draw it again when it's saved is redundant and computationally expensive.
To avoid drawing things twice, you can connect a callback function to the draw event, and output your HTML image map inside this function. As a quick example:
import numpy as np
import matplotlib.pyplot as plt

def print_pixel_coords(event):
    fig = event.canvas.figure
    ax = fig.axes[0] # I'm assuming there's only one subplot here...
    for i in range(28):
        x, y = ax.transData.transform_point([i,i])
        print '%i, %i' % (x, fig.bbox.height - y)

fig = plt.figure()
ax = fig.add_subplot(111)
im = ax.imshow(np.random.random((27,27)), interpolation='nearest')

fig.canvas.mpl_connect('draw_event', print_pixel_coords)

fig.savefig('foo.png', dpi=fig.dpi)

Which yields the correct output, while only drawing the figure once, when it is saved:
143, 55
157, 69
171, 83
...
498, 410
512, 424
527, 439

Another advantage is that you can use any dpi in the call to fig.savefig without having to manually set the fig object's dpi beforehand.  Therefore, when using the callback function, you can just do fig.savefig('foo.png'), (or fig.savefig('foo.png', dpi=whatever)) and you'll get output that matches the saved .png file. (The default dpi when saving a figure is 100, while the default dpi for a figure object is 80, which is why you had to specify the dpi to be the same as fig.dpi in the first place)
Hopefully that's at least somewhat clear!

A: I don't know if I understand correctly what you are asking for, but
if I am , you need the pixel coordinates for the lower left corner of the graph (attempt that in the graph's units these are (-0.5, -0.5) ),
and from there, you can compute the pixel coordinates for each box, just with
the box side in pixels.
To get these, do:
x = ax.get_xaxis().get_clip_box().x0
y = ax.get_yaxis().get_clip_box().y1

(I got the values 128, 432 for the given image)


text:
Q: iOS navigate back after login from slide menu I am using ECSlidingViewController for creating "hamburger" menu for user with some options and one of them is login. I edited first example in archive with ECSlidingViewController and it's working and looking good.
Now I just want to extend this to have option after successful login to "redirect" user back to controller from which he taps on "hamburger" and go to login (like on websites). I think that I would need to save somewhere (maybe AppDelegate) from where I was going, is it right?
My AppDelegate looks like this:
@interface MAAppDelegate : UIResponder <UIApplicationDelegate>

@property (nonatomic, strong) ECSlidingViewController *slidingViewController;
@property (strong, nonatomic) UIWindow *window;

@end

This is method which is call after tap on "hamburger" (navigation bar item):
- (IBAction)menuButtonTap:(id)sender
{
    if (self.slidingViewController.currentTopViewPosition == ECSlidingViewControllerTopViewPositionCentered) {
        [self.slidingViewController anchorTopViewToLeftAnimated:YES];
    } else {
        [self.slidingViewController resetTopViewAnimated:YES];
    }
}

And in my MAMenuViewController (controller with static table for options in side menu) I have sets a few sliding segues for table cells to go to each controllers (main, login and so).

A: Why not present the login view as a modal. The user isn't going 'back' from the login, they are cancelling, and it is, conceptually, completely separate functionality to the other part of the app. Presenting modally would usually use a different transition style and marks the screen out as something different.
While the modal is presented, you can also reset the sliding controller so your 'under' menu is no longer displayed. Then, when you dismiss the login view you are already ready without further animations.

A: I think, if i'm right, that what you want to achieve here is " Pushing back " to your previous view controller. So, in that case, you might want to call, in your current view controller
[self.navigationController popViewControllerAnimated:YES];

You can get full answer with more information on this post. On this post, you may found a little more explanation on this post too, on how to identify previous view controller.


text:
Q: Flyway in common library that has integration tests I'm running into a silly situation where I have my flyway dependency defined in a common library's pom file.  This common library happens to have Spring Boot integration tests that load the context and so when those integration tests run I get

java.lang.IllegalStateException: Cannot find migrations location in: [classpath:db/migration] (please add migrations or check your Flyway configuration)

I'd rather not duplicate the dependency definition in all of the applications' poms and I can't remove the integration tests.  I'd also rather not have a dummy migrations folder.  Can I just turn this off somehow in the integration tests?
@SpringBootTest
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@DisableFlywaySomehow
public class MyITest {...}

A: Use a different profile (although you can also use your current test profile) and just set spring.flyway.enabled = false in your application.{properties,yml} file.
You can also play with the @TestPropertySource annotation on a test-by-test case.

A: To be fair, your integration tests should operate on whatever state your app is "current". Which also means (if applicable) database. Why not incorporate testcontainers or similar tool to mimic real-life situation then it'll run actual migrations from source code and you'll test what's necessary.
The disabling of db sounds dodgy unless you are testing integrity of your application disregarding the database. In that case, provide FlywayMigrationStrategy as null - it will stop from executing any migrations and you'll have no DB environment.
Once again - it's up to your application


text:
Q: SwiftUI: Sizing a popover to fit I've got a little popover sample in which a button triggers a popover. The popover only contains a little bit of UI, two buttons in this case, but it still takes up a lot of space instead of wrapping neatly around the content like I'm used to from UIKit. How do I make the popover fit to the size of the content?
Screenshot from the iPad simulator and code below:

struct ContentView: View {

    @State private var showingPopupA = false

    var body: some View {
        HStack {
            Button(action: {
                self.showingPopupA.toggle()
            }, label: {
                Text("Button")
            }).popover(isPresented: self.$showingPopupA) {
                VStack {
                    Button(action: {
                        // Do something
                        self.showingPopupA = false
                    }) {
                        Text("Option A")
                    }
                    Button(action: {
                        // Do something
                        self.showingPopupA = false
                    }) {
                        Text("Option B")
                    }
                }.background(Color.red)
            }
        }
    }
}

Screenshot from macOS:

A: On macOS the code below will look like this:

struct PopoverExample: View {

    @State private var showingPopupA:Bool = false
    var body: some View {
        HStack {
            Button(action: {
                self.showingPopupA.toggle()
            }, label: {
                Text("Button")
            }).popover(isPresented: self.$showingPopupA) {
                VStack {
                    Button(action: {
                        // Do something
                        self.showingPopupA = false
                    }) {
                        Text("Option A")
                    }
                    Button(action: {
                        // Do something
                        self.showingPopupA = false
                    }) {
                        Text("Option B")
                    }
                }.background(Color.red)
            }
        }
        .frame( maxWidth: .infinity, maxHeight: .infinity)
    }
}

Project link

A: It looks like this has been fixed in iOS 13.4 / Xcode 11.4 Beta. The popover will size to whatever it's contents are now.


text:
Q: freetts - text to speech setting mbrola voice com.sun.speech.freetts.ProcessException: Processing Utterance: Working with ubuntu linux version
Almost done with freetts setting with mbrola voices us1, us2 and us3, but finally getting exceptions.
When i run the below command, i could hear kevin's voice of sun microsystems.
    $ java -Dmbrola.base="/home/amphisoft4/Downloads/mbrola" -jar bin/FreeTTSHelloWorld.jar

    All voices available:
    alan (time domain)
    kevin (general domain)
    kevin16 (general domain)
    mbrola_us1 (general domain)
    mbrola_us2 (general domain)
    mbrola_us3 (general domain

But if i specify mbrola_us1
    $ java -Dmbrola.base="/home/amphisoft4/Downloads/mbrola" -jar bin/FreeTTSHelloWorld.jar mbrola_us1

Im getting
All voices available:
    alan (time domain)
    kevin (general domain)
    kevin16 (general domain)
    mbrola_us1 (general domain)
    mbrola_us2 (general domain)
    mbrola_us3 (general domain)

    Using voice: mbrola_us1

    **Processing Utterance: com.sun.speech.freetts.ProcessException: Cannot start mbrola program: [Ljava.lang.String;@62ce0a
    Processing Utterance: com.sun.speech.freetts.ProcessException: Cannot start mbrola program: [Ljava.lang.String;@62ce0a**

A: Does /home/amphisoft4/Downloads/mbrola/mbrola exist?
If you enter:
/home/amphisoft4/Downloads/mbrola/mbrola -h

does it work?
Documentation has a note about creating this name from the distro binary. Did you build the binary  and if not it may not be a binary compatable with your Ubuntu release.
hope that give you a clue.

A: Finlay what worked for me
I am using ubuntu
Created a folder called mbrola

*

*put downloaded mbrola-base for my operating system linux to it

*put downloaded us1, us2, us3 extracted folders to this folder

*Install the mbrola in ubuntu by command line.
sudo apt-get istall mbrola
After installation use this commad to check where your files has located
dpkg -L mbrola

*Copied /usr/bin/mbrola  file to the above mbrola  folder

*Update the program with the path to above program
System.setProperty("mbrola.base", "/home/ngs/INCUBATOR/egg-8/libries/MBROLA/mbrola");


text:
Q: Get current keyboard state without notifications I have a main view controller with a text field close to the bottom of the screen. When the keyboard is shown, the text field moves up - no problem.
This main view controller sometimes adds a child view controller to show a popup above the text field. When the keyboard is not shown, the popup is close to the bottom of the screen, and when the keyboard is shown, the popup moves up - again, no problem.
To move my views up and down when the keyboard is shown or hidden, I'm using the standard approach: register a listener for keyboardWillChangeFrame notifications and update the layout based on the keyboard's frame. This works great as long as I can register a notification listener before the keyboard is shown.
My problem is that sometimes, I add the child controller for the popup when the keyboard is already visible. This means I can only register the notification listener after the keyboard is already visible. When that happens, the popup controller does not know that the keyboard is already visible, and fails to update its layout accordingly.

(There are of course many possible workarounds for this, e.g.

*

*Initialise the child controller with the known current keyboard frame, as used by the parent controller

*Create a singleton keyboard service that always runs, and so always knows the current keyboard frame

In my code, I prefer not to use singletons, and I have a simple keyboard listener service class that I add to each view controller that needs to handle keyboard changes; my workaround there is to have a static variable in this service that tracks the current keyboard frame. This works, but it's code smell.)

What I would like to know, though, is whether iOS provides us with a way to simply get the current state of the keyboard, without needing to listen for updates.
Using notifications puts the responsibility on me to have an internal model of the keyboard state, and keep it in sync with the actual state. This is good for responding to changes, but does not give me confidence that my modeled state is always accurate -- if I miss a notification, it goes out of sync. It would be strange if there was no way to simply check the actual state.


text:
Q: Capturing conditional output with Expect or Shell I have been trying to write an expect script which would capture the output from a remote device only under some conditions . Alternately if it could capture the output to a certain file under normal conditions and to another file under failure conditions that too would work out for me .
The devices in question here are mostly Routers and Switches and in some cases modems .
For instance I would want to capture output to file "Fail_OSPF.txt" in case the OSPF neighborship is down , 2-way or attempt on an interface . In case OSPF neighborship is Full then go ahead and capture the same output to a file "Good_OSPF.txt"
I have looked at the possibilities of the if/else statements in expect but in my case the output would be complex and would need to analysed before firing the else condition
A few examples would be greatly appreciated .
Thanks
Avinash


text:
Q: why is noise always a high frequency signal ? what then is frequency of a noise? while designing signal conditioning circuits for sensors , we design low pass filters to remove high frequency noise. why can't noise be a low frequency signal or what will its frequency be ?

A: Noise is an unwanted signal, period.
Typical sources of natural noise tend to be broadband, that is all frequencies from DC to very high indeed.
The electrical noise produced by resistors, Johnson noise, has a flat frequency spectrum from DC to very high. Flat spectrum means equal power per Hz of bandwidth.
Consider listening to a flat noise signal. Looking at the noise power above and below (say) a mid A of 440Hz. There are only 440 1Hz bandwidths below it, but 10000 to 20000 (depending on how old you are and where your hearing cuts off) above it, so the noise signal sounds dominated by the high frequency hiss.
The noise produced by opamps however tends to be flat above some low frequency, usually in the audio band, most amps are flat above the 1kHz wher noise is typically specified, but then increases towards DC, due to what's called flicker noise. This is a big problem for DC instrumentation. High quality opamps intended for DC use will also have noise specs in the 0.1Hz to 10Hz range, and these numbers tend to dwarf the 1kHz numbers.
For DC signals and low frequency signals, eliminating the noise above their bandwidth can result in orders of magnitude reduction in noise voltage. Which is why it's done.
Other sources of unwanted signals can be narrow band. Your neighbour's garage door opener for instance can be removed by an RF filter. Mains hum can cause big problems in signal conditioning as the freqeuncy is so low, and can often be in the bandwidth of the signal. This then needs a reduction in the hum pickup, as filtering will do no good.

A: "why can't noise be a low frequency signal or what will its frequency be" Who says it can't ?? I can be any frequency so including low frequencies. For example Pink noise has more power at low frequencies !
It depends on the device what kind of noise it produces. If the signals you want from a sensor are low frequency only, then you could filter out the higher frequency components and get a "cleaner", nicer looking signal.
Taking out the high frequencies is similar to "averaging", you take the average of many measurements to get a more accurate reading.

A: "Signal conditioning circuits for sensors" generally use op-amps and internal op-amp voltage noise tends to have a frequency response like this: -

As can be seen, the bigger noises are at the lower frequencies. So why concentrate on the high frequency stuff?
Let's say the average (ball park) voltage noise between 0.1 Hz and 1 Hz is about 60 nV per root-hertz. The total noise that this will produce across that bandwidth is: -
\$\sqrt{1 - 0.1} \times 60nV\$ = 57 nV.
What about between 1 Hz and 10 Hz - we could use 30 nV per root-hertz as the figure and we would calculate the noise as 90 nV. Between 10 Hz and 100 Hz (10 nV per root-hertz) the noise would be about 95 nV.
As you can see, for a decade change in frequency the actual noise power (over that bandwidth) gets bigger as frequency rises.
Now let's say that the sensor has a frequency response of interest up to 10kHz - how much noise exists in the range 10 kHz to 100 kHz i.e. how much noise could we get rid of (because we don't use or need that part of the spectrum)?
the spectral noise density looks to me about 3 nV per root-hertz from the graph so total noise produced by this op-amp in the frequency range 10 kHz to 100 kHz is: -
\$\sqrt{100k - 10k} \times 60nV\$ = 900 nV.
This is why we mainly concentrate on removing high frequency noise.
Another very good reason might be to avoid aliasing when feeding the (amplified or not) sensor output into an analogue to digital converter. Noise above the Nyquist sampling rate (if not significantly reduced) will be folded down into the converted base-band. if you don't understand this you can maybe imagine a sinewave under-sampled like this: -

Imagine the red signal is noise above the Nyquist sampling rate. When sampled it can appear to be a sinewave (blue) that is of a much lower frequency. This is aliasing.


text:
Q: Read and display all file bytes in C++ I'm trying to show all the bytes in a .DAT file. I'm completely new to programming and I managed to find how to display the file size correctly but every output byte that I get are 0s even if in HxD the bytes aren't all zero.
What I get:
size is: 11
0000000000000000000000

What I should get:
size is: 11
48656C6C6F20776F726C64

Code:
#include <iostream>
#include <fstream>
#include <vector>
#include <fstream>
#include <iterator>
#include <iomanip>
using namespace std;

int main () {
  //open file and get size
  streampos begin,end;
  ifstream myfile ("TRPTRANS.DAT", ios::binary);
  begin = myfile.tellg();
  myfile.seekg (0, ios::end);
  end = myfile.tellg();
  int n;
  n=(end-begin);
  cout << "size is: " << n<<endl;

  //read file
  vector<char> randomBytes(n);
  myfile.read(&randomBytes[0], n);

  //display bytes
  for (auto& el : randomBytes)
  cout << setfill('0') << setw(2) << hex << (0xff & (unsigned int)el);
  cout << '\n';

  return 0;
}

Can someone help me fix this and show the bytes correctly thanks

A: First, you seek to the end of the file:
  myfile.seekg (0, ios::end);

But then you don't go back to the beginning, so the read call tries to read from the end of the file, which fails.
Try adding this before the read call:
  myfile.seekg (0, ios::beg);

And also check the error status afterwards:
  if (!myfile) {
    cerr << "could only read " << myfile.gcount() << " bytes\n";
  }

A: Here is a simple code that avoids looking at file size, using iterator to read the bytes into a char vector.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <iterator>
#include <vector>

using namespace std;
int main()
{
    ifstream input("TRPTRANS.DAT", ios::binary);
    //read bytes into vector
    vector<char> bytes(
    (istreambuf_iterator<char>(input)),
    (istreambuf_iterator<char>()));

    input.close();

    //print bytes as hex
    for (vector<char>::const_iterator i = bytes.begin(); i != bytes.end(); ++i)
        cout << setfill('0') << setw(2) << hex << (0xff & (unsigned int) *i) << endl;

    return 0;
}

If you are using the C++11 standard (or later) then you can use the auto keyword to help the readability:
for (auto i = bytes.begin(); i != bytes.end(); ++i)


text:
Q: Map a set of Images into a image tag in react component I have 20 images in my src folder src/images i want to map that images into the image tag in a app.js. How to do this?
Below is my Setup, I Get error by this.
import ImageDetails from "../data/ImageDetails";

{
    ImageDetails.map((Images) => {
        return ()
    })
}

My Json:
[
  {
    "id": 1,
     "images": "../../assets/images/sample1.jpg",
  },
  {
    "id": 2,
     "images": "../../assets/images/sample2.jpg",
  },
  .
  .
  So on upto 20 images...
]

A: import ImageDetails from "../data/ImageDetails";
{
    ImageDetails.map((Images) => {
        return ()
    })
}

You need to use Images instead of ImageDetails inside the .map


text:
Q: How to delete an element from a vector of custom objects I'm trying to delete an item from a vector with erase() function but I keep getting an error. I
searched everywhere but can't find an answer
#include <iostream>
#include <vector>
#include <map>
#include <iterator>
#include <algorithm>
using namespace std;

class Person{
  private:
    string name;

  public:
    void set_name(string name){
      this->name = name;
    }
    string get_name(){
      return name;
    }

class Record{
private:
  vector <Person> book;
public:
    void delete_person(string name){
        for(Person p : book){
            if(book.get_name() == name){
                book.erase(p);
            }
        }
    }
};

int main(){

    // nothing in main yet

    return 0;
}

I get en error in the delete_person() function in the record class: No matching member function for call to 'erase'

A: book.erase(p);

book is a vector. The parameter to a vector's erase() method is an iterator.
for(Person p : book){

p is the value in the vector, and actually it is a copy of the value in the vector. You cannot pass a value to erase(). You must pass an iterator as a parameter. Passing some random copy of some random value in a vector to its erase() method is not going to accomplish anything useful.
std::vector has begin() and end() methods that return the iterator to the beginning and the end of a sequence that defines the contents of the vector.
This may be used with various algorithms, like std::find_if or std::remove_if, together with std::vector::erase to effect the removal of a value or multiple values from your vector.

A: void delete_person(string name){
        for(Person p : book){
            if(book.get_name() == name){
                book.erase(p);
            }
        }
    }

fails for several reasons.
std::vector::erase does not accept items, it accepts iterators, locations of items to be removed.
Range-based for loops are very simple and limited in their abilities. They go from start to finish and are extremely intolerant of changes to the container while iterating. If you add or remove an item while iterating it, the hidden bookkeeping used by the loop becomes invalid and the loop breaks. And not the nice break sort of breaking. They tend to take the whole program down with them.
In Person p : book p is a new object that is a copy of an item in book. It's not the original or a reference to the original in the container. C++ defaults to values instead of references in almost every case. Unless you specifically request otherwise, you pass by value, return by value, and iterate by value.
Instead, employ the Erase-Remove Idiom. Here is an example with added commentary where I saw it fitting or educational.
#include <iostream>
#include <vector>
#include <map>
#include <iterator>
#include <algorithm>
using namespace std;

class Person
{
private:
    string name;

public:
    Person(const std::string & name) // added for testing
        : name(name) // this is a member initializer list In C++ all class members
                     // and base classes must be initialized before the program can
                     // enter the body of the constructor. This trick allows us to
                     // initialize members rather than initializing them to their
                     // defaults (if the type has a default) and then setting them
                     // inside the body and wasting time doing two things where one
                     // thing was required
    {

    }
    void set_name(string name) // side note consider saving construction of a new
                               // string and accepting name by const reference rather
                               // than by value and potentially making a copy.
                               // void set_name(const string & name)
                               // const because we do not intend to change `name`
                               // and because the compiler can take advantage of the
                               // promise not to change it in many interesting ways.
    {
        this->name = name;
    }
    string get_name() const // const because getters generally should not change the
                            // object this allows us to keep the class "const-correct"
                            // side note consider saving construction of a new
                            // string and returning by const reference rather than
                            // by value and making a copy.
                            // const string & get_name() const
    {
        return name;
    }
};
class Record
{
private:
    vector<Person> book;
public:
    void add_person(const std::string & name) // added for testing
    {
        book.emplace_back(name);
    }
    void delete_person(string name) // again consider passing name by const reference
    {
        book.erase(std::remove_if(book.begin(), // from start of list
                                  book.end(),   // to the end
                                  [name](const Person &p)
                                  {
                                      return p.get_name() == name;
                                  }), //  moves all items to be removed to the end of the
                                      // list, then returns start of range to erase
                   book.end()); // erase to the end of the list
    // Why erase separately? Because remove functions don't actually remove. They
    // move the unwanted values to the end of the list. Looks silly, but much easier
    // and safer to write. For example, this won't change the size of the list and
    // break loops that count on the size to remain the same.
    }
    friend std::ostream & operator<<(std::ostream & out,
                                     const Record & rec) // added for testing
    {
        for (const auto & item: rec.book) // print all items in book
                                          // const because printing should not change
                                          // the printed
                                          // auto to let the compiler figure out the type
                                          // & because we don't want to make a copy
        {
            out << item.get_name() << '\n';
        }
        return out;
    }
};
int main()
{

    Record r;
    r.add_person("Bill");
    r.add_person("Ted");
    r.add_person("Rufus");
    std::cout << r << std::endl;
    r.delete_person("Ted");
    std::cout << r << std::endl; // Ted should now be gone from the list
    return 0;
}

Expected output:
Bill
Ted
Rufus

Bill
Rufus


text:
Q: How do I install firmware on debian wheezy from command-line? I have Ubuntu 14.04 and Debian-7.4-Standard on my Acer Aspire One laptop.
I have Standard Debian OS which is command-line only. In the Debian OS I am not able to connect to the web through my wi-fi.
I am missing the needed drivers.
So far I have downloaded firmware-nonfree_0.36+wheezy.1.tar.gz in my Ubuntu OS and placed it into my home directory in my Debian OS. But now what? Any ideas on how I can install my needed driver from there?

Update:
I managed to make some ground. What I did was to download from my Ubuntu system the firmware-linux-nonfree_0.36+wheezy.1_all.deb file and placed it into my home directory in my Debian system. Then I booted into my Debian OS and from my home directory as a superuser I ran the command
dpkg -i firmware-linux-nonfree_0.36+wheezy.1_all.deb
and then rebooted the system. Now my display looks much better, but I still am unable to connect the system to the web. As a result I am still unable to use apt-get update. At least the firmware problem is now solved.

A: What finally worked for me in installing the non-free firmware was to first download firmware-linux-nonfree_0.36+wheezy.1_all.deb to a directory in my home directory. Then from the directory with that file I ran the command
dpkg -i firmware-linux-nonfree_0.36+wheezy.1_all.deb
As far as I can see this has added all the missing drivers that I needed for my Acer laptop.


text:
Q: Expected Number of Tests to Find Defective Parts Not doing this for homework, but for interview prep. The problem is this:

A bin of 5 electrical components is known to contain 2 that are
  defective. If the components are to be tested one at a time, in random
  order, until the defectives are discovered, find the expected number
  of tests that are made.

My attempt at the solution is this:
$E[X = tests] = 2(\frac{1}{5*4}) + 3(2!*\frac{3}{5*4*3}) + 4(\frac{3!}{2!1!}*\frac{3*2}{5*4*3*2}) + 5(\frac{4!}{3!1!}*\frac{3*2*1}{5*4*3*2*1}) = 2$
Although I don't actually know the correct solution to this problem, 2 seems like it would not intuitively be correct for the problem.
Can anyone point out what I'm doing wrong or how to solve the problem?
Thanks!

A: Since the tests are conducted sequentially, there are $\binom{5}{2} = 10$ distinct ways in which the two defective components can appear in the testing sequence order:  $$\begin{align*} (D,D,G,G,G) \\ (D,G,D,G,G) \\ (D,G,G,D,G) \\ (D,G,G,G,D) \\ (G,D,D,G,G) \\ (G,D,G,D,G) \\ (G,D,G,G,D) \\ (G,G,D,D,G) \\ (G,G,D,G,D) \\ (G,G,G,D,D) \end{align*}$$  Each of these is equally likely.  Now, for each enumerated ordering, what is the number of components tested until the second occurrence of $D$ is encountered?  For the first outcome, this happens on the second test, for example.
For those outcomes where the second defective item is last in the testing sequence, you would note that by the fourth test it has not yet been found, yet the final test is not needed since you know that it must be defective.  Moreover, for the final case where three items were tested and were all good, you could also stop there because the last two tests are guaranteed to be on the defective items.


text:
Q: mysite.domain.com is not working on 2-server farm If I shutdown server A, I can't open mysite.domain.com AAM configured on Default Zone Internal URL http://mysite.domain.com Public URL http://mysite.domain.com
The DNS record points to server A only (I am not sure if adding a DNS record for mysite.domain.com pointing to server B will work). The application pool is running on server B which runs under the identity "spservice". I changed my local hosts file pointing mysite.domain.com to server B, which only worked when I restarted the UPS service. Any ideas?

A: Perhaps this article will help you. Basically when setting up software NLB on a small server farm, some switches (like the Cisco Catalyst mentioned in the article) have problems with multicast MAC addresses in their ARP table.
In the case of the Catalyst you can fix it with a command like this:
arp 172.16.63.241 0300.5311.1111

The article explains:

In this command the first parameter is the IP Address of your cluster (in same VLAN as servers).  The second parameter is the MAC address of the cluster, which you can read from NLB manager.   It's in a little different format – for example the above entry would look like 03-00-53-11-11-11 in NLB manager.  You can find this information under Cluster->Properties from the NLB manager menus.

Hope that helps resolve the issue!


text:
Q: How do I append onto pipes? So my question is if I can somehow send data to my program and then send the same data AND its result to another program without having to create a temporary file (in my case ouputdata.txt).
Preferably using linux pipes/bash.
I currently do the following:
cat inputdata.txt | ./MyProg > outputdata.txt
cat inputdata.txt outputdata.txt | ./MyProg2

A: Here is another way, which can be extended to put the output of two programs together:
( Prog1; Prog2; Prog3; ...  ) | ProgN

That at least works in Bash.

A: Choice 1 - fix MyProg to write the merged output from the input and it's own output.  Then you can do this.
./MyProg <inputdata.txt | ./MyProg2

Choice 2 - If you can't fix MyProg to write both input and output, you need to merge.
./MyProg <inputdata.txt | cat inputdata.txt - | ./MyProg2


text:
Q: SalesForce DML set-based operations and atomic transactions I have just begun to read about Salesforce APEX and its DML.  It seems you can do bulk updates by constructing a list, adding items to be updated to the list, and then issuing an update myList call.
Does such an invocation of update create an atomic transaction, so that if for any reason an update to one of the items in the list should fail, the entire update operation is rolled back?  If not, is there a way to wrap an update in an atomic transaction?

A: Your whole context is an atomic transaction. By the time Apex code runs SF has already started, whether it's a Visualforce button click, a trigger or any other entry point. If you hit a validation error, null pointer reference exception, attempt to divide by zero, thrown exception etc - whole thing will be rolled back.
update myList; works in "all or nothing" mode. If one of records fails on validation rule required field missing etc - you'll get an exception. You can wrap it in a try-catch block but still - whole list just failed to load.
If you need "save what you can" behavio(u)r - read up about Database.update() version of this call. It takes optional parameter that lets you do exactly that.
Last but not least if you're inserting complex scenarios (insert account, insert contacts, one of contacts fails but you had that in try-catch so the account saved OK so what now, do you have to manually delete it? Weak...) you have Database.setSavepoint() and Database.rollback() calls.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_dml_database.htm
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_transaction_control.htm
https://salesforce.stackexchange.com/questions/9410/rolling-back-dml-operation-in-apex-method


text:
Q: Can I pass a bit register as a function argument in Hi-Tech C compiler for PIC16? Is there a way to pass a bit from a PIC's register as a function parameter?
Taking, for example, the PIC16F887, its registers (SFRs) and individual bits are defined as fallows in the corresponding header file (...\HI-TECH Software\PICC\9.80\include\pic16f887.h):
volatile       unsigned char    PORTB       @ 0x006;

volatile       bit  RB3     @ ((unsigned)&PORTB*8)+3;

How can I pass the RB3 bit as a parameter in a function so that it will allow me to call the function in this way:
setBitHigh (RB3);

What would be the function's prototype?
I'm using the HI-TECH C Compiler for PIC10/12/16 MCUs (PRO Mode) V9.80.
EDIT: The setBitHigh function is just a simplified example. I actually want to pass bits as parameters to more complex functions and to be able to choose at runtime which bits should the function use.

A: Maybe this would work, but it is not standard C:
void setBitHigh( bit *b ){
   b = 1;
}
setBitHigh( & RB3 );

If not, then there is no direct way to do what you want. You could of course return the value from the function and then assign it:
RB3 = newBitValue();

or you could pass the function both the byte address and the offset, and leave it to the function to do the dirty work:
void setBitHigh( unsigned char *a, bit_offset b ){
   *a |= ( 1 << b );
}
setBitHigh( & PORTB, 3 );

A: What you are really asking is a compiler question.  Look at the PIC16 instruction set and you will see that there is no way to directly address bits in data memory from runtime computed addresses.  Addresses are for whole bytes of 8 bits.
However, you could establish a convention for passing information that identifies a particular bit.  Whatever you do, the PIC would not natively address a individual bit from your address description, so some instructions are required to read or write a bit selected at run time.  You could define bit addresses to have 3 extra low bits, which would be the bit offset within the byte, or you could pass a mask of the bit within its byte, or a separate byte and bit address, just to name 3 possible conventions.
However, think carefully why you really want to do this.  Given the PIC instruction set, it is better to know the bit within a byte at build time, since all the bit-addressing instructions have a fixed bit number encoded within them.  Perhaps the best answer is to step back and think about what you are really trying to accomplish, and come up with a scheme that uses the PIC instruction set to advantage instead of fighting against it.  Some amazing things are possible with a little planning and advanced preprocessing.  Explain what you are trying to accomplish two levels up, and maybe we can suggest ways to make runtime bit addressing unnecessary.

A: There is no mechanism in HT-PIC to pass a register bit as a parameter.  There are a variety of ways one can achieve such a result, which involve various trade-offs with regard to execution speed, call-site code, and called-method code.
The simplest approach is probably to pass a bit mask as one parameter, and an address or I/O address offset as a second.  If the address will always be in one of the upper banks, or always in one of the lower banks, this will mean passing two parameter bytes.
If the I/O bits of interest will always be within a small group of registers (e.g. PORTA-PORTH) one could compress both pieces of information reasonably efficiently into a byte; I'd suggest that to encode bits 4-7, one have the upper four bits represent a bit mask, have bit 3 set, and have bits 0-2 represent an I/O address offset.  For bits 0-3, have the upper 4 bits represent a bit mask shifted left 4 bits, bit 3 clear, and have bits 0-2 represent the address offset.  If one can afford a couple of global locations to hold the address and bitmask, one could then have a routine:
void calcIo(uint8_t portBit)
{
  ioPort = (&PORTA)+(portBit & 7);

  ioBit = portBit & 0xF0;
  if (!portBit & 8)
    ioBit = (ioBit << 4) | (ioBit >> 4); // Allow SWAPF
}

The odd-looking last statement should if memory serves allow the compiler to use a conditional SWAPF instruction on ioBit [the expression (ioBit << 4) will always be zero, if it weren't there the compiler would feel obliged to mask off those bits].


text:
Q: jQuery fadeOut not working second time JQuery fadeOut is not running the second time.

click here

JS
$('#clickme').click(function() {
    $('#feedback').html('hello world').fadeOut('slow', function() {
        $(this).remove();
    });
});

I have tried without remove; it's not working in that case either.

A: 1/ Do not remove the element, instead hide it.
2/ You need to show the element before fadeOut, it does not fade out if it is already hidden.
( or use animate with proper parameters )
http://jsfiddle.net/QmajJ/
$('#clickme').click(function() {
    $('#feedback').html('hello world').show().fadeOut('slow', function() {
        $(this).hide();
    });
});

A: i dont know what are you trying to do but its not working the second time because you are removing the element from the first time
$('#clickme').click(function() {
    $('#feedback').html('hello world').fadeOut('slow', function() {
        $(this).remove(); // <----- you are removing the feedback element so in the second time there will be no "$('#feedback')" because of that its not working
    });
});

A: with unbind your click control properly
$('#clickme').unbind().click(function() {
   //your content
});

A: You have removed the element you want to be animated
$('#feedback').html('hello world').fadeOut('slow', function() {
    $(this).remove();
});


text:
Q: Why day in sysdate not working for monday in plsql trigger? create or replace trigger trig1
before delete or insert or update on students
begin
if( To_char(sysdate,'day') = 'monday' then
raise_application_error(-20500,'table is secured');
end if;
end;

I create trigger but it is not working for monday and it performs DML actions on table. I found one solution - to use dy instead of day - but why?

A: There are two reasons.
When you use day then result is padded with blanks to longest name, try
SELECT '"'||To_char(sysdate, 'day')||'"'
FROM dual;

"monday   "

Use 'fmday' to avoid this.
Then result of TO_CHAR() depends on current user session NLS_DATE_LANGUAGE settings. Use
To_char(sysdate, 'fmday', 'NLS_DATE_LANGUAGE = american') = 'monday'`

in order to be independent from settings of current user session.

A: Wernfried Domscheit has answered "why" your query is not working (TO_CHAR( datevalue, 'DAY' ) is right-padded with spaces).
Rather than relying on NLS_DATE_LANGUAGE and NLS_TERRITORY settings that may break if the query is used internationally, you can truncate the date and compare it to the start of the ISO-week (which is always Monday) which is independent of those settings:
create or replace trigger trig1
before delete or insert or update on students
begin
  IF TRUNC( SYSDATE ) = TRUNC( SYSDATE, 'IW' ) THEN
    raise_application_error(-20500,'table is secured');
  END IF;
end;
/

A: You can work with the day numbers instead:
create or replace trigger trig1
before delete or insert or update on students
begin
if( To_char(sysdate,'d') = '2' then
raise_application_error(-20500,'table is secured');
end if;
end;

Documentation: https://docs.oracle.com/database/121/SQLRF/sql_elements004.htm#SQLRF00210

D - Day of week (1-7). This element depends on the NLS territory of the session.


text:
Q: Calling API in method and getting [object Promise] I'm using Nuxt.js in static site mode, and trying to get an image from an API using a string passed in a prop, however, in the template I am getting [object Promise]. I would've thought that return before the get request would resolve the promise, but I think my grasp of promises and Nuxt.js a little off. Any help would be greatly appreciated.
<template>
    <div>
        {{ getThumbnailSrc() }}
    </div>
</template>

<script>
import axios from 'axios'

export default {
    props: {
        link: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            imageUrl: null
        }
    },
    methods: {
        getVimeoId(link) {
            return link.split('/').pop()
        },
        getThumbnailSrc() {
            return axios
                .get(
                    `https://vimeo.com/api/v2/video/${this.getVimeoId(
                        this.link
                    )}.json`
                )
                .then(response => {
                    const vimeoThumbnailUrl = response.data[0].thumbnail_large
                    console.log(vimeoThumbnailUrl)
                    return {
                        vimeoThumbnailUrl
                    }
                })
                .catch(error => {
                    console.log(error)
                })
        }
    }
}
</script>

A: It sure won't! XHR requests are asynchronous and therefore the template has no idea that it needs to wait.
Solve it by using an additional data property on the component, and using that instead:
data() {
    return {
        imageUrl: null,
        thumbnailSrc: null
    }
},

And in your callback:
.then(response => {
    const vimeoThumbnailUrl = response.data[0].thumbnail_large
    console.log(vimeoThumbnailUrl)
    this.thumbnailSrc = vimeoThumbnailUrl
})

Now you can use {{thumbnailSrc}} and it will load appropriately.


text:
Q: How to WaitForUpdates from VMs in a cluster? I am using VMWare VSphere WS SDK in Python using the suds client. I want to wait for any changes to VMs. I am specifically interested in VMs of a particular cluster. Is there a way in the propertyfilterspec to say that? I tried setting the managed object reference of the cluster in the ObjectSpec with no avail. Like:
object_spec = client_factory.create('ns0:ObjectSpec')
object_spec.obj = cluster_mor
object_spec.skip = False

A: Figured out myself. I had to set proper traversal spec also:
object_spec = client_factory.create('ns0:ObjectSpec')
object_spec.obj = cluster_mor
object_spec.skip = False
object_spec.selectSet = build_recursive_traversal_spec(client_factory)

def build_recursive_traversal_spec(client_factory):
    #Recurse through all ResourcePools
    rp_to_rp = client_factory.create('ns0:TraversalSpec')
    rp_to_rp.name = 'rpToRp'
    rp_to_rp.type = 'ResourcePool'
    rp_to_rp.path = 'resourcePool'
    rp_to_rp.skip = False
    rp_to_vm = client_factory.create('ns0:TraversalSpec')
    rp_to_vm.name = 'rpToVm'
    rp_to_vm.type = 'ResourcePool'
    rp_to_vm.path = 'vm'
    rp_to_vm.skip = False
    spec_array_resource_pool = [client_factory.create('ns0:SelectionSpec'),
                                client_factory.create('ns0:SelectionSpec')]
    spec_array_resource_pool[0].name = 'rpToRp'
    spec_array_resource_pool[1].name = 'rpToVm'
    rp_to_rp.selectSet = spec_array_resource_pool

    #Traversal through resource pool branch
    cr_to_rp = client_factory.create('ns0:TraversalSpec')
    cr_to_rp.name = 'crToRp'
    cr_to_rp.type = 'ComputeResource'
    cr_to_rp.path = 'resourcePool'
    cr_to_rp.skip = False
    spec_array_computer_resource = [client_factory.create('ns0:SelectionSpec'),
                                    client_factory.create('ns0:SelectionSpec')]
    spec_array_computer_resource[0].name = 'rpToRp'
    spec_array_computer_resource[1].name = 'rpToVm'
    cr_to_rp.selectSet = spec_array_computer_resource

    #Traversal through host branch
    cr_to_h = client_factory.create('ns0:TraversalSpec')
    cr_to_h.name = 'crToH'
    cr_to_h.type = 'ComputeResource'
    cr_to_h.path = 'host'
    cr_to_h.skip = False

    #Traversal through hostFolder branch
    dc_to_hf = client_factory.create('ns0:TraversalSpec')
    dc_to_hf.name = 'dcToHf'
    dc_to_hf.type = 'Datacenter'
    dc_to_hf.path = 'hostFolder'
    dc_to_hf.skip = False
    spec_array_datacenter_host = [client_factory.create('ns0:SelectionSpec')]
    spec_array_datacenter_host[0].name = 'visitFolders'
    dc_to_hf.selectSet = spec_array_datacenter_host

    #Traversal through vmFolder branch
    dc_to_vmf = client_factory.create('ns0:TraversalSpec')
    dc_to_vmf.name = 'dcToVmf'
    dc_to_vmf.type = 'Datacenter'
    dc_to_vmf.path = 'vmFolder'
    dc_to_vmf.skip = False
    spec_array_datacenter_vm = [client_factory.create('ns0:SelectionSpec')]
    spec_array_datacenter_vm[0].name = 'visitFolders'
    dc_to_vmf.selectSet = spec_array_datacenter_vm

    #Traversal through datastore branch
    dc_to_ds = client_factory.create('ns0:TraversalSpec')
    dc_to_ds.name = 'dcToDs'
    dc_to_ds.type = 'Datacenter'
    dc_to_ds.path = 'datastore'
    dc_to_ds.skip = False
    spec_array_datacenter_ds = [client_factory.create('ns0:SelectionSpec')]
    spec_array_datacenter_ds[0].name = 'visitFolders'
    dc_to_ds.selectSet = spec_array_datacenter_ds

    #Recurse through all hosts
    h_to_vm = client_factory.create('ns0:TraversalSpec')
    h_to_vm.name = 'hToVm'
    h_to_vm.type = 'HostSystem'
    h_to_vm.path = 'vm'
    h_to_vm.skip = False
    spec_array_host_vm = [client_factory.create('ns0:SelectionSpec')]
    spec_array_host_vm[0].name = 'visitFolders'
    h_to_vm.selectSet = spec_array_host_vm

    #Recurse through all datastores
    ds_to_vm = client_factory.create('ns0:TraversalSpec')
    ds_to_vm.name = 'dsToVm'
    ds_to_vm.type = 'Datastore'
    ds_to_vm.path = 'vm'
    ds_to_vm.skip = False
    spec_array_datastore_vm = [client_factory.create('ns0:SelectionSpec')]
    spec_array_datastore_vm[0].name = 'visitFolders'
    ds_to_vm.selectSet = spec_array_datastore_vm

    #Recurse through the folders
    visit_folders = client_factory.create('ns0:TraversalSpec')
    visit_folders.name = 'visitFolders'
    visit_folders.type = 'Folder'
    visit_folders.path = 'childEntity'
    visit_folders.skip = False
    spec_array_visit_folders = [client_factory.create('ns0:SelectionSpec'),
                                client_factory.create('ns0:SelectionSpec'),
                                client_factory.create('ns0:SelectionSpec'),
                                client_factory.create('ns0:SelectionSpec'),
                                client_factory.create('ns0:SelectionSpec'),
                                client_factory.create('ns0:SelectionSpec'),
                                client_factory.create('ns0:SelectionSpec'),
                                client_factory.create('ns0:SelectionSpec'),
                                client_factory.create('ns0:SelectionSpec')]
    spec_array_visit_folders[0].name = 'visitFolders'
    spec_array_visit_folders[1].name = 'dcToHf'
    spec_array_visit_folders[2].name = 'dcToVmf'
    spec_array_visit_folders[3].name = 'crToH'
    spec_array_visit_folders[4].name = 'crToRp'
    spec_array_visit_folders[5].name = 'dcToDs'
    spec_array_visit_folders[6].name = 'hToVm'
    spec_array_visit_folders[7].name = 'dsToVm'
    spec_array_visit_folders[8].name = 'rpToVm'
    visit_folders.selectSet = spec_array_visit_folders

    #Add all of them here
    spec_array = [visit_folders, dc_to_vmf, dc_to_ds, dc_to_hf, cr_to_h,
                  cr_to_rp, rp_to_rp, h_to_vm, ds_to_vm, rp_to_vm]
    return spec_array