text:
Q: Custom UITableViewCells disappearing when scrolling I am making an app in which I have MKMapView with some MKAnnotations on it. I also have a list (a UITableView) with more info about places represented by those annotations, in which my problem occurs. I use my own UITableViewCell subclass, which has 3 UILabels: the default textLabel for name of the place, addressLabel and phoneNumberLabel. I have to consider situation where texts in those labels are too big to be displayed in one line and resize the UILabels accordingly. I also have to consider situation, where there is no phone number or address and according UILabels should "disappear" (frame size is 0).
Problem is, when I scroll down the table, cells disappear from the upper part of the screen (the further I scroll, the more of them are invisible, and for most of the UITableView there are no cells displayed at all, just section headers, even though the size of the whole table doesn't change).
(screenshot was supposed to go here, but stackoverflow didn't allow me to post it :( )
![enter image description here][1]
Here's my custom UITableViewCell subclass:
@implementation POICell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        self.addressLabel = [[UILabel alloc] init];
        self.phoneNumberLabel = [[UILabel alloc] init];
        [self addSubview:self.addressLabel];
        [self addSubview:self.phoneNumberLabel];
        self.addressLabel.font = [UIFont fontWithName:@"Helvetica" size:14];
        self.phoneNumberLabel.font = [UIFont fontWithName:@"Helvetica" size:14];
        self.textLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:20];

        self.addressLabel.lineBreakMode = UILineBreakModeWordWrap;
        self.phoneNumberLabel.lineBreakMode = UILineBreakModeWordWrap;
        self.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];

    CGRect titleFrame = self.frame;
    titleFrame.origin.x += 30;
    titleFrame.size.width -= 60;
    titleFrame.size.height = [self.textLabel.text sizeWithFont:self.textLabel.font forWidth:self.textLabel.frame.size.width lineBreakMode:NSLineBreakByWordWrapping].height;
    self.textLabel.frame = titleFrame;
    if (self.addressLabel.text != nil) {
        self.addressLabel.frame = CGRectMake(titleFrame.origin.x, [DDUtility yRelativeTo:self.textLabel withMargin:0], titleFrame.size.width, [self.addressLabel.text sizeWithFont:self.addressLabel.font forWidth:self.addressLabel.frame.size.width lineBreakMode:NSLineBreakByWordWrapping].height);
    }
    else {
        self.addressLabel.frame = CGRectMake(titleFrame.origin.x, [DDUtility yRelativeTo:self.textLabel withMargin:0], 0, 0);
    }
    NSString *labelText = self.addressLabel.text;
    if (self.phoneNumberLabel.text != nil) {
        self.phoneNumberLabel.frame = CGRectMake(titleFrame.origin.x, [DDUtility yRelativeTo:self.addressLabel withMargin:0], titleFrame.size.width, [self.phoneNumberLabel.text sizeWithFont:self.phoneNumberLabel.font forWidth:self.phoneNumberLabel.frame.size.width lineBreakMode:NSLineBreakByWordWrapping].height);

    }
    else {
        self.phoneNumberLabel.frame = CGRectMake(titleFrame.origin.x, [DDUtility yRelativeTo:self.addressLabel withMargin:0], 0, 0);
    }
    labelText = self.phoneNumberLabel.text;

}

And here part of my UIViewController, which is both a delegate and datasource for 2 of my tables - categoryTable works just fine, it's poiTable I have problems with.
poiArraysDictionary is a dictionary in which keys are names of the Point of Interest categories and values are arrays of points of this category. Points themselves are dictionaries I get as JSONs from server, with keys like name, address (can be null) and phone (can be null).
- (void) viewDidLoad {
    (...)

    UITableView *poiTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 120, listView.frame.size.width, listView.frame.size.height -  120) style:UITableViewStylePlain];
    poiTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    //poiTable.rowHeight = 80;
    poiTable.dataSource = self;
    poiTable.delegate = self;
    poiTable.backgroundColor = [UIColor clearColor];
    self.poiTable = poiTable;
    [poiTable reloadData];
    [self.listView addSubview:poiTable];

    (...)
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == self.categoryTable) {
        return 1;
    }
    else {
        return [self.categoryArray count];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.categoryTable) {
        return [self.categoryArray count];
    }
    else {
        return [[self.poiArraysDictionary objectForKey:[self.categoryArray objectAtIndex:section]] count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.categoryTable) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"categoryCell"];
        if (cell == nil) {
            cell = [[[CategoryCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"categoryCell"] autorelease];
        }

        cell.textLabel.text = [self.categoryArray objectAtIndex:indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];

        return cell;
    }
    else {
        POICell *cell = [tableView dequeueReusableCellWithIdentifier:@"poiCell"];
        if (cell == nil) {
            cell = [[[POICell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"poiCell"] autorelease];
        }

        /*int maxIndex = [self.pointsOfInterestArray count];
         int index;
         int indexInSection = 0;
         for (index = 0; index < maxIndex; ++index) {
         if ([((NSString*)([((NSDictionary*)([self.pointsOfInterestArray objectAtIndex:index])) objectForKey:@"category"])) isEqualToString:[self.categoryArray objectAtIndex:indexPath.section]]) {
         if (indexInSection != indexPath.row) {
         ++indexInSection;
         }
         else {
         break;
         }
         }
         }

         cell.textLabel.text = [[self.pointsOfInterestArray objectAtIndex:index] objectForKey:@"name"];
         if ([[[self.pointsOfInterestArray objectAtIndex:index] objectForKey:@"address"] class] != [NSNull class]) {
         cell.addressLabel.text = [[self.pointsOfInterestArray objectAtIndex:index] objectForKey:@"address"];
         }
         if ([[[self.pointsOfInterestArray objectAtIndex:index] objectForKey:@"phone"] class] != [NSNull class]) {
         cell.phoneNumberLabel.text = [[self.pointsOfInterestArray objectAtIndex:index] objectForKey:@"phone"];
         }*/

        if ([[[[self.poiArraysDictionary objectForKey:[self.categoryArray objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row] objectForKey:@"name"] class] == [NSNull class]) {
            return nil;
        }

        cell.textLabel.text = [[[self.poiArraysDictionary objectForKey:[self.categoryArray objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row] objectForKey:@"name"];

        if ([[[[self.poiArraysDictionary objectForKey:[self.categoryArray objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row] objectForKey:@"address"] class] == [NSNull class]) {
            cell.addressLabel.text = nil;
        }
        else {
            cell.addressLabel.text = [[[self.poiArraysDictionary objectForKey:[self.categoryArray objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row] objectForKey:@"address"];
        }

        if ([[[[self.poiArraysDictionary objectForKey:[self.categoryArray objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row] objectForKey:@"phone"] class] == [NSNull class]) {
            cell.phoneNumberLabel.text = nil;
        }
        else {
            cell.phoneNumberLabel.text = [@"telefon: " stringByAppendingString:[[[self.poiArraysDictionary objectForKey:[self.categoryArray objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row] objectForKey:@"phone"]];
        }

        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];

        CGRect cellFrame = cell.frame;
        return cell;

    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView == self.categoryTable) {
        return 0;
    }
    else {
        return 40;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.categoryTable) {
        return 50;
    }
    else {
        NSDictionary *point = [[self.poiArraysDictionary objectForKey:[self.categoryArray objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
        CGFloat rowHeight = 0;
        if ([[point objectForKey:@"name"] class] != [NSNull class]) {
            rowHeight += [[point objectForKey:@"name"] sizeWithFont:[UIFont fontWithName:@"Helvetica-Bold" size:20] forWidth:self.poiTable.frame.size.width lineBreakMode:NSLineBreakByWordWrapping].height;
        }

        if ([[point objectForKey:@"address"] class] != [NSNull class]) {
            rowHeight += [[point objectForKey:@"address"] sizeWithFont:[UIFont fontWithName:@"Helvetica" size:14] forWidth:self.poiTable.frame.size.width lineBreakMode:NSLineBreakByWordWrapping].height;
        }

        if ([[point objectForKey:@"phone"] class] != [NSNull class]) {
            rowHeight += [[point objectForKey:@"phone"] sizeWithFont:[UIFont fontWithName:@"Helvetica" size:14] forWidth:self.poiTable.frame.size.width lineBreakMode:NSLineBreakByWordWrapping].height;
        }

        return rowHeight;
    }
}


text:
Q: Pyramid callback after response is sent and connection closed I need a callback in Pyramid that would be executed after the response was sent and connection to the client closed.
I'm aware of finished callbacks. This is however not what I want. Finished callbacks are evaluated right before the connection is closed (as far as I can tell).
Any clues? I need that for sending emails without creating a few second delay. Typically I should use something like Celery, I guess. I can't however afford a background worker on Heroku.

A: My understanding is that a WSGI application is basically a Python function which recieves a set of arguments and returns an blob of text which represents an HTTP respose. That blob may be passed to some filters in WSGI pipeline, which also are just functions, after which the webserver sends the response to the client and closes the connection. From the Wikipedia article:
def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/plain')])
    yield 'Hello World\n'

As Pyramid is a WSGI application, you can see that things like connection closing are likely to happen outside of its area of influence.
In your situation, if you can't/don't want to use existing solutions (pyramid_mailer in queued mode, as suggested by Chris McDonough), I would look at something like having a background thread which reads data every few seconds from a queue and sends emails. Then your view code just puts data in the queue and happily returns, while the working thread sends emails.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I stub a dependency in a Rails service I have:

*

*a web service wrapper that calls a 3rd party API (lib)

*a service that calls that wrapper and does some finagling (service)

Testing the lib class with VCR works great, but I am not sure how to test the service.  Specifically, how can I stub the API call inside the service?
class GetBazsForBars
  def self.call(token)
    bazs = Foo.new(token).bars

    # do some other stuff
    bazs
  end
end

And the test:
require 'rails_helper'

RSpec.describe GetBazsForBars, type: :service do
  describe ".call" do
    let(:token) { Rails.configuration.x.test_token }
    let(:bazs)  { GetBazsForBars.call(token) }

    it { expect(bazs.any?).to eq(true) }
  end
end

I'd prefer not to pass in the Foo to the service.
In Payola the author uses a StripeMock to dummy up the responses.  Can I write up something similar, like a FooMock that calls VCR and have the service use that instead?
Not sure how to do this with Ruby, I am used to C# / Java DI passing to constructors.
Thanks for the help.
Update
Moved to a full answer

A: foo = double(bars: 'whatever')
allow(Foo).to receive(:new).with(:a_token).and_return foo

or
allow(Foo).to receive(:new).with(:a_token)
  .and_return double(bar: 'whatever')

A: @mori provided a good starting point and I ended up...
1) stubbing the const of the service name:
require 'rails_helper'

RSpec.describe GetBazsForBars, type: :service do
  describe ".call" do
    before { stub_const("Foo", FakeFoo) } # <-- added this

    let(:token) { Rails.configuration.x.test_token }
    let(:bazs)  { GetBazsForBars.call(token) }

    it { expect(bazs.any?).to eq(true) }
  end
end

2) creating a fake foo wrapper in /spec/fakes:
class FakeFoo < Foo
  def bars
    VCR.use_cassette("foo_bars") do
      super()
    end
  end
end

This means in my service I can just Foo.new and it handles test and real life the same (great integration test). And I didn't have setup any mocking chains in the test that would require an actual instance to get the VCR call correct.
There may be an easier way, but the code looks pretty good to me so ship it.


text:
Q: Android Studio JJOE64 Graphview - Displaying a single point of data on a graph I have been using graphview to produce line graphs, and I have noticed that the graphs will only display data if atleast 2 points of data are in the series. Is there a function or other method by which a single point of data could be displayed on a graphview linegraph?
For reference, this is the general format I used to produce the line graphs
"
GraphView graph = (GraphView) findViewById(R.id.graphth);
series = new LineGraphSeries<DataPoint>();
DataPoint[] a = new DataPoint[arraysize];
for(int i = 0; i < arraysize; i++) {
       a[i] = new DataPoint(xvalue[i], yvalue[i]);
       series.appendData(a[i], true, arraysize + 40);
 }
 graph.addSeries(series);
"


text:
Q: Defragment the Windows registry?
Possible Duplicate:
Is it worth cleaning the registry?

Are there benefits to defragmenting the Windows registry? Or at least rewrite it in some way so as to take less space? Is there a reliable and safe tool to do this?


text: Q: Visual studio 2013 community edition doesn't open solution file I am using VS 2013 community edition. It doesn't  open one of my solution. I came to know that '.suo' file is a reason for that. After deleting .suo file its worked perfectly. But every time i need to delete that file whenever I opened that solution. Is that correct ? Am I missing anything ? Please help me.


text:
Q: JavaFX: Group is not centered within VBox I'd like to center a group of nodes within a VBox and scale the group if it exceeds the bounds of the parent VBox.
I tried the following setup: A ScrollPane contains a VBox, which should center a Group of Nodes (e.g. Circles, Lines, etc).
The Nodes are added dynamically: myCustomPane.getContentPane().getChildren().addAll(ellipse, line)
Unfortunately neither the (red) group is centered nor visible on the window. However I do see the (orange) ScalablePane, the (blue) VBox, and all the nodes.
public class ScalablePane extends ScrollPane {

    private Property<Group> contentPaneProperty = new SimpleObjectProperty<>();
    public ScalablePane() {
        setContentPane(new Group());
        setPannable(true);
        setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        setFitToHeight(true); // center
        setFitToWidth(true); // center
        setStyle("-fx-background-color: orange;");
    }

    public final void setContentPane(Group contentPane) {
        contentPane.setManaged(false);
        contentPane.setStyle("-fx-background-color: red;");

        VBox vBox = new VBox();
        vBox.setAlignment(Pos.CENTER);
        vBox.setManaged(true);
        vBox.getChildren().add(contentPane);
        vBox.setStyle("-fx-background-color: blue;");

        setContent(vBox);
        contentPaneProperty.setValue(contentPane);
     }

     public Group getContentPane() {
        return contentPaneProperty.getValue();
     }
}

Usage:
public class Main extends Application {

  @Override
  public void start(Stage primaryStage) {
    try {
      ScalablePane pane = new ScalablePane();
      Circle circle = new Circle(200, 40, 20);
      Circle circle2 = new Circle(100, 150, 20);

      pane.getContentPane().getChildren().addAll(circle, circle2);

      Scene scene = new Scene(pane, 400, 400);
      primaryStage.setScene(scene);
      primaryStage.sizeToScene();
      primaryStage.show();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    launch(args);
  }
}

Update: drag-support added
I tried to add drag-support for my nodes, so I can check when the inner pane is rescaling. I also changed the Group to a simple Pane so I can make the boundaries of the inner pane visible. Unfortunately the inner pane (red) does not snap to the child nodes. How can I force the content pane, to take the size of its children and rescale if it's size exceeds the parent boundaries?
public class ScalablePane extends ScrollPane {

  private final Pane contentPane;
  private final Scale contentScaleTransform;

  public ScalablePane() {
    contentPane = new Pane();
    contentScaleTransform = new Scale(1, 1);

    initializeScrollPane();
    initializeContentPane();
  }

  public void initializeScrollPane() {
    setPannable(true);
    setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
    setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
    setFitToHeight(true); // center
    setFitToWidth(true); // center
    setStyle("-fx-background-color: orange;");
  }

  private final void initializeContentPane() {
    contentPane.setStyle("-fx-background-color: red;");

    VBox vBox = new VBox();
    VBox.setMargin(contentPane, new Insets(10));
    vBox.setAlignment(Pos.CENTER);
    vBox.setManaged(true);
    vBox.getChildren().add(contentPane);
    vBox.setStyle("-fx-background-color: blue;");

    setContent(vBox);

    contentPane.layoutBoundsProperty()
        .addListener(new ChangeListener<Bounds>() {
          @Override
          public void changed(ObservableValue<? extends Bounds> observable,
              Bounds oldValue, Bounds newValue) {

            double parentWidth = getContentPane().getParent().getLayoutBounds()
                .getWidth() - 10;
            double parentHeight = getContentPane().getParent().getLayoutBounds()
                .getHeight() - 10;

            if (parentHeight > 0 && parentWidth > 0) {
              if (newValue.getHeight() > parentHeight
                  || newValue.getWidth() > parentWidth) {
                computeScale();
              }
            }
          }
        });
  }

  public void computeScale() {
    double realWidth = getContentPane().prefWidth(getWidth());
    double realHeight = getContentPane().prefHeight(getHeight());

    double leftAndRight = getInsets().getLeft() + getInsets().getRight();
    double topAndBottom = getInsets().getTop() + getInsets().getBottom();

    double contentWidth = getWidth() - leftAndRight;
    double contentHeight = getHeight() - topAndBottom;

    double scaleX = contentWidth / realWidth;
    double scaleY = contentHeight / realHeight;

    double scale = Math.min(scaleX, scaleY);
    getContentScaleTransform().setX(scale);
    getContentScaleTransform().setY(scale);

    getContentPane().resize(contentWidth / getContentScaleTransform().getX(),
        contentHeight / getContentScaleTransform().getY());
  }

  public Pane getContentPane() {
    return contentPane;
  }

  public final Scale getContentScaleTransform() {
    return contentScaleTransform;
  }
}

Usage:
public class Main extends Application {

  private double dragOriginalSceneX;
  private double dragOriginalSceneY;

  @Override
  public void start(Stage primaryStage) {
    try {
      ScalablePane pane = new ScalablePane();
      Circle circle = new Circle(200, 40, 20);
      Circle circle2 = new Circle(100, 150, 20);
      addDragSupport(circle, pane);
      addDragSupport(circle2, pane);

      pane.getContentPane().getChildren().addAll(circle, circle2);

      Scene scene = new Scene(pane, 400, 400);
      primaryStage.setScene(scene);
      primaryStage.sizeToScene();
      primaryStage.show();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    launch(args);
  }

  private void addDragSupport(Circle node, ScalablePane graphPane) {
    node.setOnMousePressed(e -> {
      dragOriginalSceneX = e.getSceneX()
          / graphPane.getContentScaleTransform().getX();
      dragOriginalSceneY = e.getSceneY()
          / graphPane.getContentScaleTransform().getY();
    });

    node.setOnMouseDragged(e -> {
      Circle circle = (Circle) e.getSource();
      circle.setManaged(true);
      double eventX = e.getSceneX()
          / graphPane.getContentScaleTransform().getX();
      double eventY = e.getSceneY()
          / graphPane.getContentScaleTransform().getY();

      double offsetX = eventX - dragOriginalSceneX;
      double offsetY = eventY - dragOriginalSceneY;

      double newX = circle.getCenterX() + offsetX;
      double newY = circle.getCenterY() + offsetY;

      circle.setCenterX(newX);
      circle.setCenterY(newY);

      // remember last coordinates
      dragOriginalSceneX = eventX;
      dragOriginalSceneY = eventY;
    });
  }

A: I think I have this working the way you want except scaling give it a try let me know if it works also you cannot add css to a group here is an example of things a group can do if you are looking for more
information https://docs.oracle.com/javase/8/javafx/api/javafx/scene/doc-files/cssref.html#group
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.VBox;

public class ScalablePane extends ScrollPane {

//    private Property<Group> contentPaneProperty = new SimpleObjectProperty<>();
    private Group contentPane = new Group();

    public ScalablePane() {
        setContentPane(/*new Group()*/);
        setPannable(true);
        setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        setFitToHeight(true); // center
        setFitToWidth(true); // center
        setStyle("-fx-background-color: orange;");
    }

    public final void setContentPane(/*Group contentPane*/) {
//        contentPane.setManaged(false);
        contentPane.setStyle("-fx-background-color: red;");

        VBox vBox = new VBox();
        vBox.setAlignment(Pos.CENTER);
        vBox.setManaged(true);
        vBox.getChildren().add(contentPane);
        vBox.setStyle("-fx-background-color: blue;");

        setContent(vBox);
//        contentPaneProperty.setValue(contentPane);
    }

    public Group getContentPane() {
        return contentPane;
    }
}


text:
Q: Maximizing sum of a spiral path on a grid Lets define a spiral path as one who movements are in a cycle of [right, down, left, up, right, down, left, up, ...] (note that you don't need to necessarily start with right, only that right must come after up, down after right, and so on). However, the path must not intersect with itself.
Given a grid, how would you find the maximum sum that can be attained by traversing such a path?
So for example, if the grid is

-5   -4   -3
 3      2     1
 -1     2     4

The spiral path that maximizes the sum is

-5   -4   -3
 3      2     1
 -1     2     4

The path goes like: {3, 2, 1, 4, 2}

My thinking is that this can be solved with some sort of prefix sum method, but I am not too sure on how to approach it. Another thought was just to run a depth-first-search from each point but that will be too inefficient of an algorithm.

A: Let's build the spiral outwards, in clockwise order (the counter-clockwise case works analogously). The state of the  building process can be described by three variables:

*

*The bounding box of the spiral so far

*The current position

*The current direction (north, east, south, west)

We are allowed to make at most two different moves:

*

*go one step further in the current direction

*switch direction clockwise and go one step in the new direction. This is only allowed if we passed the borders of the bounding box already

There are O(n^4) bounding boxes and the current position is always at a border of the box, so this yields an O(n^5) time and space DP algorithm.
We can eliminate one dimension by noting that all but the last line segment we walk will completely cover the side of the current bounding box, so we can define f(x1, y1, x2, y2, d) as the maximum sum spiral with bounding box (x1, y1), (x2, y2) where the current positition is in the corner uniquely defined by the current position d.
The moves are then:

*

*Walk one step further in the current direction, extending the bounding box

*Switch the direction and walk all the way up to the end of the bounding box

For the second move we need to compute partial row and column sums in O(1), which is easy to do with some preprocessing. We also need to introduce a special case for the last segment of the spiral, because there we are allowed to not go up to the edge of the bounding box. The whole algorithm can be implemented in O(n^4).


text:
Q: Как реализовать динамичную смену языка? JavaFX Хочу реализовать адекватное переключение языков в приложении, чтобы сразу после нажатие кнопки "сменить язык" все компоненты автоматически поменяли название.
Пока что сделал так:
public  void setEnglish(ActionEvent actionEvent) {

    Main.locale = new Locale("en");
    rb = ResourceBundle.getBundle("ua.javaFX.myprograms.address_book.bundles.Locale", Main.locale);

    mainStage.setTitle(rb.getString("key.address_book"));
    btnAdd.setText(rb.getString("key.add"));
    btnEdit.setText(rb.getString("key.change"));
    btnDelete.setText(rb.getString("key.delete"));
    btnSearch.setText(rb.getString("key.search"));
    btnLanguage.setText(rb.getString("key.language"));
    btnEnglish.setText(rb.getString("key.english"));
    btnRussian.setText(rb.getString("key.russian"));
}

Суть вопроса: есть какой-то цивилизованный способ для обновления содержания страницы?
Если я не ошибаюсь, в SWING таким является:
SwingUtilities.updateComponentTreeUI(frame);

A: Для того, чтобы вам сделать такое, необходимо использовать bindings.
Вам нужна resources factory :
public class ObservableResourceFactory {

    private ObjectProperty<ResourceBundle> resources = new SimpleObjectProperty<>();
    public ObjectProperty<ResourceBundle> resourcesProperty() {
        return resources ;
    }
    public final ResourceBundle getResources() {
        return resourcesProperty().get();
    }
    public final void setResources(ResourceBundle resources) {
        resourcesProperty().set(resources);
    }

    public StringBinding getStringBinding(String key) {
        return new StringBinding() {
            { bind(resourcesProperty()); }
            @Override
            public String computeValue() {
                return getResources().getString(key);
            }
        };
    }
}

Далее, в своем коде можете написать такое
ObservableResourceFactory resourceFactory = .... ;

resourceBundle.setResources(...);

Label greetingLabel = new Label();
greetingLabel.textProperty().bind(resourceFactory.getStringBinding("greeting"));

И в любой момент, когда вы будет обновлять ресурсы
resourceFactory.setResources(...);

на лейбле текст будет меняться.
Вот пример, как это работает
import java.util.ListResourceBundle;
import java.util.Locale;
import java.util.ResourceBundle;

import javafx.application.Application;
import javafx.beans.binding.StringBinding;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class ResourceBundleBindingExample extends Application {

    private static final String RESOURCE_NAME = Resources.class.getTypeName() ;

    private static final ObservableResourceFactory RESOURCE_FACTORY = new ObservableResourceFactory();

    static {
        RESOURCE_FACTORY.setResources(ResourceBundle.getBundle(RESOURCE_NAME));
    }

    @Override
    public void start(Stage primaryStage) {
        ComboBox<Locale> languageSelect = new ComboBox<>();
        languageSelect.getItems().addAll(Locale.ENGLISH, Locale.FRENCH);
        languageSelect.setValue(Locale.ENGLISH);
        languageSelect.setCellFactory(lv -> new LocaleCell());
        languageSelect.setButtonCell(new LocaleCell());

        languageSelect.valueProperty().addListener((obs, oldValue, newValue) -> {
            if (newValue != null) {
                RESOURCE_FACTORY.setResources(ResourceBundle.getBundle(RESOURCE_NAME, newValue));
            }
        });

        Label label = new Label();
        label.textProperty().bind(RESOURCE_FACTORY.getStringBinding("greeting"));

        BorderPane root = new BorderPane(null, languageSelect, null, label, null);
        root.setPadding(new Insets(10));
        Scene scene = new Scene(root, 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static class LocaleCell extends ListCell<Locale> {
        @Override
        public void updateItem(Locale locale, boolean empty) {
            super.updateItem(locale, empty);
            if (empty) {
                setText(null);
            } else {
                setText(locale.getDisplayLanguage(locale));
            }
        }
    }

    public static class ObservableResourceFactory {

        private ObjectProperty<ResourceBundle> resources = new SimpleObjectProperty<>();
        public ObjectProperty<ResourceBundle> resourcesProperty() {
            return resources ;
        }
        public final ResourceBundle getResources() {
            return resourcesProperty().get();
        }
        public final void setResources(ResourceBundle resources) {
            resourcesProperty().set(resources);
        }

        public StringBinding getStringBinding(String key) {
            return new StringBinding() {
                { bind(resourcesProperty()); }
                @Override
                public String computeValue() {
                    return getResources().getString(key);
                }
            };
        }

    }

    public static class Resources extends ListResourceBundle {

        @Override
        protected Object[][] getContents() {
            return new Object[][] {
                    {"greeting", "Hello"}
            };
        }

    }

    public static class Resources_fr extends ListResourceBundle {

        @Override
        protected Object[][] getContents() {
            return new Object[][] {
                    {"greeting", "Bonjour"}
            };
        }

    }

    public static void main(String[] args) {
        launch(args);
    }
}

P.S. ответ взят с английского SO.


text:
Q: What's up with the Review Audits -- I believe this is incorrect I was trying to make a dent in the VTC queue, and came across this question.
Phonegap 3.0.0 + Android always wants to use remote environment
I read it through, and VTC - Unclear, as there was no question.  In fact, I would put this up as a textbook example of VTC-Unclear.
All of a sudden, I get a surprise audit -- You Failed -- ...
No, I didn't fail. Audit failed.

A: This is a question about software tools commonly used by programmers. The author is encountering several problems when attempting to use them, which he describes in the question along with the specific errors returned by the tools.
Yes, there were some minor issues with the grammar and formatting - if you felt they made the question unacceptable, you could have clicked the "edit" button and passed the audit that way too...

A: The audits are selected by finding questions with no flags, no votes to close, no downvotes, at least five upvotes, and a handful of other criteria.  It assumes that if those criteria are met, the question shouldn't be closed.
Occasionally that is incorrect because people fail to downvote/flag/vote to close questions that should indeed be closed.
To prevent this particular question from ever being an audit again, if you indeed feel that it should be closed, just downvote or vote to close (FYI, this has already happened for this particular question).


text:
Q: rsRenderingExtensionNotFound error using SSRS 2005 I am trying to use the Sharp-shooter Silverlight report viewer control.
This control has a server side component that renders the reports as XAML for displaying in the client side control. I have tried manually installing the rendering extension, according to the instructions on their website, and also the instructions on MSDN.
I have basically copied the dll's into the reporting services bin folder and added the following line to rsreportserver.config file:
<Extension Name="XAML" Type="PerpetuumSoft.ReportingService.XamlRendering.XamlRenderer,PerpetuumSoft.ReportingService.XamlRendering"/>

I've also added a line into the rssrvpolicy.config file as specified on their site.
After I made these changes I went into windows services and restarted the Reporting Services services but I get the following error when I try to run reports:

rsRenderingExtensionNotFound: An
  attempt has been made to use a
  rendering extension that is not
  registered for this report server

Is there anything else that I need to do to use a custom rendering extension within SSRS 2005?

A: Turns out it was a problem with the dll, after much to-ing and fro-ing with the guys at Perpetuum software they figured out the bug and put out another release.


text:
Q: Problema con horas y minutos hola con todos tengo el siguiente código en java para capturar la hora y los minutos, el código funciona me devuelve la hora y los minutos del sistema pero, en horas y minutos menores a 10 me devuelve solo un dígito sin incluir el cero a la izquierda, por favor necesito ayuda para solucionar este detalle.
Por ejemplo me aparece 9:6, y yo desearía que aparezca 09:06.
Calendar Cal = Calendar.getInstance();
    String fec = Cal.get(Cal.HOUR_OF_DAY) + ":" + Cal.get(Cal.MINUTE);
    txtHoraSalida.setText(fec);

A: Puedes usar String.format para lo que necesitas:
Calendar cal = Calendar.getInstance();
String hour = String.format("%02d",cal.get(Calendar.HOUR_OF_DAY));
String minute = String.format("%02d",cal.get(Calendar.MINUTE));
String fec = hour + ":" + minute;
txtHoraSalida.setText(fec);

Nota:  Prestar atención al nombre de las variables, no van capitalizadas.
Nota 2: MINUTE y HOUR_OF_DAY son estáticos, y deben ser accedidos como tal.
Ejemplo:
Si seteamos la hora de manera manual, podemos comprobar la salida correcta.
    cal.set(Calendar.HOUR_OF_DAY, 5);
    cal.set(Calendar.MINUTE, 6);

Salida: 05:06

A: Utiliza este código para dar formato de dos dígitos.
 Calendar Cal = Calendar.getInstance();

 String time = String.format("%02d:%02d", Cal.get(Calendar.HOUR_OF_DAY), Cal.get(Calendar.MINUTE));

 txtHoraSalida.setText(time);


text:
Q: Repeat CSS settings for every image in loop (jQuery) I have this HTML for image slider:

I am using map method to apply CSS settings to all images:
var imageContainer = $('#imageContainer'),
states = [
    { zIndex: 1, width: 120, height: 347, top: 0, left: 170, opacity: 0 },
    { zIndex: 2, width: 130, height: 390, top: 0, left: 0, opacity: 1 },
    { zIndex: 3, width: 160, height: 475, top: 0, left: 147, opacity: 1 },
    { zIndex: 4, width: 220, height: 638, top: 0, left: 322, opacity: 1 },
    { zIndex: 3, width: 160, height: 475, top: 0, left: 555, opacity: 1 },
    { zIndex: 2, width: 130, height: 390, top: 0, left: 730, opacity: 1 },
    { zIndex: 1, width: 120, height: 347, top: 0, left: 570, opacity: 0 },
];

imageContainer.map(function(index, element) {
    imageContainer.find('li:last').prependTo(imageContainer);
    var state = states[index];
    $(element).animate(state);
});

This works if I am using 7 images (I have 7 states in object), but I am using 9 images (CSS settings are applied only to first 7 images, the last 2 are undefined). How can I use these CSS settings if I have more than 7 images?
Here is fiddle. I do not see 8th and 9th image in the slider.

A: I don't know why you don't add more state in your states object but, you can check before your function if the li count is more than states object.
This example below work. I used modulo for add more value in states object. I add a litle short code inside your $lis.each function. Please see

$(function () {
 $('.slide').customSlide();
});

(function($) {
    var slide = function(ele, options) {
        var $ele = $(ele);
        var setting = {
            speed: 1000,
            interval: 2000,
        };
  var cssPercentFromTop = 50 + '%';
  var states = [
      { zIndex: 1, width: 120, height: 347, top: cssPercentFromTop, left: 170, opacity: 0 },
      { zIndex: 2, width: 130, height: 390, top: cssPercentFromTop, left: 0, opacity: 1 },
      { zIndex: 3, width: 160, height: 475, top: cssPercentFromTop, left: 147, opacity: 1 },
      { zIndex: 4, width: 220, height: 638, top: cssPercentFromTop, left: 322, opacity: 1 },
      { zIndex: 3, width: 160, height: 475, top: cssPercentFromTop, left: 555, opacity: 1 },
      { zIndex: 2, width: 130, height: 390, top: cssPercentFromTop, left: 730, opacity: 1 },
      { zIndex: 1, width: 120, height: 347, top: cssPercentFromTop, left: 570, opacity: 0 },
  ];

  $.extend(true, setting, options);

        var $lis = $ele.find('li');
        var timer = null;

        $ele.find('.custom-slider-next').on('click', function() {
            next();
        });

  $ele.find('.custom-slider-prev').on('click', function() {
            states.push(states.shift());
            move();
        });

  $ele.on('mouseenter', function() {
            clearInterval(timer);
            timer = null;
        }).on('mouseleave', function() {
            //autoPlay();
        });

        move();
        //autoPlay();

        function move() {

         var imageContainer = $('.custom-slider ul');
         imageContainer.find('li:last').prependTo(imageContainer);

      $lis.each(function(index, element) {
    ///// NEW CODE BY P.Frank /////
        if(index >= states.length){
         var tap = index % states.length;
          states.push(states[tap])
        }
        ///// NEW CODE BY P.Frank /////

    var state = states[index];

    $(element).animate(state, setting.speed);
    $(element).css('transform', 'translate(0, -50%)');
   });

        }

        function next() {
            states.unshift(states.pop());
            move();
        }

        function autoPlay() {
            timer = setInterval(next, setting.interval);
        }
    }

 $.fn.customSlide = function(options) {
        $(this).each(function(index, ele) {
            slide(ele, options);
        });
        return this;
    }

})(jQuery);
.custom-slider {
 position: relative;
 width: 860px;
 height: 375px;
 margin: 0 auto;
}

.custom-slider .custom-slider-next,
.custom-slider .custom-slider-prev {
 position: absolute;
 top: 50%;
 margin-top: -96px;
 cursor: pointer;
}

.custom-slider .custom-slider-prev {
 left: -200px;
}

.custom-slider .custom-slider-next {
 right: -200px;
}

.custom-slider ul {
 list-style: none;
 position: relative;
 width: 860px;
 height: 630px;
 margin: 0 auto;
 padding: 0;
}

.custom-slider ul li {
 overflow: hidden;
 position: absolute;
 z-index: 0;
 left: 377px;
 top: 146px;
 width: 0;
 height: 0;
 margin: 0;
 padding: 0;
}

.custom-slider ul li img {
 max-width: 100%;
 height: auto;
 object-fit: contain;
}

A: if you wan't to loop thru your states array I think you can do something like this:
imageContainer.map(function(index, element) {
    imageContainer.find('li:last').prependTo(imageContainer);
    var state = states[index % states.length];
    $(element).animate(state);
});

index % states.length returns the remainder from dividing the index by the length of the state array.

A: You can also use the each() method and then use this to specify the element property. This should loop through each image.
imageContainer.each(function(index, element) {
    imageContainer.find('li:last').prependTo(imageContainer);
    var state = states[index];
    $(this).animate(state);
});


text:
Q: 60s (or earlier) book with elevator-like time travel, a sentient planet in the future and a blockage of time by aliens from gas giants I read this book in the 70s and was quite an old book then maybe 60s or earlier. I have read The End of Eternity but there were similarities but the male female main characters were more naive.
Time travel was like an elevator and the main characters (man and his girlfriend) travel to the distant future and distant past. I remember the extreme future mankind has gone but I remember the planet was sentient.
Part of the story revolved around a blockage in a section of time, this turned out to be blocked by an alien presence from one of our gas giants. These aliens were also trying to stop humans from developing space travel. Not much to go on but I also remember that the temperature in space was a theme used to stop the development of space travel.
The story started in the near future for the book, time travel was available but space travel had been discouraged and I think this was on purpose and was related to the future blockage in time. I do remember the main characters traveled to the distant past (encountering dinosaurs) and the distant future were mankind had died out. I think they were running from something.


text:
Q: Processing multiple queries in Talend open studio Is it possible to process multiple queries in  tOracleInput palette in Talend, If yes, how ? If no then what palette should I use to do the same ? The goal is to update a flag to 0 in oracle after it is moved to Postgres using Talend.
After changes. Here is the result:

A: You are not able to use multiple queries in one tOracleInput component. It seems to me you would need to add a tOracleOutput to update the field after you inserted the data with a tPostgresOutput component and no error occured.


text:
Q: Where is the basic Control-TAB (MRU) behavior in Xcode? In most multi-document editors for windowing environments, Control-TAB will utilize an MRU list to bring the user back to the last visible file.  What is the appropriate command to accomplish this in Xcode 3.x?
I currently have Ctrl-TAB mapped to "View|Previous File", however this does not appear to be an MRU. Worse yet, if it hits the "beginning" of the list (should be a circular buffer), it falls back on inserting an actual TAB character into the text editor.

A: As of Xcode Version 3, there isn't anything that's exactly like the MRU you describe - however, check out the discussion on this page for some options that will get you closer to the behavior you want.

A: In recent XCode (10.3), when in a code editor press:
ctrl+1, right, right
Then use up and down keys and enter
to select from the MRU sorted list of recent files.
There is even an option to increase the size of the history.

A: In Xcode 3 (or any Mac application) you can use Command-Tilde (⌘~) to switch between open windows.
In Xcode 4 you use ⌘} for next tab and ⌘{ for previous tab - command shift bracket.
As a side note, for some reason Xcode 4 won't let me set the key binding for previous/next tab to the standard Control-Tab.  When I try it puts in Command-Control-Tab.


text:
Q: twisted support for diffie-hellman-group1-sha1 Does anyone know if/when diffie-hellman-group1-sha1 will be supported by twisted? I currently see the following list of supported key exchanges:
ecdh-sha2-nistp256, ecdh-sha2-nistp384, ecdh-sha2-nistp521, diffie-hellman-group-exchange-sha256, diffie-hellman-group-exchange-sha1, diffie-hellman-group14-sha1, diffie-hellman-group1-exchange-sha1

Currently using version 18.9

A: Search the Twisted issue tracker for a ticket for adding such a feature.
If you do not find such a ticket, file one.
If the ticket is up for review, review it.
If the ticket is not up for review, implement it and submit it for review.
If you are unable to review or implement such a feature, post on the mailing list about your interest in the feature and any incentives you may be able to offer to motivate someone else to do the work.
The feature will be included in the first Twisted release to take place after the feature implementation has been merged into master.


text:
Q: Is there a definition of morphism of gluing data of schemes that makes gluing an adjoint functor? Tag 01JA of the Stacks Project is about gluing schemes. There, a gluing data is defined as a collection of schemes, and isomorphisms between open subsets of those schemes satisfying the cocycle relation. Such a gluing data can be glued to a scheme which I will denote $glue(X)$
The description for the set of morphisms from $glue(X)$ to $Y$ seems like some kind of adjoint functor/universal property. However without a notion of morphism of gluing data, we don't have a category of gluing data.
My question is: is there a way to define morphisms of gluing data so that $glue(X)$ is a functor that has an adjoint?


text:
Q: How do you define (infinity,1) categories in Homotopy Type Theory? One of the major motivations of Homotopy Type Theory is that it naturally builds in higher coherences from the beginning.  One important setting where higher coherence requirements get annoying is higher category theory.  It's easy to talk about $\infty$-groupoids in HoTT, they're just types and you build them as higher inductive types.  What about the next step?  How do you talk about $(\infty,1)$-categories?  I looked around at the nlab and the relevant blogs, but didn't find anything.
The natural setup is that you have a type of objects and a (dependent) type of morphisms.  But composition seems to run into all the usual difficulties of coherence in higher category theory.  Does the HoTT point of view simplify things at all here?
Feel free to assume that I'm familiar with the discussion of ordinary categories in the HoTT book and the background in the HoTT book.  On the other hand, also assume that I find all definitions of higher categories beyond dimension 2 at least somewhat confusing.   My motivation is that I'm trying to understand what you would need to do in order to give a formal proof of the cobordism hypothesis in dimension 1.

A: Emily Riehl and Mike Shulman now have a preprint which builds a version of type theory which includes $(\infty,1)$-categories as certain kinds of types.

A: While this question has an accepted answer, let me just mention that there is now a preprint by James Cranch about doing categories structured over homotopy types, you might be interested to have a look.

A: This is an important open problem.  There are several imaginable approaches, including but not limited to:

*

*Mimic some commonly used homotopical definition of $(\infty,1)$-category inside HoTT.  The most likely candidate seems to be complete Segal spaces, since they have a space of objects rather than a set of objects.  This would require a definition of "simplicial type" in HoTT, which is another important open problem (which is motivating some people to try modifying type theory).

*Use a definition in a more type-theoretic style.  The $\infty$-groupoids of HoTT are naturally "algebraic" a la Grothendieck/Batanin, so maybe it would be more natural to use a similarly algebraic definition of $(\infty,1)$-category.  One could, for instance, try to encode an operad of a suitable sort with an inductive definition.

*Invent a sort of "directed type theory" whose basic objects are $(\infty,1)$-categories, in the same way that the basic objects of HoTT are $\infty$-groupoids.

*Leverage the fact that HoTT admits models not just in $\infty$-groupoids but in other $(\infty,1)$-toposes, noting that complete segal spaces live inside the $(\infty,1)$-topos of simplicial spaces.  I proposed this here; Andre Joyal independently had the same idea.
At this point I wouldn't presume to bet on which approach will prove the best, or whether it will be something entirely different.


text:
Q: 13.04: update-initramfs works but mkinitramfs fails from APT I'm experiencing a strange thing, I've freshly upgraded from 12.10 to 13.04, Everything is fine except that it can't build the initrd image automatically, it fails and prints out the mkinitramfs's Usage output.
I tried to debug the "mkinitramfs" script and it appears the $outfile variable is never set.
However, I'm able to produce the ramdisk manually like follow: update-initramfs -c -u 3.0.8-23-generic
I tried most of the stuff seen on the net: purge, reinstall but no help but nothing, and I can't use linux-image is marked as "broken" but the kernel exists in /boot.

A: I was able to fix it, it seems that the kernel postinstall scripts is not compatible with my version of mkinitramfs (initramfs-tools 0.103ubuntu0.7).
In the linux-image postinstall script file, the call lacks of a parameter:
at line 837:
my $ret = system("$ramdisk " . ($upgrading ? "-u" : "-c") . " -k " . $version . " >&2");

should be  (Note the -o parameter before the $version variable.)
my $ret = system("$ramdisk " . ($upgrading ? "-u" : "-c") . " -k " . " -o " . $version . " >&2");

And it works! I was always bypassing this issue with a manual update-initramfs but I didn't like the fact that each time I used apt-get, dpkg status kept printing this error which fortunately was not blocking, then I had some spare time tonight and decided to put these on this annoying stuff and it pays off! =)
Unfortunately, it doesn't explain why an how I got this issue after an  distro-upgrade of my Ubuntu server using the official repositories. :/


text:
Q: Is it possible to get all facebook checkins of user's friend list through facebook api? I need all of the facebook checkins made by friend list of a user through facebook api. I am not able to get any proper documention for this.

A: looks like they dont offer it anymore
https://developers.facebook.com/docs/graph-api/reference/v2.1/user/checkins

A: Late answer, but the Graph query you were looking for is /me/friends?fields=tagged_places.


text:
Q: "Neither . . . nor" vs. "nor . . . neither" In my native language we have a neither-nor-like structure which can be used either
as:

I neither like thing A and nor thing B.

or as:

I nor like thing A and neither thing B.

Is it possible to do that in English?

A: No, "neither" must always come first in this construction.
Also it generally comes after the verb in the example you give, not before it:

I like neither thing A nor thing B.

As @Richard points out, putting "neither" before the verb implies that the verb is part of what the "neither" is applying to:

I neither like nor detest thing A.

A: In English, the sequence must be 'neither ... nor ...'.  You also do not use an 'and' in the construction:

I neither like thing A nor like thing B.
I like neither thing A nor thing B.

The second is generally better where the verb ('like') is the same; the first is necessary if the verbs differ:

I neither like thing A nor dislike thing B.

If the noun phrases ('thing A' in the example) are in fact compound phrases, then the repeated verb might still be beneficial even when it is the same in both parts (though I'm not convinced this example manages to demonstrate the point):

I neither like the carelessness of the average mailing list correspondent nor like the tendency of mailing lists to degenerate into ad hominem attacks.

However, at that point, it might be written as:

I do not like the carelessness of the average mailing list correspondent, nor do I like the tendency of mailing lists to degenerate into ad hominem attacks.


text:
Q: array of objects send through href I'm trying to send some data through href tag, I`m using template literals, it works fine with strings and simple objects, but with an array doesn't seem to be working.
This is the link
 const link =`https://wa.me/number?text=Thanks%20for%20your%20purchase%20${input.name}!%0A${items}%0AName:%20${input.name}%0AAdress:%20${input.addess}%0APhone:%20${input.Phone}%0ACity:%20${input.city}%0ATotal:%20$${total}`

This is the JS, and I am not really sure if it's okay to use template literals here.
code snipped
const items = cart && cart.map((p, i) => {
    return(
      `

${p.title}

           {p.salsa && p.salsa.map(item =>
{item}
)}

           {p.toppings && p.toppings.map(item => item)}

${p.quantity}

${p.Comments}

`
    )
})


text:
Q: What happens when an exception is thrown from a filter after the servlet completes? I am working on a service hosting several REST API using Java Servlet.
The Servlet uses annotations provided by javax.ws.rs to define the API's URL, HTTP method, etc. So one of them may look like as follows:
@Path("root")
@Service
public class MyClass {
    @Path("path")
    @Get
    @Produces("application/json; charset=UTF-8")
    public ResponseObject myAction() { ... }
}

I also have a filter that due to some bug, could throw an exception after executing the servlet. So it behaves as follows:
public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
        chain.doFilter(request, response);
        throws new Exception();
    }
}

The web.xml contains following definition: (not complete, just those I think might be relevant)
<servlet>
    <servlet-name>jersey-servlet</servlet-name>
    <servlet-class>
        com.sun.jersey.spi.spring.container.servlet.SpringServlet
    </servlet-class>
    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<filter>
    <filter-name>MyFilter</filter-name>
    <filter-class>myorg.MyFilter</filter-class>
</filter>

When I call this API using different approaches, I get different results.

*

*Using Jersey client and get as string
WebResource resource = client.resource("https://my-service/root/path");
ClientResponse response = resource.get(ClientResponse.class);
String s = response.getEntity(String.class);

This will give me below error:
Caused by: java.io.IOException: Premature EOF
at sun.net.www.http.ChunkedInputStream.readAheadBlocking(ChunkedInputStream.java:565)
at sun.net.www.http.ChunkedInputStream.readAhead(ChunkedInputStream.java:609)
at sun.net.www.http.ChunkedInputStream.read(ChunkedInputStream.java:696)
at java.io.FilterInputStream.read(FilterInputStream.java:133)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3393)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.Reader.read(Reader.java:140)
at com.sun.jersey.core.util.ReaderWriter.readFromAsString(ReaderWriter.java:171)
at com.sun.jersey.core.util.ReaderWriter.readFromAsString(ReaderWriter.java:157)
at com.sun.jersey.core.provider.AbstractMessageReaderWriterProvider.readFromAsString(AbstractMessageReaderWriterProvider.java:114)
at com.sun.jersey.core.impl.provider.entity.StringProvider.readFrom(StringProvider.java:73)
at com.sun.jersey.core.impl.provider.entity.StringProvider.readFrom(StringProvider.java:58)
at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:634)

*Using Jersey client but de-serializing the JSON response into an object
WebResource resource = client.resource("https://my-service/root/path");
ClientResponse response = resource.get(ClientResponse.class);
ResponseObject result = response.getEntity(ResponseObject.class);

This will return successfully and the resulting ResponseObject contains correct content.

*Call this API using HTTP tool Postman. This will also return status 200 and correct response body.

*Call the API using .Net core library RestSharp
var restClient = new RestClient("https://my-service/");
var request = new RestRequest("/root/path", method);
var response = restClient.Execute(request);

This will fail with following error:
The server returned an invalid or unrecognized response.
at System.Net.Http.HttpConnection.FillAsync()
at System.Net.Http.HttpConnection.ChunkedEncodingReadStream.ReadAsyncCore(Memory`1 buffer, CancellationToken cancellationToken)
at System.Net.Http.HttpConnection.HttpContentReadStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at RestSharp.Extensions.MiscExtensions.ReadAsBytes(Stream input)
at RestSharp.Http.ProcessResponseStream(Stream webResponseStream, HttpResponse response)
at RestSharp.Http.ExtractResponseData(HttpResponse response, HttpWebResponse webResponse)
at RestSharp.Http.GetResponse(HttpWebRequest request)

My question is:
What happened to my HTTP response in this case and why different clients behaved differently ? I guess when MyClass.myAction completed, the serialized return object ResponseObject was already sent to the client. However, when the control was given back to MyFilter, an error was thrown. This must have had some impact on the HTTP response, but what ? And why would this by observed in some cases by some client but ignored by others ?
It's quite easy for me to fix the bug itself - to not throw exception in the filter. But I want to understand more about what happened underneath and appreciate any help.


text:
Q: What does "come in" mean here? Does it mean "take part in trading"?

"Optimism is quite high but everyone is a little bit nervous about when we should come in, what's the president going to do, what changes are going to come through, so they've been holding back, so loan growth is going to be a big focus of these numbers," he added.

Source: http://www.cnbc.com/2017/04/18/us-banks-are-now-truly-turning-the-page-asset-manager-says.html

A: I think it does mean "take part in trading". I think he is using the phrase to imply "come in to the marketplace" or "come in with our money to the market" or "come bringing our assets".

A: The author could also imply that we should be optimistic when taking a risk when it involves getting a loan.
According to the article's title, the article speaks in the context of the US banks giving out loans so in that context, it also perhaps refers to the 2008 financial crisis in the US caused by too many loans given out and people becoming bankrupt and not being able to pay back. So perhaps the focus is more on banks in the US being more cautious when giving out loans by checking the credit of each individual to ensure they are able to pay it back. So this involves stricter laws in order to avoid another economic crackdown.
Your question seems to be a bit vague but this is what I had in mind. Perhaps if you can elaborate a little more.
Cheers!


text:
Q: Current usage with multiple PWM controlled motors I have a circuit that can use 25 A of current max, it is on a 25 A fuse. I am looking to control 4 DC brushless motors using ESC's. The trouble is that the motors are rated at 7A max current. I know that ESC's use a PWM signal to control the speed of the motors, so that means when the voltage is High in the PWM pulse the current will be ~7A for that period of time. I am worried that if I run all 4 motors (even on low speed) all at once, if the PWM signals all go high at the same time then the fuse will blow. Is this idea correct and if so what can I do to avoid this happening?
Further info: I am using these motors and they will be driving a propeller for a ROV. The manual for the esc is here, I believe the PWM frequency is 2Khz (they refer to it as operating frequency so I am not 100% sure).

A: The PWM frequency should be high enough that the motor's inductance has a smoothing effect, so current should not go to max as soon the PWM signal goes high. However the current will ramp up, so you should put plenty of capacitance across the power supply to reduce ripple (good ESC's already have low-ESR caps built in, but it doesn't hurt to add more externally). Most brushless ESC's run a PWM frequency of 8KHz or higher, which is fine for high inductance iron cored motors (coreless motors need 30KHz or higher).
If these two conditions are met then the power supply should 'see' a peak current only slightly higher than the average current draw, even if all PWM signals go high at the same time. Just make sure that the average current doesn't exceed 25A and you should be safe. If the motors experience heavy loading during start up or fast throttle changes then you may need to limit the throttle change rate and/or apply current limiting, to keep below the power supply's current limit.
The power absorbed by a propeller is proportional to rpm squared, so at low speed it will put much less load on the motor, eg. if the full throttle current draw was 7A then at 25% throttle it would drop to about 0.3 Amps. So long as your props are small enough to keep the full throttle current below 6.25A per motor you shouldn't have anything to worry about.
The oscilloscope picture below shows current flowing through the windings of a high power brushless motor at a PWM frequency of 12KHz. You can see the current ramping up to about 32A during the PWM ON time (full throttle current draw was 40A). Current at the power supply would have been much smoother than this, as I had several 220uF low-ESR caps across it.


text:
Q: Serializing a Javascript object with contained arrays to json? I have a javascript object that contains a few objects that contain associative arrays. I've been trying to use the json2.js library's stringify function but the output doesn't contain the arrays held in the contained object members.
In my code I start with something like this
obj = {"arr1" : [], "arr2" : [], "arr3" : []};

then I add to it with loops that fill each of the contained arrays
obj[arr*].push[arritem*];
obj[arr*][arritem*] = something;

The arr* and arritem* I put in just to represent the variable I am putting in for the loops.
I try Json.stringify(obj) but the string I get back is
'{"arr1" : [0], "arr2" : [0], "arr3" : [0]}'

I would like to see the ouput as
'{"arr1" : [ "arritem1" : something, "arritem2" : something2], "arr2" : [ "arritem1" : something, "arritem2" : something2], "arr3" : [ "arritem1" : something, "arritem2" : something2]}'

is there a better library for this or is there something I have to do before strinfying?

A: var obj = {"arr1" : [], "arr2" : [], "arr3" : []};
console.log(JSON.stringify(obj));

Works for me.
Filling the arrays works too.

Update
You imply that you are trying to add elements with non-numeric keys to arrays.
This is not valid. In particular, your desired output is not valid JSON. Arrays have only numeric keys, and they are not included in the JSON itself as they are implicitly, sequentially defined.
Arrays are a special type of Object, which handles numeric indexes for you.
var arr = [];   // Create array.
arr.push(1);    // There is now one element, with index 0 and value 1.
arr["txt"] = 2; // You tried to create a new element,
                // but didn't use .push and gave a non-numeric key.
                // This broke your array.

console.log(JSON.stringify(arr));
// Output: [1]

Live demo.
Long story short... don't do this. If you want an "associative array", stick with basic objects:
var obj    = {}; // Create object.
obj[0]     = 1;  // There is now one element, with key "0" and value 1.
obj["txt"] = 2;  // There is now a second element, with key "txt" and value 2.

console.log(JSON.stringify(arr));
// Output: {"0":1,"txt":2}

Live demo.

A: obj.toSource()

this will convert your array to source string.


text:
Q: How to access continuity through applescript or command line Goal:
I want to handoff my localhost site to my phone for testing. I can access my localhost by going to http://my.ip.add.ress/localhost on my iphone. Of course, on my computer the actual address is just http://localhost. Instead of typing that address I want to trigger a script that will "handoff" the concatenation of my computer's ip address + localhost/page.
My question is if I can trigger a "handoff" through applescript or command-line. Is there a handoff API?
I'm not asking about how to get my computer's ip address.

A: You can probably avoid all the hassle by just using one nice service - http://xip.io
Instead of browsing to http://localhost - look up your IP and browse to http://192.168.12.13.xip.io/
Of course, your actual IP address for the local host is needed unless your router was set up to assign your test Mac 192.168.12.13 - even though you aren't asking how to get your IP, that's the key to making this easy for safari to hand off the session from macOS to iOS.

Does xip.io cost anything?
Nope! xip.io is a free service from Basecamp, the
  creators of Pow. We were tired of jumping through hoops
  to test our apps on other devices and decided to solve
  the problem once and for all.


text:
Q: Existence of intermediate fields with order $9$ and $3$ of a Galois field extension of order $27$. Here is the question again:
Let $F$ be a Galois extension of $K$ such that $[F:K] = 27$. Show that there are intermediate fields of order $9$ and $3$.
I am stumped.
By the Galois correspondence, the Galois group of the extension has order 27 and it suffices to find subgroups of order $9$ and $3$. I know by Lagrange's Theorem that intermediate fields of order $9$ and $3$ are allowed.

A: The Galois group of $F/K$ is a $p$-group.
A $p$-group of order $p^n$ has subgroups of order $p^m$ for all $m \le n$. This follows from the Sylow theorems.
Therefore, the Galois group has subgroups of order $3$ and $9$. The fixed fields of these subgroups have degree $9$ and $3$, respectively.


text:
Q: Can a FileVault-encrypted partition be accessed using a password I supplied during OS X install? I have a MacBook (Retina, Mid 2012 if it's relevant) which I installed Mountain Lion onto, creating one user account only (an Admin account). There is a Guest User, marked for "Sharing Only". The hard drive was encrypted with FileVault 2 at the time of install, and the recovery key stored away.
For various reasons the password to my user account was disclosed (but NOT the FileVault recovery key). I changed the password on my user account before it could be used, but the old password is still known.
Is the old password still retained with respect to the FileVault partition, and might enable someone to decrypt the FileVault-encrypted drive? Put another way, are my new password and the recovery key the only way to decrypt the FileVault partition?

A: Once you change the password, it has been charged and the old password can not access the FileVault decryption protocol. It would be nightmarish if you had to always remember any and all passwords ever used by the FileVault account(s).
If you want really great info to FileVault please watch: http://docs.macsysadmin.se/2013/video/Day2Session5.mp4

A: You need a current working password for your filevaulted system. Anyone who has access to such can unlock the file system. The recovery key will always be the emergency key when you forget your passcode. Think of that as your key under the rug at your house. Safely store that so you can gain access in the worst case scenario. Remember if you enabled the option when you activated filevault to store ur recovery key with apple, they can access that for you if you lose it. If you are worried the FEDS are getting into your encrypted hard drive. well you might as well say bye bye.
Here is a good site to read about how it works and what it does:
http://afp548.com/2012/06/05/filevault-2-the-silent-protector/
*Edit
Also read this,
"When FileVault is turned on, guest users can only log in and use Safari. Guests can't access your FileVault-encrypted disk or create files. Instead, they log in and use Safari from your computer's built-in recovery disk." support.apple.com/kb/PH11321
Guest account boots in a different partition that does not have access to the encrypted partition
The question your asking is confusing:
The password to unlock the encrypted drive is whatever your password is to login to your user account. I don't understand your problem. If you changed your user account password. Use the new user account password to unlock the system-or recovery key if necessary. Could you elaborate anymore?


text:
Q: Add-Leaf function "hanging", custom BST Class in C++ This problem is a little more complicated than previous ones I've brought here, so I'll try to be very explicit about what I've narrowed it down to.
I'm writing a Binary Search Tree data class in C++ that functions like a standard BST except that it stores duplicates of Odd numbers using a "count" field in the BST node.
I've written a test driver to test the member functions of the class and have run into an error that I cannot seem to solve. When I attempt to add a set number of random integers to a BST object none of them  seem to make it into the tree. To check the contents I use a printInOrder function that I have confirmed works properly so I know the problem isn't there.
For starters, I'll post the addLeaf, printInOrder, and createLeaf functions, and the small block of code where I call them in my driver file.
bool fixedDupBST::addLeaf(int key)
{
    if(root == nullptr){
        root = createLeaf(key);
        assert(root != nullptr);
    }
    else {
        node *prev = nullptr;
        node *scanPtr = root;
        bool right, dupe = false;
        while(scanPtr != nullptr) {
            prev = scanPtr;
            if(key < scanPtr->key) {
                scanPtr = scanPtr->left;
                right = false;
            }
            else if (key == scanPtr->key) {
                if (scanPtr->keyCount >= 1)
                    dupe = true;
                else{
                    dupe = false;
                    scanPtr = nullptr;
                }
            }
            else {
                scanPtr = scanPtr->right;
                right = true;
            }
        }
        if (dupe)
            prev->keyCount++;
        else if (!dupe)
            return false;
        else if (right) {
            prev->right = createLeaf(key);
            assert(prev->right != nullptr);
        }
        else {
            prev->left = createLeaf(key);
            assert(prev->left != nullptr);
        }
    }
    return true;
}

fixedDupBST::node* fixedDupBST::createLeaf(int key)
{
    node* newNode = new node;
    assert(newNode != nullptr);
    newNode->key = key;
    newNode->left = nullptr;
    newNode->right = nullptr;
    if (key % 2 != 0)
        newNode->keyCount = 1;
    else
        newNode->keyCount = 0;
    return newNode;
}

void fixedDupBST::printInOrder()
{
    printInOrderPr(root);
}
void fixedDupBST::printInOrderPr(node* Ptr)
{
    if(root != nullptr) {
        if(Ptr->left != nullptr){
            printInOrderPr(Ptr->left);
        }
        cout << Ptr->key << ' ';
        if(Ptr->right != nullptr) {
            printInOrderPr(Ptr->right);
        }
    }
    else {
        cout << "The tree is empty" << endl;
    }

    return;
}

void testInsert(fixedDupBST &BST)
{
    int temp;

    for (int i = 0; i < TEST_PARAM; i++) {
        temp = randNum();
        BST.addLeaf(temp);
    }
    BST.printInOrder();
    return;
}

The problem I'm getting is that when I call printInOrder() it always gives "The tree is empty". At first I thought it might be a problem with how I was passing parameters in the class member functions (pass by references vs pass by value) but that didn't provide any solutions. If there are any problems at all with the rest of the function it doesn't seem to matter because root never gets assigned to that first node, (hence why print in order just says "the tree is empty".
I need a second set of eyes on this; thanks in advanced for you help, and let me know if I can rephrase my question or provide more information to help make the situation clearer.
EDIT: R Sahu had the error correct, but his answer is a little off. I realized that a bool wouldn't work cleanly for what I was trying to do because there are actually 3 cases:
The number is a duplicate and is odd,
the number is a duplicate and is even
and the number is NOT a duplicate.
The problem stemmed from the fact that the quit condition for the while loop was scanPtr being null, and the if/else-if statement at the end had no way of knowing if it was null because it reached the end of a subtree and was ready to insert, or if I had manually set it to null upon finding a duplicate in order to break the loop appropriately.
Here is the solution I came up with.
bool fixedDupBST::addLeaf(int key)
{
    if(root == nullptr){
        root = createLeaf(key);
        assert(root != nullptr);
    }
    else {
        node *prev = nullptr;
        node *scanPtr = root;
        bool right;
        int dupe = 0;  // switch variable
        while(scanPtr != nullptr) {
            prev = scanPtr;
            if(key < scanPtr->key) {
                scanPtr = scanPtr->left;
                right = false;
            }
            else if (key == scanPtr->key) {
                if (key % 2 != 0) {
                    dupe = 1;
                    scanPtr = nullptr;
                }
                else{
                    dupe = 2;
                    scanPtr = nullptr;
                }
            }
            else {
                scanPtr = scanPtr->right;
                right = true;
            }
        }
        if (dupe == 2)
            return false;

        if (dupe == 1)
            prev->keyCount++;
        else if (right) {
            prev->right = createLeaf(key);
            assert(prev->right != nullptr);
        }
        else {
            prev->left = createLeaf(key);
            assert(prev->left != nullptr);
        }
    }
    return true;
}

Everything works appropriately now.

A: You have a logic error in this block.
    if (dupe)
        prev->keyCount++;
    else if (!dupe)    // This is pointless
                       // dupe is either true or false.
                       // Your code will never get to the next "else if"
        return false;
    else if (right) {
        prev->right = createLeaf(key);
        assert(prev->right != nullptr);
    }
    else {
        prev->left = createLeaf(key);
        assert(prev->left != nullptr);
    }

What you need is:
    if (dupe) {
        prev->keyCount++;
        return false;   // I think you want to return false here but I am not sure
    }
    else if (right) {
        prev->right = createLeaf(key);
        assert(prev->right != nullptr);
    }
    else {
        prev->left = createLeaf(key);
        assert(prev->left != nullptr);
    }

A: R Sahu had the error correct, but his answer is a little off. I realized that a bool wouldn't work cleanly for what I was trying to do because there are actually 3 cases:
1: The number is a duplicate and is odd.
2: the number is a duplicate and is even.
3: the number is NOT a duplicate.
The problem stemmed from the fact that the quit condition for the while loop was scanPtr being null, and the if/else-if statement at the end had no way of knowing if it was null because it reached the end of a subtree and was ready to insert, or if I had manually set it to null upon finding a duplicate in order to break the loop appropriately.
Here is the solution I came up with.
bool fixedDupBST::addLeaf(int key)
{
    if(root == nullptr){
        root = createLeaf(key);
        assert(root != nullptr);
    }
    else {
        node *prev = nullptr;
        node *scanPtr = root;
        bool right;
        int dupe = 0;  // switch variable
        while(scanPtr != nullptr) {
            prev = scanPtr;
            if(key < scanPtr->key) {
                scanPtr = scanPtr->left;
                right = false;
            }
            else if (key == scanPtr->key) {
                if (key % 2 != 0) {
                    dupe = 1;
                    scanPtr = nullptr;
                }
                else{
                    dupe = 2;
                    scanPtr = nullptr;
                }
            }
            else {
                scanPtr = scanPtr->right;
                right = true;
            }
        }
        if (dupe == 2)
            return false;

        if (dupe == 1)
            prev->keyCount++;
        else if (right) {
            prev->right = createLeaf(key);
            assert(prev->right != nullptr);
        }
        else {
            prev->left = createLeaf(key);
            assert(prev->left != nullptr);
        }
    }
    return true;
}

Everything works appropriately now.


text:
Q: Time-ordering operators: Can we simplify expressions inside? Clearly if we have two operators $\phi(t_1)$ and $\psi(t_2)$ and define a time ordering operator $T$ acting on operators such that $$T(\phi(t_1)\psi(t_2)):=\phi(t_1)\psi(t_2),~\text{if $t_1>t_2$ otherwise the other way around}$$
we could pretend that inside $T$ these operators commute. However I am not quite convinced that we are allowed to simplify expressions inside, as there might well be such operators $A$ and $B$ that $A(x)B(y)$ is non-zero for all $x,y$ but $B(y)A(x)$ is always zero. Thus if we choose to simplify expressions inside $T$ it may well go wrong as we end up with a null operator, and $T(0)$ certainly will not return you with a time-ordered non-zero result.
What is going on here?


text:
Q: Programming BeagleBone Green Wireless without installing an image? I have just had an SeeedStudio BeagleBone Green Wireless. It's completely compatible with BeagleBone Black and I know that it has already had an Linux in on-board 4GB eMMC.
So I think I could program the GPIO of the board without installing a new image (in Micro SD Card). But when I tried to write value 1 to GPIO 48, I didn't see the LED flash.
root@beaglebone:/sys/class/gpio# echo 48 > export
root@beaglebone:/sys/class/gpio/gpio44# echo out > direction
root@beaglebone:/sys/class/gpio/gpio44# echo 1 > value

I tried it with Cloud9 IDE in an different language also but it's still not successful. When I change the connection of the bus from GPIO 48 to the VCC, the LED was bright, so the hardware setup was ok.
Is there any reason behind the scences ?
Do I need to install an image in SD Card to program the GPIO ?

A: You export 48 then use gpio44 (based on prompt).


text:
Q: use the correct number of arguments for new in Ruby I am working on a gem that can uses different version of Gherkin, but I'm facing a problem:
in the 2.4.0 version Gherkin::Formatter::Model::Scenario.new takes 6 arguments but in 2.6.5 it takes 7 arguments.
So my question is what is a best practice in this case ? Should I do:
case Gherkin::Version
when '2.4.0'
  do the init with 6 arguments
else
  with the 7
end

I was thinking also of creating a new_with_arity method:
class Object
  def new_with_arity(*params)
    puts method(:initialize).arity # => -1
    puts method(:new).arity        # => -1
    new(*(params + [nil] * (params.count - method(:new).arity)))
  end
end

However this does not work, the arity of new and initialize is -1.
Do you have an idea ?

A: I would build 2 Gherkin adapters and load up the proper one for the proper version. Or, you are using Rubygems, so you can force a specific version of the Gherkin parser

A: I would recommend following Jim Deville's advice. Saying that it's quite an interesting idea and you were pretty close. The problem is you can't get the method without having an instance, so the trick is to use allocate first.
class Object
  def new_with_arity(*params)
    new *(params + [nil] * (allocate.method(:initialize).arity - params.size))
  end
end

class One
  def initialize a
    [a]
  end
end

class Two
  def initialize a, b
    [a, b]
  end
end

One.new_with_arity 1     #=> [1]
Two.new_with_arity 1, 2  #=> [1, 2]
Two.new_with_arity 1     #=> [1, nil]


text:
Q: how i can use SAX parser This is what the result should look like when i parse it through a SAX parser
http://img13.imageshack.us/img13/6950/75914446.jpg
This is the XML source code from which i need to generate the display:
<orders>
  <order>
    <count>37</count>
    <price>49.99</price>
    <book>
      <isbn>0130897930</isbn>
      <title>Core Web Programming Second Edition</title>
      <authors>
         <count>2</count>
        <author>Marty Hall</author>
        <author>Larry Brown</author>
      </authors>
    </book>
  </order>
  <order>
    <count>1</count>
    <price>9.95</price>
    <yacht>
      <manufacturer>Luxury Yachts, Inc.</manufacturer>
      <model>M-1</model>
      <standardFeatures oars="plastic" lifeVests="none">false</standardFeatures>
</yacht>
  </order>
  <order>
    <count>3</count>
    <price>22.22</price>
    <book>
      <isbn>B000059Z4H</isbn>
      <title>Harry Potter and the Order of the Phoenix</title>
      <authors>
         <count>1</count>
        <author>J.K. Rowling</author>
      </authors>
    </book>
  </order>

i really have no clue how to code the functions but i have just set up the parser
$xmlParser = xml_parser_create("UTF-8");
xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, false);
xml_set_element_handler($xmlParser, 'startElement', 'endElement');
xml_set_character_data_handler($xmlParser, 'HandleCharacterData');
$fileName = 'orders.xml';
    if (!($fp = fopen($fileName, 'r'))){
        die('Cannot open the XML file: ' . $fileName);
    }
    while ($data = fread($fp, 4096)){
        $parsedOkay = xml_parse($xmlParser, $data, feof($fp));
        if (!$parsedOkay){
            print ("There was an error or the parser was finished.");
            break;
        }
    }
    xml_parser_free($xmlParser);

    function startElement($xmlParser, $name, $attribs)
    {
    }

    function endElement($parser, $name)
    {
    }

    function HandleCharacterData($parser, $data)
    {
    }

A: A SimpleXML-based recursive approach might be a simpler solution perhaps, something like:
  $xml = new SimpleXmlElement($data);

  function renderTree(SimpleXmlElement $xml, $depth = 0) {
    $output = str_repeat('| ', $depth);
    $output .= '+-' . $xml->getName();

    if (sizeof($xml->attributes()) > 0) {
      $attrs = '';
      foreach ($xml->attributes() as $key => $value) {
        $attrs .= $key . '=' . $value . ', ';
      }
      $output .= ' (' . trim($attrs, ', ') . ')';
    }

    $output .= ': ' . (string)$xml;
    $output .= '<br />';

    if ($xml->count() > 0) {
      foreach ($xml->children() as $child) {
        $output .= renderTree($child, $depth + 1);
      }
    }

    return $output;
  }

  echo renderTree($xml);

Would render the tree as in the example image.


text:
Q: How often does Python switch threads? In cPython (the default Python implementation), how often does thread switching happen? This is not a question about using multiple cores; I know about the GIL, and realize that only one thread will be run at at time.
I have seen a few cases where I have two log messages in sequence, and the first log message will be emitted, but the second is not emitted for several seconds. This probably happens because Python decided to switch threads in between the two log statements. This leads me to believe that Python switches between threads once every couple of seconds, which is much slower than I would have expected. Is this correct?

A: Since Python 3.2 the interpreter's thread switch time interval can be adjusted using sys.setswitchinterval: https://docs.python.org/3.6/library/sys.html#sys.setswitchinterval
In earlier versions the interpreter checks for periodic things such as thread switches and signal handlers by default every 100 virtual instructions. This can be modified by sys.setcheckinterval: https://docs.python.org/2/library/sys.html#sys.setcheckinterval

A: By default, Python 2 will switch threads every 100 instructions. This can be adjusted with sys.setcheckinterval which is documented here: https://docs.python.org/2/library/sys.html#sys.setcheckinterval
I found additional information on pages 10, 11, and 12 of this presentation: http://www.dabeaz.com/python/UnderstandingGIL.pdf
(These answers come from the comments of the question, but since nobody has written them down in an answer I will do it myself. It has been 6+ months since the comments were made.)
UPDATE:
Since Python 3.2, sys.setcheckinterval was deprecated. CPython has another approach to improve the GIL. Instead of release the GIL after 100 virtual instruction, they changed to switch by time interval instead.
By default, the GIL will be released after 5 milliseconds (5000 microseconds) so that other thread can have a change to acquire the GIL. And you can change this default value by using sys.setswitchinterval


text:
Q: is it possible to tell dependabot to not connect to central maven at all In enterprise environment, the connection to central maven could be blocked. In this case,
i) either don't connect to central maven at all
ii) or if the connection to central maven is not successful, don't raise exception, just move on to other repositories
currently i see below exception
/vendor/ruby/2.6.0/gems/excon-0.76.0/lib/excon/socket.rb:285:in `select_with_timeout': connect_write timeout reached (Excon::Error::Timeout)

so I am wondering if there is any way to tell dependabot to not try connecting to maven central at all.
fyi. i am running https://github.com/dependabot/dependabot-script

A: Generally what happens in an enterprise environment, it does have the local repository like Nexus within the network. Now you mirror your local nexus repo in settings.xml. You can mirror any no. of  repo in your settings.xml. Now, maven first try to find the dependencies in your all local repo first and if it does not find it, only then it goes for maven central repo.
If the maven central is not block, then the library first downloaded to your local nexus repo and then would be downloaded to your local. So next time when you will try to download this library, it will be available in your local enterprise nesus repo.
You can block the maven central repo, refer -  https://stackoverflow.com/questions/4997219/disable-maven-central-repository#:~:text=In%20maven's%20home%2C%20in%20the,or%20just%20override%20it's%20definition.
But as per your question, if the dependency library not found in any repo, there would always be an exception in maven build.


text:
Q: Given the function $f(x) = \cos(2 x \pi) + i \sin(2 x \pi)$ find $x \in \mathbb{R}$ such that $f(x)$ is a fourth root of unity. I am given the following function:
$$f : \mathbb{R} \rightarrow \mathbb{C} ^ * \hspace{2cm} f(x) = \cos(2 x \pi) + i \sin(2 x \pi)$$
and I have to find $x \in \mathbb{R}$ such that $f(x)$ is a $4$th root of unity.
This is what I did:
$$( f(x) ) ^ 4 = 1 \Rightarrow f(x) = \pm 1$$
Case number $1$:
$$f(x) = 1$$
$$\cos(2x\pi) + i\sin(2x\pi) = 1$$
Now matching the real part from the left-hand side with the real part from the right hand side and the imaginary part from the left-hand with the imaginary part from the right-hand side we get:
$$\hspace{5cm} \cos(2x\pi) = 1 \hspace{5cm} (1)$$
$$\hspace{5cm} \sin(2x\pi) = 0 \hspace{5cm} (2)$$
Solving $(1)$ I got:
$$x = k, \hspace{.25 cm} k \in \mathbb{Z}$$
Solving $(2)$ I got:
$$x = \dfrac{k}{2}, \hspace{.25 cm} k \in \mathbb{Z}$$
Intersecting these two I got that:
$$\hspace{5cm} x \in \{ k \hspace{.1cm} | \hspace{.1cm} k\in \mathbb{Z}\} \hspace{5cm} (*)$$
Case number $2$:
$$f(x) = -1$$
$$\cos(2x\pi) + i\sin(2x\pi) = -1$$
Acting in a similar manner as we did in Case $1$, we get that:
$$\hspace{5cm} \cos(2x\pi) = -1 \hspace{5cm} (3)$$
$$\hspace{5.3cm} \sin(2x\pi) = 0 \hspace{5.2cm} (4)$$
Solving $(3)$ I got:
$$x = \dfrac{2k + 1}{2}, k \in \mathbb{Z}$$
Solving $(4)$ I got:
$$x = \dfrac{k}{2}, k \in \mathbb{Z}$$
Intersecting these two I got:
$$\hspace{5cm} x \in \bigg \{ \dfrac{2k + 1}{2} \hspace{.1cm} | \hspace{.1cm} k \in \mathbb{Z} \bigg\} \hspace{5cm} (**)$$
Now taking the unity of the two intervals at $(*)$ and at $(**)$ we get that the equation $( f(x) ) ^ 4 = 1$ has solutions if
$$x \in \{ k \hspace{.1cm} | \hspace{.1cm} k \in \mathbb{Z} \} \hspace{.1cm} \cup \hspace{.1cm} \bigg \{ \dfrac{2k + 1}{2} \hspace{.1cm} | \hspace{.1cm} k \in \mathbb{Z} \bigg \} $$
So that's that. The problem is that the solution given from the source of this exercise is actually:
$$x \in \bigg \{ \dfrac{k}{4} \hspace{.1cm} | \hspace{.1cm} k \in \mathbb{Z} \bigg \}$$
So what did I do wrong?

A: Note $f^4(x) = 1$ leads to $f(x)=e^{i\frac {2\pi k}4}$ with $k \in \mathbb{Z}$. Then,
$$f(x) = \cos(2 x \pi) + i \sin(2 x \pi)=e^{i2x\pi}=e^{i\frac {2\pi k}4}$$
Thus, $$x \in \bigg \{ \dfrac{k}{4} \hspace{.1cm} | \hspace{.1cm} k \in \mathbb{Z} \bigg \}$$

A: You also need to consider the cases
$f(x) = i$
and
$f(x) = -i$.
Also note that
$f(x) = e^{2\pi i x}$
so
$f(x)^4
=e^{8\pi i x}
$
so you want
$8\pi x = 2k\pi
$
or
$x = \frac{k}{4}$.


text:
Q: I keep getting None
My code:
def get_feedback(mark, out_of):
    percentage = int((mark / out_of) * 100)

    if percentage >= 80:
        print("Excellent")
    if 60 < percentage < 70:
        print("Good")
    if 50 < percentage < 59:
        print("Pass")
    if percentage < 50:
        print("Not a pass")

I know I have to use a return statement somewhere but I'm not really sure how it works or when to use it. If anyone could help, that would be great thank you!

A: def get_feedback(mark, out_of):
    percentage = int((mark / out_of) * 100)
    remark = ''
    if percentage >= 80:
        remark = "Excellent"
    elif 60 <= percentage <= 79:
        remark = "Good"
    elif 50 <= percentage <= 59:
        remark = "Pass"
    else percentage < 50:
        remark = "Not a pass"
    return remark

Some suggestions:

*

*I believe you need inclusive range, so include <= instead of <

*If one condition satisfies, no need to check the rest of the conditions. So instead of using if for every check, use if - elif- else checks.

*Also your question says the range between 60 and 79 for grade 'Good'. You haven't checked it.

A: Use return in place of print. Example :- return "Excellent".

A: You can make a variable to represent the value of its condition.
def get_feedback(mark, out_of):
    percentage = int((mark / out_of) * 100)

    if percentage >= 80:
        feedback = "Excellent"
    elif 60 < percentage < 70:
        feedback = "Good"
    elif 50 < percentage < 59:
        feedback = "Pass"
    elif percentage < 50:
        feedback = "Not a pass"

    return print(feedback)

At the very end, we use return to give us the result of the function. Also, notice that I used elif statements, which are faster than just using if statements.

A: Another way to do it :
def get_feedback(mark, out_of):
    percentage = int((mark / out_of) * 100)

    if percentage >= 80:
        return "Excellent"
    elif 60 <= percentage <= 79:
        return "Good"
    elif 50 <= percentage <= 59:
        return "Pass"
    else:
        return "Not a pass"


text:
Q: How to change styles in UWP correctly? Tell me how you can change the styles more succinctly? The thing is, I change the style for each element separately, which is not very good
 <VisualStateManager.VisualStateGroups>
            <VisualStateGroup>
                <VisualState>
                    <VisualState.StateTriggers>
                        <StateTrigger IsActive="{Binding IsOfferSO}" />
                    </VisualState.StateTriggers>
                    <VisualState.Setters>
                        <Setter Target="gridOffer1.Style" Value="{StaticResource SelectedOffer}" />
                        <Setter Target="gridOffer2.Style" Value="{StaticResource UnSelectedOffer}" />
                        <Setter Target="durationOffer1.Style" Value="{StaticResource SelectedTxtBlock}" />
                        <Setter Target="durationOffer2.Style" Value="{StaticResource UnSelectedTxtBlock}" />
                        <Setter Target="priceOffer1.Style" Value="{StaticResource SelectedTxtBlock}" />
                        <Setter Target="priceOffer2.Style" Value="{StaticResource UnSelectedTxtBlock}" />
                    </VisualState.Setters>
                </VisualState>

                <VisualState>
                    <VisualState.StateTriggers>
                        <AdaptiveTrigger MinWindowWidth="0" />
                    </VisualState.StateTriggers>
                    <VisualState.Setters>
                        <Setter Target="gridOffer1.Style" Value="{StaticResource UnSelectedOffer}" />
                        <Setter Target="gridOffer2.Style" Value="{StaticResource SelectedOffer}" />
                        <Setter Target="durationOffer1.Style" Value="{StaticResource UnSelectedTxtBlock}" />
                        <Setter Target="durationOffer2.Style" Value="{StaticResource SelectedTxtBlock}" />
                        <Setter Target="priceOffer1.Style" Value="{StaticResource UnSelectedTxtBlock}" />
                        <Setter Target="priceOffer2.Style" Value="{StaticResource SelectedTxtBlock}" />
                    </VisualState.Setters>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>

Are there any examples that would allow you to do the same, but in a simpler way?

A: Please refer to this document to edit your style, you could specific a TargetType and an x:Key attribute attribute for the Style and then by setting the target control's Style property with a {StaticResource} markup extension reference that uses the explicit key.
And if you want to this style could effect for each target control by default. please specific only a TargetType for the Style.


text:
Q: In chrome, why does DOMContentLoaded appear to take longer than the request/response itself?
As you can see, the actual length of the request and its subsequent response is very quick. You cant see it in this view, but the blue bar represents a transaction that took 9 milliseconds.
The two lines, red and blue (which completed nearly instantaneously and are thus very close to each other), pictured far to the right of that, show up around 51ms.
So, what is happening here? is this actually time being spent? or is it just how the browser records it?

A: Your request took 9 milliseconds to complete
After that your browser received some data, it converted this into an html object(DOM) and displays this on your screen(DOMLoaded)
The action of converting and displaying took your browser 42 milliseconds, which is the gap between response and domLoaded.

edit:
I didn't manage to find the exact things the browser does but when i look into the dom of an empty page (which takes 100ms on my browser btw) i can find things like local storage, screen resolution, geo location and history.
Besides that i can imagine that cookie and add-ins can also take up some time if they are hooked. My ghostery for example is ment to block trackers so i assume he does so before the page is fully loaded.
I wish i could have given you a list of things the browser does in that window but alas. Maybe someone else can provide an actual list.


text:
Q: Why are all functions $\{0,1\}^t \rightarrow \{0,1\}$ expressable as polynomials? Siegelmann, Neural Networks and Analog Computation, p. 41, considers an arbitrary function $\beta(d_1,\ldots,d_t)$ : $\{0,1\}^t \rightarrow \{0,1\}$, and assumes that it can be expressed as a polynomial--a linear combination of products of zero or more $d_i$'s:
$$\beta(d_1,\ldots,d_t) = c_1 + c_2d_1 + \cdots + c_{t+1}d_t + c_{t+2}d_1d_2 + \cdots + c_{2t}d_1d_2\cdots d_t$$
I don't yet understand why every such function $\beta$ can be expressed in this way.  Why does this follow merely from the fact that $\beta$ is a map from $\{0,1\}^t$ to $\{0,1\}$?

A: One way is to associate a monomial with each input vector, and then just add up the monomials to get the desired polynomial.  For example, if you want $(0,1,1,0,1)\mapsto 1$, the monomial is $$(1-d_1)d_2 d_3 (1-d_4) d_5.$$  If instead you want $(0,1,1,0,1)\mapsto 0$, the monomial is $$1-(1-d_1)d_2 d_3 (1-d_4) d_5.$$